From 52e2f7239361287aec22246087656b3a5cfc4ea4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:13:11 +0800 Subject: [PATCH 01/83] refactor(evm): report the reservoir where the result settles, without a handler latch --- crates/mega-evm/src/evm/execution.rs | 66 +++++++++++++--------------- 1 file changed, 31 insertions(+), 35 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 88052fd64..455bb792a 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -9,7 +9,7 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::{cell::Cell, num::NonZeroU64}; +use core::num::NonZeroU64; use op_revm::{ handler::{IsTxError, OpHandler}, @@ -67,23 +67,16 @@ pub const SYSTEM_CALL_REGULAR_GAS_LIMIT: u64 = 30_000_000; /// The Satin handler. /// /// It wraps op-revm's [`OpHandler`] and delegates every phase `MegaETH` does not extend to it. -/// One handler runs one transaction, so what a phase learns about it is kept here. +/// It keeps nothing of the transaction it runs: what a phase learns is kept on the context. #[derive(Debug)] pub struct MegaHandler { op: OpHandler, - /// The reservoir the transaction's result settled with, read by - /// [`post_execution`](Handler::post_execution) where revm builds the result's gas, and - /// consumed by the report once the result is built - /// ([`execution_result`](Handler::execution_result)) or by the error path - /// ([`catch_error`](Handler::catch_error)), so a handler reused for a system call, whose path - /// makes no capture, reports the system call's own reservoir. - settled_reservoir: Cell>, } impl MegaHandler { /// Creates a handler. pub fn new() -> Self { - Self { op: OpHandler::new(), settled_reservoir: Cell::new(None) } + Self { op: OpHandler::new() } } } @@ -387,10 +380,11 @@ where Ok(()) } - /// revm's post-execution, with the reservoir the transaction leaves unspent read first, where - /// revm builds the result's gas: before the EIP-7623 floor check, which absorbs the reservoir - /// into the floor's cost when the floor binds. The refund before it does not move the - /// reservoir. + /// revm's post-execution, with the reservoir the transaction leaves unspent reported first + /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)), + /// where revm builds the result's gas: before the EIP-7623 floor check, which absorbs the + /// reservoir into the floor's cost when the floor binds. The refund before it does not move + /// the reservoir. fn post_execution( &self, evm: &mut Self::Evm, @@ -398,7 +392,8 @@ where init_and_floor_gas: InitialAndFloorGas, eip7702_gas_refund: i64, ) -> Result { - self.settled_reservoir.set(Some(exec_result.gas().reservoir())); + let reservoir = exec_result.gas().reservoir(); + evm.ctx_mut().additional_limit.set_reservoir_remaining(reservoir); self.op.post_execution(evm, exec_result, init_and_floor_gas, eip7702_gas_refund) } @@ -427,22 +422,24 @@ where self.op.reward_beneficiary(evm, exec_result) } - /// op-revm's result, and the reservoir it settled with reported + /// op-revm's result; for a system call, with the reservoir it settled with reported /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)). /// - /// revm's system-call path settles without [`post_execution`](Handler::post_execution): the - /// result it hands over here is the settled one, and the capture it finds is none, since the - /// report of the execution before consumed it. A deposit that halts is not a result: op-revm - /// turns it into a failed deposit, which leaves no reservoir. + /// revm's system-call path settles without [`post_execution`](Handler::post_execution), which + /// reports a transaction's: the result it hands over here is the settled one. A deposit that + /// halts is not a result: op-revm turns it into a failed deposit, which leaves no reservoir + /// ([`catch_error`](Handler::catch_error)). fn execution_result( &mut self, evm: &mut Self::Evm, result: FrameResult, result_gas: revm::context::result::ResultGas, ) -> Result, Self::Error> { - let reservoir = self.settled_reservoir.take().unwrap_or_else(|| result.gas().reservoir()); + let system_call = evm.ctx_ref().is_system_call().then(|| result.gas().reservoir()); let result = self.op.execution_result(evm, result, result_gas)?; - evm.ctx_mut().additional_limit.set_reservoir_remaining(reservoir); + if let Some(reservoir) = system_call { + evm.ctx_mut().additional_limit.set_reservoir_remaining(reservoir); + } Ok(result) } @@ -450,8 +447,8 @@ where /// halt and discards everything the deposit did. The halt is what the transaction reports; /// what the deposit counted stands, the body and the Oracle hints it forwarded before it /// halted, as for any transaction that halts. Any other error refuses the transaction, and the - /// layer's state is reset by the next one. A reservoir captured for a result that is not - /// reported is dropped here, so the next execution on this handler does not report it. + /// layer's state is reset by the next one. A reservoir reported for a result that op-revm then + /// refused is taken back here: a failed deposit leaves none, nor does an error. /// /// A failed deposit still bumps its caller's nonce and mints, so one whose caller had no /// account creates it: one account of state growth, which the transaction reports and its @@ -462,7 +459,7 @@ where evm: &mut Self::Evm, error: Self::Error, ) -> Result, Self::Error> { - self.settled_reservoir.take(); + evm.ctx_mut().additional_limit.set_reservoir_remaining(0); let result = self.op.catch_error(evm, error); let failed_deposit = matches!( result, @@ -1880,14 +1877,13 @@ mod tests { } } - /// One handler runs one transaction, and what a phase learns about it is kept on the handler: - /// the reservoir the transaction settled with is read where revm builds its result's gas and - /// reported once the result is built. A handler reused for a system call, whose path builds - /// no result gas and skips that read, reports the system call's own reservoir: the capture is - /// consumed by the report, and by the error path, which gives no report. A transaction below - /// the execution cap leaves a capture of nothing, one above it a capture of its own margin, and - /// a deposit that halts a capture its failed-deposit result never reports; after each, a - /// system call on revm's default gas limit reports the margin above the system-call budget. + /// The reservoir a transaction settled with is reported where revm builds its result's gas, and + /// a system call's, whose path builds no result gas there, once its result is built: a handler + /// reused for a system call reports the system call's own reservoir, not the transaction's + /// before it. A transaction below the execution cap reports nothing, one above it its own + /// margin, and a deposit that halts nothing, its failed-deposit result leaving no reservoir; + /// after each, a system call on revm's default gas limit reports the margin above the + /// system-call budget. #[test] fn test_a_reused_handler_reports_each_executions_own_reservoir() { use crate::{ @@ -1939,7 +1935,7 @@ mod tests { let result = handler.run(&mut evm).expect(case); assert_eq!(result.is_success(), succeeds, "{case}: {result:?}"); let settled = evm.ctx().additional_limit().reservoir_remaining(); - assert_ne!(settled, DEFAULT_RESERVOIR, "{case}: the capture would show"); + assert_ne!(settled, DEFAULT_RESERVOIR, "{case}: the transaction's own would show"); let call = MegaTransaction::new_system_tx_with_caller(CALLER, TARGET, Bytes::new()); evm.inner.ctx.set_tx(call); @@ -1949,7 +1945,7 @@ mod tests { assert_eq!( evm.ctx().additional_limit().reservoir_remaining(), DEFAULT_RESERVOIR, - "{case}: the system call's own reservoir, not the capture" + "{case}: the system call's own reservoir, not the transaction's" ); } } From 0c0231e86bf88ab5895e2dc59fc1d74826196909 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:15:20 +0800 Subject: [PATCH 02/83] refactor(limit): price the body's history and the first frame's record where they are read --- crates/mega-evm/src/evm/context.rs | 16 ++++- crates/mega-evm/src/evm/execution.rs | 65 ++++++++++++------- crates/mega-evm/src/evm/validation.rs | 2 +- crates/mega-evm/src/limit/limit.rs | 43 +----------- .../mega-evm/tests/satin/pool_validation.rs | 2 +- 5 files changed, 58 insertions(+), 70 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 7dd04b1b6..c6afae930 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -18,7 +18,7 @@ use revm::{ use crate::{ constants, evm::{ - history::transaction_body_bytes, + history::{history_gas, transaction_body_bytes}, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, limit::{Accounts, Counted}, @@ -412,6 +412,20 @@ impl MegaContext { self.prices_history } + /// The history gas of the running (or last) transaction's body: the bytes it carries and the + /// write records its inclusion makes, which are known before it runs, at the cost per history + /// byte; nothing for a transaction that pays no history ([`prices_history`]). Its gas pays it + /// before the first frame, reservoir first, as intrinsic gas. A body whose bytes have no price + /// costs `u64::MAX`, which no gas limit covers. + /// + /// [`prices_history`]: Self::prices_history + pub fn intrinsic_history_gas(&self) -> u64 { + if !self.prices_history() { + return 0; + } + history_gas(self.additional_limit.body()).unwrap_or(u64::MAX) + } + /// Prepares the common execution layer for a new transaction, which is a system-address /// transaction or not as `system_transaction` says. The handler calls it first thing, once /// validation has read the live system address, so the layer is prepared before anything diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 455bb792a..9eb0d5ccb 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -52,7 +52,7 @@ use revm::{ use crate::{ access::ComputeStop, - charge_write_records_history, history_gas, + charge_write_records_history, limit::{CreatorBefore, StartBefore}, synthetic_frame_result, system::keyless, @@ -255,10 +255,9 @@ where if !evm.ctx_ref().prices_history() { return Ok(gas); } - let bytes = evm.ctx_ref().additional_limit.body(); // A byte count with no price saturates, which no gas limit covers: the transaction is // rejected for not covering its own intrinsic gas. - let history = history_gas(bytes).unwrap_or(u64::MAX); + let history = evm.ctx_ref().intrinsic_history_gas(); let gas_limit = evm.ctx_ref().tx().gas_limit(); let initial_gas = gas .initial_regular_gas() @@ -268,7 +267,6 @@ where InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas }.into() ); } - evm.ctx_mut().additional_limit.set_intrinsic_history(history, bytes); Ok(gas) } @@ -293,7 +291,7 @@ where /// the neutral configuration a system call's is not split, as revm's own runner has it. fn tx_gas(&self, evm: &mut Self::Evm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { let mut gas = self.op.tx_gas(evm, init_and_floor_gas); - let history = evm.ctx_ref().additional_limit.intrinsic_history_gas(); + let history = evm.ctx_ref().intrinsic_history_gas(); if history != 0 { let spilled = gas.state_gas_spilled(); let charged = gas.record_history_cost(history); @@ -309,7 +307,8 @@ where } /// revm's first frame, on the transaction's pool, carrying as its start charge the history - /// charged before execution for the write record it makes; with a read of the block + /// charged before execution for the write record it makes, priced again here on the journal + /// as pre-execution left it ([`first_frame_record_charge`]); with a read of the block /// beneficiary's account marked for gas detention when the transaction's recipient delegates /// to the beneficiary: revm resolves that delegate through the journal, where the Host does /// not see it. @@ -324,6 +323,9 @@ where evm: &mut Self::Evm, gas: &mut GasTracker, ) -> Result, Self::Error> { + // Priced before revm's runtime gas phase loads the recipient: on the journal the charge + // was made on. + let charge = StartCharge::new(first_frame_record_charge(evm.ctx_ref()), PoolAmounts::ZERO); gas.set_pools_remaining(evm.ctx_ref().additional_limit.first_frame_pools()); let Some(mut frame) = self.op.first_frame_input(evm, gas)? else { // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge @@ -337,10 +339,6 @@ where evm.ctx_mut().additional_limit.take_back_authorities(); return Ok(None); }; - let charge = StartCharge::new( - evm.ctx_ref().additional_limit.first_frame_charge(), - PoolAmounts::ZERO, - ); match &mut frame.frame_input { FrameInput::Call(inputs) => inputs.charged_start = charge, FrameInput::Create(inputs) => inputs.set_charged_start(charge), @@ -1557,12 +1555,12 @@ fn applied_authorities( /// its first frame, so the account it creates is one it had not changed. /// /// The authorities' records are the transaction's own and outlive a first frame that fails; the -/// first frame's record does not, so what it cost is kept for that frame to carry as its start -/// charge, which its failure gives back. A first frame revm refuses to start on its sender's -/// account makes no record, and gets the charge back as any frame that kept nothing does: among -/// the transactions that pay history, that is a creation from an account whose nonce cannot be -/// bumped, which only a caller that turned the nonce check off can run, and which revm answers -/// with a success and no address. +/// first frame's record does not, so that frame carries what it cost as its start charge, which +/// its failure gives back ([`first_frame_record_charge`]). A first frame revm refuses to start on +/// its sender's account makes no record, and gets the charge back as any frame that kept nothing +/// does: among the transactions that pay history, that is a creation from an account whose nonce +/// cannot be bumped, which only a caller that turned the nonce check off can run, and which revm +/// answers with a success and no address. /// `false` when the transaction cannot pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( ctx: &mut MegaContext, @@ -1572,22 +1570,38 @@ fn charge_records_made_outside_a_frame( if !ctx.prices_history() { return true; } + charge_write_records_history(gas, first_frame_records(ctx), applied_authorities).is_some() +} + +/// The write records the transaction's own frame makes, as the journal's state stands before the +/// first frame: the recipient's, when the value changes an account the transaction has not +/// changed, or the account a creation creates ([`charge_records_made_outside_a_frame`]). +fn first_frame_records( + ctx: &MegaContext, +) -> u64 { let tx = ctx.tx(); - let first_frame = match tx.kind() { + match tx.kind() { TxKind::Create => 1, TxKind::Call(to) => { let predicted = ctx.accounts().transfer_records(tx.caller(), to, tx.value()).transfer; debug_assert_eq!(predicted.taken, 0, "the sender's value returns no account"); predicted.added } - }; - let Some((first_frame, _)) = - charge_write_records_history(gas, first_frame, applied_authorities) - else { - return false; - }; - ctx.additional_limit.set_first_frame_charge(first_frame); - true + } +} + +/// The history gas charged before execution for the write record the transaction's own frame +/// makes, which the frame carries as its start charge: nothing for a transaction that pays no +/// history. Priced on the journal as pre-execution left it, which is the state the charge was +/// made on: nothing between the charge and the first frame's input changes it. +fn first_frame_record_charge( + ctx: &MegaContext, +) -> u64 { + if !ctx.prices_history() { + return 0; + } + // Pre-execution charged this price, so it has one. + write_record_history_gas(first_frame_records(ctx)).unwrap_or_default() } #[cfg(test)] @@ -1888,6 +1902,7 @@ mod tests { fn test_a_reused_handler_reports_each_executions_own_reservoir() { use crate::{ constants::TX_GAS_LIMIT_CAP, + history_gas, test_utils::{op_transaction, zero_fee_l1_block_info}, MegaTransaction, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; diff --git a/crates/mega-evm/src/evm/validation.rs b/crates/mega-evm/src/evm/validation.rs index 855f77da0..43574a6d3 100644 --- a/crates/mega-evm/src/evm/validation.rs +++ b/crates/mega-evm/src/evm/validation.rs @@ -147,7 +147,7 @@ pub fn validate_transaction_stateless( Ok(IntrinsicGas { regular: gas.initial_regular_gas(), state: gas.initial_state_gas_final(), - history: evm.ctx().additional_limit.intrinsic_history_gas(), + history: evm.ctx().intrinsic_history_gas(), floor: gas.floor_gas(), }) } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index e1ebff2a6..16be7be88 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -108,15 +108,6 @@ pub struct AdditionalLimit { kept: Kept, /// One per start revm decided whose result has not returned, the latest last. decided: Vec, - /// The history gas of the transaction's body, part of - /// [`history_gas_spent`](Self::history_gas_spent). - intrinsic_history_gas: u64, - /// The bytes of the body that [`intrinsic_history_gas`](Self::intrinsic_history_gas) paid - /// for, part of [`history_bytes`](Self::history_bytes). - intrinsic_history_bytes: u64, - /// The history gas charged before the first frame for the write record that frame makes, - /// which the frame carries as its start charge. - first_frame_charge: u64, /// The history gas the settled transaction spent. history_gas_spent: u64, /// The history bytes the settled transaction appended. @@ -285,9 +276,6 @@ impl AdditionalLimit { self.pre_frame_stop = None; self.kept = Kept::default(); self.decided.clear(); - self.intrinsic_history_gas = 0; - self.intrinsic_history_bytes = 0; - self.first_frame_charge = 0; self.history_gas_spent = 0; self.history_bytes = 0; self.reservoir_remaining = 0; @@ -766,35 +754,6 @@ impl AdditionalLimit { self.exempt } - /* What the transaction pays before its first frame */ - - /// The history gas of the transaction's body: the bytes the transaction carries and the write - /// records its inclusion makes, which are known before it runs. The transaction's gas pays it - /// before the first frame, reservoir first, as intrinsic gas. - pub const fn intrinsic_history_gas(&self) -> u64 { - self.intrinsic_history_gas - } - - /// Records the history gas the transaction's body costs, and the `bytes` of the body it pays - /// for. - pub(crate) const fn set_intrinsic_history(&mut self, gas: u64, bytes: u64) { - self.intrinsic_history_gas = gas; - self.intrinsic_history_bytes = bytes; - } - - /// Records the history gas charged before execution for the write record the transaction's own - /// frame makes: the recipient of its value, or the account it creates. The frame carries it as - /// its start charge, which its failure gives back. - pub(crate) const fn set_first_frame_charge(&mut self, gas: u64) { - self.first_frame_charge = gas; - } - - /// The history gas charged before execution for the write record the transaction's own frame - /// makes. - pub(crate) const fn first_frame_charge(&self) -> u64 { - self.first_frame_charge - } - /* What the settled transaction reports */ /// The history gas the last settled transaction spent. @@ -829,7 +788,7 @@ impl AdditionalLimit { pub(crate) fn settle_history(&mut self, priced: bool, spent: u64) { self.history_gas_spent = spent; self.history_bytes = if priced { - self.intrinsic_history_bytes + self.body .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) .saturating_add(positive(self.kept.net(LimitKind::DataSize) as i128)) .saturating_sub(TRANSFER_LOG_SIZE.saturating_mul(self.kept.transfer_logs)) diff --git a/crates/mega-evm/tests/satin/pool_validation.rs b/crates/mega-evm/tests/satin/pool_validation.rs index 9158a408e..9707dca23 100644 --- a/crates/mega-evm/tests/satin/pool_validation.rs +++ b/crates/mega-evm/tests/satin/pool_validation.rs @@ -213,7 +213,7 @@ fn evm(tx: MegaTransaction, system_address: Option
) -> Verdict { } result => Verdict::Admitted { floor: result.gas().floor_gas(), - history: evm.ctx().additional_limit().intrinsic_history_gas(), + history: evm.ctx().intrinsic_history_gas(), }, }, } From 14ca3e3a25b7ca21d626e85e6c49e568b15515b5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:18:31 +0800 Subject: [PATCH 03/83] refactor(evm): read the protocol's own work off the layer's one exemption --- crates/mega-evm/src/access/detention.rs | 78 ++++++++++++------------ crates/mega-evm/src/evm/context.rs | 80 +++++++++++++++++-------- crates/mega-evm/src/evm/execution.rs | 2 +- 3 files changed, 94 insertions(+), 66 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index e8b8723fd..b69f32049 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -188,13 +188,10 @@ pub struct Detention { /// Whether the wrapper of an opcode that reads volatile data runs it: the Host refuses and /// marks a load only then. reading: bool, - /// Whether the transaction's reads are held to a cap. A system-originated transaction's are - /// not, and neither are a transaction's whose caps are both unlimited. - detains: bool, - /// The cap a read of the block environment or of the beneficiary's account sets. - block_env_cap: u64, - /// The cap a read of the Oracle's storage sets. - oracle_cap: u64, + /// The cap a read of the block environment or of the beneficiary's account sets, if any. + block_env_cap: Option, + /// The cap a read of the Oracle's storage sets, if any. + oracle_cap: Option, /// Whether the running frame's volatile reads are refused. refusing: bool, /// The depth of the shallowest frame that switched volatile-data access off, if one did. @@ -219,16 +216,15 @@ pub struct Detention { impl Detention { /// Clears the state for a new transaction, keeping its allocation. /// - /// `detains` is whether the transaction's reads may be held to a cap at all; - /// `block_env_cap` and `oracle_cap` are the caps its reads set, `u64::MAX` for none. A - /// transaction whose caps are both unlimited is not detained: nothing it reads can cap it. - pub(crate) fn reset(&mut self, detains: bool, block_env_cap: u64, oracle_cap: u64) { + /// `block_env_cap` and `oracle_cap` are the caps the transaction's reads set, `u64::MAX` for + /// none. A transaction whose caps are both unlimited is not detained: nothing it reads can cap + /// it. The protocol's own work is begun so, whatever the limits say. + pub(crate) fn reset(&mut self, block_env_cap: u64, oracle_cap: u64) { self.observed.set(VolatileDataAccess::empty()); self.refused.set(VolatileDataAccess::empty()); self.reading = false; - self.detains = detains && (block_env_cap != u64::MAX || oracle_cap != u64::MAX); - self.block_env_cap = block_env_cap; - self.oracle_cap = oracle_cap; + self.block_env_cap = (block_env_cap != u64::MAX).then_some(block_env_cap); + self.oracle_cap = (oracle_cap != u64::MAX).then_some(oracle_cap); self.refusing = false; self.answer_disables_from = None; #[cfg(any(test, feature = "test-utils"))] @@ -269,9 +265,12 @@ impl Detention { self.limit } - /// Whether the transaction's reads are held to a cap. + /// Whether the transaction's reads are held to a cap: one of its caps is not unlimited. The + /// protocol's own work is begun with both unlimited, and so is a detention no transaction + /// reset yet. + #[inline] pub const fn detains(&self) -> bool { - self.detains + self.block_env_cap.is_some() || self.oracle_cap.is_some() } /* The Host */ @@ -292,7 +291,7 @@ impl Detention { /// commits the read once the opcode completed. A load outside a wrapper marks nothing. #[inline] pub(crate) fn observe(&self, access: VolatileDataAccess) { - if self.detains && self.reading { + if self.detains() && self.reading { self.observed.set(self.observed.get() | access); } } @@ -376,7 +375,7 @@ impl Detention { /// recipient that is the block beneficiary, an EIP-7702 authority that is, or a recipient that /// delegates to it. No compute has been spent, so the limit is the read's cap. pub(crate) fn mark_before_execution(&mut self, access: VolatileDataAccess) { - if !self.detains { + if !self.detains() { return; } self.accessed |= access; @@ -412,7 +411,7 @@ impl Detention { #[inline] pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize) { self.refusing = self.disabled_from.is_some_and(|from| depth >= from); - if !self.detains { + if !self.detains() { debug_assert!(self.limit.is_none(), "a limit on a transaction detention does not hold"); return; } @@ -425,7 +424,7 @@ impl Detention { /// until the child returns. #[inline] pub(crate) fn on_frame_suspend(&mut self, gas: &Gas, depth: usize, stipend: u64) { - if self.detains { + if self.detains() { self.figures.on_frame_suspend(gas, depth, stipend); } } @@ -436,7 +435,7 @@ impl Detention { /// ([`commit_reads`](Self::commit_reads)). A transaction detention does not hold records /// nothing, as the Host observes nothing for it. pub(crate) fn read_by_frame(&mut self, access: VolatileDataAccess, gas: &mut Gas) { - if self.detains { + if self.detains() { self.commit_reads(access, gas, 0); } } @@ -466,7 +465,7 @@ impl Detention { if self.disabled_from.is_some_and(|from| from >= depth) { self.disabled_from = None; } - if !self.detains { + if !self.detains() { return None; } self.figures.on_frame_end(depth); @@ -541,7 +540,7 @@ impl Detention { depth: usize, gas_limit: u64, ) -> Option { - if !self.detains { + if !self.detains() { return None; } if self.limit.is_none() && result.gas.withheld_crossing().is_none() { @@ -720,10 +719,10 @@ impl Detention { fn cap_of(&self, access: VolatileDataAccess) -> u64 { let mut cap = u64::MAX; if access.has_block_env_access() || access.has_beneficiary_balance_access() { - cap = cap.min(self.block_env_cap); + cap = cap.min(self.block_env_cap.unwrap_or(u64::MAX)); } if access.has_oracle_access() { - cap = cap.min(self.oracle_cap); + cap = cap.min(self.oracle_cap.unwrap_or(u64::MAX)); } cap } @@ -792,7 +791,7 @@ mod tests { fn detaining() -> Detention { let mut detention = Detention::default(); - detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + detention.reset(BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); detention } @@ -800,7 +799,7 @@ mod tests { #[test] fn test_the_cap_of_a_read_is_its_kinds_lowest() { let mut detention = Detention::default(); - detention.reset(true, 7, 5); + detention.reset(7, 5); assert_eq!(detention.cap_of(VolatileDataAccess::TIMESTAMP), 7); assert_eq!(detention.cap_of(VolatileDataAccess::SLOT_NUM), 7); assert_eq!(detention.cap_of(VolatileDataAccess::BENEFICIARY_BALANCE), 7); @@ -997,7 +996,7 @@ mod tests { fn test_a_first_read_below_frames_counts_what_they_computed() { const CAP: u64 = 1_000; let mut detention = Detention::default(); - detention.reset(true, CAP, CAP); + detention.reset(CAP, CAP); let mut caller = gas(1_000_000, 0); detention.on_frame_run(&mut caller, 0); assert!(caller.record_regular_cost(2_000)); @@ -1064,7 +1063,7 @@ mod tests { detention.on_frame_run(&mut child, 1); assert_eq!(detention.figures.suspended, 7_000); - detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + detention.reset(BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); let mut caller = gas(1_000_000, 0); detention.on_frame_run(&mut caller, 0); assert!(caller.record_regular_cost(3_000)); @@ -1271,7 +1270,8 @@ mod tests { } /// A frame's own read is committed as an opcode's is: the limit is its compute at the read - /// plus the cap. A transaction detention does not hold records nothing. + /// plus the cap. A transaction detention does not hold — the protocol's own work, begun with + /// both caps unlimited — records nothing. #[test] fn test_a_frames_own_read_sets_the_limit_from_its_compute() { let mut detention = detaining(); @@ -1284,7 +1284,7 @@ mod tests { assert_eq!(call.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); let mut free = Detention::default(); - free.reset(false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + free.reset(u64::MAX, u64::MAX); free.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call); assert_eq!((free.compute_limit(), free.accessed()), (None, VolatileDataAccess::empty())); } @@ -1428,16 +1428,16 @@ mod tests { } } - /// A transaction that is not detained records nothing and caps nothing: a system-originated - /// one, and one whose caps are both unlimited. One unlimited cap leaves its kind uncapped. + /// A transaction that is not detained records nothing and caps nothing: one whose caps are + /// both unlimited, as a system-originated one is begun, and a detention no transaction reset + /// yet. One unlimited cap leaves its kind uncapped. #[test] fn test_an_exempt_or_unlimited_transaction_is_not_detained() { - for (detains, block_env_cap, oracle_cap) in [ - (false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS), - (true, u64::MAX, u64::MAX), - ] { + for reset in [true, false] { let mut detention = Detention::default(); - detention.reset(detains, block_env_cap, oracle_cap); + if reset { + detention.reset(u64::MAX, u64::MAX); + } assert!(!detention.detains()); let mut frame = gas(100_000_000, 0); detention.on_frame_run(&mut frame, 0); @@ -1449,7 +1449,7 @@ mod tests { } let mut detention = Detention::default(); - detention.reset(true, u64::MAX, 5); + detention.reset(u64::MAX, 5); assert!(detention.detains()); let mut frame = gas(100_000_000, 0); detention.on_frame_run(&mut frame, 0); diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index c6afae930..de9b39c0a 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -66,14 +66,9 @@ pub struct MegaContext, @@ -114,9 +109,7 @@ impl MegaContext { bucket_multipliers: BucketMultipliers::default(), bucket_record: BucketRecord::default(), oracle_reads: OracleReadRecord::default(), - system_originated: false, system_call: false, - prices_history: true, keyless_creation: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, @@ -176,7 +169,6 @@ impl MegaContext { self.inner = self.inner.with_cfg(op_cfg(&cfg)); self.cfg = cfg; self.neutral = true; - self.prices_history = false; self } @@ -390,9 +382,12 @@ impl MegaContext { /// A transaction's answer is decided when it is validated: a system-address transaction is /// recognised by the live system address its validation reads out of the `SequencerRegistry` /// in the state the EVM runs on, so every EVM answers as block execution does, however it was - /// built. + /// built. It is the common execution layer's exemption, which is decided once with it + /// ([`AdditionalLimit::is_exempt`]): the protocol's own work is held to no per-transaction + /// limit, is not detained, pays no history gas and prices at the minimum bucket, all for the + /// one reason. pub const fn is_system_originated(&self) -> bool { - self.system_originated + self.additional_limit.is_exempt() } /// Whether the running (or last) transaction pays history gas for the bytes it appends. @@ -408,8 +403,14 @@ impl MegaContext { /// SALT bucket like any other transaction — it is exempt from history alone, because the /// bytes it appends were paid for on L1. A system transaction is both: it prices at the /// minimum bucket *and* pays no history. - pub const fn prices_history(&self) -> bool { - self.prices_history + /// + /// The neutral configuration prices no history at all. + pub fn prices_history(&self) -> bool { + #[cfg(any(test, feature = "test-utils"))] + if self.neutral { + return false; + } + !(self.is_system_originated() || self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE) } /// The history gas of the running (or last) transaction's body: the bytes it carries and the @@ -504,20 +505,20 @@ impl MegaContext { // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call's // creation unsettled. self.keyless_creation = None; - self.system_originated = system_originated; - let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || system_originated; - self.set_history_exempt(exempt); // The body is data size whether or not the transaction pays history for it. A deposit, // a system transaction and a system call are exempt from the charge, not from the count. let body = transaction_body_bytes(self.tx()); self.additional_limit.begin_transaction(system_originated, transfer_logs, body); - // The protocol's own transactions are not detained: they maintain the volatile data. + self.install_history_schedule(); + // The protocol's own transactions are not detained: they maintain the volatile data. Their + // reads set no cap. let limits = self.additional_limit.limits(); - self.detention.reset( - !system_originated, - limits.block_env_access_compute_gas_limit, - limits.oracle_access_compute_gas_limit, - ); + let (block_env_cap, oracle_cap) = if system_originated { + (u64::MAX, u64::MAX) + } else { + (limits.block_env_access_compute_gas_limit, limits.oracle_access_compute_gas_limit) + }; + self.detention.reset(block_env_cap, oracle_cap); self.mark_beneficiary_transaction(); } @@ -554,8 +555,8 @@ impl MegaContext { } } - /// Records whether the running transaction is exempt from history gas, and installs the - /// schedule that matches. + /// Installs the schedule that matches whether the running transaction pays history gas + /// ([`prices_history`](Self::prices_history)). /// /// The engine's own history charges read [`prices_history`](Self::prices_history); the one /// charge revm makes itself reads the schedule, so an exempt transaction runs the schedule @@ -564,13 +565,12 @@ impl MegaContext { /// once for the process, so the swap is a shared clone. /// /// The neutral configuration prices no history and keeps its own schedule. - fn set_history_exempt(&mut self, exempt: bool) { + fn install_history_schedule(&mut self) { #[cfg(any(test, feature = "test-utils"))] if self.neutral { - self.prices_history = false; return; } - self.prices_history = !exempt; + let exempt = !self.prices_history(); let id = GasId::code_deposit_history_gas(); let params = if exempt { satin_gas_params_history_exempt() } else { satin_gas_params() }; if self.inner.cfg.gas_params.get(id) != params.get(id) { @@ -732,6 +732,7 @@ impl ContextSetters for MegaContext MegaContext { let mut ctx = MegaContext::new(db, MegaSpecId::SATIN); - ctx.detention.reset(true, cap, cap); + ctx.detention.reset(cap, cap); ctx.detention.mark_before_execution(VolatileDataAccess::TIMESTAMP); ctx } From 73c6d6ab8d84c2a10138405a5173270c70f73b62 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:21:11 +0800 Subject: [PATCH 04/83] refactor(limit): read the EIP-7708 switch off the journal's own configuration --- crates/mega-evm/src/evm/context.rs | 37 ++++++---------- crates/mega-evm/src/limit/limit.rs | 19 +++----- crates/mega-evm/src/limit/mod.rs | 2 + crates/mega-evm/src/limit/record.rs | 69 ++++++++++++++++------------- 4 files changed, 60 insertions(+), 67 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index de9b39c0a..766792139 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -24,9 +24,8 @@ use crate::{ limit::{Accounts, Counted}, system::{self, keyless}, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, - Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, - LimitUsage, MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, - VolatileDataAccess, + Detention, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, LimitUsage, + MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, VolatileDataAccess, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -297,7 +296,7 @@ impl MegaContext { /// The accounts the running transaction holds, read for the write records a write makes. pub(crate) fn accounts(&self) -> Accounts<'_> { - Accounts::of(self.journal_ref(), self.additional_limit.counts_transfer_logs()) + Accounts::of(self.journal_ref()) } /// Gas detention for the running (or last) transaction: the volatile data it read and the @@ -499,7 +498,6 @@ impl MegaContext { /// it uses is counted all the same. A user's deposit is not system-originated and is held /// to every one of them. fn prepare(&mut self, system_originated: bool) { - let transfer_logs = emits_transfer_logs(&self.inner.cfg); self.bucket_multipliers.reset(); self.oracle_reads.clear(); // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call's @@ -508,7 +506,7 @@ impl MegaContext { // The body is data size whether or not the transaction pays history for it. A deposit, // a system transaction and a system call are exempt from the charge, not from the count. let body = transaction_body_bytes(self.tx()); - self.additional_limit.begin_transaction(system_originated, transfer_logs, body); + self.additional_limit.begin_transaction(system_originated, body); self.install_history_schedule(); // The protocol's own transactions are not detained: they maintain the volatile data. Their // reads set no cap. @@ -632,16 +630,6 @@ pub fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { cfg } -/// Whether a value movement journals an EIP-7708 transfer log under `cfg`: from Amsterdam on, or -/// with the switch on, unless EIP-7708 is disabled. It is the rule revm's journal applies, read -/// off the configuration the journal was synced with, so the data size counts a transfer log -/// exactly where revm emits one. -fn emits_transfer_logs(cfg: &CfgEnv) -> bool { - let spec = EthSpecId::from(cfg.spec); - (spec.is_enabled_in(EthSpecId::AMSTERDAM) || cfg.enable_amsterdam_eip7708()) && - !cfg.is_eip7708_disabled() -} - /// The op-revm view of `cfg`: the same fields, keyed by the Optimism spec. fn op_cfg(cfg: &CfgEnv) -> CfgEnv { cfg.clone().with_spec_and_gas_params(cfg.spec.into_op_spec(), cfg.gas_params.clone()) @@ -731,7 +719,7 @@ impl ContextSetters for MegaContext| { @@ -1178,8 +1166,11 @@ mod tests { MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(cfg); ctx.set_tx(call_from(Address::repeat_byte(0x11))); ctx.on_new_tx(false); - assert_eq!(ctx.additional_limit.counts_transfer_logs(), emits_transfer_logs(ctx.cfg())); - emits_transfer_logs(ctx.cfg()) + let counts = emits_transfer_logs(ctx.journal_ref()); + let (from, to) = (Address::repeat_byte(0x11), Address::repeat_byte(0x22)); + ctx.journal_mut().eip7708_transfer_log(from, to, U256::from(1)); + assert_eq!(counts, !ctx.journal_ref().logs.is_empty(), "revm's journal emits it"); + counts }; let with = |enabled: bool, disabled: bool| { let mut cfg = osaka_cfg(); @@ -1199,7 +1190,7 @@ mod tests { }); ctx.set_tx(call_from(Address::repeat_byte(0x11))); ctx.on_new_tx(false); - assert!(ctx.additional_limit.counts_transfer_logs()); + assert!(emits_transfer_logs(ctx.journal_ref())); } /// The protocol's own work is held to no per-transaction limit, pays no history and is not diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 16be7be88..f96861ac0 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -80,8 +80,6 @@ pub struct AdditionalLimit { /// Whether the transaction is exempt from every per-transaction limit, sticky for the /// transaction. See [`is_exempt`](Self::is_exempt). exempt: bool, - /// Whether a value movement journals an EIP-7708 transfer log. - transfer_logs: bool, /// The crossing the result of the frame returning next was made of, noted where the stop /// became that result ([`note_frame_stop`](Self::note_frame_stop)) and taken when the frame /// returns. @@ -258,14 +256,12 @@ impl AdditionalLimit { } /// Clears the state for a new transaction, keeping allocations and the limits, and begins it: - /// exempt from every limit or not, its value movements journaling transfer logs or not, its - /// body weighing `body` bytes. + /// exempt from every limit or not, its body weighing `body` bytes. /// /// The exemption is decided before the body is counted: the protocol's own work is exempt /// whatever it carries. - pub(crate) fn begin_transaction(&mut self, exempt: bool, transfer_logs: bool, body: u64) { + pub(crate) fn begin_transaction(&mut self, exempt: bool, body: u64) { self.exempt = exempt; - self.transfer_logs = transfer_logs; self.frame_stop = None; self.limit_exceeded = None; self.body = body; @@ -329,11 +325,6 @@ impl AdditionalLimit { self.body } - /// Whether the transaction's value movements journal EIP-7708 transfer logs. - pub(crate) const fn counts_transfer_logs(&self) -> bool { - self.transfer_logs - } - /// Whether the transaction's body, with one write record for each of its `authorizations`, /// fits its data-size limit: what validation holds a transaction to. /// @@ -848,7 +839,7 @@ mod tests { #[test] fn test_the_exemption_answers_every_crossing_and_lasts_one_transaction() { let mut limit = AdditionalLimit::default(); - limit.begin_transaction(true, false, 0); + limit.begin_transaction(true, 0); assert!(limit.is_exempt()); for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { for frame_local in [false, true] { @@ -856,7 +847,7 @@ mod tests { assert_eq!(verdict, LimitCheck::WithinLimit, "{kind:?}, frame-local {frame_local}"); } } - limit.begin_transaction(false, false, 0); + limit.begin_transaction(false, 0); assert!(!limit.is_exempt()); assert_eq!( limit.crossed(LimitKind::ComputeGas, 0, 1, false), @@ -880,7 +871,7 @@ mod tests { let limits = EvmTxRuntimeLimits::no_limits() .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE); let mut limit = AdditionalLimit::new(limits); - limit.begin_transaction(false, false, crate::TX_BODY_SIZE); + limit.begin_transaction(false, crate::TX_BODY_SIZE); limit.count_authorities(2, 0); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index f30e5c408..ca0cd4adc 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -185,6 +185,8 @@ mod record; pub use limit::AdditionalLimit; pub(crate) use limit::Counted; +#[cfg(test)] +pub(crate) use record::emits_transfer_logs; #[cfg(any(test, feature = "test-utils"))] pub(crate) use record::is_transfer_log; pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes, StartBefore}; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index d4d3e855a..6db62420f 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -42,6 +42,7 @@ use revm::{ }, primitives::{ eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}, + hardfork::SpecId, Address, Log, StorageKey, KECCAK_EMPTY, U256, }, state::{Account, AccountInfo, EvmState, TransactionId}, @@ -157,7 +158,8 @@ pub(crate) struct Accounts<'a> { /// The logs the journal holds, which a failed frame's revert takes back with its entries. logs: &'a [Log], transaction_id: TransactionId, - /// Whether a value movement journals an EIP-7708 transfer log. + /// Whether a value movement journals an EIP-7708 transfer log, as the journal's own + /// configuration says ([`emits_transfer_logs`]). transfer_logs: bool, } @@ -212,16 +214,24 @@ pub(crate) fn is_transfer_log(log: &Log) -> bool { log.address == ETH_TRANSFER_LOG_ADDRESS && log.topics().first() == Some(Ð_TRANSFER_LOG_TOPIC) } +/// Whether a value movement journals an EIP-7708 transfer log on `journal`: from Amsterdam on, or +/// with the switch on, unless EIP-7708 is disabled. It is the rule revm's journal emits one by, +/// read off the journal's own copy of the configuration, so the data size counts a transfer log +/// exactly where revm emits one. +pub(crate) fn emits_transfer_logs(journal: &Journal) -> bool { + (journal.cfg.spec.is_enabled_in(SpecId::AMSTERDAM) || journal.amsterdam_eip7708_enabled()) && + !journal.cfg.eip7708_disabled +} + impl<'a> Accounts<'a> { - /// The accounts `journal` holds, in a transaction whose value movements journal transfer logs - /// or not (`transfer_logs`). - pub(crate) fn of(journal: &'a Journal, transfer_logs: bool) -> Self { + /// The accounts `journal` holds. + pub(crate) fn of(journal: &'a Journal) -> Self { Self { state: &journal.state, entries: &journal.journal, logs: &journal.logs, transaction_id: journal.transaction_id, - transfer_logs, + transfer_logs: emits_transfer_logs(journal), } } @@ -659,7 +669,7 @@ mod tests { let journal = journal(); let slot = slot(original, present, new); let write = CompletedWrite::Sstore { address: OTHER, key: U256::ZERO, result: &slot }; - Accounts::of(&journal, false).write_counted(&write).0 + Accounts::of(&journal).write_counted(&write).0 } /// A slot counts once, on its first change in the transaction; writing it back to its @@ -709,7 +719,7 @@ mod tests { #[test] fn test_log_bytes() { let journal = journal(); - let accounts = Accounts::of(&journal, false); + let accounts = Accounts::of(&journal); let counted = |topics, data_len| { let (counted, history, _) = accounts.write_counted(&CompletedWrite::Log { address: OTHER, topics, data_len }); @@ -733,13 +743,14 @@ mod tests { let records_bytes = |records| WRITE_RECORD_SIZE * records; let mut fresh = journal(); + fresh.set_amsterdam_eip7708_enabled(true); fresh.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); - let (counted, history, _) = - Accounts::of(&fresh, true).write_counted(&destruction(OTHER, 5)); + let (counted, history, _) = Accounts::of(&fresh).write_counted(&destruction(OTHER, 5)); assert_eq!(counted, Counted::records(2, 0, true)); assert_eq!(history, HistoryBytes { appended: records_bytes(2), taken: 0 }); + fresh.set_amsterdam_eip7708_enabled(false); assert_eq!( - Accounts::of(&fresh, false).write_counted(&destruction(OTHER, 5)).0, + Accounts::of(&fresh).write_counted(&destruction(OTHER, 5)).0, Counted::records(2, 0, false), "no transfer logs, no log" ); @@ -750,8 +761,7 @@ mod tests { drained.transfer(DESTRUCTED, SENDER, U256::from(1)).unwrap(); drained.transfer(OTHER, SENDER, U256::from(4)).unwrap(); drained.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); - let (counted, history, _) = - Accounts::of(&drained, false).write_counted(&destruction(OTHER, 4)); + let (counted, history, _) = Accounts::of(&drained).write_counted(&destruction(OTHER, 4)); assert_eq!(counted, Counted::records(0, 1, false)); assert_eq!(history, HistoryBytes { appended: 0, taken: records_bytes(1) }); @@ -759,7 +769,7 @@ mod tests { funded.transfer(SENDER, DESTRUCTED, U256::from(2)).unwrap(); funded.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); assert_eq!( - Accounts::of(&funded, false).write_counted(&destruction(OTHER, 7)).0, + Accounts::of(&funded).write_counted(&destruction(OTHER, 7)).0, Counted::records(1, 0, false), "the beneficiary's record alone" ); @@ -767,7 +777,7 @@ mod tests { // A pre-existing account destructing to itself keeps its balance: nothing changes. let to_itself = journal(); assert_eq!( - Accounts::of(&to_itself, true).write_counted(&destruction(DESTRUCTED, 5)).0, + Accounts::of(&to_itself).write_counted(&destruction(DESTRUCTED, 5)).0, Counted::NONE ); } @@ -790,7 +800,7 @@ mod tests { result: &result, }; let journal = journal(); - let counted = Accounts::of(&journal, true).write_counted(&write).0; + let counted = Accounts::of(&journal).write_counted(&write).0; (counted.added.get(STATE_GROWTH_POOL), counted.taken.get(STATE_GROWTH_POOL)) }; let fresh = address!("00000000000000000000000000000000000000f5"); @@ -834,9 +844,9 @@ mod tests { let fresh = address!("00000000000000000000000000000000000c4ea7"); let slots = [(3, 1), (1, 7), (2, 1), (2, 0)]; let mut made = created(MemoryDatabase::default(), fresh, 0, &slots, &[0x60, 0x00, 0xff]); - assert!(!Accounts::of(&made, true).is_destroyed(fresh)); + assert!(!Accounts::of(&made).is_destroyed(fresh)); made.selfdestruct(fresh, OTHER, false).unwrap(); - let accounts = Accounts::of(&made, true); + let accounts = Accounts::of(&made); let parts = DestroyedParts { leaf: true, code: 3, @@ -890,7 +900,7 @@ mod tests { let mut made = created(db, fresh, 0, &[(1, 1)], &[]); made.selfdestruct(fresh, OTHER, false).unwrap(); assert_eq!( - Accounts::of(&made, true).destroyed_parts(fresh, false), + Accounts::of(&made).destroyed_parts(fresh, false), Some(DestroyedParts { leaf: false, code: 0, @@ -917,14 +927,14 @@ mod tests { loaded.create_account_checkpoint(SENDER, fresh, U256::ZERO, spec).unwrap(); loaded.sstore(fresh, U256::from(8), U256::from(6)).unwrap(); loaded.selfdestruct(fresh, OTHER, false).unwrap(); - let parts = Accounts::of(&loaded, true).destroyed_parts(fresh, false).unwrap(); + let parts = Accounts::of(&loaded).destroyed_parts(fresh, false).unwrap(); assert_eq!(parts, DestroyedParts { leaf: false, code: 0, slots: vec![], deleted: 1 }); assert_eq!(parts.counted(), Counted::records(1, 0, false)); // An account the transaction did not create is an ordinary deletion. let mut older = journal(); older.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); - let accounts = Accounts::of(&older, true); + let accounts = Accounts::of(&older); assert_eq!(accounts.destroyed_parts(DESTRUCTED, false), None); assert!(!accounts.is_destroyed(DESTRUCTED)); } @@ -951,7 +961,7 @@ mod tests { #[test] fn test_a_starts_priced_records_follow_the_net_change() { let mut journal = journal(); - let accounts = Accounts::of(&journal, true); + let accounts = Accounts::of(&journal); let both = accounts.transfer_records(OTHER, DESTRUCTED, U256::from(1)); assert_eq!(both.transfer, RecordDelta { added: 2, taken: 0 }); assert_eq!(accounts.transfer_records(OTHER, OTHER, U256::from(1)), StartRecords::NONE); @@ -960,11 +970,11 @@ mod tests { // OTHER sent 1 to DESTRUCTED: sending it back returns both. journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); - let back = Accounts::of(&journal, true).transfer_records(DESTRUCTED, OTHER, U256::from(1)); + let back = Accounts::of(&journal).transfer_records(DESTRUCTED, OTHER, U256::from(1)); assert_eq!(back.transfer, RecordDelta { added: 0, taken: 2 }); let created = address!("00000000000000000000000000000000000c4ea7"); - let accounts = Accounts::of(&journal, true); + let accounts = Accounts::of(&journal); let creation = accounts.creation_records(SENDER, Some(created), U256::from(1)); assert_eq!( creation, @@ -994,11 +1004,10 @@ mod tests { journal.set_amsterdam_eip7708_enabled(true); journal.load_account(empty).unwrap(); let before = |journal: &Journal, first, second| { - Accounts::of(journal, true).start_before(first, Some(second), journal.logs.len()) - }; - let made = |journal: &Journal, before| { - Accounts::of(journal, true).start_made(&before) + Accounts::of(journal).start_before(first, Some(second), journal.logs.len()) }; + let made = + |journal: &Journal, before| Accounts::of(journal).start_made(&before); let funding = before(&journal, OTHER, empty); assert_eq!(made(&journal, funding), (RecordDelta::NONE, Counted::NONE), "nothing moved"); @@ -1043,7 +1052,7 @@ mod tests { let mut journal = journal(); journal.load_account(empty).unwrap(); journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); - let accounts = Accounts::of(&journal, true); + let accounts = Accounts::of(&journal); let [sender, changed, empty_before] = [SENDER, DESTRUCTED, empty].map(|address| accounts.creator_before(address)); for before in [sender, changed, empty_before] { @@ -1053,7 +1062,7 @@ mod tests { for address in [SENDER, DESTRUCTED, empty] { assert!(journal.load_account_mut(address).unwrap().data.bump_nonce()); } - let accounts = Accounts::of(&journal, true); + let accounts = Accounts::of(&journal); let record = Counted::records(1, 0, false); for (before, counted) in [(sender, record), (changed, Counted::NONE), (empty_before, record.with_growth(1, 0))] @@ -1067,7 +1076,7 @@ mod tests { for address in [SENDER, DESTRUCTED] { journal.load_account_mut(address).unwrap().data.set_nonce(0); } - let accounts = Accounts::of(&journal, true); + let accounts = Accounts::of(&journal); assert_eq!(accounts.creator_counted(&sender), Counted::NONE); assert_eq!(accounts.creator_counted(&changed), Counted::NONE); } From 6d8a3404193fc3400d8fef47d8ea2e0c767682f0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:26:28 +0800 Subject: [PATCH 05/83] refactor(system): carry the access switch-off on the interceptor's answer instead of staging it --- AGENTS.md | 2 +- crates/mega-evm/src/access/detention.rs | 75 ----------------------- crates/mega-evm/src/evm/execution.rs | 81 ++++++++++++++++++++++--- crates/mega-evm/src/system/control.rs | 25 +++----- crates/mega-evm/src/system/intercept.rs | 27 ++++++++- crates/mega-evm/src/system/mod.rs | 2 +- 6 files changed, 108 insertions(+), 104 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 44acd821e..0f69c6161 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -408,7 +408,7 @@ Detention caps how much a transaction may still compute once it read such data ( A frame-starting opcode whose caller cannot pay the start's records starts no frame: the frame-start hook hands the forward back before the opcode fails, and records what the frame has then, since the failed charge recorded the gas left after the forward was taken. An inspector's refused charge leaves its record as an opcode's does, as revm leaves it: a later halt that records nothing of its own is read off it. - **Refused reads.** - `MegaAccessControl` switches volatile-data access off for the frame that calls `disableVolatileDataAccess()` and every frame below it, once the answer is settled and only when gas detention did not turn it into the stop (`Detention::disable_access_on_answer`), until that frame calls `enableVolatileDataAccess()` or returns; a frame below cannot switch back on what a frame above switched off (`DisabledByParent()`), and `isVolatileDataAccessDisabled()` answers for the caller. + `MegaAccessControl` switches volatile-data access off for the frame that calls `disableVolatileDataAccess()` and every frame below it, once the answer is settled and only when gas detention did not turn it into the stop (the interceptor's answer carries the switch-off, `system::Answer`, which the settlement applies), until that frame calls `enableVolatileDataAccess()` or returns; a frame below cannot switch back on what a frame above switched off (`DisabledByParent()`), and `isVolatileDataAccessDisabled()` answers for the caller. The caller is the frame one level above the one the call would start (frame depth = the frame-init depth less one, where the legacy engine used the caller's journal depth, the same frame); a transaction that calls the contract directly has no frame above it, so disabling changes nothing, enabling succeeds and the query answers `false`. The state is `Detention`'s, and `MegaContext::with_volatile_access_disabled_from` is the test helper that sets it without a call. The Host then refuses the load and the wrapper reverts the frame with `VolatileDataAccessDisabled(accessType)` on the gas it had after the opcode's static gas, so a refused read pays its static gas and nothing else. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index b69f32049..a98d701d0 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -199,10 +199,6 @@ pub struct Detention { /// The depth the switch starts off from in every transaction: test tooling. #[cfg(any(test, feature = "test-utils"))] disabled_from_at_start: Option, - /// The depth of the frame an answer being settled switches volatile-data access off for, if - /// it does: applied once the answer settles without a crossing. See - /// [`disable_access_on_answer`](Self::disable_access_on_answer). - answer_disables_from: Option, /// What the transaction read. accessed: VolatileDataAccess, /// The most compute the transaction may reach, once it read volatile data. @@ -226,7 +222,6 @@ impl Detention { self.block_env_cap = (block_env_cap != u64::MAX).then_some(block_env_cap); self.oracle_cap = (oracle_cap != u64::MAX).then_some(oracle_cap); self.refusing = false; - self.answer_disables_from = None; #[cfg(any(test, feature = "test-utils"))] { self.disabled_from = self.disabled_from_at_start; @@ -511,34 +506,12 @@ impl Detention { /// /// Until a read sets a limit an answer can only burn: nothing it spends can cross a limit, and /// only the engine marks an answer as a crossing, which it does only under a limit. - /// - /// A switch-off the answer staged - /// ([`disable_access_on_answer`](Self::disable_access_on_answer)) is applied when the - /// answer did not cross, and dropped when it did. #[inline] pub(crate) fn on_answer( &mut self, result: &mut InterpreterResult, depth: usize, gas_limit: u64, - ) -> Option { - let stop = self.classify_answer(result, depth, gas_limit); - if let Some(caller) = self.answer_disables_from.take() { - if stop.is_none() { - self.disable_access(caller); - } - } - stop - } - - /// [`on_answer`](Self::on_answer)'s verdict on `result`, the answer to the frame at `depth` - /// whose gas limit was `gas_limit`. - #[inline] - fn classify_answer( - &mut self, - result: &mut InterpreterResult, - depth: usize, - gas_limit: u64, ) -> Option { if !self.detains() { return None; @@ -658,15 +631,6 @@ impl Detention { self.disabled_from = Some(self.disabled_from.map_or(depth, |from| from.min(depth))); } - /// Switches volatile-data access off for the frame at `depth`, as - /// [`disable_access`](Self::disable_access) does, once the answer being built for a call it - /// made settles without crossing the compute limit ([`on_answer`](Self::on_answer)): an answer - /// that becomes the stop did not succeed, and the frame that catches it resumes with the - /// switch as it was. - pub(crate) const fn disable_access_on_answer(&mut self, depth: usize) { - self.answer_disables_from = Some(depth); - } - /// Switches volatile-data access back on for the frame at `depth`, and reports whether it /// could: a frame cannot switch back on what a frame above it switched off. pub fn enable_access(&mut self, depth: usize) -> bool { @@ -1157,45 +1121,6 @@ mod tests { } } - /// A switch-off an answer stages applies once the answer settles without a crossing: an - /// answer gas detention turns into the stop leaves access as it was, one that settles within - /// the limit switches it off, and so does one of a transaction that is not detained. A staged - /// switch goes with the answer it was staged for, whatever that answer settled as. - #[test] - fn test_an_answer_switches_access_off_only_when_it_does_not_cross() { - let mut detention = detaining(); - let mut caller = gas(100_000_000, 0); - detention.on_frame_run(&mut caller, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); - assert!(caller.record_withheld_first_cost(90_000_000)); - detention.on_frame_suspend(&caller, 0, 0); - let answer = |spent: u64| { - let mut gas = gas(90_000_000, 0); - assert!(gas.record_regular_cost(spent)); - InterpreterResult::new(InstructionResult::Return, Bytes::new(), gas) - }; - - detention.disable_access_on_answer(0); - let mut beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1); - assert!(detention.on_answer(&mut beyond, 1, 90_000_000).is_some(), "the answer crossed"); - assert!(!detention.is_access_disabled(0), "and access stays on"); - - let mut unstaged = answer(0); - assert_eq!(detention.on_answer(&mut unstaged, 1, 90_000_000), None); - assert!(!detention.is_access_disabled(0), "the crossing answer took its switch with it"); - - detention.disable_access_on_answer(0); - let mut within = answer(0); - assert_eq!(detention.on_answer(&mut within, 1, 90_000_000), None); - assert!(detention.is_access_disabled(0), "an answer within the limit switches it off"); - - let mut free = Detention::default(); - assert!(!free.detains()); - free.disable_access_on_answer(0); - assert_eq!(free.on_answer(&mut answer(0), 1, 90_000_000), None); - assert!(free.is_access_disabled(0), "a transaction that is not detained switches it off"); - } - /// A precompile run on the allowance gets the rest of the forward back: a success keeps it /// unspent, a halt burns the forward as it would without the read, and an out-of-gas on the /// allowance is a crossing, which the answer's settlement stops with the whole forward back. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index a32e3871c..9bf3f7b03 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -55,7 +55,7 @@ use crate::{ charge_write_records_history, limit::{CreatorBefore, StartBefore}, synthetic_frame_result, - system::keyless, + system::{keyless, Answer}, write_record_history_gas, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; @@ -593,13 +593,13 @@ impl EvmTr for MegaEvm( ctx: &mut MegaContext, depth: usize, gas_limit: u64, answer: &mut FrameResult, -) { +) -> bool { let answer = answer.interpreter_result_mut(); - if let Some(stop) = ctx.detention.on_answer(answer, depth, gas_limit) { - stop_at_the_compute_limit(ctx, answer, stop); + let Some(stop) = ctx.detention.on_answer(answer, depth, gas_limit) else { return false }; + stop_at_the_compute_limit(ctx, answer, stop); + true +} + +/// Settles `answer`, a `keylessDeploy` call's or an interceptor's to the frame at `depth` whose +/// gas limit was `gas_limit` ([`settle_answer`]), then applies what follows it, unless it became +/// gas detention's stop: the switch-off of volatile-data access `disableVolatileDataAccess()` +/// answers its caller with. An answer that became the stop did not succeed, and the frame that +/// catches it resumes with the switch as it was. +fn settle_intercepted( + ctx: &mut MegaContext, + depth: usize, + gas_limit: u64, + answer: Answer, +) -> FrameResult { + let Answer { mut result, disables_access_from } = answer; + let stopped = settle_answer(ctx, depth, gas_limit, &mut result); + if let Some(from) = disables_access_from.filter(|_| !stopped) { + ctx.detention.disable_access(from); } + result } /// How gas detention holds the precompile call a frame start makes ([`hold_precompile`]). @@ -1136,7 +1156,7 @@ impl MegaEvm { /// An answer is a [`synthetic_frame_result`](crate::synthetic_frame_result), so it settles /// like a frame revm ran. What each contract answers is in the `system` module. #[inline] - fn intercept(&mut self, frame_init: &FrameInit) -> Option { + fn intercept(&mut self, frame_init: &FrameInit) -> Option { let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; if !matches!(inputs.scheme, CallScheme::Call | CallScheme::StaticCall) { return None; @@ -1869,6 +1889,49 @@ mod tests { } } + /// A switch-off an interceptor's answer carries applies once the answer settles without a + /// crossing: an answer gas detention turns into the stop leaves access as it was, one that + /// settles within the limit switches it off, and so does one of a transaction that is not + /// detained. The switch goes with the answer that carried it, whatever that answer settled as. + #[test] + fn test_an_answer_switches_access_off_only_when_it_does_not_cross() { + use crate::{constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, system::Answer}; + const FORWARD: u64 = 90_000_000; + let answer = |spent: u64, disables_access_from| { + let input = static_call(TARGET, &[], FORWARD).frame_input; + let mut result = + synthetic_frame_result(&input, InstructionResult::Return, Bytes::new()); + assert!(result.gas_mut().record_regular_cost(spent)); + Answer { result, disables_access_from } + }; + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + ctx.detention.reset(BLOCK_ENV_ACCESS_COMPUTE_GAS, BLOCK_ENV_ACCESS_COMPUTE_GAS); + let mut caller = Gas::new_with_regular_gas_and_reservoir(100_000_000, 0); + ctx.detention.on_frame_run(&mut caller, 0); + ctx.detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); + assert!(caller.record_withheld_first_cost(FORWARD)); + ctx.detention.on_frame_suspend(&caller, 0, 0); + + let beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1, Some(0)); + let result = settle_intercepted(&mut ctx, 1, FORWARD, beyond); + assert_eq!(result.instruction_result(), InstructionResult::Revert, "the answer crossed"); + assert!(!ctx.detention.is_access_disabled(0), "and access stays on"); + + settle_intercepted(&mut ctx, 1, FORWARD, answer(0, None)); + assert!( + !ctx.detention.is_access_disabled(0), + "the crossing answer took its switch with it" + ); + + settle_intercepted(&mut ctx, 1, FORWARD, answer(0, Some(0))); + assert!(ctx.detention.is_access_disabled(0), "an answer within the limit switches it off"); + + let mut free = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + assert!(!free.detention.detains()); + settle_intercepted(&mut free, 1, FORWARD, answer(0, Some(0))); + assert!(free.detention.is_access_disabled(0), "a transaction that is not detained"); + } + /// A frame answered with a success that the engine then rewrote into the stop, at any depth, /// has what its start wrote taken back to where its start began. An answer revm made a failure /// took its writes back itself, and one the engine did not rewrite keeps them. diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs index 23d017262..a9023b534 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -8,14 +8,11 @@ use alloy_evm::Database; use alloy_primitives::{address, Address, Bytes}; use alloy_sol_types::{SolCall, SolError}; -use revm::{ - handler::FrameResult, - interpreter::{CallInputs, InstructionResult}, -}; +use revm::interpreter::{CallInputs, InstructionResult}; use crate::{ synthetic_call_result, - system::intercept::{peek_selector, reject_non_zero_transfer}, + system::intercept::{peek_selector, reject_non_zero_transfer, Answer}, ExternalEnvTypes, MegaContext, }; @@ -63,9 +60,9 @@ pub const SLOT_NUM_ACCESS_TYPE: u8 = 12; /// for the frame that made the call — the caller, one level above the frame the call would start: /// /// - `disableVolatileDataAccess()` switches volatile-data access off for the caller and every frame -/// below it, once its answer settles without crossing gas detention's compute limit: an answer -/// that becomes the stop leaves the switch as it was. A switch already off from a frame above -/// stays as it is. +/// below it, once its answer settles without crossing gas detention's compute limit: the answer +/// carries the switch-off ([`Answer::disables_access_from`]), and an answer that becomes the stop +/// leaves the switch as it was. A switch already off from a frame above stays as it is. /// - `enableVolatileDataAccess()` switches it back on, and reverts with `DisabledByParent()` when a /// frame above the caller switched it off: a frame cannot lift a restriction its caller placed. /// Switching on what is not off succeeds and changes nothing. @@ -87,7 +84,7 @@ pub(crate) fn intercept( ctx: &mut MegaContext, inputs: &CallInputs, depth: usize, -) -> Option { +) -> Option { let selector = peek_selector(&inputs.input, ctx)?; // Selector-only admission: the four bytes decide, whatever follows them. let method = if selector == IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR { @@ -100,16 +97,14 @@ pub(crate) fn intercept( return None; }; if let Some(rejected) = reject_non_zero_transfer(inputs) { - return Some(rejected); + return Some(Answer::new(rejected)); } let caller = depth.checked_sub(1); let detention = &mut ctx.detention; let (result, output) = match method { Method::Disable => { - if let Some(caller) = caller { - detention.disable_access_on_answer(caller); - } - (InstructionResult::Return, Bytes::new()) + let result = synthetic_call_result(inputs, InstructionResult::Return, Bytes::new()); + return Some(Answer { result, disables_access_from: caller }); } Method::Enable => { if caller.is_none_or(|caller| detention.enable_access(caller)) { @@ -125,7 +120,7 @@ pub(crate) fn intercept( (InstructionResult::Return, Bytes::from(output)) } }; - Some(synthetic_call_result(inputs, result, output)) + Some(Answer::new(synthetic_call_result(inputs, result, output))) } /// The three methods `MegaAccessControl` intercepts. diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 1dd165d30..5798dcdb0 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -35,7 +35,8 @@ //! //! An answer is a [`synthetic_call_result`]: the forwarded gas untouched, the caller's reservoir //! carried, and the calling opcode's upfront state-gas flags, so the caller settles it exactly -//! like a frame revm ran. +//! like a frame revm ran. It carries what follows it once it settled ([`Answer`]), so the +//! settlement knows no method. use alloy_evm::Database; use alloy_primitives::{Address, Bytes}; @@ -70,6 +71,23 @@ const SYSTEM_CONTRACT_PREFIX: [u8; 19] = { prefix }; +/// An interceptor's answer to a call, and what follows it once the answer settled. +#[derive(Debug)] +pub(crate) struct Answer { + /// The answer: a [`synthetic_call_result`]. + pub(crate) result: FrameResult, + /// The depth of the frame the answer switches volatile-data access off for, once it settled + /// without becoming gas detention's stop: `disableVolatileDataAccess()`'s, for its caller. + pub(crate) disables_access_from: Option, +} + +impl Answer { + /// `result`, which nothing follows. + pub(crate) const fn new(result: FrameResult) -> Self { + Self { result, disables_access_from: None } + } +} + /// A system contract whose calls the engine answers or rewrites. /// /// The High-Precision Timestamp wrapper and the `SequencerRegistry` are not here: they have no @@ -125,13 +143,16 @@ pub(crate) fn intercept( inputs: &CallInputs, depth: usize, caller_remaining: u64, -) -> Option { +) -> Option { match intercepted_contract(&inputs.target_address)? { - InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs, depth), + InterceptedContract::Oracle => { + crate::system::oracle::intercept(ctx, inputs, depth).map(Answer::new) + } InterceptedContract::KeylessDeploy => None, InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs, depth), InterceptedContract::LimitControl => { crate::system::limit_control::intercept(ctx, inputs, depth, caller_remaining) + .map(Answer::new) } } } diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index a062c4c1c..13b4723a7 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -36,7 +36,7 @@ pub use sequencer_registry::*; pub use timestamp::*; pub use tx::*; -pub(crate) use intercept::intercept; +pub(crate) use intercept::{intercept, Answer}; pub(crate) use tx::{classify_system_transaction, validate_and_promote}; #[cfg(test)] From ed9932384abdb1508ff2fbd65b4f57c20511a487 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:29:09 +0800 Subject: [PATCH 06/83] refactor(system): price the keyless signer's give-backs again instead of storing them --- .../mega-evm/src/system/keyless/dispatch.rs | 85 +++++++++++-------- crates/mega-evm/src/system/keyless/settle.rs | 14 ++- 2 files changed, 60 insertions(+), 39 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 990875528..c048551f3 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -36,7 +36,8 @@ use crate::{ KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS, }, }, - untouched_call_gas, ExternalEnvTypes, MegaContext, VolatileDataAccess, + untouched_call_gas, write_record_history_gas, ExternalEnvTypes, MegaContext, + VolatileDataAccess, }; /// What a `keylessDeploy` call's creation is settled into the call with, kept on the context while @@ -48,13 +49,10 @@ pub(crate) struct Started { /// The signer, and its nonce before the creation's start bumped it. pub(super) signer: Address, pub(super) signer_nonce: u64, - /// What the call was charged for the signer's account, which the creation's start creates: - /// zero when the signer had one. - pub(super) signer_account_charge: u64, - /// The history the call paid for the signer's nonce record: zero when the transaction had - /// changed the signer's account already — the transaction's sender among them — which makes - /// no record, or when the transaction pays no history. - pub(super) signer_record_charge: u64, + /// Whether the call was charged for the signer's account, which the creation's start creates: + /// not when the signer had one. The charge is priced again where it is given back + /// ([`signer_account`]). + pub(super) signer_account_charged: bool, /// Whether the deposit of empty code at the deploy address was refused, which reverts the /// creation ([`refuses_empty_deposit`](super::settle::refuses_empty_deposit)). pub(super) empty_deposit_refused: bool, @@ -204,15 +202,14 @@ pub(crate) fn start( ); create.set_charged_create_state_gas(deployment.charged_create_state_gas); create.set_charged_state_gas_address(deployment.deploy_address); - let (on_frame, signer_record) = deployment.record_charges.unwrap_or((0, 0)); - create.set_charged_start(StartCharge::new(on_frame, PoolAmounts::ZERO)); + create + .set_charged_start(StartCharge::new(deployment.on_frame_record_charge, PoolAmounts::ZERO)); create.set_pool_shares(shares.pools); ctx.keyless_creation = Some(Started { deploy_address: deployment.deploy_address, signer: deployment.signer, signer_nonce: deployment.signer_nonce, - signer_account_charge: deployment.signer_account_charge, - signer_record_charge: signer_record, + signer_account_charged: deployment.signer_account_charged, empty_deposit_refused: false, }); Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) @@ -222,8 +219,8 @@ pub(crate) fn start( struct Deployment { signer: Address, signer_nonce: u64, - /// What the call was charged for the signer's account, when the signer has none. - signer_account_charge: u64, + /// Whether the call was charged for the signer's account: the signer has none. + signer_account_charged: bool, deploy_address: Address, value: U256, init_code: Bytes, @@ -231,9 +228,10 @@ struct Deployment { gas_limit: u64, /// Whether the call was charged the created account. charged_create_state_gas: bool, - /// What the call paid for the records the creation's start makes: the created account's, and - /// the signer's nonce. `None` when the transaction pays no history. - record_charges: Option<(u64, u64)>, + /// What the call paid for the record the creation's start makes on the creation, the created + /// account's: zero when the transaction pays no history. The signer's nonce record, which the + /// call paid for too, is the call's own ([`signer_record_charge`]). + on_frame_record_charge: u64, } /// Why a call is refused. @@ -360,14 +358,9 @@ fn prepare( // The signer's nonce bump is what creates an empty signer's account: a caller the `CREATE` // opcode starts from exists already. It is charged where the legacy engine charged it, and // the forward checked right after, before the deploy address and the balance are. - let mut signer_account_charge = 0; - if signer_info.is_empty() { - let charge = - StateGasCharge::one(GasId::new_account_state_gas(), StateGasSite::account(signer)); - signer_account_charge = state_gas(ctx, charge)?; - if !gas.record_state_cost(signer_account_charge) { - return Ok(Err(Refusal::OutOfGas)); - } + let signer_account_charged = signer_info.is_empty(); + if signer_account_charged && !gas.record_state_cost(state_gas(ctx, signer_account(signer))?) { + return Ok(Err(Refusal::OutOfGas)); } forward!(); if ctx.journal_mut().load_account(deploy_address)?.data.info.code_hash != KECCAK_EMPTY { @@ -394,18 +387,17 @@ fn prepare( } } let records = ctx.accounts().creation_records(signer, Some(deploy_address), tx.value); - let record_charges = if ctx.prices_history() { - let charged = charge_write_records_history( + let on_frame_record_charge = if ctx.prices_history() { + let Some((on_frame, _)) = charge_write_records_history( gas.tracker_mut(), records.on_frame().added, u64::from(records.creator), - ); - if charged.is_none() { + ) else { return Ok(Err(Refusal::OutOfGas)); - } - charged + }; + on_frame } else { - None + 0 }; // The forward is not the call's own work: it draws the part detention withholds first, as a @@ -417,19 +409,42 @@ fn prepare( Ok(Ok(Deployment { signer, signer_nonce: signer_info.nonce, - signer_account_charge, + signer_account_charged, deploy_address, value: tx.value, init_code: tx.input.clone(), gas_limit, charged_create_state_gas, - record_charges, + on_frame_record_charge, })) } +/// The state gas charge for the account of `signer`, which the creation's start creates when the +/// signer has none: one new account, at the signer's account. The call is charged it before the +/// creation starts, and given it back, priced again at the same site, when the start never +/// created the account; the price is the same, since a bucket's multiplier is read once per +/// transaction. +pub(super) fn signer_account(signer: Address) -> StateGasCharge { + StateGasCharge::one(GasId::new_account_state_gas(), StateGasSite::account(signer)) +} + +/// The history the call paid for the signer's nonce record when the creation's start makes one — +/// the bump changes an account the transaction had not changed — and the transaction pays +/// history: one write record's. It is given back, priced again, when the record goes +/// ([`take_back_bump`](super::settle)). +pub(super) fn signer_record_charge( + ctx: &MegaContext, +) -> u64 { + if !ctx.prices_history() { + return 0; + } + // The call charged this price, so it has one. + write_record_history_gas(1).unwrap_or_default() +} + /// Prices `charge` through the SALT pricing hook. A failed lookup is the error the hook recorded, /// which fails the transaction. -fn state_gas( +pub(super) fn state_gas( ctx: &mut MegaContext, charge: StateGasCharge, ) -> Result> { diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 293af60a9..13186c1f8 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -26,7 +26,7 @@ use crate::{ ExternalEnvTypes, LimitCheck, MegaContext, MegaHaltReason, }; -use super::dispatch::Started; +use super::dispatch::{signer_account, signer_record_charge, state_gas, Started}; /// What a `keylessDeploy` call answers from, once its creation returned into it. #[derive(Debug)] @@ -159,8 +159,8 @@ pub(crate) fn settle( // all the same; one an inspector answered in its place never started, and adds no account. // A signer that had an account was charged nothing, and gets nothing back. let nonce = account_nonce(ctx, started.signer); - if nonce == started.signer_nonce { - gas.refill_reservoir(started.signer_account_charge); + if nonce == started.signer_nonce && started.signer_account_charged { + gas.refill_reservoir(state_gas(ctx, signer_account(started.signer))?); } let bumped = signer.filter(|signer| ctx.accounts().bumped(signer)); // A deployment from nonce 1 keeps no bump of its own: a failure leaves the address @@ -255,6 +255,12 @@ fn holds_code( /// as the transaction loaded it, and stays when the account keeps another write it stands for — /// the value a creation that succeeded moved out of it, or into it. A creation that failed took /// its value transfer back with the rest of its writes. +/// +/// A signer the nonce set back leaves as the transaction loaded it was one the transaction had not +/// changed when the call charged the record: a signer it had changed is its sender or an applied +/// EIP-7702 authority, whose nonce the transaction moved from 0 to 1 before the call, so setting +/// it back to 1 never returns it to what the transaction loaded. So the history given back is the +/// one record's the call paid ([`signer_record_charge`]). fn take_back_bump( ctx: &mut MegaContext, gas: &mut Gas, @@ -262,7 +268,7 @@ fn take_back_bump( ) -> Result<(), ContextError> { ctx.journal_mut().load_account_mut(started.signer)?.data.set_nonce(started.signer_nonce); if !ctx.accounts().is_changed(started.signer) { - gas.refill_history(started.signer_record_charge); + gas.refill_history(signer_record_charge(ctx)); } Ok(()) } From 3b5f614cfff5972d9baa8e6aeb3e121fffd81b7e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:32:10 +0800 Subject: [PATCH 07/83] refactor(evm): reduce the destruction table's pricing switch to the neutral configuration --- crates/mega-evm/src/evm/context.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 766792139..e15140452 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -4,8 +4,8 @@ use delegate::delegate; use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpSpecId}; use revm::{ context::{ - BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Journal, - LocalContext, Transaction, + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Journal, LocalContext, + Transaction, }, context_interface::{ cfg::{gas::GasTracker, GasId}, @@ -474,16 +474,17 @@ impl MegaContext { /// Whether the destruction table prices state gas: a destruction of an account created in the /// transaction gives back the state gas of the parts the transaction made, and from that mark - /// the account keeps no further state gas. So under the spec's configuration, which charges - /// EIP-8037 state gas. The neutral configuration prices as the fixture's fork does, and - /// EIP-8037 gives back no state gas for this destruction; the table's counts are the same - /// under both. - pub(crate) fn destruction_table_prices_state_gas(&self) -> bool { + /// the account keeps no further state gas. The spec's configuration does: it always charges + /// EIP-8037 state gas, which no caller can switch off ([`spec_cfg`]). The neutral configuration + /// prices as the fixture's fork does, and EIP-8037 gives back no state gas for this + /// destruction; the table's counts are the same under both. + #[inline] + pub(crate) const fn destruction_table_prices_state_gas(&self) -> bool { #[cfg(any(test, feature = "test-utils"))] if self.neutral { return false; } - self.inner.cfg.is_amsterdam_eip8037_enabled() + true } /// Prepares the common execution layer for a transaction or a system call that is, or is not, From a7b4673104e4ed3b51b0398b21409c015dcadbd2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:33:52 +0800 Subject: [PATCH 08/83] refactor(evm): read the context by shared reference in the pre-execution record charge --- crates/mega-evm/src/evm/execution.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9bf3f7b03..41a23ed51 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -190,7 +190,7 @@ where eip7702_refund }; let (applied, created) = applied_authorities(evm.ctx_mut(), checkpoint.journal_i); - if !charge_records_made_outside_a_frame(evm.ctx_mut(), gas, applied) { + if !charge_records_made_outside_a_frame(evm.ctx_ref(), gas, applied) { runtime_oog_unwind(evm.ctx(), checkpoint)?; return Ok(None); } @@ -1583,7 +1583,7 @@ fn applied_authorities( /// answers with a success and no address. /// `false` when the transaction cannot pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( - ctx: &mut MegaContext, + ctx: &MegaContext, gas: &mut GasTracker, applied_authorities: u64, ) -> bool { From 1ca589b087edca95db1ebc2383cc444f65b76087 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:33:52 +0800 Subject: [PATCH 09/83] docs(skills): name where an interceptor's access switch-off is applied in the review guide's map --- .claude/skills/satin-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 0795c99af..cb39e8802 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -263,7 +263,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. ### Gas detention -- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, the loads the Host marks or refuses in `src/evm/host.rs`, `hold_precompile`, `settle_answer` and `end_frame` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. +- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, the loads the Host marks or refuses in `src/evm/host.rs`, `hold_precompile`, `settle_answer`, `settle_intercepted` (which applies the switch-off an interceptor's answer carries) and `end_frame` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. - **Read first:** the module doc of `src/access/mod.rs`. - **Check:** - The split into spendable and withheld gas is applied when a read completes, when a frame starts or resumes, and after an `SSTORE`; only regular charges are held to the spendable part, every other reader sees both. From 9e514db8da8025e3b012053a69977ce8535d993c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:51:32 +0800 Subject: [PATCH 10/83] refactor(evm): share the records' history price, name the system answer's settlement and the neutral check --- .claude/skills/satin-review/SKILL.md | 2 +- crates/mega-evm/src/access/detention.rs | 2 +- crates/mega-evm/src/evm/context.rs | 54 ++++++++----- crates/mega-evm/src/evm/execution.rs | 80 ++++++++----------- crates/mega-evm/src/system/intercept.rs | 3 +- .../mega-evm/src/system/keyless/dispatch.rs | 25 ++---- crates/mega-evm/src/system/keyless/settle.rs | 15 ++-- 7 files changed, 88 insertions(+), 93 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index cb39e8802..4d075ae73 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -263,7 +263,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. ### Gas detention -- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, the loads the Host marks or refuses in `src/evm/host.rs`, `hold_precompile`, `settle_answer`, `settle_intercepted` (which applies the switch-off an interceptor's answer carries) and `end_frame` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. +- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, the loads the Host marks or refuses in `src/evm/host.rs`, `hold_precompile`, `settle_answer`, `settle_system_answer` (which applies the switch-off an interceptor's answer carries) and `end_frame` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. - **Read first:** the module doc of `src/access/mod.rs`. - **Check:** - The split into spendable and withheld gas is applied when a read completes, when a frame starts or resumes, and after an `SSTORE`; only regular charges are held to the spendable part, every other reader sees both. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index a98d701d0..5de739335 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -1357,7 +1357,7 @@ mod tests { /// both unlimited, as a system-originated one is begun, and a detention no transaction reset /// yet. One unlimited cap leaves its kind uncapped. #[test] - fn test_an_exempt_or_unlimited_transaction_is_not_detained() { + fn test_an_unlimited_cap_caps_nothing() { for reset in [true, false] { let mut detention = Detention::default(); if reset { diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index e15140452..97fe8b730 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -18,7 +18,7 @@ use revm::{ use crate::{ constants, evm::{ - history::{history_gas, transaction_body_bytes}, + history::{history_gas, transaction_body_bytes, write_record_history_gas}, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, limit::{Accounts, Counted}, @@ -189,6 +189,17 @@ impl MegaContext { self.neutral } + /// Whether the context runs the neutral configuration: never outside the test tooling, which + /// alone can set it. + #[inline] + const fn runs_neutral(&self) -> bool { + #[cfg(any(test, feature = "test-utils"))] + let neutral = self.neutral; + #[cfg(not(any(test, feature = "test-utils")))] + let neutral = false; + neutral + } + /// Replaces the block environment. pub fn with_block(mut self, block: BlockEnv) -> Self { self.inner.block = block; @@ -404,12 +415,14 @@ impl MegaContext { /// minimum bucket *and* pays no history. /// /// The neutral configuration prices no history at all. + /// + /// It is read off the transaction the context holds and the exemption the transaction was + /// prepared with, so a caller that replaces the transaction and asks before running it gets + /// the new transaction's type with the last one's exemption. pub fn prices_history(&self) -> bool { - #[cfg(any(test, feature = "test-utils"))] - if self.neutral { - return false; - } - !(self.is_system_originated() || self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE) + !(self.runs_neutral() || + self.is_system_originated() || + self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE) } /// The history gas of the running (or last) transaction's body: the bytes it carries and the @@ -426,6 +439,18 @@ impl MegaContext { history_gas(self.additional_limit.body()).unwrap_or(u64::MAX) } + /// The history gas the running transaction pays for `records` write records: their price, or + /// nothing for a transaction that pays no history ([`prices_history`]). Read where a charge + /// made earlier is carried or given back, so the records have a price: the charge had one. + /// + /// [`prices_history`]: Self::prices_history + pub(crate) fn records_history_charge(&self, records: u64) -> u64 { + if !self.prices_history() { + return 0; + } + write_record_history_gas(records).unwrap_or_default() + } + /// Prepares the common execution layer for a new transaction, which is a system-address /// transaction or not as `system_transaction` says. The handler calls it first thing, once /// validation has read the live system address, so the layer is prepared before anything @@ -464,12 +489,8 @@ impl MegaContext { /// configuration: which pool pays the protocol's own state writes, and what `GAS` reads inside /// a system contract, are part of executing the chain. No transaction's is, and under the /// neutral configuration no system call's either, as revm's own runner has it. - pub(crate) fn splits_system_call_gas(&self) -> bool { - #[cfg(any(test, feature = "test-utils"))] - if self.neutral { - return false; - } - self.system_call + pub(crate) const fn splits_system_call_gas(&self) -> bool { + !self.runs_neutral() && self.system_call } /// Whether the destruction table prices state gas: a destruction of an account created in the @@ -480,11 +501,7 @@ impl MegaContext { /// destruction; the table's counts are the same under both. #[inline] pub(crate) const fn destruction_table_prices_state_gas(&self) -> bool { - #[cfg(any(test, feature = "test-utils"))] - if self.neutral { - return false; - } - true + !self.runs_neutral() } /// Prepares the common execution layer for a transaction or a system call that is, or is not, @@ -565,8 +582,7 @@ impl MegaContext { /// /// The neutral configuration prices no history and keeps its own schedule. fn install_history_schedule(&mut self) { - #[cfg(any(test, feature = "test-utils"))] - if self.neutral { + if self.runs_neutral() { return; } let exempt = !self.prices_history(); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 41a23ed51..2eb92ccda 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -308,7 +308,7 @@ where /// revm's first frame, on the transaction's pool, carrying as its start charge the history /// charged before execution for the write record it makes, priced again here on the journal - /// as pre-execution left it ([`first_frame_record_charge`]); with a read of the block + /// as pre-execution left it (`first_frame_records`); with a read of the block /// beneficiary's account marked for gas detention when the transaction's recipient delegates /// to the beneficiary: revm resolves that delegate through the journal, where the Host does /// not see it. @@ -323,9 +323,12 @@ where evm: &mut Self::Evm, gas: &mut GasTracker, ) -> Result, Self::Error> { - // Priced before revm's runtime gas phase loads the recipient: on the journal the charge - // was made on. - let charge = StartCharge::new(first_frame_record_charge(evm.ctx_ref()), PoolAmounts::ZERO); + // Priced before revm's runtime gas phase loads the recipient, on the journal as + // pre-execution left it, which is the state the charge was made on: nothing between the + // charge and the first frame's input changes it. + let records = first_frame_records(evm.ctx_ref()); + let charge = + StartCharge::new(evm.ctx_ref().records_history_charge(records), PoolAmounts::ZERO); gas.set_pools_remaining(evm.ctx_ref().additional_limit.first_frame_pools()); let Some(mut frame) = self.op.first_frame_input(evm, gas)? else { // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge @@ -433,9 +436,10 @@ where result: FrameResult, result_gas: revm::context::result::ResultGas, ) -> Result, Self::Error> { - let system_call = evm.ctx_ref().is_system_call().then(|| result.gas().reservoir()); + let system_call_reservoir = + evm.ctx_ref().is_system_call().then(|| result.gas().reservoir()); let result = self.op.execution_result(evm, result, result_gas)?; - if let Some(reservoir) = system_call { + if let Some(reservoir) = system_call_reservoir { evm.ctx_mut().additional_limit.set_reservoir_remaining(reservoir); } Ok(result) @@ -599,7 +603,7 @@ impl EvmTr for MegaEvm( ctx: &mut MegaContext, depth: usize, gas_limit: u64, answer: &mut FrameResult, -) -> bool { +) { let answer = answer.interpreter_result_mut(); - let Some(stop) = ctx.detention.on_answer(answer, depth, gas_limit) else { return false }; - stop_at_the_compute_limit(ctx, answer, stop); - true + if let Some(stop) = ctx.detention.on_answer(answer, depth, gas_limit) { + stop_at_the_compute_limit(ctx, answer, stop); + } } -/// Settles `answer`, a `keylessDeploy` call's or an interceptor's to the frame at `depth` whose -/// gas limit was `gas_limit` ([`settle_answer`]), then applies what follows it, unless it became -/// gas detention's stop: the switch-off of volatile-data access `disableVolatileDataAccess()` -/// answers its caller with. An answer that became the stop did not succeed, and the frame that -/// catches it resumes with the switch as it was. -fn settle_intercepted( +/// Settles `answer`, a system contract's to the frame at `depth` whose gas limit was `gas_limit` +/// — an interceptor's, or a `keylessDeploy` call's carrying value — ([`settle_answer`]), then +/// applies what follows it once it settled as a success: the switch-off of volatile-data access +/// `disableVolatileDataAccess()` answers its caller with. The answer that carries it succeeds +/// unless gas detention turned it into the stop, which did not succeed, and the frame that catches +/// the stop resumes with the switch as it was. +fn settle_system_answer( ctx: &mut MegaContext, depth: usize, gas_limit: u64, answer: Answer, ) -> FrameResult { let Answer { mut result, disables_access_from } = answer; - let stopped = settle_answer(ctx, depth, gas_limit, &mut result); - if let Some(from) = disables_access_from.filter(|_| !stopped) { + settle_answer(ctx, depth, gas_limit, &mut result); + if let Some(from) = disables_access_from.filter(|_| result.instruction_result().is_ok()) { ctx.detention.disable_access(from); } result @@ -1576,11 +1580,11 @@ fn applied_authorities( /// /// The authorities' records are the transaction's own and outlive a first frame that fails; the /// first frame's record does not, so that frame carries what it cost as its start charge, which -/// its failure gives back ([`first_frame_record_charge`]). A first frame revm refuses to start on -/// its sender's account makes no record, and gets the charge back as any frame that kept nothing -/// does: among the transactions that pay history, that is a creation from an account whose nonce -/// cannot be bumped, which only a caller that turned the nonce check off can run, and which revm -/// answers with a success and no address. +/// its failure gives back (priced again where the frame's input is built). A first frame revm +/// refuses to start on its sender's account makes no record, and gets the charge back as any frame +/// that kept nothing does: among the transactions that pay history, that is a creation from an +/// account whose nonce cannot be bumped, which only a caller that turned the nonce check off can +/// run, and which revm answers with a success and no address. /// `false` when the transaction cannot pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( ctx: &MegaContext, @@ -1610,20 +1614,6 @@ fn first_frame_records( } } -/// The history gas charged before execution for the write record the transaction's own frame -/// makes, which the frame carries as its start charge: nothing for a transaction that pays no -/// history. Priced on the journal as pre-execution left it, which is the state the charge was -/// made on: nothing between the charge and the first frame's input changes it. -fn first_frame_record_charge( - ctx: &MegaContext, -) -> u64 { - if !ctx.prices_history() { - return 0; - } - // Pre-execution charged this price, so it has one. - write_record_history_gas(first_frame_records(ctx)).unwrap_or_default() -} - #[cfg(test)] mod tests { use super::*; @@ -1889,7 +1879,7 @@ mod tests { } } - /// A switch-off an interceptor's answer carries applies once the answer settles without a + /// A switch-off a system contract's answer carries applies once the answer settles without a /// crossing: an answer gas detention turns into the stop leaves access as it was, one that /// settles within the limit switches it off, and so does one of a transaction that is not /// detained. The switch goes with the answer that carried it, whatever that answer settled as. @@ -1913,22 +1903,22 @@ mod tests { ctx.detention.on_frame_suspend(&caller, 0, 0); let beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1, Some(0)); - let result = settle_intercepted(&mut ctx, 1, FORWARD, beyond); + let result = settle_system_answer(&mut ctx, 1, FORWARD, beyond); assert_eq!(result.instruction_result(), InstructionResult::Revert, "the answer crossed"); assert!(!ctx.detention.is_access_disabled(0), "and access stays on"); - settle_intercepted(&mut ctx, 1, FORWARD, answer(0, None)); + settle_system_answer(&mut ctx, 1, FORWARD, answer(0, None)); assert!( !ctx.detention.is_access_disabled(0), "the crossing answer took its switch with it" ); - settle_intercepted(&mut ctx, 1, FORWARD, answer(0, Some(0))); + settle_system_answer(&mut ctx, 1, FORWARD, answer(0, Some(0))); assert!(ctx.detention.is_access_disabled(0), "an answer within the limit switches it off"); let mut free = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); assert!(!free.detention.detains()); - settle_intercepted(&mut free, 1, FORWARD, answer(0, Some(0))); + settle_system_answer(&mut free, 1, FORWARD, answer(0, Some(0))); assert!(free.detention.is_access_disabled(0), "a transaction that is not detained"); } diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 5798dcdb0..46b1bb96a 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -71,7 +71,8 @@ const SYSTEM_CONTRACT_PREFIX: [u8; 19] = { prefix }; -/// An interceptor's answer to a call, and what follows it once the answer settled. +/// A system contract's answer to a call — an interceptor's, or a `keylessDeploy` call's carrying +/// value — and what follows it once the answer settled. #[derive(Debug)] pub(crate) struct Answer { /// The answer: a [`synthetic_call_result`]. diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index c048551f3..aa6d914e2 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -36,8 +36,7 @@ use crate::{ KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS, }, }, - untouched_call_gas, write_record_history_gas, ExternalEnvTypes, MegaContext, - VolatileDataAccess, + untouched_call_gas, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; /// What a `keylessDeploy` call's creation is settled into the call with, kept on the context while @@ -230,7 +229,8 @@ struct Deployment { charged_create_state_gas: bool, /// What the call paid for the record the creation's start makes on the creation, the created /// account's: zero when the transaction pays no history. The signer's nonce record, which the - /// call paid for too, is the call's own ([`signer_record_charge`]). + /// call paid for too, is the call's own, and its history is given back at the settlement when + /// the record goes. on_frame_record_charge: u64, } @@ -422,26 +422,13 @@ fn prepare( /// The state gas charge for the account of `signer`, which the creation's start creates when the /// signer has none: one new account, at the signer's account. The call is charged it before the /// creation starts, and given it back, priced again at the same site, when the start never -/// created the account; the price is the same, since a bucket's multiplier is read once per -/// transaction. +/// created the account. The price is the same: a bucket's multiplier is read once per +/// transaction, and the signer is no account the transaction created, whose charges a destruction +/// would price at nothing. pub(super) fn signer_account(signer: Address) -> StateGasCharge { StateGasCharge::one(GasId::new_account_state_gas(), StateGasSite::account(signer)) } -/// The history the call paid for the signer's nonce record when the creation's start makes one — -/// the bump changes an account the transaction had not changed — and the transaction pays -/// history: one write record's. It is given back, priced again, when the record goes -/// ([`take_back_bump`](super::settle)). -pub(super) fn signer_record_charge( - ctx: &MegaContext, -) -> u64 { - if !ctx.prices_history() { - return 0; - } - // The call charged this price, so it has one. - write_record_history_gas(1).unwrap_or_default() -} - /// Prices `charge` through the SALT pricing hook. A failed lookup is the error the hook recorded, /// which fails the transaction. pub(super) fn state_gas( diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 13186c1f8..983274197 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -26,7 +26,7 @@ use crate::{ ExternalEnvTypes, LimitCheck, MegaContext, MegaHaltReason, }; -use super::dispatch::{signer_account, signer_record_charge, state_gas, Started}; +use super::dispatch::{signer_account, state_gas, Started}; /// What a `keylessDeploy` call answers from, once its creation returned into it. #[derive(Debug)] @@ -256,11 +256,12 @@ fn holds_code( /// the value a creation that succeeded moved out of it, or into it. A creation that failed took /// its value transfer back with the rest of its writes. /// -/// A signer the nonce set back leaves as the transaction loaded it was one the transaction had not -/// changed when the call charged the record: a signer it had changed is its sender or an applied -/// EIP-7702 authority, whose nonce the transaction moved from 0 to 1 before the call, so setting -/// it back to 1 never returns it to what the transaction loaded. So the history given back is the -/// one record's the call paid ([`signer_record_charge`]). +/// The history given back is one record's, which the call paid when the transaction pays history. +/// A signer the transaction had already changed when the call charged it paid nothing for the +/// record, and the nonce set back never leaves such a signer as the transaction loaded it: it is +/// the transaction's sender or an applied EIP-7702 authority, whose nonce the transaction moved +/// from 0 to 1 before the call, and setting it back to 1 leaves it changed. So when the record +/// goes, the call had paid for it. fn take_back_bump( ctx: &mut MegaContext, gas: &mut Gas, @@ -268,7 +269,7 @@ fn take_back_bump( ) -> Result<(), ContextError> { ctx.journal_mut().load_account_mut(started.signer)?.data.set_nonce(started.signer_nonce); if !ctx.accounts().is_changed(started.signer) { - gas.refill_history(signer_record_charge(ctx)); + gas.refill_history(ctx.records_history_charge(1)); } Ok(()) } From 0903f86ebfb6826fdce5ebce51c68075d4acef34 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 14:51:32 +0800 Subject: [PATCH 11/83] test(system): give the signer's account back at a crowded bucket's price when an inspector answers the creation --- .../tests/system/keyless/inspector.rs | 53 ++++++++++++++++++- crates/mega-evm/tests/system/keyless/mod.rs | 22 ++++++-- 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index 6e2a3a0ed..cbf0fee57 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -13,7 +13,7 @@ use revm::{ interpreter::{ interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, CreateInputs, CreateOutcome, CreateScheme, Gas, InstructionResult, Interpreter, - InterpreterResult, + InterpreterResult, InterpreterTypes, }, primitives::KECCAK_EMPTY, Database, Inspector, @@ -220,6 +220,57 @@ fn test_a_creation_an_inspector_answers_keeps_what_its_start_was_charged() { } } +/// Answers every creation with a revert on the gas it was given, carrying back the created +/// account's charge: a tool's rewrite, for any context. +struct AnswersCreations; + +impl Inspector for AnswersCreations { + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + Some(CreateOutcome { + result: InterpreterResult::new( + InstructionResult::Revert, + Bytes::new(), + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()), + ), + address: None, + charged_create_state_gas: inputs.charged_create_state_gas(), + charged_state_gas_address: inputs.charged_state_gas_address(), + charged_start: Default::default(), + }) + } +} + +/// The signer's account a creation's start never created, because an inspector answered the +/// creation, comes back at the price it was charged, however crowded the signer's bucket: priced +/// again at the signer's account, whose bucket the transaction reads once. With the created +/// account's charge, which the answer carries back, the deployment keeps no state gas. +#[test] +fn test_an_answered_creation_gives_the_signers_account_back_at_its_price() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if crate::common::state_is_free() { + return; + } + let deployment = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + for m in [1, 2, 8] { + let envs = crowded(TestExternalEnvs::new(), deployment.signer, m); + let outcome = MegaEvm::new(salt_context(system_db(), envs.clone())) + .with_inspector(AnswersCreations) + .execute_transaction(salt_tx(&deployment, gas_limit)) + .expect("valid"); + let case = format!("m = {m}, gas limit {gas_limit}"); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(nonce(&outcome, deployment.signer), 0, "{case}: no creation started"); + assert_eq!(outcome.gas.state, 0, "{case}: both charges came back"); + assert_eq!( + envs.bucket_queries(bucket(deployment.signer)), + 1, + "{case}: one read priced the charge and its give-back", + ); + } + } +} + /// A transaction whose body crosses the data-size limit is rejected at validation on the inspected /// path too: the inspector sees no frame, neither the call nor a creation. #[test] diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs index 1c369b637..f553bd3ec 100644 --- a/crates/mega-evm/tests/system/keyless/mod.rs +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -294,23 +294,37 @@ pub(crate) fn intrinsic(data: &[u8]) -> u64 { 12_000 + 3_000 + calldata + crate::common::body_history(data.len() as u64) } -/// A Satin context over `db` reading `envs`. +/// `deployment` run at `gas_limit` on a Satin context over `db` reading `envs`. pub(crate) fn salt_run( db: MemoryDatabase, envs: TestExternalEnvs, deployment: &Deployment, gas_limit: u64, ) -> MegaTransactionOutcome { - let context = MegaContext::<_, TestExternalEnvs>::new_with_external_envs( + MegaEvm::new(salt_context(db, envs)) + .execute_transaction(salt_tx(deployment, gas_limit)) + .expect("the transaction is valid") +} + +/// A Satin context over `db` reading `envs`. +pub(crate) fn salt_context( + db: MemoryDatabase, + envs: TestExternalEnvs, +) -> MegaContext> { + MegaContext::<_, TestExternalEnvs>::new_with_external_envs( db, MegaSpecId::SATIN, ExternalEnvs { salt_env: envs.clone(), oracle_env: envs }, ) .with_block(block()) - .with_chain(mega_evm::test_utils::zero_fee_l1_block_info()); + .with_chain(mega_evm::test_utils::zero_fee_l1_block_info()) +} + +/// The transaction that calls `KeylessDeploy` with `deployment` at `gas_limit`. +pub(crate) fn salt_tx(deployment: &Deployment, gas_limit: u64) -> mega_evm::MegaTransaction { let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); tx.0.base.gas_limit = gas_limit; - MegaEvm::new(context).execute_transaction(tx).expect("the transaction is valid") + tx } /// The bucket `account`'s own state lives in. From b08c3b803cd55e033a2a9dd81379073a03db22bd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:28:48 +0800 Subject: [PATCH 12/83] fix(evm): report a system call's own reservoir when it runs through the handler unprepared The reported reservoir is forgotten where every execution builds its gas, and the result reports its own unless post-execution already reported it, so a system call run through revm's public handler entry points without the crate's preparation no longer reports the reservoir of the execution before it. --- crates/mega-evm/src/evm/execution.rs | 116 ++++++++++++++++++--------- crates/mega-evm/src/limit/limit.rs | 26 ++++-- 2 files changed, 97 insertions(+), 45 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 2eb92ccda..ada2f9d52 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -289,7 +289,13 @@ where /// is no delegator. Every transaction's gas is split by the execution cap alone, the /// system-address transaction's included, which is a deposit and not a system call; and under /// the neutral configuration a system call's is not split, as revm's own runner has it. + /// + /// Every execution builds its gas here, a transaction or a system call, prepared by the crate + /// or run straight through revm's public entry points, so the reservoir the last one reported + /// is forgotten here: the running one reports its own once it settles + /// ([`execution_result`](Handler::execution_result)). fn tx_gas(&self, evm: &mut Self::Evm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { + evm.ctx_mut().additional_limit.forget_reservoir_remaining(); let mut gas = self.op.tx_gas(evm, init_and_floor_gas); let history = evm.ctx_ref().intrinsic_history_gas(); if history != 0 { @@ -423,25 +429,25 @@ where self.op.reward_beneficiary(evm, exec_result) } - /// op-revm's result; for a system call, with the reservoir it settled with reported - /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)). + /// op-revm's result, with the reservoir it settled with reported + /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)) + /// unless the execution reported it already. /// - /// revm's system-call path settles without [`post_execution`](Handler::post_execution), which - /// reports a transaction's: the result it hands over here is the settled one. A deposit that - /// halts is not a result: op-revm turns it into a failed deposit, which leaves no reservoir - /// ([`catch_error`](Handler::catch_error)). + /// A transaction reports it in [`post_execution`](Handler::post_execution), before the floor + /// absorbs it. revm's system-call path settles without that phase, whether the crate prepared + /// the system call or it was run straight through the handler: the result it hands over here + /// is the settled one, and nothing of this execution reported a reservoir since it built its + /// gas ([`tx_gas`](Handler::tx_gas)). A deposit that halts is not a result: op-revm turns it + /// into a failed deposit, which leaves no reservoir ([`catch_error`](Handler::catch_error)). fn execution_result( &mut self, evm: &mut Self::Evm, result: FrameResult, result_gas: revm::context::result::ResultGas, ) -> Result, Self::Error> { - let system_call_reservoir = - evm.ctx_ref().is_system_call().then(|| result.gas().reservoir()); + let reservoir = result.gas().reservoir(); let result = self.op.execution_result(evm, result, result_gas)?; - if let Some(reservoir) = system_call_reservoir { - evm.ctx_mut().additional_limit.set_reservoir_remaining(reservoir); - } + evm.ctx_mut().additional_limit.set_reservoir_remaining_unless_reported(reservoir); Ok(result) } @@ -1948,9 +1954,11 @@ mod tests { /// a system call's, whose path builds no result gas there, once its result is built: a handler /// reused for a system call reports the system call's own reservoir, not the transaction's /// before it. A transaction below the execution cap reports nothing, one above it its own - /// margin, and a deposit that halts nothing, its failed-deposit result leaving no reservoir; - /// after each, a system call on revm's default gas limit reports the margin above the - /// system-call budget. + /// margin less the body's history, which the reservoir pays first, and a deposit that halts + /// nothing, its failed-deposit result leaving no reservoir. After each, a system call on + /// revm's default gas limit reports the margin above the system-call budget; and one run + /// through the public handler entry points without the crate's preparation, plain or + /// inspected, reports its own, on a gas limit no budget splits: nothing. #[test] fn test_a_reused_handler_reports_each_executions_own_reservoir() { use crate::{ @@ -1963,7 +1971,7 @@ mod tests { use revm::{ context::{ContextSetters, TxEnv}, handler::{system_call::SYSTEM_CALL_GAS_LIMIT, SystemCallTx}, - inspector::NoOpInspector, + inspector::{InspectorHandler, NoOpInspector}, }; const HALTS: Address = address!("00000000000000000000000000000000000e0003"); const DEFAULT_RESERVOIR: u64 = SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT; @@ -1980,7 +1988,9 @@ mod tests { crate::MegaEvmError, EthFrame, >::new(); - let room = 100_000 + history_gas(crate::TX_BODY_SIZE).unwrap(); + const MARGIN: u64 = 10_000_000; + let body_history = history_gas(crate::TX_BODY_SIZE).unwrap(); + let room = 100_000 + body_history; let tx = |to: Address, gas_limit: u64, nonce: u64| { OpTx(op_transaction(TxEnv { caller: CALLER, @@ -1990,31 +2000,57 @@ mod tests { ..Default::default() })) }; - let mut deposit = tx(HALTS, room, 0); - deposit.0.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); - deposit.0.base.gas_price = 0; - - for (case, tx, succeeds) in [ - ("below the cap", tx(TARGET, room, 0), true), - ("above the cap", tx(TARGET, TX_GAS_LIMIT_CAP + 10_000_000, 1), true), - ("a halting deposit", deposit, false), + + let mut nonce = 0; + for (case, to, gas_limit, deposits, settled) in [ + ("below the cap", TARGET, room, false, 0), + ("above the cap", TARGET, TX_GAS_LIMIT_CAP + MARGIN, false, MARGIN - body_history), + ("a halting deposit", HALTS, room, true, 0), ] { - evm.inner.ctx.set_tx(tx); - let result = handler.run(&mut evm).expect(case); - assert_eq!(result.is_success(), succeeds, "{case}: {result:?}"); - let settled = evm.ctx().additional_limit().reservoir_remaining(); - assert_ne!(settled, DEFAULT_RESERVOIR, "{case}: the transaction's own would show"); - - let call = MegaTransaction::new_system_tx_with_caller(CALLER, TARGET, Bytes::new()); - evm.inner.ctx.set_tx(call); - evm.inner.ctx.on_new_system_call(); - let result = handler.run_system_call(&mut evm).expect("the system call runs"); - assert!(result.is_success(), "{case}: {result:?}"); - assert_eq!( - evm.ctx().additional_limit().reservoir_remaining(), - DEFAULT_RESERVOIR, - "{case}: the system call's own reservoir, not the transaction's" - ); + for inspected in [false, true] { + let mut tx = tx(to, gas_limit, nonce); + if deposits { + tx.0.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); + tx.0.base.gas_price = 0; + } else { + nonce += 1; + } + evm.inner.ctx.set_tx(tx); + let result = handler.run(&mut evm).expect(case); + assert_eq!(result.is_success(), !deposits, "{case}: {result:?}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + settled, + "{case}: the transaction's own reservoir" + ); + + // revm's public entry points, without the crate's preparation. + let call = MegaTransaction::new_system_tx_with_caller(CALLER, TARGET, Bytes::new()); + evm.inner.ctx.set_tx(call.clone()); + let result = if inspected { + handler.inspect_run_system_call(&mut evm) + } else { + handler.run_system_call(&mut evm) + }; + let result = result.expect("the unprepared system call runs"); + assert!(result.is_success(), "{case}: {result:?}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + 0, + "{case}, inspected {inspected}: the unprepared system call's own reservoir, \ + not the transaction's" + ); + + evm.inner.ctx.set_tx(call); + evm.inner.ctx.on_new_system_call(); + let result = handler.run_system_call(&mut evm).expect("the system call runs"); + assert!(result.is_success(), "{case}: {result:?}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + DEFAULT_RESERVOIR, + "{case}: the system call's own reservoir, not the transaction's" + ); + } } } } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index f96861ac0..c9b1e4fdb 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -110,8 +110,9 @@ pub struct AdditionalLimit { history_gas_spent: u64, /// The history bytes the settled transaction appended. history_bytes: u64, - /// The EIP-8037 reservoir the settled transaction left unspent. - reservoir_remaining: u64, + /// The EIP-8037 reservoir the settled transaction or system call left unspent: none from where + /// an execution builds its gas until it reports what it settled with. + reservoir_remaining: Option, } /// What a transaction's frames keep: the signed net of each counted dimension, indexed by its @@ -274,7 +275,7 @@ impl AdditionalLimit { self.decided.clear(); self.history_gas_spent = 0; self.history_bytes = 0; - self.reservoir_remaining = 0; + self.reservoir_remaining = None; } /* What the transaction keeps */ @@ -757,12 +758,27 @@ impl AdditionalLimit { /// ([`MegaGasUsage::reservoir_remaining`](crate::MegaGasUsage::reservoir_remaining)). It is /// read before the EIP-7623 floor absorbs it, and a failed deposit leaves none. pub const fn reservoir_remaining(&self) -> u64 { - self.reservoir_remaining + match self.reservoir_remaining { + Some(reservoir) => reservoir, + None => 0, + } + } + + /// Forgets the reservoir the last execution reported: the running one builds its gas, and + /// reports what it leaves unspent once it settles. + pub(crate) const fn forget_reservoir_remaining(&mut self) { + self.reservoir_remaining = None; } /// Records the reservoir the settled transaction or system call left unspent. pub(crate) const fn set_reservoir_remaining(&mut self, reservoir: u64) { - self.reservoir_remaining = reservoir; + self.reservoir_remaining = Some(reservoir); + } + + /// Records `reservoir` as what the settled execution left unspent, unless the execution + /// reported it already, where it read it before the result was built. + pub(crate) fn set_reservoir_remaining_unless_reported(&mut self, reservoir: u64) { + self.reservoir_remaining.get_or_insert(reservoir); } /// The history bytes the last settled transaction appended, whoever paid for them, which a From 608a746b0de715533ce19f3ef7c2a8c5f0e38f2c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:30:40 +0800 Subject: [PATCH 13/83] fix(evm): decide whether a transaction pays history when it is prepared The layer keeps one value, set when it begins a transaction or a system call, that says whether it is the protocol's own work, a deposit or an ordinary transaction; the exemption and prices_history derive from it, so a transaction set on the context and not run yet changes neither. prices_history is const again. --- crates/mega-evm/src/evm/context.rs | 23 +++++--- crates/mega-evm/src/limit/limit.rs | 58 +++++++++++++------ crates/mega-evm/src/limit/mod.rs | 2 +- .../mega-evm/tests/satin/history_exemption.rs | 36 +++++++++++- 4 files changed, 90 insertions(+), 29 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 97fe8b730..8fea549a9 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -21,7 +21,7 @@ use crate::{ history::{history_gas, transaction_body_bytes, write_record_history_gas}, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - limit::{Accounts, Counted}, + limit::{Accounts, Counted, TxClass}, system::{self, keyless}, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, Detention, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, LimitUsage, @@ -416,13 +416,11 @@ impl MegaContext { /// /// The neutral configuration prices no history at all. /// - /// It is read off the transaction the context holds and the exemption the transaction was - /// prepared with, so a caller that replaces the transaction and asks before running it gets - /// the new transaction's type with the last one's exemption. - pub fn prices_history(&self) -> bool { - !(self.runs_neutral() || - self.is_system_originated() || - self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE) + /// It is decided when the transaction is prepared, with its exemption, from what it is then + /// (a promoted system-address transaction is the protocol's own either way): a transaction + /// set in the context's hands and not run yet changes neither until it is prepared. + pub const fn prices_history(&self) -> bool { + !self.runs_neutral() && matches!(self.additional_limit.class(), TxClass::Ordinary) } /// The history gas of the running (or last) transaction's body: the bytes it carries and the @@ -524,7 +522,14 @@ impl MegaContext { // The body is data size whether or not the transaction pays history for it. A deposit, // a system transaction and a system call are exempt from the charge, not from the count. let body = transaction_body_bytes(self.tx()); - self.additional_limit.begin_transaction(system_originated, body); + let class = if system_originated { + TxClass::ProtocolOwn + } else if self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE { + TxClass::Deposit + } else { + TxClass::Ordinary + }; + self.additional_limit.begin_transaction(class, body); self.install_history_schedule(); // The protocol's own transactions are not detained: they maintain the volatile data. Their // reads set no cap. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index c9b1e4fdb..9fb207b33 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -77,9 +77,9 @@ use super::{ #[derive(Clone, Debug, Default)] pub struct AdditionalLimit { limits: EvmTxRuntimeLimits, - /// Whether the transaction is exempt from every per-transaction limit, sticky for the - /// transaction. See [`is_exempt`](Self::is_exempt). - exempt: bool, + /// What the running execution is, decided when it is begun and sticky for it: the exemption + /// follows from it ([`is_exempt`](Self::is_exempt)). + class: TxClass, /// The crossing the result of the frame returning next was made of, noted where the stop /// became that result ([`note_frame_stop`](Self::note_frame_stop)) and taken when the frame /// returns. @@ -115,6 +115,22 @@ pub struct AdditionalLimit { reservoir_remaining: Option, } +/// What the running execution is, decided when the layer begins it from what the transaction is, +/// and kept until the next one begins: what it is held to and what it pays follow from it, so +/// replacing the transaction the context holds without beginning it changes neither. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum TxClass { + /// The protocol's own work, a system-originated transaction or a system call: held to no + /// per-transaction limit, not detained, priced at the minimum bucket and paying no history. + ProtocolOwn, + /// A user's deposit: held to every limit like any transaction, and paying no history, its + /// bytes paid for on L1. + Deposit, + /// Any other transaction, which pays history for the bytes it appends. + #[default] + Ordinary, +} + /// What a transaction's frames keep: the signed net of each counted dimension, indexed by its /// pool, and, among the bytes, the EIP-7708 transfer logs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -257,12 +273,12 @@ impl AdditionalLimit { } /// Clears the state for a new transaction, keeping allocations and the limits, and begins it: - /// exempt from every limit or not, its body weighing `body` bytes. + /// a transaction of `class`, its body weighing `body` bytes. /// /// The exemption is decided before the body is counted: the protocol's own work is exempt /// whatever it carries. - pub(crate) fn begin_transaction(&mut self, exempt: bool, body: u64) { - self.exempt = exempt; + pub(crate) fn begin_transaction(&mut self, class: TxClass, body: u64) { + self.class = class; self.frame_stop = None; self.limit_exceeded = None; self.body = body; @@ -334,7 +350,7 @@ impl AdditionalLimit { /// record for each distinct authority that applies — and a transaction validation admits /// cannot cross the limit there. An exempt transaction is held to nothing. pub(crate) const fn admits_tx_body(&self, authorizations: u64) -> bool { - self.exempt || + self.is_exempt() || self.body.saturating_add(WRITE_RECORD_SIZE.saturating_mul(authorizations)) <= self.limits.tx_data_size_limit } @@ -353,11 +369,11 @@ impl AdditionalLimit { self.authorities = authorities; self.created_authorities = created; debug_assert!( - self.exempt || !self.usage().exceeds_data_size(self.limits.tx_data_size_limit), + self.is_exempt() || !self.usage().exceeds_data_size(self.limits.tx_data_size_limit), "validation admits no body whose authority records cross the data-size limit" ); debug_assert!( - self.exempt || + self.is_exempt() || (authorities == 0 && created == 0) || [LimitKind::KvUpdate, LimitKind::StateGrowth] .iter() @@ -390,7 +406,7 @@ impl AdditionalLimit { let records = self.tx_limit(LimitKind::KvUpdate) as i128 - self.net(LimitKind::KvUpdate); let created = self.tx_limit(LimitKind::StateGrowth) as i128 - self.net(LimitKind::StateGrowth); - !self.exempt && (entries as i128 > records || entries as i128 > created) + !self.is_exempt() && (entries as i128 > records || entries as i128 > created) } /// The verdict on an authorization list that would keep `records` write records and create @@ -423,7 +439,7 @@ impl AdditionalLimit { /// its body and the counts made before the frame are counted, the data size under the frame /// cap; unlimited for an exempt transaction. pub(crate) const fn first_frame_pools(&self) -> PoolAmounts { - if self.exempt { + if self.is_exempt() { return PoolAmounts::UNLIMITED; } let caps = self.frame_caps(); @@ -450,7 +466,7 @@ impl AdditionalLimit { /// The most each of a frame's pools may start with: the data-size frame cap, and no cap on the /// other pools; nothing for an exempt transaction. pub(crate) const fn frame_caps(&self) -> PoolAmounts { - if self.exempt { + if self.is_exempt() { return PoolAmounts::UNLIMITED; } PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, self.limits.frame_data_size_limit) @@ -471,7 +487,7 @@ impl AdditionalLimit { used: u64, frame_local: bool, ) -> LimitCheck { - if self.exempt { + if self.is_exempt() { return LimitCheck::WithinLimit; } LimitCheck::ExceedsLimit { kind, limit, used, frame_local } @@ -741,9 +757,15 @@ impl AdditionalLimit { } } - /// Whether the running transaction is exempt from every per-transaction limit. + /// Whether the running transaction is exempt from every per-transaction limit: the protocol's + /// own work is. pub const fn is_exempt(&self) -> bool { - self.exempt + matches!(self.class, TxClass::ProtocolOwn) + } + + /// What the running (or last) execution is, decided when it was begun. + pub(crate) const fn class(&self) -> TxClass { + self.class } /* What the settled transaction reports */ @@ -855,7 +877,7 @@ mod tests { #[test] fn test_the_exemption_answers_every_crossing_and_lasts_one_transaction() { let mut limit = AdditionalLimit::default(); - limit.begin_transaction(true, 0); + limit.begin_transaction(TxClass::ProtocolOwn, 0); assert!(limit.is_exempt()); for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { for frame_local in [false, true] { @@ -863,7 +885,7 @@ mod tests { assert_eq!(verdict, LimitCheck::WithinLimit, "{kind:?}, frame-local {frame_local}"); } } - limit.begin_transaction(false, 0); + limit.begin_transaction(TxClass::Ordinary, 0); assert!(!limit.is_exempt()); assert_eq!( limit.crossed(LimitKind::ComputeGas, 0, 1, false), @@ -887,7 +909,7 @@ mod tests { let limits = EvmTxRuntimeLimits::no_limits() .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE); let mut limit = AdditionalLimit::new(limits); - limit.begin_transaction(false, crate::TX_BODY_SIZE); + limit.begin_transaction(TxClass::Ordinary, crate::TX_BODY_SIZE); limit.count_authorities(2, 0); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index ca0cd4adc..c049f8455 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -184,7 +184,7 @@ mod limit; mod record; pub use limit::AdditionalLimit; -pub(crate) use limit::Counted; +pub(crate) use limit::{Counted, TxClass}; #[cfg(test)] pub(crate) use record::emits_transfer_logs; #[cfg(any(test, feature = "test-utils"))] diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 90da9fe90..f6d4cc5fe 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -26,7 +26,7 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{CALL, CREATE, LOG0, POP}, - context::TxEnv, + context::{ContextSetters, TxEnv}, }; use crate::common::{context, deposit, runs_at_measurement_prices}; @@ -328,3 +328,37 @@ fn test_the_exemption_does_not_outlive_its_transaction() { assert!(paying.gas.history > 0, "the next transaction pays for its own bytes"); assert_eq!(paying.gas.history, PROGRAM_HISTORY_BYTES * COST_PER_HISTORY_BYTE, "all of them"); } + +/// Whether a transaction pays history, and whether it is the protocol's own, are decided when the +/// transaction is prepared to run, from what it is: a transaction set in the context's hands but +/// not run yet changes neither. After a user's transaction, a deposit or a system transaction set +/// in its place still answers as the user's transaction did; after a deposit, a user's transaction +/// still answers that it pays none; after a system transaction, a user's transaction still answers +/// that it is the protocol's own. Each answers for itself once it runs. +#[test] +fn test_what_a_transaction_pays_is_decided_when_it_is_prepared() { + let user = || call_from(CALLER, CONTRACT); + let user_deposit = || deposit(call_from(CALLER, CONTRACT)); + // (case, transaction, pays history, the protocol's own) + let cases: [(&str, fn() -> MegaTransaction, bool, bool); 3] = [ + ("a user's transaction", user, true, false), + ("a user's deposit", user_deposit, false, false), + ("a system transaction", system_tx, false, true), + ]; + for (ran, run, pays, own) in cases { + for (set, replacement, its_pays, its_own) in cases { + let mut evm = MegaEvm::new(context(db())); + evm.execute_transaction(run()).expect("the transaction is valid"); + assert_eq!(evm.ctx().prices_history(), pays, "{ran}"); + assert_eq!(evm.ctx().is_system_originated(), own, "{ran}"); + + evm.ctx_mut().set_tx(replacement()); + assert_eq!(evm.ctx().prices_history(), pays, "{ran}, then {set} set and not run"); + assert_eq!(evm.ctx().is_system_originated(), own, "{ran}, then {set} set and not run"); + + evm.execute_transaction(replacement()).expect("the transaction is valid"); + assert_eq!(evm.ctx().prices_history(), its_pays, "{ran}, then {set} run"); + assert_eq!(evm.ctx().is_system_originated(), its_own, "{ran}, then {set} run"); + } + } +} From bf6e0b30fce56dacf08f01b8d0bbcb7099c4bce2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:32:18 +0800 Subject: [PATCH 14/83] fix(evm): report a body's intrinsic history only once validation admitted it The layer records the body's bytes when validation finds the gas limit covers their history, and the intrinsic history gas and the settled history bytes read that record, so a transaction validation refuses reports none, as before the history figures were recomputed. --- crates/mega-evm/src/evm/context.rs | 16 ++++++++-------- crates/mega-evm/src/evm/execution.rs | 6 +++--- crates/mega-evm/src/limit/limit.rs | 19 ++++++++++++++++++- crates/mega-evm/tests/satin/intrinsic.rs | 22 +++++++++++++++++++++- 4 files changed, 50 insertions(+), 13 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 8fea549a9..293f5f62a 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -423,18 +423,18 @@ impl MegaContext { !self.runs_neutral() && matches!(self.additional_limit.class(), TxClass::Ordinary) } - /// The history gas of the running (or last) transaction's body: the bytes it carries and the + /// The history gas of the running (or last) transaction's body — the bytes it carries and the /// write records its inclusion makes, which are known before it runs, at the cost per history - /// byte; nothing for a transaction that pays no history ([`prices_history`]). Its gas pays it - /// before the first frame, reservoir first, as intrinsic gas. A body whose bytes have no price - /// costs `u64::MAX`, which no gas limit covers. + /// byte — once validation admitted it: the gas limit covers it, and the transaction's gas pays + /// it before the first frame, reservoir first, as intrinsic gas. Nothing before that, so a + /// transaction validation refused reports none, and nothing for a transaction that pays no + /// history ([`prices_history`]). /// /// [`prices_history`]: Self::prices_history pub fn intrinsic_history_gas(&self) -> u64 { - if !self.prices_history() { - return 0; - } - history_gas(self.additional_limit.body()).unwrap_or(u64::MAX) + // Validation admits no body whose bytes have no price: their gas saturates, which no gas + // limit covers. + history_gas(self.additional_limit.intrinsic_history_bytes()).unwrap_or(u64::MAX) } /// The history gas the running transaction pays for `records` write records: their price, or diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index ada2f9d52..dec907ddb 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -52,7 +52,7 @@ use revm::{ use crate::{ access::ComputeStop, - charge_write_records_history, + charge_write_records_history, history_gas, limit::{CreatorBefore, StartBefore}, synthetic_frame_result, system::{keyless, Answer}, @@ -257,7 +257,7 @@ where } // A byte count with no price saturates, which no gas limit covers: the transaction is // rejected for not covering its own intrinsic gas. - let history = evm.ctx_ref().intrinsic_history_gas(); + let history = history_gas(evm.ctx_ref().additional_limit.body()).unwrap_or(u64::MAX); let gas_limit = evm.ctx_ref().tx().gas_limit(); let initial_gas = gas .initial_regular_gas() @@ -267,6 +267,7 @@ where InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas }.into() ); } + evm.ctx_mut().additional_limit.admit_body_history(); Ok(gas) } @@ -1963,7 +1964,6 @@ mod tests { fn test_a_reused_handler_reports_each_executions_own_reservoir() { use crate::{ constants::TX_GAS_LIMIT_CAP, - history_gas, test_utils::{op_transaction, zero_fee_l1_block_info}, MegaTransaction, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 9fb207b33..964e3d1bf 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -106,6 +106,9 @@ pub struct AdditionalLimit { kept: Kept, /// One per start revm decided whose result has not returned, the latest last. decided: Vec, + /// The bytes of the body the transaction's intrinsic history gas pays for: the body once + /// validation admitted that gas, and none before or for a transaction that pays no history. + intrinsic_history_bytes: u64, /// The history gas the settled transaction spent. history_gas_spent: u64, /// The history bytes the settled transaction appended. @@ -289,6 +292,7 @@ impl AdditionalLimit { self.pre_frame_stop = None; self.kept = Kept::default(); self.decided.clear(); + self.intrinsic_history_bytes = 0; self.history_gas_spent = 0; self.history_bytes = 0; self.reservoir_remaining = None; @@ -342,6 +346,19 @@ impl AdditionalLimit { self.body } + /// The bytes of the body the transaction's intrinsic history gas pays for: the body once + /// validation admitted that gas ([`admit_body_history`](Self::admit_body_history)), and none + /// before or for a transaction that pays no history. + pub(crate) const fn intrinsic_history_bytes(&self) -> u64 { + self.intrinsic_history_bytes + } + + /// Records that validation admitted the history gas of the transaction's body: its gas limit + /// covers it, and the transaction pays it before its first frame. + pub(crate) const fn admit_body_history(&mut self) { + self.intrinsic_history_bytes = self.body; + } + /// Whether the transaction's body, with one write record for each of its `authorizations`, /// fits its data-size limit: what validation holds a transaction to. /// @@ -817,7 +834,7 @@ impl AdditionalLimit { pub(crate) fn settle_history(&mut self, priced: bool, spent: u64) { self.history_gas_spent = spent; self.history_bytes = if priced { - self.body + self.intrinsic_history_bytes .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) .saturating_add(positive(self.kept.net(LimitKind::DataSize) as i128)) .saturating_sub(TRANSFER_LOG_SIZE.saturating_mul(self.kept.transfer_logs)) diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 41dff06eb..7500d9e1a 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -33,7 +33,7 @@ use revm::{ Database, ExecuteCommitEvm, ExecuteEvm, }; -use crate::common::{call, context, create, runs_at_measurement_prices}; +use crate::common::{call, context, create, history_is_free, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000800000"); const CALLEE: Address = address!("0000000000000000000000000000000000800001"); @@ -436,3 +436,23 @@ fn test_a_gas_limit_short_of_the_body_is_rejected() { } assert_eq!(gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, minimum)), Ok(minimum)); } + +/// The history of a transaction's body is its intrinsic history gas once validation admitted it, +/// and nothing before: a transaction validation refuses — its gas limit below the intrinsic charge +/// alone, or short of the body's history — reports none, neither the figure it would have paid nor +/// the one the transaction before it paid. +#[test] +fn test_the_bodys_history_is_reported_once_validation_admits_it() { + if history_is_free() { + return; + } + let mut evm = MegaEvm::new(context(funded())); + let minimum = EMPTY_CALL + body_history(0); + evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, minimum)).expect("the minimum is admitted"); + assert_eq!(evm.ctx().intrinsic_history_gas(), body_history(0), "admitted"); + for gas_limit in [1, EMPTY_CALL, minimum - 1] { + let refused = evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(refused.is_err(), "at {gas_limit}: {refused:?}"); + assert_eq!(evm.ctx().intrinsic_history_gas(), 0, "at {gas_limit}: refused"); + } +} From 36f2313bc8e636138226a7ebf9c0077a0a442e2b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:34:00 +0800 Subject: [PATCH 15/83] test(evm): pin that a journal whose transfer-log switch is turned off counts no transfer log The count of a value movement's transfer log follows the journal's own EIP-7708 switch, so a caller or an inspector that turns it off through the context's mutable journal gets no log and no 160 bytes; a SELFDESTRUCT moving value is held to a data-size limit of its body and records alone. Documented in AGENTS.md and the record module. --- AGENTS.md | 1 + crates/mega-evm/src/limit/record.rs | 8 ++- crates/mega-evm/tests/satin/transfer_logs.rs | 58 +++++++++++++++++++- 3 files changed, 64 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0f69c6161..05d3dc7b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -192,6 +192,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - EIP-7708 is on: every value movement — the transaction's value, a value `CALL`, a creation's endowment, a `SELFDESTRUCT`'s balance moved to another account — emits a `Transfer(from, to, amount)` log from `0xff…fe`, which revm journals itself, without a `LOG` opcode, and the receipt carries in execution order among the contracts' own logs. A `CALLCODE`, a call to itself and a transaction's value to its own sender move nothing to another account and log nothing; a deposit's value is logged and its mint is not; a destruction to itself burns the balance of an account created in the transaction without a log, because the base spec predates EIP-8246 and this revm emits no `Burn` log. A transfer log is data size like any log, counted by the rule a `LOG3` of one word is — 160 bytes, `TRANSFER_LOG_SIZE` — and nothing else: it is no write record and pays no history gas, because Ethereum prices it at nothing and it is not a byte the transaction chose to write. + Whether a movement logs is read off the journal's own EIP-7708 switch, the rule revm's journal emits by (`limit::emits_transfer_logs`), not off the configuration: a caller or an inspector that turns the journal's switch off through the context's mutable journal, past the configuration the spec fixes, gets no transfer log, and none is counted (`tests/satin/transfer_logs.rs`). It is counted where the value moves, on the pool of the frame whose journal checkpoint holds the move: a frame start's log with its records, on the started frame; a `SELFDESTRUCT`'s with its records once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. A frame start's records and log are read off what revm did, in `MegaEvm::frame_init`: the start's accounts on its frame — a call's caller and target, a creation's created account — are read before revm decides the start, with a journal mark (`Accounts::start_before`), and again once it did, each account's record by its change since, one account of state growth for each that was empty and is not, and the transfer log revm journaled since the mark (`Accounts::start_made`), drawn on the pool the frame starts with (`AdditionalLimit::count_start`): a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; a success revm gave without building the frame — a call to an account with no code, to a precompile that answers — gives way to the stop on its untouched gas, and its committed move and log are taken back to the mark (`take_back_a_stopped_answer`). An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: its result is revm's, so a value call to a precompile that fails burns its forward as any failed precompile does, whatever its value transfer would have counted. diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 6db62420f..9d9a6236c 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -30,6 +30,12 @@ //! nothing ([`Accounts::is_destroyed`]). Every fact is the journal's: revm's flags of an account //! created and of one destroyed in the transaction, which a failed frame's revert takes back with //! the rest of it, the account's original info and each slot's original value. +//! +//! Whether a value movement journals an EIP-7708 transfer log, whose bytes a frame start and a +//! `SELFDESTRUCT` count, is the journal's too: its own switch, read by the rule revm emits the log +//! by ([`emits_transfer_logs`]). A caller or an inspector that turns the journal's switch through +//! the context's mutable journal, past the configuration the spec fixes, changes what revm emits, +//! and the count follows the logs revm emits. #[cfg(not(feature = "std"))] use alloc as std; @@ -217,7 +223,7 @@ pub(crate) fn is_transfer_log(log: &Log) -> bool { /// Whether a value movement journals an EIP-7708 transfer log on `journal`: from Amsterdam on, or /// with the switch on, unless EIP-7708 is disabled. It is the rule revm's journal emits one by, /// read off the journal's own copy of the configuration, so the data size counts a transfer log -/// exactly where revm emits one. +/// exactly where revm emits one, a switch a caller turned on the journal itself included. pub(crate) fn emits_transfer_logs(journal: &Journal) -> bool { (journal.cfg.spec.is_enabled_in(SpecId::AMSTERDAM) || journal.amsterdam_eip7708_enabled()) && !journal.cfg.eip7708_disabled diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 54e1f642e..280f619a1 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -49,7 +49,7 @@ use revm::{ }, context::{ result::{ExecutionResult, Output}, - TxEnv, + ContextTr, JournalTr, TxEnv, }, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue, InstructionResult, @@ -58,7 +58,7 @@ use revm::{ }; use crate::common::{ - account_state_gas, context, execute_under, history_rounds, share, value_call_room, + account_state_gas, call, context, execute_under, history_rounds, share, value_call_room, }; const CALLER: Address = address!("0000000000000000000000000000000000d00000"); @@ -777,6 +777,60 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { assert_eq!(balance(&older, DESTRUCTOR), value, "an older account keeps its balance"); } +/// The data size counts a transfer log where revm's journal emits one, read off the journal's own +/// switch: a caller or an inspector that turns the journal's EIP-7708 switch off through the +/// context's mutable journal, past the configuration the spec fixes, gets no transfer log and has +/// none counted. Here a `SELFDESTRUCT` moves a balance to an account that does not exist: its two +/// records and the account it adds are counted, and no 160 bytes of a log, so a data-size limit of +/// exactly the body and the two records holds it as no limit does. With the switch the spec fixes, +/// the same destruction logs the move, and the same limit stops it. +#[test] +fn test_a_journal_switched_off_neither_logs_nor_counts_a_transfer_log() { + let value = U256::from(1); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(DESTRUCTOR, value) + .account_code(DESTRUCTOR, BytecodeBuilder::default().selfdestruct(PAYEE).build()); + let tx = call(CALLER, DESTRUCTOR, U256::ZERO, 20_000_000); + let records = 2 * WRITE_RECORD_SIZE; + let kept = transaction_body_bytes(&tx) + records; + let unlimited = EvmTxRuntimeLimits::no_limits(); + let tight = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(kept); + let run = |switched_off: bool, limits: EvmTxRuntimeLimits| { + let mut ctx = context(db.clone()).with_tx_runtime_limits(limits); + if switched_off { + ctx.journal_mut().set_amsterdam_eip7708_enabled(false); + } + MegaEvm::new(ctx).execute_transaction(tx.clone()).expect("the transaction is valid") + }; + + for (case, limits) in [("no limit", unlimited), ("a limit of what it keeps", tight)] { + let outcome = run(true, limits); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert!(outcome.result.logs().is_empty(), "{case}: no transfer log"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: kept, write_records: 2, state_growth: 1 }, + "{case}: the records and the new account, and no log", + ); + assert_eq!(outcome.gas.history_bytes, kept, "{case}"); + assert_eq!(balance(&outcome, PAYEE), value, "{case}: the balance moved"); + } + + let logged = run(false, unlimited); + assert_eq!(transfer_logs(&logged), [transfer_log(DESTRUCTOR, PAYEE, value)]); + assert_eq!(logged.usage.data_size, kept + TRANSFER_LOG_SIZE, "the spec's switch"); + let stopped = run(false, tight); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: records }; + assert_eq!( + stopped.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "the log crosses what the body leaves the transaction's own frame: {:?}", + stopped.result, + ); + assert_eq!(balance(&stopped, PAYEE), U256::ZERO, "the stop took the move back"); +} + /// A start revm refuses on its caller's account moves nothing and writes nothing, so nothing is /// counted for it, and no limit stops it for what it would have counted: it runs as it does with /// no limit. Here, a value call its caller cannot fund, which revm answers with `OutOfFunds` and no From d64d264593841644759ce4a33b31b3de2019f49e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:34:00 +0800 Subject: [PATCH 16/83] test(limit): set the bare journal's spec where a record test relies on a pre-Amsterdam default --- crates/mega-evm/src/limit/record.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 9d9a6236c..99f02d246 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -749,6 +749,8 @@ mod tests { let records_bytes = |records| WRITE_RECORD_SIZE * records; let mut fresh = journal(); + // Below Amsterdam, where the switch alone decides whether the move logs. + fresh.set_spec_id(SpecId::OSAKA); fresh.set_amsterdam_eip7708_enabled(true); fresh.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); let (counted, history, _) = Accounts::of(&fresh).write_counted(&destruction(OTHER, 5)); From 9a1cdc00a4735af97a18265ce01750013c5ffdde Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:34:15 +0800 Subject: [PATCH 17/83] docs: name the class the layer begins an execution as where AGENTS.md cites the exemption --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 05d3dc7b3..eaad088f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -246,7 +246,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A builder's policy changes which transactions it packs, never what a packed block computes (`tests/block/building_policy.rs`). Satin carries no fork parameter: the `SequencerRegistry`'s roles are what the registry the legacy forks left holds. A genesis file's `config` object carries Satin as one key, `satinTime`, and every reader — a node, a stateless validator, a genesis generator, `mega-evme --genesis` — reads it with `SatinChainConfig::from_genesis_config` (`block/genesis.rs`), which refuses any other key starting with `satin`, the registry, `satinInitialFromBlock` and limit keys of the format's earlier versions among them, a value that is not a 64-bit integer, and a schedule `validate_schedule` refuses; the key format is provisional. -- The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them. +- The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::is_exempt`, read off the class the layer begins the execution as — the protocol's own work, a deposit or an ordinary transaction — which `MegaContext::prices_history` reads too, so a transaction set on the context and not run yet changes neither), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them. It is the set history gas exempts, for the same reason: the protocol's maintenance must not fail on a resource limit. The exemption covers the KV updates and state growth beside data size. What they use is counted all the same and reported, in the outcome's usage and in the block's counters, as a deposit's is. From 25b25a6eb3ea41a214eda6cc952c827dc019abfa Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:42:44 +0800 Subject: [PATCH 18/83] refactor(evm): read the protocol's detention caps off the class it is prepared as --- crates/mega-evm/src/evm/context.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 293f5f62a..6250c2fa3 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -534,7 +534,7 @@ impl MegaContext { // The protocol's own transactions are not detained: they maintain the volatile data. Their // reads set no cap. let limits = self.additional_limit.limits(); - let (block_env_cap, oracle_cap) = if system_originated { + let (block_env_cap, oracle_cap) = if class == TxClass::ProtocolOwn { (u64::MAX, u64::MAX) } else { (limits.block_env_access_compute_gas_limit, limits.oracle_access_compute_gas_limit) From b07f4d45d46fa0934d3721a4dfbc4a5152f2ff6d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:42:44 +0800 Subject: [PATCH 19/83] test: assert the exact refusal, set every record test journal's spec, run the unprepared system call above the cap --- crates/mega-evm/src/evm/execution.rs | 7 +++++-- crates/mega-evm/src/limit/record.rs | 6 +++--- crates/mega-evm/tests/satin/intrinsic.rs | 14 +++++++++++--- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index dec907ddb..7accf26c2 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1959,7 +1959,8 @@ mod tests { /// nothing, its failed-deposit result leaving no reservoir. After each, a system call on /// revm's default gas limit reports the margin above the system-call budget; and one run /// through the public handler entry points without the crate's preparation, plain or - /// inspected, reports its own, on a gas limit no budget splits: nothing. + /// inspected, reports its own: nothing, even on a gas limit above the execution cap, since revm + /// caps no system call's gas into a reservoir and only the crate's preparation splits it. #[test] fn test_a_reused_handler_reports_each_executions_own_reservoir() { use crate::{ @@ -2026,7 +2027,9 @@ mod tests { // revm's public entry points, without the crate's preparation. let call = MegaTransaction::new_system_tx_with_caller(CALLER, TARGET, Bytes::new()); - evm.inner.ctx.set_tx(call.clone()); + let mut unprepared = call.clone(); + unprepared.0.base.gas_limit = TX_GAS_LIMIT_CAP + MARGIN; + evm.inner.ctx.set_tx(unprepared); let result = if inspected { handler.inspect_run_system_call(&mut evm) } else { diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 99f02d246..6eceab69b 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -646,13 +646,15 @@ mod tests { } } - /// A journal holding three accounts as the transaction loaded them. + /// A journal holding three accounts as the transaction loaded them, below Amsterdam, where the + /// EIP-7708 switch alone decides whether a value movement logs. fn journal() -> Journal { let db = MemoryDatabase::default() .account_balance(SENDER, U256::from(10)) .account_balance(OTHER, U256::from(4)) .account_balance(DESTRUCTED, U256::from(5)); let mut journal = Journal::new(db); + journal.set_spec_id(SpecId::OSAKA); for address in [SENDER, OTHER, DESTRUCTED] { journal.load_account(address).unwrap(); } @@ -749,8 +751,6 @@ mod tests { let records_bytes = |records| WRITE_RECORD_SIZE * records; let mut fresh = journal(); - // Below Amsterdam, where the switch alone decides whether the move logs. - fresh.set_spec_id(SpecId::OSAKA); fresh.set_amsterdam_eip7708_enabled(true); fresh.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); let (counted, history, _) = Accounts::of(&fresh).write_counted(&destruction(OTHER, 5)); diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 7500d9e1a..2a2f2ca53 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -450,9 +450,17 @@ fn test_the_bodys_history_is_reported_once_validation_admits_it() { let minimum = EMPTY_CALL + body_history(0); evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, minimum)).expect("the minimum is admitted"); assert_eq!(evm.ctx().intrinsic_history_gas(), body_history(0), "admitted"); - for gas_limit in [1, EMPTY_CALL, minimum - 1] { - let refused = evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, gas_limit)); - assert!(refused.is_err(), "at {gas_limit}: {refused:?}"); + for (gas_limit, initial_gas) in + [(EMPTY_CALL - 1, EMPTY_CALL), (EMPTY_CALL, minimum), (minimum - 1, minimum)] + { + let refused = evm + .transact_raw(call(CALLER, CALLEE, U256::ZERO, gas_limit)) + .expect_err("a gas limit below the minimum is refused"); + assert_eq!( + refused.as_invalid_tx_err().and_then(InvalidTxError::as_invalid_tx_err), + Some(&InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas }), + "at {gas_limit}: the intrinsic charge refused it", + ); assert_eq!(evm.ctx().intrinsic_history_gas(), 0, "at {gas_limit}: refused"); } } From bd86f70003a88f8b745a1a5e1523edc7bf0834b4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:42:44 +0800 Subject: [PATCH 20/83] docs: name the class the layer begins an execution as in the AGENTS.md module map --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eaad088f4..c61c9d7a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,7 +138,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | | `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | | `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the exemption, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit or an ordinary transaction), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | | `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | | `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | | `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | @@ -246,8 +246,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A builder's policy changes which transactions it packs, never what a packed block computes (`tests/block/building_policy.rs`). Satin carries no fork parameter: the `SequencerRegistry`'s roles are what the registry the legacy forks left holds. A genesis file's `config` object carries Satin as one key, `satinTime`, and every reader — a node, a stateless validator, a genesis generator, `mega-evme --genesis` — reads it with `SatinChainConfig::from_genesis_config` (`block/genesis.rs`), which refuses any other key starting with `satin`, the registry, `satinInitialFromBlock` and limit keys of the format's earlier versions among them, a value that is not a 64-bit integer, and a schedule `validate_schedule` refuses; the key format is provisional. -- The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::is_exempt`, read off the class the layer begins the execution as — the protocol's own work, a deposit or an ordinary transaction — which `MegaContext::prices_history` reads too, so a transaction set on the context and not run yet changes neither), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them. +- The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::is_exempt`, read off the class the layer begins the execution as, as `MegaContext::prices_history` is), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them. It is the set history gas exempts, for the same reason: the protocol's maintenance must not fail on a resource limit. + The class is decided when the layer prepares a transaction or a system call, so a transaction set on the context and not run yet changes neither the exemption nor what it pays. The exemption covers the KV updates and state growth beside data size. What they use is counted all the same and reported, in the outcome's usage and in the block's counters, as a deposit's is. A block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction the block's packing budgets and the builder's policy never refuse, while the block's gas limit and the data-availability footprint hold it as any legacy transaction, because the block decides on the envelope (see the block executor below). From 0b1f069322753b22e5158000edefd55baac607f0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 15:44:30 +0800 Subject: [PATCH 21/83] test: build the classification cases from transaction values --- .../mega-evm/tests/satin/history_exemption.rs | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index f6d4cc5fe..cef7cb1f4 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -337,26 +337,25 @@ fn test_the_exemption_does_not_outlive_its_transaction() { /// that it is the protocol's own. Each answers for itself once it runs. #[test] fn test_what_a_transaction_pays_is_decided_when_it_is_prepared() { - let user = || call_from(CALLER, CONTRACT); - let user_deposit = || deposit(call_from(CALLER, CONTRACT)); + let user = call_from(CALLER, CONTRACT); // (case, transaction, pays history, the protocol's own) - let cases: [(&str, fn() -> MegaTransaction, bool, bool); 3] = [ - ("a user's transaction", user, true, false), - ("a user's deposit", user_deposit, false, false), - ("a system transaction", system_tx, false, true), + let cases = [ + ("a user's transaction", user.clone(), true, false), + ("a user's deposit", deposit(user), false, false), + ("a system transaction", system_tx(), false, true), ]; - for (ran, run, pays, own) in cases { - for (set, replacement, its_pays, its_own) in cases { + for (ran, run, pays, own) in cases.clone() { + for (set, replacement, its_pays, its_own) in cases.clone() { let mut evm = MegaEvm::new(context(db())); - evm.execute_transaction(run()).expect("the transaction is valid"); + evm.execute_transaction(run.clone()).expect("the transaction is valid"); assert_eq!(evm.ctx().prices_history(), pays, "{ran}"); assert_eq!(evm.ctx().is_system_originated(), own, "{ran}"); - evm.ctx_mut().set_tx(replacement()); + evm.ctx_mut().set_tx(replacement.clone()); assert_eq!(evm.ctx().prices_history(), pays, "{ran}, then {set} set and not run"); assert_eq!(evm.ctx().is_system_originated(), own, "{ran}, then {set} set and not run"); - evm.execute_transaction(replacement()).expect("the transaction is valid"); + evm.execute_transaction(replacement).expect("the transaction is valid"); assert_eq!(evm.ctx().prices_history(), its_pays, "{ran}, then {set} run"); assert_eq!(evm.ctx().is_system_originated(), its_own, "{ran}, then {set} run"); } From 2e482f2239cb883ccc1f553add5eaeeccf8058d2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 16:11:00 +0800 Subject: [PATCH 22/83] fix(evm): keep a context switched back from the neutral configuration unpriced for history until it is prepared Switching to the neutral configuration records, in the class the layer keeps, that an ordinary execution pays no history, and the next preparation decides again; with_cfg alone no longer prices history, so a system call run straight through the handler's public entry points on a context switched to the neutral configuration and back pays none, as before the history policy was derived. --- AGENTS.md | 3 +- crates/mega-evm/src/evm/context.rs | 13 ++- crates/mega-evm/src/limit/limit.rs | 22 ++++- .../mega-evm/tests/satin/history_exemption.rs | 96 ++++++++++++++++++- 4 files changed, 123 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c61c9d7a2..23a800d8a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,7 +138,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | | `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | | `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit or an ordinary transaction), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | | `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | | `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | | `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | @@ -249,6 +249,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::is_exempt`, read off the class the layer begins the execution as, as `MegaContext::prices_history` is), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them. It is the set history gas exempts, for the same reason: the protocol's maintenance must not fail on a resource limit. The class is decided when the layer prepares a transaction or a system call, so a transaction set on the context and not run yet changes neither the exemption nor what it pays. + Switching the context to the neutral configuration decides that an ordinary execution pays no history, until the next preparation decides again: switching back with `with_cfg` alone does not price it, so a system call run straight through the handler, which prepares nothing, pays none (`tests/satin/history_exemption.rs`). The exemption covers the KV updates and state growth beside data size. What they use is counted all the same and reported, in the outcome's usage and in the block's counters, as a deposit's is. A block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction the block's packing budgets and the builder's policy never refuse, while the block's gas limit and the data-availability footprint hold it as any legacy transaction, because the block decides on the envelope (see the block executor below). diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 6250c2fa3..a6c71484a 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -168,6 +168,9 @@ impl MegaContext { self.inner = self.inner.with_cfg(op_cfg(&cfg)); self.cfg = cfg; self.neutral = true; + // Decided here, as a preparation decides it, and kept until the next one: switching back + // to the spec's configuration alone does not price history again. + self.additional_limit.price_no_history(); self } @@ -417,10 +420,12 @@ impl MegaContext { /// The neutral configuration prices no history at all. /// /// It is decided when the transaction is prepared, with its exemption, from what it is then - /// (a promoted system-address transaction is the protocol's own either way): a transaction - /// set in the context's hands and not run yet changes neither until it is prepared. + /// (a promoted system-address transaction is the protocol's own either way) and the + /// configuration it runs: a transaction set in the context's hands and not run yet changes + /// neither until it is prepared. Switching the context to the neutral configuration decides + /// it too, and switching back alone does not: the next preparation decides again. pub const fn prices_history(&self) -> bool { - !self.runs_neutral() && matches!(self.additional_limit.class(), TxClass::Ordinary) + matches!(self.additional_limit.class(), TxClass::Ordinary) } /// The history gas of the running (or last) transaction's body — the bytes it carries and the @@ -526,6 +531,8 @@ impl MegaContext { TxClass::ProtocolOwn } else if self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE { TxClass::Deposit + } else if self.runs_neutral() { + TxClass::Neutral } else { TxClass::Ordinary }; diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 964e3d1bf..d8364e951 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -118,9 +118,10 @@ pub struct AdditionalLimit { reservoir_remaining: Option, } -/// What the running execution is, decided when the layer begins it from what the transaction is, -/// and kept until the next one begins: what it is held to and what it pays follow from it, so -/// replacing the transaction the context holds without beginning it changes neither. +/// What the running execution is, decided when the layer begins it from what the transaction is +/// and the configuration it runs, and kept until the next one begins: what it is held to and what +/// it pays follow from it, so replacing the transaction the context holds without beginning it +/// changes neither. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) enum TxClass { /// The protocol's own work, a system-originated transaction or a system call: held to no @@ -129,6 +130,11 @@ pub(crate) enum TxClass { /// A user's deposit: held to every limit like any transaction, and paying no history, its /// bytes paid for on L1. Deposit, + /// Any other transaction under the neutral configuration, which prices no history: held as + /// an ordinary transaction is, paying no history. Switching the context to the neutral + /// configuration makes an ordinary execution this until the next one begins, whatever + /// configuration the context is switched to in between. + Neutral, /// Any other transaction, which pays history for the bytes it appends. #[default] Ordinary, @@ -785,6 +791,16 @@ impl AdditionalLimit { self.class } + /// Makes the running (or last) execution pay no history where it would, as the neutral + /// configuration the context is switched to prices none; the next execution the layer begins + /// decides again. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) const fn price_no_history(&mut self) { + if matches!(self.class, TxClass::Ordinary) { + self.class = TxClass::Neutral; + } + } + /* What the settled transaction reports */ /// The history gas the last settled transaction spent. diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index cef7cb1f4..121418735 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -19,14 +19,22 @@ use mega_evm::{ ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP, }, + spec_cfg, system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, - test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, - transaction_body_bytes, LimitUsage, MegaEvm, MegaTransaction, MegaTransactionOutcome, - LOG_BASE_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + test_utils::{ + neutral_cfg, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, + transaction_body_bytes, EthSpecId, EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, + MegaEvmError, MegaHandler, MegaSpecId, MegaTransaction, MegaTransactionOutcome, LOG_BASE_SIZE, + TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{CALL, CREATE, LOG0, POP}, - context::{ContextSetters, TxEnv}, + context::{CfgEnv, ContextSetters, TxEnv}, + handler::{EthFrame, Handler, SystemCallTx}, + inspector::{InspectorHandler, NoOpInspector}, + interpreter::interpreter::EthInterpreter, + ExecuteEvm, }; use crate::common::{context, deposit, runs_at_measurement_prices}; @@ -34,6 +42,8 @@ use crate::common::{context, deposit, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000400000"); const CONTRACT: Address = address!("0000000000000000000000000000000000400001"); const PAYEE: Address = address!("0000000000000000000000000000000000400002"); +/// A contract that writes its slot 0 and stops. +const STORER: Address = address!("0000000000000000000000000000000000400003"); /// Room for the state gas of a new slot, a new account and a deployment. const GAS_LIMIT: u64 = 50_000_000; @@ -361,3 +371,81 @@ fn test_what_a_transaction_pays_is_decided_when_it_is_prepared() { } } } + +/// Whether a context prices history is decided when its configuration is switched to the neutral +/// one, as it is when a transaction is prepared, and kept until the next preparation decides +/// again: switching back with `with_cfg` alone changes nothing. So a system call run straight +/// through the handler's public entry points, plain or inspected, which prepare nothing, pays no +/// history on a context switched to the neutral configuration and back: it spends what the same +/// call spends where the neutral configuration still runs, and on exactly that gas limit it keeps +/// the slot it writes. +#[test] +fn test_a_context_switched_back_from_the_neutral_configuration_prices_no_history_until_prepared() { + let evm = |switched_back: bool, gas_limit: Option| { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code( + STORER, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ); + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut ctx = if switched_back { + ctx.with_neutral_cfg(neutral_cfg(EthSpecId::OSAKA).expect("Osaka has a configuration")) + .with_cfg(CfgEnv::new_with_spec(MegaSpecId::SATIN)) + } else { + // The neutral configuration on the spec's own fields: on this call, it differs from + // the spec's in the history it prices alone. + ctx.with_neutral_cfg(spec_cfg(CfgEnv::new_with_spec(MegaSpecId::SATIN))) + }; + let mut call = MegaTransaction::new_system_tx_with_caller(CALLER, STORER, Bytes::new()); + if let Some(gas_limit) = gas_limit { + call.0.base.gas_limit = gas_limit; + } + ctx.set_tx(call); + MegaEvm::new(ctx) + }; + // (gas used, history gas, history bytes, slot 0 of STORER) + let run = |mut evm: MegaEvm, inspected: bool| { + let mut handler = MegaHandler::< + _, + MegaEvmError, + EthFrame, + >::new(); + let result = if inspected { + handler.inspect_run_system_call(&mut evm) + } else { + handler.run_system_call(&mut evm) + }; + let result = result.expect("the system call runs"); + let layer = evm.ctx().additional_limit(); + let (history, bytes) = (layer.history_gas_spent(), layer.history_bytes()); + let state = ExecuteEvm::finalize(&mut evm); + let slot = state + .get(&STORER) + .and_then(|account| account.storage.get(&U256::ZERO)) + .map(|slot| slot.present_value) + .unwrap_or_default(); + assert!(result.is_success(), "inspected {inspected}: {result:?}"); + (result.tx_gas_used(), history, bytes, slot) + }; + + for inspected in [false, true] { + let (spent, history, bytes, slot) = run(evm(false, None), inspected); + assert_eq!((history, bytes, slot), (0, 0, U256::from(1)), "inspected {inspected}: neutral"); + + let back = evm(true, None); + assert!(!back.ctx().prices_history(), "the switch decided it, and with_cfg left it"); + assert_eq!( + run(back, inspected), + (spent, 0, 0, U256::from(1)), + "inspected {inspected}: switched back, the same call at the same price", + ); + assert_eq!( + run(evm(true, Some(spent)), inspected), + (spent, 0, 0, U256::from(1)), + "inspected {inspected}: on exactly what it spends, it keeps its slot", + ); + } +} From edf3fa1e4f250cfcfadc23f27c51bab0b8cdaf0d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 16:53:47 +0800 Subject: [PATCH 23/83] test(limit): pin when an authorization list needs the simulation --- crates/mega-evm/src/limit/limit.rs | 43 ++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index d8364e951..cc21c5553 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -945,4 +945,47 @@ mod tests { limit.begin_transaction(TxClass::Ordinary, crate::TX_BODY_SIZE); limit.count_authorities(2, 0); } + + /// An authorization list may cross exactly when it has more entries than the KV or the + /// state-growth limit leaves the transaction, the limit less what the transaction already + /// counts: a list that fills the room exactly cannot cross, one entry more may. An exempt + /// transaction's list never may, whatever its length. + #[test] + fn test_an_authorization_list_may_cross_only_past_what_both_limits_leave() { + let records = |kv| Counted::records(kv, 0, false); + let growth = |accounts| Counted::NONE.with_growth(accounts, 0); + // (case, KV limit, state-growth limit, counted before the list, entries, may cross) + let cases = [ + ("no entries", 3, 5, Counted::NONE, 0, false), + ("entries fill the KV room", 3, 10, Counted::NONE, 3, false), + ("one entry past the KV room", 3, 10, Counted::NONE, 4, true), + ("entries fill the state-growth room", 10, 3, Counted::NONE, 3, false), + ("one entry past the state-growth room", 10, 3, Counted::NONE, 4, true), + ("entries fill the KV room left after records", 5, 10, records(2), 3, false), + ("one entry past the KV room left after records", 5, 10, records(2), 4, true), + ("entries fill the state-growth room left after growth", 10, 5, growth(2), 3, false), + ("one entry past the state-growth room left after growth", 10, 5, growth(2), 4, true), + ("no KV room", 0, 10, Counted::NONE, 1, true), + ("no state-growth room", 10, 0, Counted::NONE, 1, true), + ("the longest list under no limit", u64::MAX, u64::MAX, Counted::NONE, u64::MAX, false), + ]; + for (case, kv, state_growth, before, entries, may_cross) in cases { + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_kv_update_limit(kv) + .with_tx_state_growth_limit(state_growth); + let mut limit = AdditionalLimit::new(limits); + limit.begin_transaction(TxClass::Ordinary, crate::TX_BODY_SIZE); + limit.count(&before); + assert_eq!(limit.authorization_list_may_cross(entries), may_cross, "{case}"); + } + + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_kv_update_limit(0) + .with_tx_state_growth_limit(0); + let mut limit = AdditionalLimit::new(limits); + limit.begin_transaction(TxClass::ProtocolOwn, crate::TX_BODY_SIZE); + for entries in [1, u64::MAX] { + assert!(!limit.authorization_list_may_cross(entries), "exempt, {entries} entries"); + } + } } From 7eabf0bb3c1edab3b178eb644615fa2a20ee2269 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:08:37 +0800 Subject: [PATCH 24/83] bench(block): add a block of ERC-20 transfers Sixty-four ERC-20 transfers, each from a sender of its own to a recipient that already holds tokens, through MegaBlockExecutor: a block of the commonest contract call there is, two balance reads and writes and one log per transaction. The token's source sits beside the bench, with the solc command that rebuilds the embedded runtime code byte for byte. --- crates/mega-evm/benches/block.rs | 116 +++++++++++++++----- crates/mega-evm/benches/contracts/Token.sol | 27 +++++ 2 files changed, 118 insertions(+), 25 deletions(-) create mode 100644 crates/mega-evm/benches/contracts/Token.sol diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 35e6b8396..ded22b6f2 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -12,7 +12,7 @@ //! detention's caps, with no building policy on top (`BlockLimits::default()`); //! - from a fresh `State` over that database, as a node starts each block. //! -//! Two workloads of `N` transactions each, whose per-transaction work beyond the transaction +//! Three workloads of `N` transactions each, whose per-transaction work beyond the transaction //! itself is the executor's own: the admission checks, the size estimates, the limits, the //! counters, the receipt and the commit. //! @@ -21,6 +21,10 @@ //! - `storage_writes`: calls to a contract that writes the slot the transaction names in its //! calldata, so every transaction changes storage and carries a write record through the //! counters, with a log-free receipt. +//! - `erc20_transfers`: ERC-20 `transfer`s, each from a sender of its own to a recipient of its own +//! that already holds tokens, on the token `contracts/Token.sol` builds: a block of the commonest +//! contract call there is. Each reads and writes two balances and emits one `Transfer` log, so it +//! carries two write records and a log through the counters. //! //! The measurement runs `apply_pre_execution_changes`, the transactions and `finish` — the whole //! block a node executes — and hands the state back, so dropping it is not measured. One more arm, @@ -35,7 +39,7 @@ use alloy_eips::{ }; use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_primitives::{address, hex, keccak256, Address, Bytes, Signature, TxKind, B256, U256}; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ system::{MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, @@ -73,6 +77,16 @@ const PARENT_BEACON_ROOT: B256 = B256::repeat_byte(0xcd); const SENDER: Address = address!("0x2000000000000000000000000000000000000002"); const RECIPIENT: Address = address!("0x3000000000000000000000000000000000000003"); const WRITER: Address = address!("0x1000000000000000000000000000000000000001"); +const TOKEN: Address = address!("0x4000000000000000000000000000000000000004"); + +/// The runtime code of `contracts/Token.sol`, compiled with solc 0.8.30: +/// `solc --optimize --optimize-runs 200 --metadata-hash none --bin-runtime Token.sol`. +const TOKEN_CODE: [u8; 492] = hex!("608060405234801561000f575f5ffd5b5060043610610034575f3560e01c806370a0823114610038578063a9059cbb1461006a575b5f5ffd5b610057610046366004610178565b5f6020819052908152604090205481565b6040519081526020015b60405180910390f35b61007d610078366004610198565b61008d565b6040519015158152602001610061565b335f90815260208190526040812054828110156100da5760405162461bcd60e51b815260206004820152600760248201526662616c616e636560c81b604482015260640160405180910390fd5b335f9081526020819052604080822085840390556001600160a01b03861682528120805485929061010c9084906101c0565b90915550506040518381526001600160a01b0385169033907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a360019150505b92915050565b80356001600160a01b0381168114610173575f5ffd5b919050565b5f60208284031215610188575f5ffd5b6101918261015d565b9392505050565b5f5f604083850312156101a9575f5ffd5b6101b28361015d565b946020939093013593505050565b8082018082111561015757634e487b7160e01b5f52601160045260245ffdfea164736f6c634300081e000a"); + +/// The first of the `N` accounts the ERC-20 transfers are sent from, and the first of the `N` +/// accounts they pay, each one per transaction. +const TOKEN_SENDER_BASE: u64 = 0x60_0000; +const TOKEN_HOLDER_BASE: u64 = 0x70_0000; /// Code that writes 1 to the slot its first calldata word names, so every call that names a slot /// of its own changes storage and leaves a write record behind. @@ -92,13 +106,43 @@ fn slot_calldata(nonce: u64) -> Bytes { Bytes::from(U256::from(nonce + 1).to_be_bytes::<32>()) } +/// The `index`-th account of the run of accounts that starts at `base`. +fn nth_account(base: u64, index: u64) -> Address { + Address::from_word(B256::from(U256::from(base + index))) +} + +/// The slot of the token's `balanceOf` mapping, its first, that holds `owner`'s balance. +fn token_balance_slot(owner: Address) -> U256 { + let mut word = [0_u8; 64]; + word[12..32].copy_from_slice(owner.as_slice()); + U256::from_be_bytes(keccak256(word).0) +} + +/// The calldata of `transfer(to, value)`. +fn token_transfer_calldata(to: Address, value: u64) -> Bytes { + let mut data = Vec::with_capacity(68); + data.extend_from_slice(&hex!("a9059cbb")); + data.extend_from_slice(&to.into_word().0); + data.extend_from_slice(&U256::from(value).to_be_bytes::<32>()); + Bytes::from(data) +} + /// The accounts the workloads use, the EIP-2935 and EIP-4788 contracts' code, and the seven -/// predeploys as a chain that ran Rex6 holds them. +/// predeploys as a chain that ran Rex6 holds them. Every ERC-20 sender holds ether and tokens, +/// and every ERC-20 recipient holds tokens already, so no transfer adds a slot. fn database() -> MemoryDatabase { let mut db = MemoryDatabase::default().rex6_predeploys(MEGA_SYSTEM_ADDRESS); db.set_account_code(WRITER, writer_code()); db.set_account_code(RECIPIENT, Bytes::new()); db.set_account_balance(SENDER, U256::from(1_000_000_000_000_000_u64)); + db.set_account_code(TOKEN, Bytes::from_static(&TOKEN_CODE)); + for index in 0..N { + let sender = nth_account(TOKEN_SENDER_BASE, index); + db.set_account_balance(sender, U256::from(1_000_000_000_000_000_u64)); + db.set_account_storage(TOKEN, token_balance_slot(sender), U256::from(1_000_000_u64)); + let holder = nth_account(TOKEN_HOLDER_BASE, index); + db.set_account_storage(TOKEN, token_balance_slot(holder), U256::from(1_u64)); + } db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); db @@ -135,27 +179,46 @@ fn block_ctx() -> MegaBlockExecutionCtx { ) } -/// `N` transactions to `to`, one per nonce, each carrying the input `input` builds for it. +/// A legacy call from `sender` at `nonce` to `to`, carrying `value` and `input`. +fn transaction( + sender: Address, + nonce: u64, + to: Address, + value: u64, + gas_limit: u64, + input: Bytes, +) -> Recovered { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: 0, + gas_limit, + to: TxKind::Call(to), + value: U256::from(value), + input, + }; + let signed = Signed::new_unchecked(tx, Signature::test_signature(), B256::repeat_byte(1)); + Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), sender) +} + +/// `N` transactions from `SENDER` to `to`, one per nonce, each carrying the input `input` builds +/// for it. fn transactions( to: Address, value: u64, gas_limit: u64, input: impl Fn(u64) -> Bytes, ) -> Vec> { + (0..N).map(|nonce| transaction(SENDER, nonce, to, value, gas_limit, input(nonce))).collect() +} + +/// `N` ERC-20 transfers of one token, the `i`-th from the `i`-th sender to the `i`-th holder. +fn token_transfers() -> Vec> { (0..N) - .map(|nonce| { - let tx = TxLegacy { - chain_id: Some(CHAIN_ID), - nonce, - gas_price: 0, - gas_limit, - to: TxKind::Call(to), - value: U256::from(value), - input: input(nonce), - }; - let signed = - Signed::new_unchecked(tx, Signature::test_signature(), B256::repeat_byte(1)); - Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), SENDER) + .map(|index| { + let sender = nth_account(TOKEN_SENDER_BASE, index); + let input = token_transfer_calldata(nth_account(TOKEN_HOLDER_BASE, index), 1); + transaction(sender, 0, TOKEN, 0, 300_000, input) }) .collect() } @@ -226,15 +289,18 @@ fn bench_block(c: &mut Criterion) { // Checked once before measurement, so a block that is not a steady one is not measured as one. assert_steady_pre_block(&steady); + // Each workload with the write records each of its transactions keeps. let workloads = [ - // Both budgets clear the state gas the Satin gas table charges: a transfer to an account + // The budgets clear the state gas the Satin gas table charges: a transfer to an account // that does not exist yet pays for the new account, a storage write pays for the slot. - ("transfers", transactions(RECIPIENT, 1, 300_000, |_| Bytes::new())), - ("storage_writes", transactions(WRITER, 0, 300_000, slot_calldata)), + ("transfers", transactions(RECIPIENT, 1, 300_000, |_| Bytes::new()), 1), + ("storage_writes", transactions(WRITER, 0, 300_000, slot_calldata), 1), + // The sender's balance and the recipient's. + ("erc20_transfers", token_transfers(), 2), ]; let mut group = c.benchmark_group("block"); - for (name, txs) in &workloads { + for (name, txs, records) in &workloads { // The workload runs once outside the measurement, so a block that does not execute — or // one whose transactions keep nothing — is caught here rather than being measured. { @@ -248,16 +314,16 @@ fn bench_block(c: &mut Criterion) { executor.execute_transaction_without_commit(tx).expect("the transaction runs"); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "no limit stops the workload"); - assert!( - outcome.usage.write_records > 0, - "every transaction of the workload keeps a write record" + assert_eq!( + outcome.usage.write_records, *records, + "every transaction of the workload keeps its write records" ); executor.commit_transaction(outcome); } let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), N as usize); assert!(result.gas.execution > 0); - assert_eq!(result.usage.write_records, N, "one record per transaction, at least"); + assert_eq!(result.usage.write_records, N * records); } group.bench_function(*name, |b| { diff --git a/crates/mega-evm/benches/contracts/Token.sol b/crates/mega-evm/benches/contracts/Token.sol new file mode 100644 index 000000000..92222ad69 --- /dev/null +++ b/crates/mega-evm/benches/contracts/Token.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +/// A minimal ERC-20 transfer path for `benches/block.rs`: two balance reads, two balance writes +/// and one `Transfer` log, the shape of OpenZeppelin's `_update` without allowances or hooks. +/// +/// The bench embeds the runtime code this source compiles to: +/// +/// solc --optimize --optimize-runs 200 --metadata-hash none --bin-runtime Token.sol +/// +/// with solc 0.8.30. Without a metadata hash the output does not depend on the source's path. +contract Token { + mapping(address => uint256) public balanceOf; + + event Transfer(address indexed from, address indexed to, uint256 value); + + function transfer(address to, uint256 value) external returns (bool) { + uint256 balance = balanceOf[msg.sender]; + require(balance >= value, "balance"); + unchecked { + balanceOf[msg.sender] = balance - value; + } + balanceOf[to] += value; + emit Transfer(msg.sender, to, value); + return true; + } +} From 7e2e83f4b8fa1184be91b1b5c44d10fae865b3c3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:19:43 +0800 Subject: [PATCH 25/83] feat(state-test): print what each transaction and block read below the journal --json-witness prints, beside each digest line, the Keccak-256 of the canonical record of everything a transaction read below the journal: the accounts, codes, slots and block hashes the database served and the SALT buckets and Oracle slots the external environment answered, recorded by the witness recorder around the database and environments the test runs on. btest --json-witness prints the same per imported block. A change that keeps every outcome and reads other state now moves a line a run can compare; the digest lines are unchanged, and one pass prints both. --- .claude/skills/satin-review/SKILL.md | 3 +- AGENTS.md | 2 + crates/mega-state-test/README.md | 19 ++ .../mega-state-test/src/blockchain/chain.rs | 93 +++++++--- crates/mega-state-test/src/blockchain/mod.rs | 56 +++++- crates/mega-state-test/src/digest.rs | 172 +++++++++++++++++- crates/mega-state-test/src/runner.rs | 105 +++++++++-- crates/mega-state-test/tests/blockchain.rs | 2 +- crates/mega-state-test/tests/runner.rs | 32 ++++ crates/state-test/README.md | 4 + crates/state-test/src/btest.rs | 16 +- crates/state-test/src/main.rs | 26 ++- crates/state-test/tests/cli.rs | 144 +++++++++++++++ 13 files changed, 622 insertions(+), 52 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 4d075ae73..119d0467c 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -179,6 +179,7 @@ Four notes that are easy to miss: Evidence that a change alters no result: `state-test --json-digest` at two commits, detached, over both fixture releases, in equivalence mode, in Satin mode and in Satin mode under tighter limits (the `--limit-*` options), each sorted and compared byte for byte, plus the gates and the byte-price grid. The digest hashes each transaction's whole outcome, its gas by ledger and its usage counts included, so it catches a shift between ledgers that `--json-outcome` does not. +`--json-witness` (and `state-test btest --json-witness`, per block) adds the hash of what each transaction read below the journal, so a change that keeps every outcome and reads other state — a code, a block hash, a SALT bucket, an account a rejected transaction loads — is caught too; it prints in the same pass as the digest, whose lines it leaves unchanged. A golden or snapshot changes only for a stated reason: regenerate it and read the diff. ## Reading order @@ -365,7 +366,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **Check:** - No consensus path changed for a tool's sake; tool overrides (`--override.limits`, `with_tx_runtime_limits`, `with_protocol_limits` under `test-utils`) are explicit and never default. - A limits file of the first shape, without the KV-update and state-growth fields, reads with the default spec's values for them; every other field stays required, and an unknown one is refused. - - `state-test --json-digest` hashes each transaction's whole outcome, and the `--limit-*` options run Satin mode under tighter limits in each dimension. + - `state-test --json-digest` hashes each transaction's whole outcome, `--json-witness` what it read below the journal (and `btest --json-witness` what each block read), and the `--limit-*` options run Satin mode under tighter limits in each dimension. - A test pins a spec rule, not the implementation; a new or changed test says which rule it checks (some headers carry a `[S
.]` tag: the spec section and item). - A figure the schedule determines is asserted against its derivation, not pinned; snapshots and goldens own only outputs with no computable expectation. - The limit matrix (`tests/satin/limit_matrix/`) runs every row, none of them ignored. diff --git a/AGENTS.md b/AGENTS.md index 23a800d8a..77d19b333 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,8 @@ MEGA_STATE_TEST_FIXTURES=$PWD//state_tests MEGA_STATE_TEST_SAMPLE MEGA_STATE_TEST_MODE=satin cargo test --release -p mega-state-test --test witness -- --ignored --nocapture # The whole-outcome digest: one line per executed transaction (the canonical record of its MegaTransactionOutcome, hashed; `-full` adds the record), for a base-against-head `sort | cmp` cargo run --release -p state-test -- --mode satin --fork Osaka /state_tests --json-digest 2>&1 >/dev/null | grep '^{' | sort > head.digest +# The read-set digest beside it, in the same pass: one more line per transaction, the hash of the canonical record of what it read below the journal (`-full` adds the record); `btest --json-witness` prints one per block +cargo run --release -p state-test -- --mode satin --fork Osaka /state_tests --json-digest --json-witness 2>&1 >/dev/null | grep '^{' | sort > head.both # Regenerate the rendered deviation registry after changing crates/mega-state-test/src/deviations.rs UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index 9dffdb534..b97af158f 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -69,6 +69,22 @@ The record holds the status with its halt or revert reason, the output, the crea It is canonical: JSON with every object's keys sorted, 256-bit numbers as lowercase hex without leading zeros, hashes and addresses at full width, maps sorted by key, so it depends on neither a thread count nor a hash map's order. It is taken from the outcome as the engine produced it, before the runner takes the base-fee vault the fee routing created back out of the state. +## The read-set digest + +An outcome says nothing of what a transaction read on its way to it, so a change that keeps every outcome and reads other state — a code it no longer loads, a block hash, a SALT bucket it now asks for, an account a rejected transaction no longer loads — moves no digest, and changes the witness a stateless validator must be given. +`--json-witness` prints, per executed transaction, a second JSON line beside the digest's, with the same identity fields, the Keccak-256 of the canonical record of what the transaction read below the journal (`witness`) and `row`; `--json-witness-full` adds the record (`reads`). +It prints for the same tests the digest does, and a run that asks for both prints both lines in one pass, the digest's unchanged, so a comparison of two revisions runs the corpus once. + +The record (`digest::reads`, in the digest's encoding) is what a database and environments around the ones the test runs on recorded, answering as those do (`test_utils::RecordingDatabase`, `RecordingEnvFactory`): every account the database answered, with its balance, nonce and code hash or nothing for one it does not hold; every code loaded, by hash; every storage slot, with its value; every block hash; every SALT bucket the environment answered, with its capacity or its error; and every Oracle read, in the order it was made. +A key read twice is listed once, in key order; the Oracle reads keep their order, which a replay answers them in. +The recording database serves code by hash, as a node's database does, so a code is in the record only where the engine loaded it. +What the journal held already, and what the runner reads itself to judge the test, are no reads of the transaction's. +The hints the Oracle service received are not reads and are not in it. +A test that panicked prints `row` `panic`, with what it read before the panic. + +`state-test btest --json-witness` prints the same record per imported block, with the test, the block's position (`block`) and whether the executor accepted it (`row`, `accepted` or `refused`): what the pre-block steps, the transactions and the end of the block read. +The import is judged as it is without it. + ## Tightened limits Satin mode holds each transaction to the spec's limits, which the corpus rarely reaches. @@ -81,6 +97,9 @@ To compare two revisions, run the same command at both, keep the lines that star ```bash state-test --mode satin --fork Osaka
/state_tests --json-digest 2>&1 >/dev/null | grep '^{' | sort > head.digest +# The digest and the read set in one pass, split by the field each line carries. +state-test --mode satin --fork Osaka
/state_tests --json-digest --json-witness 2>&1 >/dev/null | grep '^{' | sort > head.both +grep '"digest":' head.both > head.digest; grep '"witness":' head.both > head.witness ``` ## Blockchain tests diff --git a/crates/mega-state-test/src/blockchain/chain.rs b/crates/mega-state-test/src/blockchain/chain.rs index 304f4d636..2ab2410d1 100644 --- a/crates/mega-state-test/src/blockchain/chain.rs +++ b/crates/mega-state-test/src/blockchain/chain.rs @@ -26,7 +26,10 @@ use std::collections::{BTreeMap, BTreeSet}; use mega_evm::{ alloy_consensus::transaction::{Recovered, SignerRecoverable}, - alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}, + alloy_evm::{ + block::{BlockExecutionError, BlockExecutor, BlockValidationError}, + Database, + }, alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder, alloy_primitives::Bloom, op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, @@ -34,17 +37,22 @@ use mega_evm::{ bytecode::Bytecode, context::BlockEnv, database::{CacheState, PlainAccount, State}, + inspector::NoOpInspector, primitives::{keccak256, Address, B256, KECCAK_EMPTY, U256}, state::AccountInfo, + DatabaseCommit, }, system::{ keyless::KEYLESS_DEPLOY_ADDRESS, ACCESS_CONTROL_ADDRESS, CREATE2_FACTORY_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, LIMIT_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, }, - test_utils::{rex6_predeploys, SequencerRegistryRoles}, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaHardforkConfig, MegaHardforks, - ProtocolLimits, + test_utils::{ + rex6_predeploys, RecordingDatabase, RecordingEnvFactory, SequencerRegistryRoles, + SharedWitnessRecord, + }, + BlockLimits, EmptyExternalEnv, ExternalEnvFactory, ExternalEnvTypes, MegaBlockExecutionCtx, + MegaBlockExecutor, MegaEvm, MegaHardforkConfig, MegaHardforks, ProtocolLimits, }; use super::fixture::DecodedBlock; @@ -369,13 +377,63 @@ impl Chain { /// Imports `block`: runs it through the executor on a copy of the chain's state, and, when the /// executor accepts it, makes it the head and answers what it produced. A refused block leaves /// the chain as it was. - pub(crate) fn import(&mut self, block: &DecodedBlock) -> Result { + /// + /// With `reads`, the block runs on a database and environments around the state and the + /// default environments that record into it what the block read below the journal, and answer + /// as those do. + pub(crate) fn import( + &mut self, + block: &DecodedBlock, + reads: Option<&SharedWitnessRecord>, + ) -> Result { let header = &block.header; let mut state = State::builder().with_cached_prestate(self.state.clone()).build(); let window = header.number.saturating_sub(BLOCK_HASH_WINDOW); state.block_hashes.extend(self.hashes.range(window..).map(|(n, hash)| (*n, *hash))); - let evm = Mode::Equivalence.evm(FORK, &mut state, self.block_env(block), self.chain_id); + let env = self.block_env(block); + let (gas_used, receipts, bloom) = match reads { + None => { + self.execute(Mode::Equivalence.evm(FORK, &mut state, env, self.chain_id), block) + } + Some(reads) => { + let factory = RecordingEnvFactory::new(EmptyExternalEnv, reads.clone()); + let envs = factory.external_envs(header.number); + let db = RecordingDatabase::new(&mut state, reads.clone()); + self.execute( + Mode::Equivalence.evm_with_envs(FORK, db, env, self.chain_id, envs), + block, + ) + } + }?; + + let routed_base_fee = self.routed_base_fee + + U256::from(header.base_fee_per_gas.unwrap_or_default()) * U256::from(gas_used); + self.state = state.cache; + self.routed_base_fee = routed_base_fee; + self.head = header.hash_slow(); + self.head_timestamp = header.timestamp; + self.hashes.insert(header.number, self.head); + Ok(BlockOutput { + gas_used, + receipts_root: receipts, + logs_bloom: bloom, + state_root: self.state_root(), + }) + } + + /// Runs `block` through the executor on `evm`: its gas used, receipts root and logs bloom, or + /// the refusal. + fn execute( + &self, + evm: MegaEvm, + block: &DecodedBlock, + ) -> Result<(u64, B256, Bloom), Refusal> + where + DB: Database + DatabaseCommit, + E: ExternalEnvTypes, + { + let header = &block.header; let only_deposits = self.spec.admits_only_deposits(self.head_timestamp, header.timestamp); let activates_satin = self.spec.is_satin_activation_block(self.head_timestamp, header.timestamp); @@ -399,20 +457,7 @@ impl Chain { executor.execute_transaction(&Recovered::new_unchecked(tx, signer)).map_err(refusal)?; } let (_, result) = executor.finish().map_err(refusal)?; - - let routed_base_fee = self.routed_base_fee + - U256::from(header.base_fee_per_gas.unwrap_or_default()) * U256::from(result.gas_used); - self.state = state.cache; - self.routed_base_fee = routed_base_fee; - self.head = header.hash_slow(); - self.head_timestamp = header.timestamp; - self.hashes.insert(header.number, self.head); - Ok(BlockOutput { - gas_used: result.gas_used, - receipts_root: receipts_root(&result.receipts), - logs_bloom: logs_bloom(&result.receipts), - state_root: self.state_root(), - }) + Ok((result.gas_used, receipts_root(&result.receipts), logs_bloom(&result.receipts))) } } @@ -522,15 +567,17 @@ mod tests { let mut chain = Chain::new(&pre, (0, B256::ZERO), ACTIVATION - 1, 1, 5_007_716).unwrap(); chain.spec = satin_at_activation; let refusal = chain - .import(&block(1, ACTIVATION, vec![tx.clone()])) + .import(&block(1, ACTIVATION, vec![tx.clone()]), None) .expect_err("a user transaction in Satin's activation block"); assert!( refusal.detail.contains("non-deposit transaction in fork activation block"), "{}", refusal.detail ); - chain.import(&block(1, ACTIVATION, vec![])).expect("the activation block, without it"); - chain.import(&block(2, ACTIVATION + 1, vec![tx])).expect("the block after admits it"); + chain + .import(&block(1, ACTIVATION, vec![]), None) + .expect("the activation block, without it"); + chain.import(&block(2, ACTIVATION + 1, vec![tx]), None).expect("the block after admits it"); assert!( !chain_spec().admits_only_deposits(0, u64::MAX), diff --git a/crates/mega-state-test/src/blockchain/mod.rs b/crates/mega-state-test/src/blockchain/mod.rs index 3ff405710..2a52cfa1e 100644 --- a/crates/mega-state-test/src/blockchain/mod.rs +++ b/crates/mega-state-test/src/blockchain/mod.rs @@ -28,6 +28,10 @@ //! anything runs, or failed; [`Report::gate`] fails on a failed test. The summary counts the //! blocks checked against Ethereum apart from the blocks matched to a deviation. //! +//! A run can print, for every block it imports, the digest of what the block read below the +//! journal ([`Config::witness`]), the same record the state tests print per transaction +//! ([`digest::reads`](crate::digest::reads)). +//! //! The devnet release's blockchain tests are not run: the revm fork's own runner skips them too. mod chain; @@ -50,6 +54,7 @@ pub use fixture::NETWORK; use mega_evm::{ alloy_consensus::Header, revm::primitives::{keccak256, B256}, + test_utils::{SharedWitnessRecord, WitnessRecord}, }; use serde::Serialize; pub use skips::SkipReason; @@ -60,7 +65,9 @@ use self::{ }; use crate::{ deviations::{self, BlockchainEntry, Cause, ChainEnd, Deviation}, + digest, exceptions::{check_names, Mismatch}, + runner::DigestForm, }; /// How a run executes its fixtures. @@ -70,6 +77,11 @@ pub struct Config { pub threads: usize, /// Print one JSON line per test to standard error. pub json_outcome: bool, + /// Print the digest of what every imported block read below the journal to standard error, + /// in this form: the database's and the external environment's reads + /// ([`digest::reads`](crate::digest::reads)), recorded by a database and environments around + /// the ones the block runs on, which answer as those do. + pub witness: Option, /// The registry whose entries explain blocks that differ: /// [`deviations::DEVIATIONS`](crate::deviations::DEVIATIONS) for the gate. pub deviations: &'static [Deviation], @@ -502,7 +514,9 @@ pub fn run_file(path: &Path, config: Config) -> Result, Failure> let id = TestId { path: path_str.clone(), name: name.clone() }; let (outcome, blocks) = match serde_json::from_str::(raw.get()) { Ok(test) => catch_unwind(AssertUnwindSafe(|| { - run_test(&id, &test, deviations::blockchain_entry(config.deviations, &id)) + let witness = config.witness.map(|form| (form, &id)); + let listed = deviations::blockchain_entry(config.deviations, &id); + run_test(&id, &test, listed, witness) })) .unwrap_or_else(|panic| { let failure = Failure::new(FailureKind::Panic, None, panic_message(&panic)); @@ -534,18 +548,45 @@ fn print_outcome(id: &TestId, outcome: &Outcome) { eprintln!("{line}"); } +/// Prints the read-set line of the block at `index` of the test `id` to standard error: the test, +/// the block's position, whether the executor `accepted` it, and the hash of the canonical record +/// of what it read ([`digest::reads`](crate::digest::reads)); the full form carries the record +/// too. +fn print_witness( + id: &TestId, + index: usize, + accepted: bool, + form: DigestForm, + record: &WitnessRecord, +) { + let reads = digest::reads(record); + let mut line = serde_json::json!({ + "path": id.path, + "test": id.name, + "block": index, + "witness": digest::hash(&reads), + "row": if accepted { "accepted" } else { "refused" }, + }); + if form == DigestForm::Full { + line["reads"] = reads; + } + eprintln!("{line}"); +} + /// Imports the test `id` and judges it against its fixture and the entry `listed`, the deviation -/// that lists it and its entry for it, unless it is skipped. +/// that lists it and its entry for it, unless it is skipped; with `witness`, printing what each +/// block read in that form. fn run_test( id: &TestId, test: &Test, listed: Option<(&'static Deviation, &'static BlockchainEntry)>, + witness: Option<(DigestForm, &TestId)>, ) -> (Outcome, Blocks) { if let Some(reason) = skips::skip_test(&id.path, &id.name, test) { return (Outcome::Skipped { reason }, Blocks::default()); } let mut blocks = Blocks::default(); - let outcome = match import_test(test, listed.map(|(_, entry)| entry), &mut blocks) { + let outcome = match import_test(test, listed.map(|(_, entry)| entry), &mut blocks, witness) { Ok(()) => match listed { Some((deviation, _)) => Outcome::Deviated { deviation: deviation.id }, None => Outcome::Passed, @@ -659,10 +700,12 @@ fn with_differing(mut failure: Failure, differing: &[Differing]) -> Failure { /// the outcome Satin produced and a cause that holds; the chain is imported on from Satin's own /// state either way, so a failure names every block that differs, not only the first. A refusal /// the fixture does not expect, or a block it expects refused that is accepted, stops the test. +/// With `witness`, each block's reads are recorded and printed once it is imported or refused. fn import_test( test: &Test, entry: Option<&'static BlockchainEntry>, blocks: &mut Blocks, + witness: Option<(DigestForm, &TestId)>, ) -> Result<(), Failure> { let fixture = |detail: String| Failure::new(FailureKind::Fixture, None, detail); let chain_id = u64::try_from(test.config.chainid) @@ -700,7 +743,12 @@ fn import_test( with_differing(failure, &differing) })?; let header = &decoded.header; - match (&block.expect_exception, chain.import(&decoded)) { + let reads = witness.map(|_| SharedWitnessRecord::default()); + let imported = chain.import(&decoded, reads.as_ref()); + if let (Some((form, id)), Some(reads)) = (witness, &reads) { + print_witness(id, index, imported.is_ok(), form, &reads.borrow()); + } + match (&block.expect_exception, imported) { (None, Ok(output)) => { let differences = Differences::of(header, &output); on_fixture_state = !differences.state_root; diff --git a/crates/mega-state-test/src/digest.rs b/crates/mega-state-test/src/digest.rs index 252c54f25..606050efe 100644 --- a/crates/mega-state-test/src/digest.rs +++ b/crates/mega-state-test/src/digest.rs @@ -15,6 +15,15 @@ //! The one place that renders a type through `Debug` is a halt or success reason and a rejected //! transaction's error, whose names are the types' own; a dependency changing those names moves //! the digest of the transactions that end that way, and the full form shows it. +//! +//! The outcome says nothing of what a transaction read on its way to it. A change that keeps every +//! outcome and reads other state — a code it no longer loads, a block hash, a SALT bucket it now +//! asks for, an account a rejected transaction no longer loads — moves no digest, and changes the +//! witness a stateless validator must be given. [`reads`] is the record of what the engine read +//! below its journal, in the same encoding: every account, code, storage slot and block hash the +//! database served, with the answers, every SALT bucket and Oracle slot the external environment +//! answered, as a recording database and environment collect them ([`WitnessRecord`]). Its hash is +//! the read-set digest two runs are compared by, as they are by the outcome's. use std::collections::BTreeMap; @@ -22,8 +31,9 @@ use mega_evm::{ revm::{ context::result::{ExecutionResult, ResultGas}, primitives::{keccak256, Address, Log, B256, U256}, - state::{Account, EvmState}, + state::{Account, AccountInfo, EvmState}, }, + test_utils::WitnessRecord, LimitCheck, LimitUsage, MegaGasUsage, MegaHaltReason, MegaTransactionOutcome, OracleRead, }; use serde_json::{Map, Value}; @@ -213,6 +223,68 @@ pub fn panicked(message: &str) -> Value { fields([("panic", message.into())]) } +/// What the database answered for an account: its balance, code hash and nonce, or nothing for +/// one it does not hold. The code itself is read by hash, and is in the record's codes. +fn account_answer(info: Option<&AccountInfo>) -> Value { + info.map_or(Value::Null, |info| { + fields([ + ("balance", number(info.balance)), + ("code_hash", hex(info.code_hash)), + ("nonce", info.nonce.into()), + ]) + }) +} + +/// The canonical record of what the engine read below its journal: the database's accounts, +/// codes, storage slots and block hashes, with the answers it served, and the external +/// environment's SALT buckets and Oracle slots, with its answers. A key read twice is listed +/// once, every list but the Oracle reads in key order; the Oracle reads keep the order they were +/// made in, which a replay answers them in. The hints the Oracle service received are not reads, +/// and are not in it: the outcome's data size counts them. +pub fn reads(record: &WitnessRecord) -> Value { + let WitnessRecord { accounts, storage, codes, block_hashes, buckets, oracle_reads, hints: _ } = + record; + let mut slots: BTreeMap> = BTreeMap::new(); + for ((owner, key), value) in storage { + slots.entry(address(owner)).or_default().insert(format!("{key:#066x}"), number(*value)); + } + fields([ + ( + "accounts", + object( + accounts.iter().map(|(addr, info)| (address(addr), account_answer(info.as_ref()))), + ), + ), + ( + "block_hashes", + Value::Array( + block_hashes + .iter() + .map(|(block, hash)| fields([("hash", hex(hash)), ("number", (*block).into())])) + .collect(), + ), + ), + ( + "buckets", + Value::Array( + buckets + .iter() + .map(|(bucket, answer)| { + let answer = match answer { + Ok(capacity) => fields([("capacity", (*capacity).into())]), + Err(error) => fields([("error", error.as_str().into())]), + }; + fields([("answer", answer), ("bucket", (*bucket).into())]) + }) + .collect(), + ), + ), + ("codes", Value::Array(codes.keys().map(hex).collect())), + ("oracle_reads", Value::Array(oracle_reads.iter().map(oracle_read).collect())), + ("storage", object(slots.into_iter().map(|(owner, slots)| (owner, object(slots))))), + ]) +} + /// The digest of a canonical record: the Keccak-256 of its JSON text. pub fn hash(canonical: &Value) -> B256 { keccak256(text(canonical)) @@ -355,4 +427,102 @@ mod tests { assert_ne!(rejected, digest(&outcome())); assert_ne!(rejected, hash(&panicked("nonce too low"))); } + + /// A record of one read on each channel: an account the database holds and one it does not, + /// a code, a slot, a block hash, a bucket it answered and one it failed, and an Oracle read. + fn record() -> WitnessRecord { + let mut record = WitnessRecord::default(); + record.accounts.insert( + Address::repeat_byte(0xaa), + Some(AccountInfo { nonce: 1, balance: U256::from(5), ..Default::default() }), + ); + record.accounts.insert(Address::repeat_byte(0x11), None); + record.codes.insert(B256::repeat_byte(0xc0), Default::default()); + record.storage.insert((Address::repeat_byte(0xaa), U256::from(1)), U256::from(7)); + record.block_hashes.insert(9, B256::repeat_byte(0x09)); + record.buckets.insert(3, Ok(256)); + record.buckets.insert(4, Err("unavailable".into())); + record.oracle_reads.push(OracleRead { slot: U256::from(2), answer: None }); + record + } + + fn read_digest(record: &WitnessRecord) -> B256 { + hash(&reads(record)) + } + + /// The record lists its channels and each channel's keys in sorted order, and keeps the order + /// of the Oracle reads, which a replay answers in order. + #[test] + fn test_the_read_set_lists_keys_in_order_and_keeps_the_oracle_order() { + let text = text(&reads(&record())); + let markers = [ + "{\"accounts\":{\"0x1111", + ",\"0xaaaa", + "},\"block_hashes\":", + ",\"buckets\":[{\"answer\":{\"capacity\":256},\"bucket\":3}", + ",{\"answer\":{\"error\":\"unavailable\"},\"bucket\":4}", + ",\"codes\":", + ",\"oracle_reads\":", + ",\"storage\":{\"0xaaaa", + ]; + let positions: Vec<_> = markers.iter().map(|m| text.find(m).expect(m)).collect(); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "{text}"); + + let mut two = record(); + two.oracle_reads.push(OracleRead { slot: U256::from(8), answer: Some(U256::ONE) }); + let mut swapped = two.clone(); + swapped.oracle_reads.swap(0, 1); + assert_ne!(read_digest(&two), read_digest(&swapped)); + } + + /// One more read on any channel moves the record's digest: an account, absent or held, a + /// code, a slot, a block hash, a bucket and an Oracle read. + #[test] + fn test_one_more_read_moves_the_read_set() { + let base = read_digest(&record()); + let more: [fn(&mut WitnessRecord); 7] = [ + |r| { + r.accounts.insert(Address::repeat_byte(0x22), None); + }, + |r| { + r.accounts.insert(Address::repeat_byte(0x33), Some(AccountInfo::default())); + }, + |r| { + r.codes.insert(B256::repeat_byte(0xc1), Default::default()); + }, + |r| { + r.storage.insert((Address::repeat_byte(0xaa), U256::from(2)), U256::ZERO); + }, + |r| { + r.block_hashes.insert(10, B256::repeat_byte(0x0a)); + }, + |r| { + r.buckets.insert(5, Ok(256)); + }, + |r| r.oracle_reads.push(OracleRead { slot: U256::from(2), answer: None }), + ]; + for add in more { + let mut record = record(); + add(&mut record); + assert_ne!(read_digest(&record), base, "{}", text(&reads(&record))); + } + } + + /// What a source answered for a key, not only the key, is in the record. + #[test] + fn test_an_answer_alone_moves_the_read_set() { + let base = read_digest(&record()); + let mut balance = record(); + balance.accounts.get_mut(&Address::repeat_byte(0xaa)).unwrap().as_mut().unwrap().balance = + U256::from(6); + let mut slot = record(); + slot.storage.insert((Address::repeat_byte(0xaa), U256::from(1)), U256::from(8)); + let mut bucket = record(); + bucket.buckets.insert(3, Ok(512)); + let mut oracle = record(); + oracle.oracle_reads[0].answer = Some(U256::ZERO); + for moved in [balance, slot, bucket, oracle] { + assert_ne!(read_digest(&moved), base); + } + } } diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index 2dadd11af..f53ff005e 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -47,12 +47,14 @@ use mega_evm::{ BlockEnv, CfgEnv, }, database::{EmptyDB, State}, - inspector::{inspectors::TracerEip3155, Inspector}, + inspector::{inspectors::TracerEip3155, Inspector, NoOpInspector}, interpreter::interpreter::EthInterpreter, primitives::{Bytes, B256, KECCAK_EMPTY, U256}, DatabaseCommit, ExecuteCommitEvm, }, - EvmTxRuntimeLimits, MegaContext, MegaEvm, + test_utils::{RecordingDatabase, RecordingEnvFactory, SharedWitnessRecord}, + EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvFactory, ExternalEnvTypes, MegaContext, + MegaEvm, }; use serde::{ de::{Error as _, MapAccess, Visitor}, @@ -86,6 +88,11 @@ pub struct Config { pub trace: bool, /// Print the digest of every transaction's whole outcome to standard error, in this form. pub digest: Option, + /// Print the digest of what every transaction read below the journal to standard error, in + /// this form: the database's and the external environment's reads ([`digest::reads`]), + /// recorded by a database and environments around the ones the test runs on, which answer as + /// those do. + pub witness: Option, /// Satin mode: the per-transaction limits the tests run under instead of the spec's, to reach /// the limit-stop paths. Equivalence mode installs no limit and refuses these. pub limits: Option, @@ -94,7 +101,7 @@ pub struct Config { pub deviations: &'static [Deviation], } -/// How much of a transaction's digest a run prints. +/// How much of a transaction's digest, or of its read set's, a run prints. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DigestForm { /// The test's identity and the hash of the canonical record. @@ -517,22 +524,29 @@ pub fn run_file(path: &Path, config: Config) -> Result, Failure> indexes: (test.indexes.data, test.indexes.gas, test.indexes.value), }; let mut executed = None; + let reads = config.witness.map(|_| SharedWitnessRecord::default()); let outcome = match skip { Some(reason) => Outcome::Skipped { reason }, None => catch_unwind(AssertUnwindSafe(|| { - run_test(config, unit, test, &mut executed) + run_test(config, unit, test, &mut executed, reads.as_ref()) })) .unwrap_or_else(|panic| { let message = panic_message(&panic); if let Some(form) = config.digest { print_digest(config, form, &id, "panic", &digest::panicked(&message)); } + if let (Some(form), Some(reads)) = (config.witness, &reads) { + print_witness(config, form, &id, "panic", &reads.borrow()); + } Outcome::Failed(Failure::new(FailureKind::Panic, message)) }), }; if let (Some(form), Some(executed)) = (config.digest, &executed) { print_digest(config, form, &id, "outcome", executed); } + if let (Some(form), Some(reads), Some(_)) = (config.witness, &reads, &executed) { + print_witness(config, form, &id, "outcome", &reads.borrow()); + } let outcome = attribute(config, &id, outcome); if config.json_outcome { print_outcome(config, &id, &outcome); @@ -622,6 +636,36 @@ fn print_digest( eprintln!("{line}"); } +/// Prints the read-set line of a test to standard error, beside its digest line and for the same +/// tests: the compact form names the test and the hash of the canonical record of what it read +/// ([`digest::reads`]), the full form carries the record too. `row` is `outcome` for a +/// transaction that ended and `panic` for a test that panicked, whose record holds what it read +/// before the panic. +fn print_witness( + config: Config, + form: DigestForm, + id: &TestId, + row: &str, + record: &mega_evm::test_utils::WitnessRecord, +) { + let reads = digest::reads(record); + let mut line = serde_json::json!({ + "mode": config.mode, + "fork": config.fork, + "path": id.path, + "test": id.name, + "d": id.indexes.0, + "g": id.indexes.1, + "v": id.indexes.2, + "witness": digest::hash(&reads), + "row": row, + }); + if form == DigestForm::Full { + line["reads"] = reads; + } + eprintln!("{line}"); +} + fn print_outcome(config: Config, id: &TestId, outcome: &Outcome) { let line = serde_json::json!({ "mode": config.mode, @@ -649,13 +693,16 @@ pub(crate) fn chain_id(unit: &TestUnit) -> Result { /// /// `executed` receives the canonical record of what the transaction ended in as soon as it has /// ended, so a test that then fails its fixture, or panics while it is judged, still has one. +/// With `reads`, the transaction runs on a database and environments that record into it what it +/// read below the journal. fn run_test( config: Config, unit: &TestUnit, test: &Test, executed: &mut Option, + reads: Option<&SharedWitnessRecord>, ) -> Outcome { - match execute_and_check(config, unit, test, executed) { + match execute_and_check(config, unit, test, executed, reads) { Ok(None) => Outcome::Passed, Ok(Some(reason)) => Outcome::Skipped { reason }, Err(failure) => Outcome::Failed(failure), @@ -667,6 +714,7 @@ fn execute_and_check( unit: &TestUnit, test: &Test, executed: &mut Option, + reads: Option<&SharedWitnessRecord>, ) -> Result, Failure> { let Ready { chain_id, block, tx } = match prepare(config.fork, unit, test)? { Ok(ready) => ready, @@ -676,34 +724,61 @@ fn execute_and_check( let basefee = block.basefee; let mut state = State::builder().with_cached_prestate(unit.state()).with_bundle_update().build(); - let mut evm = config.mode.evm(config.fork, &mut state, block, chain_id); + let result = match reads { + None => { + let evm = config.mode.evm(config.fork, &mut state, block, chain_id); + execute(config, evm, tx, executed) + } + Some(reads) => { + let factory = RecordingEnvFactory::new(EmptyExternalEnv, reads.clone()); + let envs = factory.external_envs(block.number.saturating_to()); + let db = RecordingDatabase::new(&mut state, reads.clone()); + let evm = config.mode.evm_with_envs(config.fork, db, block, chain_id, envs); + execute(config, evm, tx, executed) + } + }; + if let Ok(result) = &result { + undo_fee_vault_credit(unit, &mut state, basefee, result.tx_gas_used()); + } + check(config.fork, test, unit.out.as_ref(), &result, &state)?; + Ok(None) +} + +/// Executes `tx` on `evm`, under the run's limits and tracer, and commits what it produced +/// ([`execute_and_commit`]). +fn execute( + config: Config, + mut evm: MegaEvm, + tx: OpTx, + executed: &mut Option, +) -> Result, EVMError> +where + DB: Database + DatabaseCommit, + E: ExternalEnvTypes, +{ if let Some(limits) = config.limits { evm.set_tx_runtime_limits(limits); } - let result = if config.trace { + if config.trace { let mut evm = evm.with_inspector(TracerEip3155::buffered(stderr()).without_summary()); execute_and_commit(&mut evm, tx, executed) } else { execute_and_commit(&mut evm, tx, executed) - }; - if let Ok(result) = &result { - undo_fee_vault_credit(unit, &mut state, basefee, result.tx_gas_used()); } - check(config.fork, test, unit.out.as_ref(), &result, &state)?; - Ok(None) } /// Executes `tx` on `evm` and commits what it produced, as `transact_commit` does, keeping the /// transaction's whole outcome: its canonical record goes to `executed`, and the result is what /// the fixture is judged on. -fn execute_and_commit( - evm: &mut MegaEvm, +fn execute_and_commit( + evm: &mut MegaEvm, tx: OpTx, executed: &mut Option, ) -> Result, EVMError> where DB: Database + DatabaseCommit, - INSP: Inspector, EthInterpreter>, + INSP: Inspector, EthInterpreter>, + E: ExternalEnvTypes, { match evm.execute_transaction(tx) { Ok(outcome) => { diff --git a/crates/mega-state-test/tests/blockchain.rs b/crates/mega-state-test/tests/blockchain.rs index 65e25d4d3..c46a66133 100644 --- a/crates/mega-state-test/tests/blockchain.rs +++ b/crates/mega-state-test/tests/blockchain.rs @@ -328,7 +328,7 @@ fn write(dir: &Path, relative: &str, tests: Value) -> PathBuf { } fn config(deviations: &'static [Deviation]) -> Config { - Config { threads: 2, json_outcome: false, deviations } + Config { threads: 2, json_outcome: false, witness: None, deviations } } fn run_one(test: Value) -> Report { diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index f94235984..874234f57 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -38,6 +38,7 @@ fn config(mode: Mode, fork: Fork) -> Config { json_outcome: false, trace: false, digest: None, + witness: None, limits: None, deviations: DEVIATIONS, } @@ -546,6 +547,37 @@ fn test_the_digest_is_stable_across_runs_and_thread_counts() { assert_eq!(hashes.len(), 6, "six distinct values, two files of each"); } +/// Recording what a run reads changes nothing it computes: with the read sets printed, every +/// test's record and verdict are the ones the run makes without them, in both modes, for +/// transactions that execute and one the engine rejects. +#[test] +fn test_recording_the_reads_changes_no_record_and_no_verdict() { + let dir = tempfile::tempdir().unwrap(); + let units: serde_json::Map<_, _> = (0..3) + .map(|n| { + let unit = unit( + &[Fork::Osaka], + json!({ "gasLimit": ["0x0f4240"], "value": [format!("0x{n:02x}")] }), + ); + (format!("call_{n}"), fill_from_ethereum(unit)) + }) + .chain([( + "rejected".to_string(), + fill_from_ethereum(unit(&[Fork::Osaka], json!({ "gasLimit": ["0x5208"] }))), + )]) + .collect(); + let path = write(dir.path(), "a.json", units.into()); + for mode in Mode::ALL { + let plain = run(std::slice::from_ref(&path), config(mode, Fork::Osaka)); + let witness = Some(state_test::runner::DigestForm::Full); + let recorded = + run(std::slice::from_ref(&path), Config { witness, ..config(mode, Fork::Osaka) }); + assert_eq!(records(&plain), records(&recorded), "{mode}"); + assert_eq!(outcomes(&plain), outcomes(&recorded), "{mode}"); + assert!(records(&plain).iter().all(Option::is_some), "{mode}: every transaction ended"); + } +} + /// A test that fails its fixture still has the record of what ran, and a transaction the engine /// rejects has one that says so; a test skipped by its fixture has none. #[test] diff --git a/crates/state-test/README.md b/crates/state-test/README.md index b461230f3..78f2829ac 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -13,6 +13,9 @@ state-test [--mode equivalence|satin] --fork Osaka|Amsterdam [options] .. - `--json-digest` prints one JSON line per executed transaction on standard error: the test's identity and the hash of the canonical record of the transaction's whole Mega outcome. `--json-digest-full` adds the record itself to each line. The two make a whole-outcome differential: run both at two revisions, sort and compare (`sort | cmp`), and read the full lines of the ids that differ. +- `--json-witness` prints, beside each digest line and for the same tests, one JSON line with the test's identity and the hash of the canonical record of everything the transaction read below the journal: the database's accounts, codes, storage slots and block hashes, and the SALT buckets and Oracle slots the external environment answered. + `--json-witness-full` adds the record itself to each line. + It is the read-set differential: a change that keeps every outcome and reads other state moves it, and a run that asks for both the digest and the witness prints both in one pass, the digest lines unchanged. - `--limit-data-size BYTES`, `--limit-frame-data-size BYTES`, `--limit-kv-updates RECORDS`, `--limit-state-growth UNITS` and `--limit-compute-gas GAS` (Satin mode only) hold every transaction to tighter per-transaction limits than the spec's, so the limit-stop paths run across the corpus; the frame budget follows `--limit-data-size`. The verdicts of such a run are expected to fail; it is for comparing digests. - `--summary-json FILE` writes the counts as JSON, `--json-outcome` prints one JSON line per test on standard error, `--trace` runs every test under an EIP-3155 tracer and `--threads` sets the worker count. @@ -26,5 +29,6 @@ state-test btest [options] ... - It exits non-zero when a test fails — a block differs from its header without the exact outcome a registered deviation lists for it, or a listed test does not deviate as listed — when a fixture file cannot be read, or when a count differs from the pin it is given. - `--expect-executed N` pins the tests executed, `--expect-skipped REASON=N` the tests skipped for one reason (repeated for each; once one is given, every reason not given is pinned at zero), and `--expect-deviations` requires every blockchain test a registered deviation lists to deviate exactly as listed; CI passes all three. - `--summary-json FILE`, `--json-outcome` and `--threads` work as for the state tests; the summary gives each skip class's reason beside its count, and the JSON summary lists every class's reason under `skip_reasons`. +- `--json-witness` prints one JSON line per imported block on standard error: the test, the block's position, whether it was accepted or refused, and the hash of the canonical record of everything the block read below the journal; `--json-witness-full` adds the record. What the two modes are, how a state test and a blockchain test are judged and the deviation registry are described in the `mega-state-test` crate's `README.md` and `DEVIATIONS.md`. diff --git a/crates/state-test/src/btest.rs b/crates/state-test/src/btest.rs index 3db133df1..16ffa19e9 100644 --- a/crates/state-test/src/btest.rs +++ b/crates/state-test/src/btest.rs @@ -35,6 +35,14 @@ pub(crate) struct Cmd { /// Print one JSON line per test to standard error. #[arg(long)] json_outcome: bool, + /// Print one JSON line per imported block on standard error: the test, the block's position, + /// whether it was accepted, and the hash of the canonical record of everything the block read + /// below the journal. + #[arg(long)] + json_witness: bool, + /// As `--json-witness`, with the canonical record of the reads in each line. + #[arg(long)] + json_witness_full: bool, /// Write the summary, as JSON, to this file. #[arg(long, value_name = "FILE")] summary_json: Option, @@ -85,8 +93,12 @@ pub(crate) fn main(args: impl IntoIterator) -> ExitCo let threads = cmd.threads.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())); - let config = - Config { threads, json_outcome: cmd.json_outcome, deviations: deviations::DEVIATIONS }; + let config = Config { + threads, + json_outcome: cmd.json_outcome, + witness: crate::digest_form(cmd.json_witness, cmd.json_witness_full), + deviations: deviations::DEVIATIONS, + }; let report = run(&files, config); let summary = report.summary(); print_summary(&report, &summary); diff --git a/crates/state-test/src/main.rs b/crates/state-test/src/main.rs index a95facd70..de8bdec7e 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -55,6 +55,15 @@ struct Cmd { /// As `--json-digest`, with the canonical record in each line, to see which field differs. #[arg(long)] json_digest_full: bool, + /// Print one JSON line per executed transaction on standard error, beside its digest line when + /// both are asked for: the test's identity and the hash of the canonical record of everything + /// the transaction read below the journal (the database's accounts, codes, slots and block + /// hashes, and the SALT buckets and Oracle slots the external environment answered). + #[arg(long)] + json_witness: bool, + /// As `--json-witness`, with the canonical record of the reads in each line. + #[arg(long)] + json_witness_full: bool, /// Satin mode: hold every transaction to this data-size limit, in bytes, instead of the /// spec's; the frame budget follows it unless `--limit-frame-data-size` names one. #[arg(long, value_name = "BYTES")] @@ -127,11 +136,8 @@ fn main() -> ExitCode { return ExitCode::FAILURE; } }; - let digest = match (cmd.json_digest, cmd.json_digest_full) { - (_, true) => Some(DigestForm::Full), - (true, false) => Some(DigestForm::Compact), - (false, false) => None, - }; + let digest = digest_form(cmd.json_digest, cmd.json_digest_full); + let witness = digest_form(cmd.json_witness, cmd.json_witness_full); let config = Config { mode: cmd.mode, fork: cmd.fork, @@ -139,6 +145,7 @@ fn main() -> ExitCode { json_outcome: cmd.json_outcome, trace: cmd.trace, digest, + witness, limits, deviations: deviations::DEVIATIONS, }; @@ -177,6 +184,15 @@ fn main() -> ExitCode { } } +/// The form a compact and a full flag ask for: the full one when both are given. +pub(crate) const fn digest_form(compact: bool, full: bool) -> Option { + match (compact, full) { + (_, true) => Some(DigestForm::Full), + (true, false) => Some(DigestForm::Compact), + (false, false) => None, + } +} + /// The limits the `--limit-*` options name, over the spec's own, or none when no option is given. fn tightened_limits(cmd: &Cmd) -> Result, String> { if cmd.limit_data_size.is_none() && diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index 9d6fc4eab..c9d8521e6 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -187,6 +187,124 @@ fn test_the_digest_options_print_a_line_per_transaction() { assert!(full[0]["record"]["rejected"].is_string(), "the transaction is rejected"); } +/// The JSON lines of a run's standard error. +fn stderr_lines(output: &Output) -> Vec { + String::from_utf8_lossy(&output.stderr) + .lines() + .filter(|line| line.starts_with('{')) + .map(|line| serde_json::from_str(line).unwrap()) + .collect() +} + +/// The witness options print one line per executed transaction on standard error, as the digest +/// options do: the compact form the test and the hash of what it read, the full form the reads +/// too, and the same line twice. Asked for with the digest, both lines are printed in one run, and +/// the digest line is the one the digest options print alone. +#[test] +fn test_the_witness_options_print_a_line_per_transaction() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + let lines = |flags: &[&str]| -> Vec { + let mut args = flags.to_vec(); + args.extend(["--fork", "Osaka"]); + let output = state_test(&args, &path); + assert!(output.status.success(), "{}", stdout(&output)); + stderr_lines(&output) + }; + let compact = lines(&["--json-witness"]); + assert_eq!(compact.len(), 1); + assert_eq!(compact[0]["row"], "outcome"); + assert!(compact[0]["witness"].as_str().unwrap().starts_with("0x")); + assert!(compact[0].get("reads").is_none() && compact[0].get("digest").is_none()); + assert_eq!(compact, lines(&["--json-witness"])); + + let full = lines(&["--json-witness-full"]); + assert_eq!(full.len(), 1); + assert_eq!(full[0]["witness"], compact[0]["witness"]); + // A transaction rejected for its intrinsic gas read the live system address and nothing else: + // every transaction reads it first, from the `SequencerRegistry`, which the pre-state lacks. + let registry = "0x6342000000000000000000000000000000000006"; + let reads = &full[0]["reads"]; + assert_eq!(reads["accounts"], json!({ registry: null }), "{reads}"); + assert_eq!(reads["storage"][registry].as_object().map(|slots| slots.len()), Some(1)); + + let both = lines(&["--json-digest", "--json-witness"]); + assert_eq!(both, [lines(&["--json-digest"])[0].clone(), compact[0].clone()]); +} + +/// A state test whose transaction calls a contract that reads the hash of the block its calldata +/// names, `number`, and keeps nothing of it, with placeholder roots: Satin mode reports it whatever +/// they are. Any one-byte number costs the same calldata. +fn block_hash_fixture(dir: &Path, number: u8) -> PathBuf { + // PUSH0 CALLDATALOAD BLOCKHASH POP STOP + let code = "0x5f35405000"; + let data = format!("0x{number:064x}"); + let unit = json!({ + "env": { + "currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "currentGasLimit": "0x1000000", + "currentNumber": "0x10", + "currentTimestamp": "0x03e8", + "currentBaseFee": "0x07", + "currentRandom": "0x0000000000000000000000000000000000000000000000000000000000020000", + }, + "pre": { + "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": { + "balance": "0x3635c9adc5dea00000", "code": "0x", "nonce": "0x00", "storage": {} + }, + "0x00000000000000000000000000000000000c0de0": { + "balance": "0x00", "code": code, "nonce": "0x01", "storage": {} + }, + }, + "transaction": { + "data": [data], + "gasLimit": ["0x0f4240"], + "gasPrice": "0x0a", + "nonce": "0x00", + "secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "to": "0x00000000000000000000000000000000000c0de0", + "value": ["0x00"], + }, + "post": { "Osaka": [{ + "indexes": { "data": 0, "gas": 0, "value": 0 }, + "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "logs": "0x0000000000000000000000000000000000000000000000000000000000000000", + }]}, + }); + let path = dir.join(format!("block-hash-{number}.json")); + std::fs::write(&path, serde_json::to_string(&json!({ "t": unit })).unwrap()).unwrap(); + path +} + +/// Two transactions that read the hashes of two different blocks and keep nothing of them end in +/// the same outcome, so their digests are equal; what they read is not, and the witness tells +/// them apart, by the one block hash each read. +#[test] +fn test_the_witness_tells_apart_two_runs_the_digest_cannot() { + let dir = tempfile::tempdir().unwrap(); + let lines = |number: u8| -> Vec { + let path = block_hash_fixture(dir.path(), number); + let output = state_test( + &["--mode", "satin", "--fork", "Osaka", "--json-digest", "--json-witness-full"], + &path, + ); + assert!(output.status.success(), "{}", stdout(&output)); + stderr_lines(&output) + }; + let (one, two) = (lines(15), lines(14)); + assert_eq!(one.len(), 2); + assert_eq!(one[0]["digest"], two[0]["digest"], "the outcomes are the same"); + assert_ne!(one[1]["witness"], two[1]["witness"], "the reads are not"); + let number = + |lines: &[serde_json::Value]| lines[1]["reads"]["block_hashes"][0]["number"].clone(); + assert_eq!((number(&one), number(&two)), (json!(15), json!(14))); + let mut without_hashes = [one[1]["reads"].clone(), two[1]["reads"].clone()]; + for reads in &mut without_hashes { + reads["block_hashes"] = json!([]); + } + assert_eq!(without_hashes[0], without_hashes[1], "the block hash is the one read apart"); +} + /// The limit options tighten Satin mode's limits; equivalence mode holds none, so it refuses them. #[test] fn test_the_limit_options_need_satin_mode() { @@ -357,6 +475,32 @@ fn test_btest_an_unattributed_failure_fails_the_gate() { assert!(!help.contains("fails exactly as listed"), "{help}"); } +/// The witness options print one line per imported block, accepted or refused, with what it +/// read; the import is judged as without them. +#[test] +fn test_btest_the_witness_options_print_a_line_per_block() { + let dir = tempfile::tempdir().unwrap(); + let path = blockchain_fixture(dir.path(), "a", |_| {}); + let output = btest(&["--json-witness"], &path); + assert!(output.status.success(), "{}", stdout(&output)); + assert_eq!(stdout(&output), stdout(&btest(&[], &path))); + let compact = stderr_lines(&output); + assert_eq!(compact.len(), 1); + assert_eq!((&compact[0]["block"], &compact[0]["row"]), (&json!(0), &json!("accepted"))); + assert!(compact[0]["witness"].as_str().unwrap().starts_with("0x")); + assert!(compact[0].get("reads").is_none()); + + let full = stderr_lines(&btest(&["--json-witness-full"], &path)); + assert_eq!(full[0]["witness"], compact[0]["witness"]); + // The pre-block calls read the EIP-2935 history contract, which the pre-state does not hold. + let history = "0x0000f90827f1c53a10cb7a02335b175320002935"; + assert!(full[0]["reads"]["accounts"][history].is_null(), "{}", full[0]["reads"]); + + let refused = blockchain_fixture(dir.path(), "b", |header| header.gas_limit = 0); + let lines = stderr_lines(&btest(&["--json-witness"], &refused)); + assert!(lines.iter().all(|line| line["block"] == 0), "{lines:?}"); +} + #[test] fn test_btest_bad_arguments_exit_non_zero() { let dir = tempfile::tempdir().unwrap(); From e7fa266c25fcbd87cb4f38c0cb7024c33365cff8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:23:50 +0800 Subject: [PATCH 26/83] perf(evm): price the first frame's write record once Pre-execution charges the history of the write record the transaction's own frame makes, and the frame's input carried the same charge priced a second time on the same journal. The charge is now kept on the layer from pre-execution, which already computes it, and taken once by the frame's input; nothing between the two changes the journal it is priced on. This stores a value the cleanup had replaced by a recomputation, on the measured cost of that recomputation: about 550 instructions on every value-transfer transaction, against nothing on any other. A debug build prices it again at the input and asserts the two agree, and a system call, which skips pre-execution and finds no kept charge, is priced at its input as before. --- .claude/skills/satin-review/SKILL.md | 5 +++ crates/mega-evm/src/evm/execution.rs | 52 ++++++++++++++++++---------- crates/mega-evm/src/limit/limit.rs | 36 +++++++++++++++++++ 3 files changed, 74 insertions(+), 19 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 119d0467c..1540696c6 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -134,6 +134,11 @@ Each change is stated here in plain words with its reason; the specification has Each runs on `PRE_BLOCK_CALL_GAS_LIMIT` = 31,566,720, whatever the block's gas limit: 30,000,000 of regular gas and a reservoir of sixteen fresh slots at the minimum bucket. Why: a pre-block call does not draw on the block's gas; Rex6's `max(block gas limit, 30,000,000)` was widened for storage gas a crowded bucket multiplied, which a system call no longer pays; a pre-block call on MegaETH's chains writes at most six fresh slots, and none of the three contracts reads `GAS`. +- **The first frame's record is priced once.** + Made after #407 merged: the history gas pre-execution charges for the write record the transaction's own frame makes is kept on the layer (`AdditionalLimit::keep_first_frame_charge`) and taken by the frame's input as its start charge, where it used to be priced a second time on the same journal. + A debug build prices it again at the input and asserts the two agree; a system call, which skips pre-execution, is priced at its input as before. + Why: nothing between the charge and the input changes the journal it is priced on, and the second pricing cost about 550 instructions per value-transfer transaction, measured. + ### Gas detention - **Compute counts the work run on a value call's stipend, and never what a halting frame burns.** diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 7accf26c2..7b0ce1cd4 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -190,11 +190,14 @@ where eip7702_refund }; let (applied, created) = applied_authorities(evm.ctx_mut(), checkpoint.journal_i); - if !charge_records_made_outside_a_frame(evm.ctx_ref(), gas, applied) { + let Some(first_frame) = charge_records_made_outside_a_frame(evm.ctx_ref(), gas, applied) + else { runtime_oog_unwind(evm.ctx(), checkpoint)?; return Ok(None); - } - evm.ctx_mut().additional_limit.count_authorities(applied, created); + }; + let layer = &mut evm.ctx_mut().additional_limit; + layer.keep_first_frame_charge(first_frame); + layer.count_authorities(applied, created); Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } @@ -314,11 +317,10 @@ where } /// revm's first frame, on the transaction's pool, carrying as its start charge the history - /// charged before execution for the write record it makes, priced again here on the journal - /// as pre-execution left it (`first_frame_records`); with a read of the block - /// beneficiary's account marked for gas detention when the transaction's recipient delegates - /// to the beneficiary: revm resolves that delegate through the journal, where the Host does - /// not see it. + /// charged before execution for the write record it makes, as pre-execution kept it + /// (`charge_records_made_outside_a_frame`); with a read of the block beneficiary's account + /// marked for gas detention when the transaction's recipient delegates to the beneficiary: + /// revm resolves that delegate through the journal, where the Host does not see it. /// /// The pools are what the transaction has left of its data-size, KV-update and state-growth /// limits once its body, the records of the authorities it applied, the accounts they created @@ -330,12 +332,21 @@ where evm: &mut Self::Evm, gas: &mut GasTracker, ) -> Result, Self::Error> { - // Priced before revm's runtime gas phase loads the recipient, on the journal as - // pre-execution left it, which is the state the charge was made on: nothing between the - // charge and the first frame's input changes it. - let records = first_frame_records(evm.ctx_ref()); - let charge = - StartCharge::new(evm.ctx_ref().records_history_charge(records), PoolAmounts::ZERO); + // What pre-execution charged, kept rather than priced again: nothing between the charge + // and the first frame's input changes the journal it was priced on, so a debug build + // prices it again here, before revm's runtime gas phase loads the recipient, and asserts + // the two agree. A system call skips pre-execution, and is priced here. + let kept = evm.ctx_mut().additional_limit.take_first_frame_charge(); + let ctx = evm.ctx_ref(); + let repriced = || ctx.records_history_charge(first_frame_records(ctx)); + let history = match kept { + Some(history) => { + debug_assert_eq!(history, repriced(), "the journal moved since pre-execution"); + history + } + None => repriced(), + }; + let charge = StartCharge::new(history, PoolAmounts::ZERO); gas.set_pools_remaining(evm.ctx_ref().additional_limit.first_frame_pools()); let Some(mut frame) = self.op.first_frame_input(evm, gas)? else { // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge @@ -1587,21 +1598,24 @@ fn applied_authorities( /// /// The authorities' records are the transaction's own and outlive a first frame that fails; the /// first frame's record does not, so that frame carries what it cost as its start charge, which -/// its failure gives back (priced again where the frame's input is built). A first frame revm +/// its failure gives back: the history it was charged, which this answers, kept on the layer for +/// the frame's input. A first frame revm /// refuses to start on its sender's account makes no record, and gets the charge back as any frame /// that kept nothing does: among the transactions that pay history, that is a creation from an /// account whose nonce cannot be bumped, which only a caller that turned the nonce check off can /// run, and which revm answers with a success and no address. -/// `false` when the transaction cannot pay, which is an out-of-gas before it runs. +/// The history gas the first frame's record was charged, nothing for a transaction that pays no +/// history; `None` when the transaction cannot pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( ctx: &MegaContext, gas: &mut GasTracker, applied_authorities: u64, -) -> bool { +) -> Option { if !ctx.prices_history() { - return true; + return Some(0); } - charge_write_records_history(gas, first_frame_records(ctx), applied_authorities).is_some() + charge_write_records_history(gas, first_frame_records(ctx), applied_authorities) + .map(|(first_frame, _)| first_frame) } /// The write records the transaction's own frame makes, as the journal's state stands before the diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index cc21c5553..53517b744 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -102,6 +102,10 @@ pub struct AdditionalLimit { /// would have kept more than a limit allows and was skipped /// ([`skip_authorization_list`](Self::skip_authorization_list)). pre_frame_stop: Option, + /// The history gas pre-execution charged for the write record the transaction's own frame + /// makes, kept from that charge until the frame's input is built, which carries it as its + /// start charge ([`take_first_frame_charge`](Self::take_first_frame_charge)). + first_frame_charge: Option, /// What the transaction's frames keep, every running frame counted as if it succeeds. kept: Kept, /// One per start revm decided whose result has not returned, the latest last. @@ -296,6 +300,7 @@ impl AdditionalLimit { self.created_authorities = 0; self.created_caller = false; self.pre_frame_stop = None; + self.first_frame_charge = None; self.kept = Kept::default(); self.decided.clear(); self.intrinsic_history_bytes = 0; @@ -458,6 +463,20 @@ impl AdditionalLimit { self.pre_frame_stop.take() } + /// Keeps `history`, the history gas pre-execution just charged for the write record the + /// transaction's own frame makes, for the frame's input to carry + /// ([`take_first_frame_charge`](Self::take_first_frame_charge)). + pub(crate) const fn keep_first_frame_charge(&mut self, history: u64) { + self.first_frame_charge = Some(history); + } + + /// The history gas pre-execution charged for the write record the transaction's own frame + /// makes; taken once, by the frame's input. `None` where no pre-execution charged it since + /// the last was taken: a system call, which skips pre-execution. + pub(crate) const fn take_first_frame_charge(&mut self) -> Option { + self.first_frame_charge.take() + } + /// The pools of the transaction's own frame: what the transaction has left of each limit once /// its body and the counts made before the frame are counted, the data size under the frame /// cap; unlimited for an exempt transaction. @@ -932,6 +951,23 @@ mod tests { ); } + /// The history pre-execution charged for the first frame's record reaches that frame's input + /// once: taken, it is gone, and an execution that skips pre-execution — a system call, begun + /// or run straight through the handler after a transaction — finds none and prices its own. + #[test] + fn test_the_first_frame_charge_is_taken_once_and_lasts_one_transaction() { + let mut limit = AdditionalLimit::default(); + limit.begin_transaction(TxClass::Ordinary, 0); + assert_eq!(limit.take_first_frame_charge(), None, "nothing charged yet"); + limit.keep_first_frame_charge(7); + assert_eq!(limit.take_first_frame_charge(), Some(7)); + assert_eq!(limit.take_first_frame_charge(), None, "taken by the frame's input"); + + limit.keep_first_frame_charge(7); + limit.begin_transaction(TxClass::ProtocolOwn, 0); + assert_eq!(limit.take_first_frame_charge(), None, "the next execution begins without it"); + } + /// Validation admits no body whose authority records cross the data-size limit, so a debug /// build trips on records that do: under a limit lowered to the body and one record, two /// applied authorities cross it. From cd89c48ff79f537b35d4b709de3640f633b550fc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:32:21 +0800 Subject: [PATCH 27/83] perf(evm): skip the start reads of a call that moves no value Every frame start read its accounts on the frame before revm decided it and again after, eight state lookups and four account clones, to count the records, new accounts and transfer log the start made. A call of any scheme that moves no value and runs no precompile makes none of them: revm's start only loads and touches its target, which changes no nonce, balance or code and journals no log. Such a start now skips both reads and counts nothing, and is still opened and held to the transaction's limits. The opcode likewise charges a call that transfers no value nothing without reading the journal, since such a call makes no record whatever the journal holds. A CALLCODE moving value stays read, and so does any call whose code address is in the EVM's precompile set: a node's own precompile runs inside the start and may write the start's accounts there. Each skip is decided by one small function with a truth-table test, and a debug build makes the skipped reads and asserts they find nothing. The reads cost about 900 instructions per start, measured, on every contract call and every internal call that moves no value. --- .claude/skills/satin-review/SKILL.md | 7 +- AGENTS.md | 3 + crates/mega-evm/src/evm/execution.rs | 121 +++++++++++++++++-- crates/mega-evm/src/evm/host.rs | 17 ++- crates/mega-evm/src/limit/mod.rs | 7 +- crates/mega-evm/src/limit/record.rs | 48 ++++++++ crates/mega-evm/tests/satin/write_records.rs | 66 +++++++++- 7 files changed, 255 insertions(+), 14 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 1540696c6..e25b00bd8 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -92,6 +92,11 @@ Each change is stated here in plain words with its reason; the specification has A precompile gas detention answers from its price before revm runs it moved nothing and is held to the price alone: its stop is kind 2, whatever records its value transfer would have made. A creation onto an occupied address fails on the collision, and is not stopped for what its start would count. Why: the limit judges what the journal kept, by the same rule at every start, instead of a prediction of revm's start held to the journal only in debug builds and checked hypothetically for the two answers that leave nothing to read; the opcode's history charge is still priced from the journal's state before revm decides, which on the plain path is exact because the opcode makes revm's refusal checks first, and the start's credit settles a price that differs from what revm made. +- **A call that moves no value is not read at its start.** + Made after #407 merged: a call of any scheme that moves no value and whose code address is not a precompile of the EVM's set skips the reads before and after revm decides its start (`start_writes_nothing` in `src/evm/execution.rs`), and the opcode charges a call that transfers no value nothing without reading the journal (`start_makes_no_records` in `src/limit/record.rs`); such a start is still opened and held to the transaction's limits. + A debug build makes the skipped reads and asserts they find nothing, and each decision has a truth-table test. + A `CALLCODE` moving value and any call to a precompile stay read: a node's own precompile runs inside the start and may write the start's accounts there (`tests/satin/tool_writes.rs`). + Why: revm's start of such a call only loads and touches its target, which changes no nonce, balance or code and journals no log, and the reads cost about 900 instructions per start, measured, on every contract call and every internal call that moves nothing. - **A creator's nonce record is counted on the creator when the creation returns with the nonce bumped.** The creation's budget is the share taken at the opcode, before that record, which is Rex6's order. The record is held to the creator's budget, not the creation's, and survives the creation's failure; a keyless signer's is counted on the call at its settlement, and the keyless creation's share is of the call's whole pools, which the call draws nothing from before it. @@ -256,7 +261,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them. - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. - - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::count` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed counts nothing and is held to no records limit, and a precompile gas detention answers from its price counts nothing and is held to the price alone; a start revm refuses on its caller's account counts nothing and is charged nothing. + - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::count` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), but for a call that moves no value and runs no precompile, which writes nothing on them (`start_writes_nothing`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed counts nothing and is held to no records limit, and a precompile gas detention answers from its price counts nothing and is held to the price alone; a start revm refuses on its caller's account counts nothing and is charged nothing. - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); a success revm gave without building a frame gives way to the stop on its untouched forward, its value move and log taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`); an answer that failed is revm's result, held to nothing. - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. diff --git a/AGENTS.md b/AGENTS.md index 77d19b333..c72c8dcf4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -197,6 +197,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Whether a movement logs is read off the journal's own EIP-7708 switch, the rule revm's journal emits by (`limit::emits_transfer_logs`), not off the configuration: a caller or an inspector that turns the journal's switch off through the context's mutable journal, past the configuration the spec fixes, gets no transfer log, and none is counted (`tests/satin/transfer_logs.rs`). It is counted where the value moves, on the pool of the frame whose journal checkpoint holds the move: a frame start's log with its records, on the started frame; a `SELFDESTRUCT`'s with its records once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. A frame start's records and log are read off what revm did, in `MegaEvm::frame_init`: the start's accounts on its frame — a call's caller and target, a creation's created account — are read before revm decides the start, with a journal mark (`Accounts::start_before`), and again once it did, each account's record by its change since, one account of state growth for each that was empty and is not, and the transfer log revm journaled since the mark (`Accounts::start_made`), drawn on the pool the frame starts with (`AdditionalLimit::count_start`): a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; a success revm gave without building the frame — a call to an account with no code, to a precompile that answers — gives way to the stop on its untouched gas, and its committed move and log are taken back to the mark (`take_back_a_stopped_answer`). + A call of any scheme that moves no value and whose code address is in none of the EVM's precompiles is not read (`start_writes_nothing` in `evm/execution.rs`): revm's start only loads and touches its target, which changes neither account's nonce, balance or code and journals no log, so the reads would find nothing, and the start counts nothing and is still held to the transaction's limits; a debug build makes the reads and asserts they find nothing. + A `CALLCODE` moving value and a call to a precompile, which a node's own may make write the start's accounts inside the start, are read. An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: its result is revm's, so a value call to a precompile that fails burns its forward as any failed precompile does, whatever its value transfer would have counted. It is not held to the transaction's limits either, having kept nothing: a deposit whose created caller alone stands over a state-growth limit of nothing, which only a tool's limit sets, and whose first frame is such an answer ends as a failed deposit, not with the stop a success answer there gets (`tests/satin/state_growth.rs`). A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` counts nothing and is stopped by nothing; it was charged nothing at its opcode, which prices a start's records from the journal's state and sees the caller cannot fund the value. @@ -441,6 +443,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The transaction's own frame and a system call's outermost frame take the whole reservoir (the fork's `forward_all_to_child`), and the neutral configuration, on the fixture fork's schedule, gives every child the whole. A caller that cannot pay, or a price that does not fit, gets the forward back and the halt's record re-written, and the opcode fails out of gas without starting a frame. The records the hook prices are one rule over caller, target and value (`Accounts::start_records`), asked at the opcode, a creation's at the address it takes (`FrameStart::target`); the records counted on the started frame's pool are those revm's start made, read off the journal once revm decided it, and a price that differs from them is settled by the start's credit. + A call that transfers no value, of any scheme, makes no record whatever the journal holds, and the hook charges it nothing without reading the journal (`limit::start_makes_no_records`; a debug build reads it and asserts there is nothing to charge). A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, and its declared part comes back only as it does for any start whose frame keeps nothing — a frame that fails, or a start revm refuses before it bumps a nonce or moves a value; its records are those revm then made. - **The instruction table.** The opcodes that can read volatile data run in detention's read wrapper (see Gas detention). diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 7b0ce1cd4..9fb14384d 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -43,8 +43,8 @@ use revm::{ inspector::{InspectorEvmTr, InspectorHandler, JournalExt}, interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, interpreter_types::LoopControl, - CallScheme, FrameInput, Gas, InitialAndFloorGas, InstructionResult, InterpreterAction, - InterpreterResult, + CallScheme, CallValue, FrameInput, Gas, InitialAndFloorGas, InstructionResult, + InterpreterAction, InterpreterResult, }, primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, Inspector, @@ -556,7 +556,9 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm( } } +/// Whether revm's start of the frame `input` asks for leaves the accounts it starts on as the +/// transaction held them and journals no transfer log, so that reading them before and after the +/// start ([`FrameStart::of`], [`FrameStart::count`]) would find no write record, no new account and +/// no log: a call, of any scheme, that moves no value and whose code address is in none of +/// `precompiles`, revm's own and a node's. Such a start only loads and touches its target, which +/// changes no account's nonce, balance or code. +/// +/// A call moving value changes its two accounts, and a `CALLCODE` moving value stays read too: +/// its value goes from the calling account to itself, which revm moves and logs nothing for, and +/// is read rather than reasoned about. A precompile runs inside the start, and a node's own may +/// write the start's accounts there, which are read with the start. A creation writes the account +/// it creates. +fn start_writes_nothing(input: &FrameInput, precompiles: &PrecompilesMap) -> bool { + match input { + FrameInput::Call(inputs) => { + let moves_value = + matches!(inputs.value, CallValue::Transfer(value) if !value.is_zero()); + !moves_value && precompiles.get(&inputs.bytecode_address).is_none() + } + FrameInput::Create(_) | FrameInput::Empty => false, + } +} + /// What holding a frame's start to the limits needs of it once revm consumed its input: where the /// start began, the accounts it writes as they stood before it, what its caller paid for it and /// what a stop answering it carries. @@ -1238,8 +1264,13 @@ struct FrameStart { mark: JournalCheckpoint, /// The accounts the start writes on its frame as the transaction held them before revm decided /// it, and the logs the journal held: what the start made is read off the journal against them - /// once revm decided it ([`count`](Self::count)). - before: StartBefore, + /// once revm decided it ([`count`](Self::count)). None for a start that writes nothing on them + /// ([`start_writes_nothing`]), which makes no record, no state growth and no transfer log. + before: Option, + /// For a start that writes nothing on its frame, in a debug build, the reads its `before` + /// skipped, which [`count`](Self::count) makes after all and asserts find nothing. + #[cfg(debug_assertions)] + skipped: Option, /// The history gas the start's caller paid at its opcode for the records on the frame. charged: u64, /// The gas limit the frame's caller forwarded, before gas detention held a precompile to less. @@ -1259,12 +1290,14 @@ impl FrameStart { /// journal stands, the accounts the start writes on its frame as the transaction holds them /// ([`Accounts::start_before`]) — a call's caller and target, a creation's created account — /// and a creation's creator. A creation's creator is not among the accounts: its nonce record - /// is the creator's, counted from the bump once the creation returned. + /// is the creator's, counted from the bump once the creation returned. The accounts are not + /// read for a start that `writes_nothing` on them ([`start_writes_nothing`]). /// /// [`Accounts::start_before`]: crate::limit::Accounts fn of( ctx: &mut MegaContext, frame_init: &FrameInit, + writes_nothing: bool, ) -> Result> { let mut creator = None; let (account, other, charged, reservoir, shares) = match &frame_init.frame_input { @@ -1306,8 +1339,12 @@ impl FrameStart { ), }; let mark = mark(ctx.journal_mut()); + debug_assert!(!writes_nothing || creator.is_none(), "a creation writes its account"); + let read = || ctx.accounts().start_before(account, other, mark.log_i); Ok(Self { - before: ctx.accounts().start_before(account, other, mark.log_i), + before: (!writes_nothing).then(read), + #[cfg(debug_assertions)] + skipped: writes_nothing.then(read), mark, charged, gas_limit: input_gas_limit(&frame_init.frame_input), @@ -1330,7 +1367,20 @@ impl FrameStart { ctx: &mut MegaContext, gas: &mut GasTracker, ) -> LimitCheck { - let (records, counted) = ctx.accounts().start_made(&self.before); + let (records, counted) = match &self.before { + Some(before) => ctx.accounts().start_made(before), + None => { + #[cfg(debug_assertions)] + if let Some(skipped) = &self.skipped { + assert_eq!( + ctx.accounts().start_made(skipped), + (crate::limit::RecordDelta::NONE, crate::limit::Counted::NONE), + "a call that moves no value and runs no precompile writes nothing" + ); + } + Default::default() + } + }; let credit = if ctx.prices_history() { let price = |records| write_record_history_gas(records).unwrap_or(0); self.charged.saturating_sub(price(records.added)).saturating_add(price(records.taken)) @@ -1642,7 +1692,10 @@ mod tests { use alloy_primitives::{address, U256}; use revm::{ context_interface::journaled_state::account::JournaledAccountTr, - interpreter::{gas::WithheldCrossing, CallInput, CallInputs, CallValue, SharedMemory}, + interpreter::{ + gas::WithheldCrossing, CallInput, CallInputs, CallValue, CreateInputs, CreateScheme, + SharedMemory, + }, }; use std::boxed::Box; @@ -2070,4 +2123,52 @@ mod tests { } } } + + /// The frame start skips its reads exactly for a call that moves no value and runs no + /// precompile: every call scheme, with no value and with value, to an account and to a + /// precompile of the set, and a creation, with and without an endowment. + #[test] + fn test_a_start_writes_nothing_only_when_it_moves_no_value_and_runs_no_precompile() { + let precompiles = crate::satin_precompiles_map(); + let ecrecover = address!("0000000000000000000000000000000000000001"); + assert!(precompiles.get(&ecrecover).is_some()); + let call = |scheme, value, code| { + let FrameInput::Call(mut inputs) = value_call() else { unreachable!() }; + inputs.scheme = scheme; + inputs.value = value; + inputs.bytecode_address = code; + FrameInput::Call(inputs) + }; + let (none, one) = (U256::ZERO, U256::from(1)); + let rows = [ + (CallScheme::Call, CallValue::Transfer(none), TARGET, true), + (CallScheme::Call, CallValue::Transfer(one), TARGET, false), + (CallScheme::Call, CallValue::Transfer(none), ecrecover, false), + (CallScheme::Call, CallValue::Transfer(one), ecrecover, false), + (CallScheme::CallCode, CallValue::Transfer(none), TARGET, true), + (CallScheme::CallCode, CallValue::Transfer(one), TARGET, false), + (CallScheme::CallCode, CallValue::Transfer(none), ecrecover, false), + (CallScheme::DelegateCall, CallValue::Apparent(none), TARGET, true), + (CallScheme::DelegateCall, CallValue::Apparent(one), TARGET, true), + (CallScheme::DelegateCall, CallValue::Apparent(one), ecrecover, false), + (CallScheme::StaticCall, CallValue::Transfer(none), TARGET, true), + (CallScheme::StaticCall, CallValue::Transfer(none), ecrecover, false), + ]; + for (scheme, value, code, writes_nothing) in rows { + let input = call(scheme, value.clone(), code); + assert_eq!( + start_writes_nothing(&input, &precompiles), + writes_nothing, + "{scheme:?} of {value:?} running {code}" + ); + } + for value in [none, one] { + for scheme in [CreateScheme::Create, CreateScheme::Create2 { salt: none }] { + let inputs = CreateInputs::new(CALLER, scheme, value, Bytes::new(), 100_000, 0); + let input = FrameInput::Create(Box::new(inputs)); + assert!(!start_writes_nothing(&input, &precompiles), "{scheme:?} of {value}"); + } + } + assert!(!start_writes_nothing(&FrameInput::Empty, &precompiles)); + } } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index dc40bdfa2..ccb6554bc 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -398,9 +398,14 @@ impl revm::context_interface::Host /// record of what the frame had, which detention reads where the frame ends, is written again /// once the forward is back: a failed charge recorded the gas left after the forward was /// taken, and a price that could not be computed failed before any charge. + /// + /// A call that transfers no value makes no record, whatever the journal holds + /// ([`start_makes_no_records`](crate::limit::start_makes_no_records)), and is charged nothing + /// without reading it; a debug build reads it and asserts there is nothing to charge. #[inline] fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { - let charge = if self.prices_history() { + let makes_no_records = crate::limit::start_makes_no_records(start.kind, start.value); + let charge = if self.prices_history() && !makes_no_records { let records = self.accounts().start_records(start.kind, start.caller, start.target, start.value); let on_frame = records.on_frame().added; @@ -412,6 +417,16 @@ impl revm::context_interface::Host }; charge } else { + debug_assert!( + !makes_no_records || + self.accounts().start_records( + start.kind, + start.caller, + start.target, + start.value + ) == crate::limit::StartRecords::NONE, + "a call that transfers no value makes no record" + ); 0 }; start.charge = StartCharge::new(charge, PoolAmounts::ZERO); diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index c049f8455..8026528c7 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -189,7 +189,12 @@ pub(crate) use limit::{Counted, TxClass}; pub(crate) use record::emits_transfer_logs; #[cfg(any(test, feature = "test-utils"))] pub(crate) use record::is_transfer_log; -pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes, StartBefore}; +#[cfg(debug_assertions)] +pub(crate) use record::RecordDelta; +pub(crate) use record::{ + start_makes_no_records, Accounts, CreatorBefore, DestroyedParts, HistoryBytes, StartBefore, + StartRecords, +}; use alloy_primitives::Bytes; use alloy_sol_types::SolError; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 6eceab69b..ea553c44d 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -214,6 +214,21 @@ pub(crate) struct StartBefore { logs: usize, } +/// Whether a frame start of `kind` that transfers `value` makes no write record whatever the +/// journal holds, so the opcode starting it prices its records at nothing without reading the +/// journal: a call of any scheme that transfers no value, whose transfer records nothing +/// ([`Accounts::transfer_records`]). A creation may record the account it creates and its +/// creator's nonce. +pub(crate) fn start_makes_no_records(kind: FrameStartKind, value: U256) -> bool { + match kind { + FrameStartKind::Create | FrameStartKind::Create2 => false, + FrameStartKind::Call | + FrameStartKind::CallCode | + FrameStartKind::DelegateCall | + FrameStartKind::StaticCall => value.is_zero(), + } +} + /// Whether `log` is the EIP-7708 transfer log revm journals for a value movement: a log from the /// system address `0xff…fe` carrying ERC-20's `Transfer` event. pub(crate) fn is_transfer_log(log: &Log) -> bool { @@ -680,6 +695,39 @@ mod tests { Accounts::of(&journal).write_counted(&write).0 } + /// The opcode prices no record without reading the journal exactly for a call that transfers + /// no value, of any scheme, and never for a creation; for every such call the journal-read + /// price is nothing too, whichever account it calls and whatever the caller holds. + #[test] + fn test_a_start_makes_no_records_only_when_a_call_transfers_no_value() { + let calls = [ + FrameStartKind::Call, + FrameStartKind::CallCode, + FrameStartKind::DelegateCall, + FrameStartKind::StaticCall, + ]; + let creations = [FrameStartKind::Create, FrameStartKind::Create2]; + let journal = journal(); + let accounts = Accounts::of(&journal); + for (value, expected) in [(U256::ZERO, true), (U256::from(1), false)] { + for kind in calls { + assert_eq!(start_makes_no_records(kind, value), expected, "{kind:?} of {value}"); + } + for kind in creations { + assert!(!start_makes_no_records(kind, value), "{kind:?} of {value}"); + } + } + for kind in calls { + for target in [OTHER, SENDER, address!("00000000000000000000000000000000000000ee")] { + let records = accounts.start_records(kind, SENDER, Some(target), U256::ZERO); + assert_eq!(records, StartRecords::NONE, "{kind:?} to {target}"); + } + } + // A transfer that does move value records: the skip is not a price of nothing in general. + let moved = accounts.start_records(FrameStartKind::Call, SENDER, Some(OTHER), U256::ONE); + assert_ne!(moved, StartRecords::NONE); + } + /// A slot counts once, on its first change in the transaction; writing it back to its /// original value takes the record back; every other write counts nothing. #[test] diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 1489ee4c9..de01a3cfe 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -31,7 +31,8 @@ use mega_evm::{ use revm::{ bytecode::opcode::{ CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, - JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STOP, + JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, + STOP, }, context::ContextTr, interpreter::{ @@ -1642,6 +1643,69 @@ fn test_zero_value_child_starts_unrecorded() { ); } +/// Code that calls `target` once with each of the four call schemes, moving no value, and stops. +fn calls_moving_no_value(target: Address) -> Bytes { + let by = |code: BytecodeBuilder, opcode| { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(target) + .append(GAS) + .append(opcode) + .append(POP) + }; + let code = BytecodeBuilder::default().call(target, U256::ZERO).append(POP); + let code = code.callcode(target, U256::ZERO).append(POP); + by(by(code, DELEGATECALL), STATICCALL).stop().build() +} + +/// A call that moves no value writes nothing on its two accounts, whichever scheme makes it, even +/// to an account empty under EIP-161 — one the state does not hold, and one it holds empty — which +/// revm touches and leaves empty: the transaction keeps its body alone, and the account is not +/// created. Its frame start reads neither account; a debug build reads them and finds nothing. +#[test] +fn test_a_call_moving_no_value_to_an_empty_account_counts_nothing() { + for held in [false, true] { + let mut db = funded().account_code(CALLEE, calls_moving_no_value(CONTRACT)); + if held { + db = db.account_balance(CONTRACT, U256::ZERO); + } + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(result.result.is_success(), "{:?}", result.result); + assert!(result.result.logs().is_empty(), "no transfer log"); + assert_eq!(usage, body_only(), "held in the state: {held}"); + let target = &result.state[&CONTRACT]; + assert!(target.info.is_empty() && !target.is_created(), "held in the state: {held}"); + } +} + +/// A call that moves no value to an account delegating to code under EIP-7702 writes nothing on +/// its two accounts: what the delegator keeps is what the delegate's code writes, one fresh slot of +/// its storage, whether the transaction itself or a contract makes the call. +#[test] +fn test_a_call_moving_no_value_to_a_delegated_account_counts_what_the_delegate_writes() { + let delegated = |mut db: MemoryDatabase| { + let delegation = revm::state::Bytecode::new_eip7702(D); + let account = db.load_account(CONTRACT2).expect("the account is in memory"); + account.info.code_hash = delegation.hash_slow(); + account.info.code = Some(delegation); + account.account_state = revm::database::AccountState::None; + db + }; + let writes_a_slot = + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(); + let caller = BytecodeBuilder::default().call(CONTRACT2, U256::ZERO).append(POP).stop().build(); + for (to, depth) in [(CONTRACT2, "the transaction"), (CALLEE, "a contract")] { + let db = funded() + .account_code(D, writes_a_slot.clone()) + .account_code(CALLEE, caller.clone()) + .account_balance(CONTRACT2, U256::ZERO); + let (result, usage) = run(delegated(db), call(CALLER, to, U256::ZERO, value_call_room())); + assert!(result.result.is_success(), "{depth}: {:?}", result.result); + let slot = &result.state[&CONTRACT2].storage[&U256::from(1)]; + assert_eq!(slot.present_value, U256::from(1), "{depth}: the delegate wrote the delegator"); + assert_eq!(usage, grown(records(1), 1), "{depth}: the slot alone"); + } +} + /// Calls `D` with `DELEGATECALL`. fn delegate_to_d() -> Bytes { BytecodeBuilder::default() From dbbbaa301ce0e526602821dd6f5bc43bb355efb6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:35:04 +0800 Subject: [PATCH 28/83] perf(limit): look each account up once per read of a write's records MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A frame start's two reads looked each account up twice — whether it was changed, then whether it was empty or what it holds now — and pricing a value transfer's records looked each side up three times and cloned its original info twice. Each read now looks an account up once and derives what it needs from that one load: changed and empty before a start, changed and grown after it, and, for a transfer or a destruction, the balance, the change now and the change with the moved balance, from one read of the original info. The records, the growth and the logs counted are those of before. --- crates/mega-evm/src/limit/record.rs | 120 +++++++++++++++------------- 1 file changed, 65 insertions(+), 55 deletions(-) diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index ea553c44d..99ddfdb7f 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -177,6 +177,32 @@ fn differs(info: &AccountInfo, original: &AccountInfo) -> bool { info.code_hash != original.code_hash } +/// Whether the transaction changed `account`, which it loaded, from what it loaded: its nonce, +/// balance or code differs from its original info. +fn changed(account: &Account) -> bool { + differs(&account.info, &account.original_info()) +} + +/// Whether the account `account` — the transaction's load of it, `None` for one it has not loaded +/// — is changed from what the transaction loaded, and whether it would be were its balance +/// `balance`, the rest of its info as it is. What the transaction loads for an account it has not +/// loaded is what the chain holds, so it is unchanged, and a balance it does not hold changes it. +/// The account's original info is read once for both. +fn changed_now_and_with_balance(account: Option<&Account>, balance: U256) -> (bool, bool) { + let Some(account) = account else { return (false, balance != U256::ZERO) }; + let original = account.original_info(); + let now = differs(&account.info, &original); + let with_balance = account.info.nonce != original.nonce || + balance != original.balance || + account.info.code_hash != original.code_hash; + (now, with_balance) +} + +/// The balance of `account`, the transaction's load of it; nothing for one it has not loaded. +fn balance_of(account: Option<&Account>) -> U256 { + account.map_or(U256::ZERO, |account| account.info.balance) +} + /// A creation's creator as the transaction held it before revm decided the creation's start: what /// tells, once the creation returned, whether revm bumped the creator's nonce and what the bump /// made of the creator ([`Accounts::creator_counted`]). @@ -197,10 +223,23 @@ struct AccountBefore { address: Address, /// Whether the transaction had changed it from what it loaded. changed: bool, - /// Whether it was empty under EIP-161. + /// Whether it was empty under EIP-161 — no nonce, no balance, no code — as the transaction + /// held it: a value moved to it, or a creation at it, makes a new account. An account the + /// transaction had not loaded is not known to be empty. empty: bool, } +impl AccountBefore { + /// The account at `address` as `account`, the transaction's load of it, holds it. + fn of(address: Address, account: Option<&Account>) -> Self { + Self { + address, + changed: account.is_some_and(changed), + empty: account.is_some_and(|account| account.info.is_empty()), + } + } +} + /// The accounts a frame's start writes on its frame — a call's caller and target, a creation's /// created account — as the transaction held them before revm decided the start, and how many logs /// the journal held then: what tells, once revm decided the start, what it made @@ -272,20 +311,7 @@ impl<'a> Accounts<'a> { /// balance or code differs from the account's original info. An account the transaction has /// not loaded is unchanged. pub(crate) fn is_changed(&self, address: Address) -> bool { - self.loaded(address).is_some_and(|account| differs(&account.info, &account.original_info())) - } - - /// Whether the account at `address` would be changed from what the transaction loaded were - /// its balance `balance`, the rest of its info as it is. - fn changed_with_balance(&self, address: Address, balance: U256) -> bool { - match self.loaded(address) { - Some(account) => { - differs(&AccountInfo { balance, ..account.info.clone() }, &account.original_info()) - } - // What the transaction loads for an account it has not loaded is what the chain holds, - // so a balance it does not hold changes it. - None => balance != U256::ZERO, - } + self.loaded(address).is_some_and(changed) } /// Whether the account at `address` was created in the transaction and has been destroyed @@ -375,38 +401,23 @@ impl<'a> Accounts<'a> { }) == Some(true) } - /// Whether the account at `address` is empty under EIP-161 — no nonce, no balance, no code — - /// as the transaction holds it: a value moved to it, or a creation at it, makes a new account. - /// An account the transaction has not loaded is not known to be empty. - pub(crate) fn is_empty(&self, address: Address) -> bool { - self.loaded(address).is_some_and(|account| account.info.is_empty()) - } - - /// The current balance of the account at `address`; nothing for one the transaction has not - /// loaded. - fn balance(&self, address: Address) -> U256 { - self.loaded(address).map_or(U256::ZERO, |account| account.info.balance) - } - /// The records a transfer of `value` from `from` to `to` makes and takes back, as the journal's /// state stands: nothing for a transfer to the same account or of nothing, which revm moves - /// nothing for, and nothing for a value `from` cannot fund, which revm refuses. + /// nothing for, and nothing for a value `from` cannot fund, which revm refuses. Each account + /// is looked up once. pub(crate) fn transfer_records(&self, from: Address, to: Address, value: U256) -> StartRecords { if from == to || value.is_zero() { return StartRecords::NONE; } - let Some(from_after) = self.balance(from).checked_sub(value) else { + let (from, to) = (self.loaded(from), self.loaded(to)); + let Some(from_after) = balance_of(from).checked_sub(value) else { return StartRecords::NONE; }; - let to_after = self.balance(to).saturating_add(value); - let transfer = RecordDelta::of_account( - self.is_changed(from), - self.changed_with_balance(from, from_after), - ) - .with(RecordDelta::of_account( - self.is_changed(to), - self.changed_with_balance(to, to_after), - )); + let to_after = balance_of(to).saturating_add(value); + let (from_now, from_moved) = changed_now_and_with_balance(from, from_after); + let (to_now, to_moved) = changed_now_and_with_balance(to, to_after); + let transfer = RecordDelta::of_account(from_now, from_moved) + .with(RecordDelta::of_account(to_now, to_moved)); StartRecords { transfer, ..StartRecords::NONE } } @@ -422,22 +433,24 @@ impl<'a> Accounts<'a> { value: U256, ) -> StartRecords { let Some(created) = created else { return StartRecords::NONE }; - if self.balance(creator) < value { + let creator = self.loaded(creator); + if balance_of(creator) < value { return StartRecords::NONE; } StartRecords { transfer: RecordDelta::NONE, created: !self.is_changed(created), - creator: !self.is_changed(creator), + creator: !creator.is_some_and(changed), } } /// The creator at `address` of a creation revm is about to decide, as the transaction holds it. /// The creator is read loaded: revm loads it first thing when it decides the creation. pub(crate) fn creator_before(&self, address: Address) -> CreatorBefore { + let account = self.loaded(address); CreatorBefore { - account: self.account_before(address), - nonce: self.loaded(address).map_or(0, |account| account.info.nonce), + account: AccountBefore::of(address, account), + nonce: account.map_or(0, |account| account.info.nonce), } } @@ -461,15 +474,15 @@ impl<'a> Accounts<'a> { /// The account at `address` as the transaction holds it. fn account_before(&self, address: Address) -> AccountBefore { - AccountBefore { address, changed: self.is_changed(address), empty: self.is_empty(address) } + AccountBefore::of(address, self.loaded(address)) } /// What changed of the account `before` was read of since, as the journal holds it now: its /// write record, by its change ([`RecordDelta::of_account`]), and whether it became a new - /// account, empty under EIP-161 then and not now. + /// account, empty under EIP-161 then and not now. The account is looked up once. fn account_made(&self, before: &AccountBefore) -> (RecordDelta, bool) { - let record = RecordDelta::of_account(before.changed, self.is_changed(before.address)); let loaded = self.loaded(before.address); + let record = RecordDelta::of_account(before.changed, loaded.is_some_and(changed)); (record, before.empty && loaded.is_some_and(|account| !account.info.is_empty())) } @@ -533,18 +546,15 @@ impl<'a> Accounts<'a> { /// destructed account held `balance` before it, and a beneficiary that is another account its /// balance less `balance`, all of which it got. fn destruction_records(&self, address: Address, target: Address, balance: U256) -> RecordDelta { - let source = RecordDelta::of_account( - self.changed_with_balance(address, balance), - self.is_changed(address), - ); + let (now, before) = changed_now_and_with_balance(self.loaded(address), balance); + let source = RecordDelta::of_account(before, now); if target == address { return source; } - let before = self.balance(target).saturating_sub(balance); - source.with(RecordDelta::of_account( - self.changed_with_balance(target, before), - self.is_changed(target), - )) + let target = self.loaded(target); + let held = balance_of(target).saturating_sub(balance); + let (now, before) = changed_now_and_with_balance(target, held); + source.with(RecordDelta::of_account(before, now)) } /// What the completed write `write` counts, the history bytes it appends and takes back, and, From f1a3589a7e1514ce32c00a7b70e6aaf9e4528c35 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:50:31 +0800 Subject: [PATCH 29/83] perf(limit): visit only the pools a completed write's count touches A completed write's count, a storage write's record or a log's bytes, moves one or two of the three pools, and the draw checked every pool's budget and every dimension's limit off a snapshot of all three, then refilled, drew and counted all three. A pool the count leaves alone crosses neither its budget nor the transaction's limit, and a draw and a refill of nothing change nothing, so the draw now visits the pools the count touches and reads each from the tracker where it is needed. A frame start, which is held to the transaction's limits whatever it counts, still checks every dimension. An equivalence test holds the draw to the previous one over every combination of pool moves, budgets, limits, prior counts and the exemption. The accounts a write is read against are now one reference to the journal, and the EIP-7708 rule is read only where a SELFDESTRUCT's count needs it, instead of on every write and every frame start. --- crates/mega-evm/src/limit/limit.rs | 228 ++++++++++++++++++++++++---- crates/mega-evm/src/limit/record.rs | 41 +++-- 2 files changed, 215 insertions(+), 54 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 53517b744..1740ac0ae 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -247,6 +247,14 @@ impl Counted { self.added.is_zero() && self.taken.is_zero() } + /// Whether it adds anything to `pool` or takes anything back from it: a count that leaves a + /// pool alone crosses neither the frame's budget in it nor, unless the transaction is held to + /// its limits whatever it counts, the transaction's limit, and a draw and a refill of nothing + /// change neither the pool nor what the frames keep. + const fn touches(&self, pool: PoolId) -> bool { + self.added.get(pool) != 0 || self.taken.get(pool) != 0 + } + /// What it adds to `pool` less what it takes back from it. const fn rise(&self, pool: PoolId) -> i128 { self.added.get(pool) as i128 - self.taken.get(pool) as i128 @@ -566,29 +574,26 @@ impl AdditionalLimit { LimitCheck::WithinLimit } - /// The verdict on `counted` kept on a frame whose pools hold `remaining` after net draws of - /// `spent`: in each counted dimension in order, the frame's budget, then the transaction's - /// limit; the first crossing is the verdict. `held` holds the transaction to its limits - /// whatever `counted` adds. - fn check( - &self, - remaining: PoolAmounts, - spent: [i64; PoolId::COUNT], - counted: &Counted, - held: bool, - ) -> LimitCheck { + /// The verdict on `counted` kept on a frame whose pools `gas` holds: in each counted dimension + /// in order, the frame's budget, then the transaction's limit; the first crossing is the + /// verdict. `held` holds the transaction to its limits whatever `counted` adds; otherwise a + /// dimension `counted` leaves alone crosses nothing and is not looked at + /// ([`Counted::touches`]). + fn check(&self, gas: &GasTracker, counted: &Counted, held: bool) -> LimitCheck { for kind in COUNTED { let Some(pool) = kind.pool() else { continue }; + if !held && !counted.touches(pool) { + continue; + } let rise = counted.rise(pool); - if rise > 0 && rise > remaining.get(pool) as i128 { - let check = self.budget_crossed( - kind, - remaining.get(pool), - spent[pool.index()], - rise as u64, - ); - if check.exceeded_limit() { - return check; + if rise > 0 { + let remaining = gas.pool_remaining(pool); + if rise > remaining as i128 { + let spent = gas.pool_spent(pool); + let check = self.budget_crossed(kind, remaining, spent, rise as u64); + if check.exceeded_limit() { + return check; + } } } let check = self.transaction_crossed(kind, counted, held); @@ -599,11 +604,6 @@ impl AdditionalLimit { LimitCheck::WithinLimit } - /// The pools `gas` holds and the nets it drew on them. - fn pools_of(gas: &GasTracker) -> (PoolAmounts, [i64; PoolId::COUNT]) { - (gas.pools_remaining(), PoolId::ALL.map(|pool| gas.pool_spent(pool))) - } - /// Counts what the frame whose pools `gas` holds keeps of `counted`, held to the frame's /// budgets and the transaction's limits in the order [`check`](Self::check) holds them: the /// amounts `counted` takes back go back to each pool first, and the amounts it adds are drawn. @@ -613,8 +613,7 @@ impl AdditionalLimit { if counted.is_none() { return LimitCheck::WithinLimit; } - let (remaining, spent) = Self::pools_of(gas); - let check = self.check(remaining, spent, counted, false); + let check = self.check(gas, counted, false); if check.exceeded_limit() { return check; } @@ -623,9 +622,13 @@ impl AdditionalLimit { LimitCheck::WithinLimit } - /// Draws `counted` on the pools `gas` holds, which the checks made sure can pay it. + /// Draws `counted` on the pools `gas` holds, which the checks made sure can pay it; a pool it + /// leaves alone is not visited. fn apply(gas: &mut GasTracker, counted: &Counted) { for pool in PoolId::ALL { + if !counted.touches(pool) { + continue; + } gas.refill_pool(pool, counted.taken.get(pool)); let drew = gas.record_pool(pool, counted.added.get(pool)); debug_assert!( @@ -649,6 +652,9 @@ impl AdditionalLimit { fn count(&mut self, counted: &Counted) { let kept = &mut self.kept; for pool in PoolId::ALL { + if !counted.touches(pool) { + continue; + } let net = &mut kept.net[pool.index()]; *net = net .saturating_add_unsigned(counted.added.get(pool)) @@ -699,8 +705,7 @@ impl AdditionalLimit { counted: &Counted, credit: u64, ) -> LimitCheck { - let (remaining, spent) = Self::pools_of(gas); - let check = self.check(remaining, spent, counted, true); + let check = self.check(gas, counted, true); if check.exceeded_limit() { return check; } @@ -951,6 +956,169 @@ mod tests { ); } + /// `draw` as it was before it learned to leave alone the pools a count does not touch: every + /// pool's budget and every dimension's limit checked off a snapshot of the pools, and every + /// pool drawn, refilled and counted. The reference [`draw`](AdditionalLimit::draw) is held to. + fn draw_by_every_pool( + limit: &mut AdditionalLimit, + gas: &mut GasTracker, + counted: &Counted, + ) -> LimitCheck { + if counted.is_none() { + return LimitCheck::WithinLimit; + } + let remaining = gas.pools_remaining(); + let spent = PoolId::ALL.map(|pool| gas.pool_spent(pool)); + for kind in COUNTED { + let Some(pool) = kind.pool() else { continue }; + let rise = counted.rise(pool); + if rise > 0 && rise > remaining.get(pool) as i128 { + let check = limit.budget_crossed( + kind, + remaining.get(pool), + spent[pool.index()], + rise as u64, + ); + if check.exceeded_limit() { + return check; + } + } + let check = limit.transaction_crossed(kind, counted, false); + if check.exceeded_limit() { + return check; + } + } + for pool in PoolId::ALL { + gas.refill_pool(pool, counted.taken.get(pool)); + if !gas.record_pool(pool, counted.added.get(pool)) { + gas.clear_pool_crossing(pool); + } + let net = &mut limit.kept.net[pool.index()]; + *net = net + .saturating_add_unsigned(counted.added.get(pool)) + .saturating_sub_unsigned(counted.taken.get(pool)); + } + limit.kept.transfer_logs += u64::from(counted.transfer_log); + LimitCheck::WithinLimit + } + + /// A draw that visits only the pools its count touches decides, draws and counts exactly as + /// one that visits every pool: for every count that adds to, takes back from or leaves alone + /// each of the three pools, with and without a transfer log, on frames whose budget in each + /// pool is exhausted, short of the count or ample, under transaction limits that the count + /// crosses or does not, after frames kept nothing, a little or more, and for an exempt + /// transaction, whose pools are unlimited. A count takes back no more data size and no more + /// records than the frames keep, which the engine never does and a debug build asserts. + #[test] + fn test_a_draw_over_the_pools_it_touches_matches_one_over_every_pool() { + // What a count does to one pool: nothing, add, take back, or both. + let moves = [(0, 0), (5, 0), (0, 2), (7, 3)]; + // A frame's pool before the draw: empty, short of the count, ample; an exempt + // transaction's frames start with unlimited pools. + let mut cases = 0; + for (class, pools) in + [(TxClass::Ordinary, &[0_u64, 4, 100][..]), (TxClass::ProtocolOwn, &[u64::MAX - 2][..])] + { + for tx_limit in [10_u64, u64::MAX] { + for kept in [0_u64, 3, 8] { + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(tx_limit) + .with_tx_kv_update_limit(tx_limit) + .with_tx_state_growth_limit(tx_limit); + let mut layer = AdditionalLimit::new(limits); + layer.begin_transaction(class, 0); + let prior = Counted::NONE; + let mut prior = prior; + for pool in PoolId::ALL { + prior.added.set(pool, kept); + } + layer.count(&prior); + for a in moves { + for b in moves { + for c in moves { + for transfer_log in [false, true] { + for &pa in pools { + for &pb in pools { + for &pc in pools { + let mut counted = Counted::NONE; + for (pool, (added, taken)) in + PoolId::ALL.into_iter().zip([a, b, c]) + { + counted.added.set(pool, added); + counted.taken.set(pool, taken); + } + counted.transfer_log = transfer_log; + let takes_more = [PoolId::ALL[0], PoolId::ALL[1]] + .into_iter() + .any(|pool| counted.taken.get(pool) > kept); + if takes_more { + continue; + } + // Two drawn already, so a frame's net is not zero. + let mut gas = GasTracker::new(1_000, 1_000, 0); + gas.set_pools_remaining( + PoolAmounts::ZERO + .with(PoolId::ALL[0], pa + 2) + .with(PoolId::ALL[1], pb + 2) + .with(PoolId::ALL[2], pc + 2), + ); + for pool in PoolId::ALL { + assert!(gas.record_pool(pool, 2)); + } + let (mut by_touched, mut by_every) = + (layer.clone(), layer.clone()); + let (mut gas_touched, mut gas_every) = (gas, gas); + let verdict = + by_touched.draw(&mut gas_touched, &counted); + let reference = draw_by_every_pool( + &mut by_every, + &mut gas_every, + &counted, + ); + let case = format!( + "{class:?}, limit {tx_limit}, kept {kept}, \ + {counted:?}, pools {pa}/{pb}/{pc}" + ); + assert_eq!(verdict, reference, "{case}"); + assert_eq!( + by_touched.kept, by_every.kept, + "{case}" + ); + assert_eq!( + gas_touched.pools_remaining(), + gas_every.pools_remaining(), + "{case}" + ); + for pool in PoolId::ALL { + assert_eq!( + ( + gas_touched.pool_spent(pool), + gas_touched.pool_crossing(pool) + ), + ( + gas_every.pool_spent(pool), + gas_every.pool_crossing(pool) + ), + "{case}" + ); + } + cases += 1; + } + } + } + } + } + } + } + } + } + } + // With nothing kept, a count takes nothing back from the first two pools: 2 of 4 moves + // each, so 16 of the 64 moves; with 3 or 8 kept, every move. The ordinary transaction runs + // on 27 pool states, the exempt one on one. + assert_eq!(cases, 2 * (16 + 64 + 64) * 2 * (27 + 1)); + } + /// The history pre-execution charged for the first frame's record reaches that frame's input /// once: taken, it is gone, and an execution that skips pre-execution — a system call, begun /// or run straight through the handler after a transaction — finds none and prices its own. diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 99ddfdb7f..aefed9cbc 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -42,6 +42,7 @@ use alloc as std; use std::vec::Vec; use revm::{ + context::JournalInner, context_interface::{ host::{CompletedWrite, FrameStartKind}, journaled_state::entry::{JournalEntry, SelfdestructionRevertStatus}, @@ -51,7 +52,7 @@ use revm::{ hardfork::SpecId, Address, Log, StorageKey, KECCAK_EMPTY, U256, }, - state::{Account, AccountInfo, EvmState, TransactionId}, + state::{Account, AccountInfo}, Journal, }; @@ -158,15 +159,11 @@ impl DestroyedParts { /// a write makes. #[derive(Clone, Copy, Debug)] pub(crate) struct Accounts<'a> { - state: &'a EvmState, - /// The journal's entries, which revm clears between transactions: this transaction's. - entries: &'a [JournalEntry], - /// The logs the journal holds, which a failed frame's revert takes back with its entries. - logs: &'a [Log], - transaction_id: TransactionId, - /// Whether a value movement journals an EIP-7708 transfer log, as the journal's own - /// configuration says ([`emits_transfer_logs`]). - transfer_logs: bool, + /// The journal: its state; its entries, which revm clears between transactions, so they are + /// this transaction's; its logs, which a failed frame's revert takes back with its entries; + /// and its configuration, which says whether a value movement journals an EIP-7708 transfer + /// log ([`emits_transfer_logs`]), read only where a write's count needs it. + journal: &'a JournalInner, } /// Whether `info` differs from `original` in what a write record stands for: the nonce, the @@ -278,27 +275,22 @@ pub(crate) fn is_transfer_log(log: &Log) -> bool { /// with the switch on, unless EIP-7708 is disabled. It is the rule revm's journal emits one by, /// read off the journal's own copy of the configuration, so the data size counts a transfer log /// exactly where revm emits one, a switch a caller turned on the journal itself included. -pub(crate) fn emits_transfer_logs(journal: &Journal) -> bool { +pub(crate) fn emits_transfer_logs(journal: &JournalInner) -> bool { (journal.cfg.spec.is_enabled_in(SpecId::AMSTERDAM) || journal.amsterdam_eip7708_enabled()) && !journal.cfg.eip7708_disabled } impl<'a> Accounts<'a> { /// The accounts `journal` holds. - pub(crate) fn of(journal: &'a Journal) -> Self { - Self { - state: &journal.state, - entries: &journal.journal, - logs: &journal.logs, - transaction_id: journal.transaction_id, - transfer_logs: emits_transfer_logs(journal), - } + pub(crate) const fn of(journal: &'a Journal) -> Self { + Self { journal: &journal.inner } } /// The account at `address` as the transaction loaded it and holds it now: `None` for one /// the transaction has not loaded, which it has not changed either. fn loaded(&self, address: Address) -> Option<&'a Account> { - self.state.get(&address).filter(|account| account.transaction_id == self.transaction_id) + let transaction_id = self.journal.transaction_id; + self.journal.state.get(&address).filter(|account| account.transaction_id == transaction_id) } /// Whether the transaction has loaded the account at `address`. An account an earlier @@ -357,8 +349,9 @@ impl<'a> Accounts<'a> { } else { account.info.code.as_ref().map_or(0, |code| code.len() as u64) }; + let transaction_id = self.journal.transaction_id; let loaded = - account.storage.iter().filter(|(_, slot)| slot.transaction_id == self.transaction_id); + account.storage.iter().filter(|(_, slot)| slot.transaction_id == transaction_id); let mut slots = Vec::new(); let mut deleted = 0; for (key, slot) in loaded { @@ -391,7 +384,7 @@ impl<'a> Accounts<'a> { return false; } account.is_loaded_as_not_existing() || - self.entries.iter().rev().find_map(|entry| match entry { + self.journal.journal.iter().rev().find_map(|entry| match entry { JournalEntry::AccountDestroyed { address: destroyed, destroyed_status, .. } if *destroyed == address => { @@ -512,7 +505,7 @@ impl<'a> Accounts<'a> { records = records.with(record); growth += u64::from(grew); } - let logs = self.logs.get(before.logs..).unwrap_or_default(); + let logs = self.journal.logs.get(before.logs..).unwrap_or_default(); let logged = logs.iter().any(is_transfer_log); (records, Counted::records(records.added, records.taken, logged).with_growth(growth, 0)) } @@ -606,7 +599,7 @@ impl<'a> Accounts<'a> { CompletedWrite::SelfDestruct { address, target, balance, result } => { let records = self.destruction_records(address, target, balance); let moved = result.had_value && target != address; - let logged = self.transfer_logs && moved; + let logged = moved && emits_transfer_logs(self.journal); let creates = moved && !result.target_exists; let counted = Counted::records(records.added, records.taken, logged) .with_growth(u64::from(creates), 0); From 156a5acef81c98f086d06efcfc355f533fd8dec8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:52:46 +0800 Subject: [PATCH 30/83] docs(evm): state what the pre-execution record charge answers, and assert a skipped start is a call The debug assertion that a start whose reads are skipped is no creation read the creator, which a creation the transaction itself makes has none of; it now reads the frame input. The doc of the pre-execution charge says what it answers in a paragraph of its own. --- crates/mega-evm/src/evm/execution.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9fb14384d..ea861d2d3 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1339,7 +1339,10 @@ impl FrameStart { ), }; let mark = mark(ctx.journal_mut()); - debug_assert!(!writes_nothing || creator.is_none(), "a creation writes its account"); + debug_assert!( + !writes_nothing || matches!(frame_init.frame_input, FrameInput::Call(_)), + "a creation writes the account it creates" + ); let read = || ctx.accounts().start_before(account, other, mark.log_i); Ok(Self { before: (!writes_nothing).then(read), @@ -1648,14 +1651,15 @@ fn applied_authorities( /// /// The authorities' records are the transaction's own and outlive a first frame that fails; the /// first frame's record does not, so that frame carries what it cost as its start charge, which -/// its failure gives back: the history it was charged, which this answers, kept on the layer for -/// the frame's input. A first frame revm -/// refuses to start on its sender's account makes no record, and gets the charge back as any frame -/// that kept nothing does: among the transactions that pay history, that is a creation from an -/// account whose nonce cannot be bumped, which only a caller that turned the nonce check off can -/// run, and which revm answers with a success and no address. -/// The history gas the first frame's record was charged, nothing for a transaction that pays no -/// history; `None` when the transaction cannot pay, which is an out-of-gas before it runs. +/// its failure gives back. A first frame revm refuses to start on its sender's account makes no +/// record, and gets the charge back as any frame that kept nothing does: among the transactions +/// that pay history, that is a creation from an account whose nonce cannot be bumped, which only a +/// caller that turned the nonce check off can run, and which revm answers with a success and no +/// address. +/// +/// Answers the history gas the first frame's record was charged, which pre-execution keeps for +/// the frame's input to carry, and nothing for a transaction that pays no history; `None` when the +/// transaction cannot pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( ctx: &MegaContext, gas: &mut GasTracker, From 062a330fdd8cc6a23d8111676b7c3d313142296e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 23:04:37 +0800 Subject: [PATCH 31/83] refactor(limit): apply review notes on the start and write-path changes A transfer's and a destruction's record flags now share the comparison a write record stands for, and name the move's before and after. The two rules that let a call that moves no value skip work, the opcode's price and the frame start's reads, point at each other. The draw asserts in a debug build that a dimension it does not look at crosses nothing. The btest witness test now checks a block the executor refuses, which prints its own line, and the crate guides name the read-set digest. --- AGENTS.md | 2 +- crates/mega-evm/src/evm/execution.rs | 7 ++++- crates/mega-evm/src/limit/limit.rs | 22 ++++++++++----- crates/mega-evm/src/limit/record.rs | 42 +++++++++++++++++++--------- crates/mega-state-test/AGENTS.md | 1 + crates/state-test/AGENTS.md | 2 +- crates/state-test/tests/cli.rs | 13 +++++++-- 7 files changed, 63 insertions(+), 26 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c72c8dcf4..4d9441d61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -198,7 +198,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It is counted where the value moves, on the pool of the frame whose journal checkpoint holds the move: a frame start's log with its records, on the started frame; a `SELFDESTRUCT`'s with its records once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. A frame start's records and log are read off what revm did, in `MegaEvm::frame_init`: the start's accounts on its frame — a call's caller and target, a creation's created account — are read before revm decides the start, with a journal mark (`Accounts::start_before`), and again once it did, each account's record by its change since, one account of state growth for each that was empty and is not, and the transfer log revm journaled since the mark (`Accounts::start_made`), drawn on the pool the frame starts with (`AdditionalLimit::count_start`): a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; a success revm gave without building the frame — a call to an account with no code, to a precompile that answers — gives way to the stop on its untouched gas, and its committed move and log are taken back to the mark (`take_back_a_stopped_answer`). A call of any scheme that moves no value and whose code address is in none of the EVM's precompiles is not read (`start_writes_nothing` in `evm/execution.rs`): revm's start only loads and touches its target, which changes neither account's nonce, balance or code and journals no log, so the reads would find nothing, and the start counts nothing and is still held to the transaction's limits; a debug build makes the reads and asserts they find nothing. - A `CALLCODE` moving value and a call to a precompile, which a node's own may make write the start's accounts inside the start, are read. + A `CALLCODE` moving value is read, and so is a call to a precompile: revm runs the precompile inside the start, and a node's own precompile may write the start's accounts there. An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: its result is revm's, so a value call to a precompile that fails burns its forward as any failed precompile does, whatever its value transfer would have counted. It is not held to the transaction's limits either, having kept nothing: a deposit whose created caller alone stands over a state-growth limit of nothing, which only a tool's limit sets, and whose first frame is such an answer ends as a failed deposit, not with the stop a success answer there gets (`tests/satin/state_growth.rs`). A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` counts nothing and is stopped by nothing; it was charged nothing at its opcode, which prices a start's records from the journal's state and sees the caller cannot fund the value. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index ea861d2d3..9e8520767 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1242,7 +1242,12 @@ fn take_back_a_stopped_answer( /// its value goes from the calling account to itself, which revm moves and logs nothing for, and /// is read rather than reasoned about. A precompile runs inside the start, and a node's own may /// write the start's accounts there, which are read with the start. A creation writes the account -/// it creates. +/// it creates. A `DELEGATECALL`'s value is its caller's, which it moves nowhere. +/// +/// The opcode that starts a call prices its records before this, by its own rule +/// ([`start_makes_no_records`](crate::limit::start_makes_no_records)): a call that transfers no +/// value makes no record whatever the journal holds, a precompile's writes being no record the +/// opcode prices. fn start_writes_nothing(input: &FrameInput, precompiles: &PrecompilesMap) -> bool { match input { FrameInput::Call(inputs) => { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 1740ac0ae..fea673f20 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -583,6 +583,10 @@ impl AdditionalLimit { for kind in COUNTED { let Some(pool) = kind.pool() else { continue }; if !held && !counted.touches(pool) { + debug_assert!( + self.transaction_crossed(kind, counted, false).within_limit(), + "a dimension a count leaves alone crosses nothing" + ); continue; } let rise = counted.rise(pool); @@ -1027,8 +1031,7 @@ mod tests { .with_tx_state_growth_limit(tx_limit); let mut layer = AdditionalLimit::new(limits); layer.begin_transaction(class, 0); - let prior = Counted::NONE; - let mut prior = prior; + let mut prior = Counted::NONE; for pool in PoolId::ALL { prior.added.set(pool, kept); } @@ -1041,14 +1044,19 @@ mod tests { for &pb in pools { for &pc in pools { let mut counted = Counted::NONE; + let pools = [ + DATA_SIZE_POOL, + KV_UPDATE_POOL, + STATE_GROWTH_POOL, + ]; for (pool, (added, taken)) in - PoolId::ALL.into_iter().zip([a, b, c]) + pools.into_iter().zip([a, b, c]) { counted.added.set(pool, added); counted.taken.set(pool, taken); } counted.transfer_log = transfer_log; - let takes_more = [PoolId::ALL[0], PoolId::ALL[1]] + let takes_more = [DATA_SIZE_POOL, KV_UPDATE_POOL] .into_iter() .any(|pool| counted.taken.get(pool) > kept); if takes_more { @@ -1058,9 +1066,9 @@ mod tests { let mut gas = GasTracker::new(1_000, 1_000, 0); gas.set_pools_remaining( PoolAmounts::ZERO - .with(PoolId::ALL[0], pa + 2) - .with(PoolId::ALL[1], pb + 2) - .with(PoolId::ALL[2], pc + 2), + .with(DATA_SIZE_POOL, pa + 2) + .with(KV_UPDATE_POOL, pb + 2) + .with(STATE_GROWTH_POOL, pc + 2), ); for pool in PoolId::ALL { assert!(gas.record_pool(pool, 2)); diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index aefed9cbc..8ea773fd9 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -169,8 +169,14 @@ pub(crate) struct Accounts<'a> { /// Whether `info` differs from `original` in what a write record stands for: the nonce, the /// balance or the code. fn differs(info: &AccountInfo, original: &AccountInfo) -> bool { + differs_with_balance(info, info.balance, original) +} + +/// Whether `info` with its balance replaced by `balance` differs from `original` in what a write +/// record stands for ([`differs`]). +fn differs_with_balance(info: &AccountInfo, balance: U256, original: &AccountInfo) -> bool { info.nonce != original.nonce || - info.balance != original.balance || + balance != original.balance || info.code_hash != original.code_hash } @@ -188,11 +194,7 @@ fn changed(account: &Account) -> bool { fn changed_now_and_with_balance(account: Option<&Account>, balance: U256) -> (bool, bool) { let Some(account) = account else { return (false, balance != U256::ZERO) }; let original = account.original_info(); - let now = differs(&account.info, &original); - let with_balance = account.info.nonce != original.nonce || - balance != original.balance || - account.info.code_hash != original.code_hash; - (now, with_balance) + (differs(&account.info, &original), differs_with_balance(&account.info, balance, &original)) } /// The balance of `account`, the transaction's load of it; nothing for one it has not loaded. @@ -255,6 +257,11 @@ pub(crate) struct StartBefore { /// journal: a call of any scheme that transfers no value, whose transfer records nothing /// ([`Accounts::transfer_records`]). A creation may record the account it creates and its /// creator's nonce. +/// +/// This is the opcode's price, read off the value the opcode transfers, which is none for a +/// `DELEGATECALL`. Whether revm's start then writes nothing on the frame's accounts, so that they +/// need not be read, is decided where the frame starts, on the frame's input, which a precompile +/// can make write (`start_writes_nothing` in `evm/execution.rs`). pub(crate) fn start_makes_no_records(kind: FrameStartKind, value: U256) -> bool { match kind { FrameStartKind::Create | FrameStartKind::Create2 => false, @@ -286,6 +293,11 @@ impl<'a> Accounts<'a> { Self { journal: &journal.inner } } + /// The journal's entries, which revm clears between transactions: this transaction's. + fn entries(&self) -> &'a [JournalEntry] { + &self.journal.journal + } + /// The account at `address` as the transaction loaded it and holds it now: `None` for one /// the transaction has not loaded, which it has not changed either. fn loaded(&self, address: Address) -> Option<&'a Account> { @@ -384,7 +396,7 @@ impl<'a> Accounts<'a> { return false; } account.is_loaded_as_not_existing() || - self.journal.journal.iter().rev().find_map(|entry| match entry { + self.entries().iter().rev().find_map(|entry| match entry { JournalEntry::AccountDestroyed { address: destroyed, destroyed_status, .. } if *destroyed == address => { @@ -403,14 +415,16 @@ impl<'a> Accounts<'a> { return StartRecords::NONE; } let (from, to) = (self.loaded(from), self.loaded(to)); - let Some(from_after) = balance_of(from).checked_sub(value) else { + let Some(from_balance) = balance_of(from).checked_sub(value) else { return StartRecords::NONE; }; - let to_after = balance_of(to).saturating_add(value); - let (from_now, from_moved) = changed_now_and_with_balance(from, from_after); - let (to_now, to_moved) = changed_now_and_with_balance(to, to_after); - let transfer = RecordDelta::of_account(from_now, from_moved) - .with(RecordDelta::of_account(to_now, to_moved)); + let to_balance = balance_of(to).saturating_add(value); + // Before the transfer the accounts are as they are now; after it they hold the balances it + // leaves them with. + let (from_before, from_after) = changed_now_and_with_balance(from, from_balance); + let (to_before, to_after) = changed_now_and_with_balance(to, to_balance); + let transfer = RecordDelta::of_account(from_before, from_after) + .with(RecordDelta::of_account(to_before, to_after)); StartRecords { transfer, ..StartRecords::NONE } } @@ -539,6 +553,8 @@ impl<'a> Accounts<'a> { /// destructed account held `balance` before it, and a beneficiary that is another account its /// balance less `balance`, all of which it got. fn destruction_records(&self, address: Address, target: Address, balance: U256) -> RecordDelta { + // After the destruction the accounts are as they are now; before it they held the + // balances it moved. let (now, before) = changed_now_and_with_balance(self.loaded(address), balance); let source = RecordDelta::of_account(before, now); if target == address { diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index fd9b08fad..c353eb2ab 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -39,6 +39,7 @@ The fixture types are the revm fork's own (`revm::statetest_types`, the `test-ty ## WHERE TO LOOK - Add or move a deviation: `src/deviations.rs`, its entries taken from a `--json-outcome` run, then `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. - Change what the outcome digest records, or how it is encoded: `src/digest.rs`; every change moves the digest of every transaction it touches, so it is made on its own, with the base's digest taken by the same code. +- Change what the read-set digest records (`digest::reads`, printed by `Config::witness` per transaction and by `blockchain::Config::witness` per block): `src/digest.rs`; the reads are recorded by `mega-evm`'s `test_utils::{RecordingDatabase, RecordingEnvFactory}` around the database and environments a test runs on, and the same rule holds: a change is made on its own, the base's read sets taken by the same code. - Tighten the limits a run is held to: `Config::limits`, from `state-test`'s `--limit-*` options. - Change what a mode configures: `src/mode.rs`, and `mega-evm`'s `src/test_utils/neutral.rs`. - Change how a test is judged: `src/runner.rs::check`, `src/exceptions.rs`. diff --git a/crates/state-test/AGENTS.md b/crates/state-test/AGENTS.md index 64a348c84..981c259bc 100644 --- a/crates/state-test/AGENTS.md +++ b/crates/state-test/AGENTS.md @@ -7,7 +7,7 @@ This crate is not published; the runner, the modes, the deviation registry and t ## STRUCTURE - `src/main.rs`: flag parsing, the printed summary, and the exit-code contract. - `src/btest.rs`: the `btest` subcommand, the blockchain tests' gate, with the same contract; `main` hands it every argument after `btest`, so the state tests' command is unchanged. -- `tests/cli.rs`: the exit-code contract CI relies on. +- `tests/cli.rs`: the exit-code contract CI relies on, and the lines the digest and witness options print. ## WHERE TO LOOK - Change CLI flags, the summary or the exit codes: `src/main.rs`, and `src/btest.rs` for the blockchain tests. diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index c9d8521e6..d5b18405d 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -496,9 +496,16 @@ fn test_btest_the_witness_options_print_a_line_per_block() { let history = "0x0000f90827f1c53a10cb7a02335b175320002935"; assert!(full[0]["reads"]["accounts"][history].is_null(), "{}", full[0]["reads"]); - let refused = blockchain_fixture(dir.path(), "b", |header| header.gas_limit = 0); - let lines = stderr_lines(&btest(&["--json-witness"], &refused)); - assert!(lines.iter().all(|line| line["block"] == 0), "{lines:?}"); + // A block without a parent beacon root, which the EIP-4788 pre-block call needs, is refused + // after what it read so far: a line of its own, which the import's failure does not drop. + let refused = blockchain_fixture(dir.path(), "b", |header| { + header.parent_beacon_block_root = None; + }); + let output = btest(&["--json-witness"], &refused); + assert!(stdout(&output).contains("unattributed 1"), "{}", stdout(&output)); + let lines = stderr_lines(&output); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!((&lines[0]["block"], &lines[0]["row"]), (&json!(0), &json!("refused"))); } #[test] From 971e05bf31f0a138e43f7a5494f61502e4cd5780 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 23:38:21 +0800 Subject: [PATCH 32/83] test(state-test): require the pre-block account read to be present as null --- crates/state-test/tests/cli.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index d5b18405d..a979e0271 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -494,7 +494,12 @@ fn test_btest_the_witness_options_print_a_line_per_block() { assert_eq!(full[0]["witness"], compact[0]["witness"]); // The pre-block calls read the EIP-2935 history contract, which the pre-state does not hold. let history = "0x0000f90827f1c53a10cb7a02335b175320002935"; - assert!(full[0]["reads"]["accounts"][history].is_null(), "{}", full[0]["reads"]); + assert_eq!( + full[0]["reads"]["accounts"].get(history), + Some(&serde_json::Value::Null), + "{}", + full[0]["reads"] + ); // A block without a parent beacon root, which the EIP-4788 pre-block call needs, is refused // after what it read so far: a line of its own, which the import's failure does not drop. From db9fce040d1ec218ff9261460cd9a31dfaf297df Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 23:38:21 +0800 Subject: [PATCH 33/83] bench(block): check the ERC-20 workload's log, return value and balances in the preflight --- crates/mega-evm/benches/block.rs | 40 +++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index ded22b6f2..4e45afffa 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -39,13 +39,15 @@ use alloy_eips::{ }; use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, hex, keccak256, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_primitives::{ + address, b256, hex, keccak256, Address, Bytes, Signature, TxKind, B256, U256, +}; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ system::{MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, test_utils::{BytecodeBuilder, CommittedStates, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, + MegaSpecId, MegaTransactionOutcome, MegaTxEnvelope, }; use op_revm::constants::L1_BLOCK_CONTRACT; use revm::{ @@ -88,6 +90,10 @@ const TOKEN_CODE: [u8; 492] = hex!("608060405234801561000f575f5ffd5b506004361061 const TOKEN_SENDER_BASE: u64 = 0x60_0000; const TOKEN_HOLDER_BASE: u64 = 0x70_0000; +/// The first topic of ERC-20's `Transfer(address,address,uint256)`. +const TRANSFER_TOPIC: B256 = + b256!("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + /// Code that writes 1 to the slot its first calldata word names, so every call that names a slot /// of its own changes storage and leaves a write record behind. fn writer_code() -> Bytes { @@ -223,6 +229,31 @@ fn token_transfers() -> Vec> { .collect() } +/// Asserts that the `index`-th ERC-20 transfer did what the workload says: it returned `true`, +/// emitted one `Transfer` log of the token with the sender, the recipient and the amount, and left +/// the two balances moved by that amount. +fn assert_token_transfer(index: u64, outcome: &MegaTransactionOutcome) { + let sender = nth_account(TOKEN_SENDER_BASE, index); + let holder = nth_account(TOKEN_HOLDER_BASE, index); + assert_eq!( + outcome.result.output(), + Some(&Bytes::from(U256::from(1_u64).to_be_bytes::<32>())), + "transfer {index} returns true" + ); + let logs = outcome.result.logs(); + assert_eq!(logs.len(), 1, "transfer {index} emits one log: {logs:?}"); + assert_eq!(logs[0].address, TOKEN); + assert_eq!( + logs[0].topics(), + [TRANSFER_TOPIC, sender.into_word(), holder.into_word()], + "transfer {index} names its sender and recipient" + ); + assert_eq!(logs[0].data.data, Bytes::from(U256::from(1_u64).to_be_bytes::<32>())); + let token = &outcome.state[&TOKEN].storage; + assert_eq!(token[&token_balance_slot(sender)].present_value, U256::from(999_999_u64)); + assert_eq!(token[&token_balance_slot(holder)].present_value, U256::from(2_u64)); +} + fn chain_spec() -> MegaHardforkConfig { MegaHardforkConfig::default().with_all_activated() } @@ -309,7 +340,7 @@ fn bench_block(c: &mut Criterion) { let mut executor = MegaBlockExecutor::new(evm, block_ctx(), &spec, OpAlloyReceiptBuilder::default()); executor.apply_pre_execution_changes().expect("the block starts"); - for tx in txs { + for (index, tx) in txs.iter().enumerate() { let outcome = executor.execute_transaction_without_commit(tx).expect("the transaction runs"); assert!(outcome.result.is_success(), "{:?}", outcome.result); @@ -318,6 +349,9 @@ fn bench_block(c: &mut Criterion) { outcome.usage.write_records, *records, "every transaction of the workload keeps its write records" ); + if *name == "erc20_transfers" { + assert_token_transfer(index as u64, &outcome); + } executor.commit_transaction(outcome); } let (_, result) = executor.finish_with_counters().expect("the block finishes"); From 2abb441ac6057114ae7ad6c94a2b8bdf4f290085 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:26:27 +0800 Subject: [PATCH 34/83] docs(spec): name Satin's EIP-8037 profile and its freeze point Satin applied EIP-8037 as of one commit with a list of later commits taken and declined spread through the Two-Pool Gas section, but did not say where that list ends, so a later edit to the EIP could be read as part of Satin. The profile gathers the base commit, the later commits taken, declined and not tracked, and Satin's own departures (the reservoir share, history gas on the reservoir, the destruction-table refill), fixes the freeze point at the last commit Satin decided on, and makes every later change to the EIP an input to a later spec rather than to Satin. --- docs/spec/upgrades/satin.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 91a568531..c6ac01d60 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -36,7 +36,7 @@ The changes, in the order this page records them: 1. **Base layer.** Optimism Karst (Ethereum Osaka), four Amsterdam opcodes, and no EIP-7825 or EIP-8037 transaction gas cap. 2. **Precompiles.** Karst's set, with KZG point evaluation still at 100,000. 3. **Contract size limits.** 512 KiB of code and 1 MiB of initcode. -4. **Two-pool gas.** EIP-8037, as of 4 September 2026, regular gas and state-gas reservoir under a 200,000,000 execution cap, and three gas ledgers. +4. **Two-pool gas.** EIP-8037 in Satin's profile, whose freeze point is 18 September 2026: regular gas and state-gas reservoir under a 200,000,000 execution cap, and three gas ledgers. 5. **Gas schedule and intrinsic gas.** Amsterdam's schedule, EIP-8038's state-access prices included, and EIP-2780 intrinsic cost. 6. **State gas and SALT pricing.** `entry × multiplier` on EIP-8037's byte counts, replacing `base × (multiplier − 1)`. 7. **History gas.** A price per byte on everything a transaction appends to history. @@ -222,6 +222,32 @@ The removal of an unused counter ([commit `052029f362`](https://github.com/ether Satin has no separate compute-gas limit: compute is regular gas, bounded by the execution cap and, after a read of volatile data, by [gas detention](#12-gas-detention-on-withheld-gas). +##### Satin's EIP-8037 profile + +Satin's EIP-8037 profile is the EIP as this section and the sections it names apply it. +Its freeze point is [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) (18 September 2026), the last commit to the EIP whose change Satin decided on. + +- **Base.** + EIP-8037 as of [commit `c406bdb2ff`](https://github.com/ethereum/EIPs/commit/c406bdb2ffbf2fbf9d85698e97b3b2e8b6e79112) (4 September 2026), with the parameters this section and [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing) set: the execution cap, and MegaETH's cost per state byte scaled by the bucket multiplier. +- **Later commits taken.** + The child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef), as the reference implementation performs it. + The failure outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5): a failure of the first frame does not give back the reservoir that an authority charge made before the frame had drawn. + The collision rule of [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898): a creation does not collide on storage. +- **Later commits declined.** + The transaction gas cap of [commit `d7087803ca`](https://github.com/ethereum/EIPs/commit/d7087803ca236498c73f64665df0ddac7d621950). + The commit of the pre-execution spill in [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5), which would keep a later return from unwinding it. +- **Later commits not tracked.** + The removal of an unused counter ([commit `052029f362`](https://github.com/ethereum/EIPs/commit/052029f3625328d6f51dec8e62a7090201e66f17)), which changes no rule a transaction executes. +- **Satin's own departures from the EIP.** + - The reservoir share: a child frame receives `reservoir_share = remaining − remaining × 2 / 100` of the reservoir its caller has left, and the caller keeps the rest, where EIP-8037 passes the whole reservoir (see [Gas Forwarding](#9-gas-forwarding)). + The reservoir a child returns joins what the caller kept, after it unwinds the caller's outstanding spill (the child-merge rule above). + - History gas: a history charge draws the reservoir first and shares the spill with state charges, is given back with them when its frame fails, and is booked on a ledger of its own; the history gas of the transaction's body is the intrinsic state gas (see [History Gas](#7-history-gas)). + - The destruction-table refill: the first effective `SELFDESTRUCT` of an account created in the same transaction refills the state gas of each part of it that was absent at the transaction's start, where EIP-8037 specifies that this destruction produces no state-gas refills (see [The destruction table](#the-destruction-table)). + +A change to EIP-8037 after [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) is an input to a later spec, not to Satin. +The co-author lines and the move to Last Call came after it and change no rule a transaction executes. +A node MUST NOT apply such a change under Satin, whatever the EIP's status becomes. + ### 5. Gas Schedule and Intrinsic Gas #### Previous behavior @@ -1551,6 +1577,7 @@ Satin is unstable and not scheduled on any network: its prices, limits and rules - [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) as of [commit `c406bdb2ff`](https://github.com/ethereum/EIPs/commit/c406bdb2ffbf2fbf9d85698e97b3b2e8b6e79112) — state gas and the reservoir. Satin adopts the child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef), drawing only the reservoir the child returns, and does not adopt the transaction gas cap of [commit `d7087803ca`](https://github.com/ethereum/EIPs/commit/d7087803ca236498c73f64665df0ddac7d621950). + Satin's profile of it, with its freeze point and its departures, is [Satin's EIP-8037 profile](#satins-eip-8037-profile). The creation-collision rule of [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) and the first-frame authority outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5) are this page's own rules, stated in [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model). - [EIP-2780](https://eips.ethereum.org/EIPS/eip-2780) — the decomposed intrinsic cost. - [EIP-8038](https://eips.ethereum.org/EIPS/eip-8038) — the state-access prices. From d8bd2a31d86fa2b3e6d26567f35eba2ef5e003c6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 10:07:32 +0800 Subject: [PATCH 35/83] test(limit): pin the frame-budget boundary of a completed write's count --- crates/mega-evm/src/limit/limit.rs | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index fea673f20..b3f234916 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -960,6 +960,45 @@ mod tests { ); } + /// A frame budget admits a count that uses exactly what the pool holds and stops one more: + /// the boundary is the pool's remaining amount, in each counted pool, with the transaction's + /// limit out of the way so only the frame's budget decides. + #[test] + fn test_a_count_equal_to_the_pools_remaining_is_within_the_frame_budget() { + let remaining = 6_u64; + for pool in PoolId::ALL { + for (added, within) in + [(remaining - 1, true), (remaining, true), (remaining + 1, false)] + { + let mut layer = AdditionalLimit::new(EvmTxRuntimeLimits::no_limits()); + layer.begin_transaction(TxClass::Ordinary, 0); + let mut gas = GasTracker::new(1_000, 1_000, 0); + gas.set_pools_remaining(PoolAmounts::ZERO.with(pool, remaining)); + let mut counted = Counted::NONE; + counted.added.set(pool, added); + let verdict = layer.draw(&mut gas, &counted); + let case = format!("{pool:?}, adds {added} to {remaining}"); + if within { + assert_eq!(verdict, LimitCheck::WithinLimit, "{case}"); + assert_eq!(gas.pool_remaining(pool), remaining - added, "{case}"); + assert_eq!( + layer.kept.net[pool.index()], + i64::try_from(added).unwrap(), + "{case}" + ); + } else { + assert!(verdict.exceeded_limit(), "{case}"); + assert!( + matches!(verdict, LimitCheck::ExceedsLimit { frame_local: true, .. }), + "{case}: {verdict:?}" + ); + assert_eq!(gas.pool_remaining(pool), remaining, "{case}: nothing drawn"); + assert_eq!(layer.kept.net[pool.index()], 0, "{case}: nothing counted"); + } + } + } + } + /// `draw` as it was before it learned to leave alone the pools a count does not touch: every /// pool's budget and every dimension's limit checked off a snapshot of the pools, and every /// pool drawn, refilled and counted. The reference [`draw`](AdditionalLimit::draw) is held to. From 3eb540182a03505c764eaca74e4f1ec2dc97d507 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 10:10:51 +0800 Subject: [PATCH 36/83] refactor(limit): drop the rise guard that the budget comparison already implies A rise of zero or below never exceeds a pool's remaining, which is unsigned, so the comparison alone decides the verdict. --- crates/mega-evm/src/limit/limit.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index b3f234916..699a2c122 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -590,14 +590,12 @@ impl AdditionalLimit { continue; } let rise = counted.rise(pool); - if rise > 0 { - let remaining = gas.pool_remaining(pool); - if rise > remaining as i128 { - let spent = gas.pool_spent(pool); - let check = self.budget_crossed(kind, remaining, spent, rise as u64); - if check.exceeded_limit() { - return check; - } + let remaining = gas.pool_remaining(pool); + if rise > remaining as i128 { + let spent = gas.pool_spent(pool); + let check = self.budget_crossed(kind, remaining, spent, rise as u64); + if check.exceeded_limit() { + return check; } } let check = self.transaction_crossed(kind, counted, held); From 68a529b5f343f4ad8dca635d9ad0d2b5a3d91d94 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 10:48:48 +0800 Subject: [PATCH 37/83] chore(deps): pin the revm and op-revm forks at the heads of their pull requests The revm fork's pull request adds an accessor that lends an account's original info by reference; the op-revm fork's pull request follows that head. --- .claude/skills/satin-review/SKILL.md | 2 +- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 26 +++++++++++++------------- docs/spec/overview.md | 2 +- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index e25b00bd8..dd195b230 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -32,7 +32,7 @@ The guide describes the code at `cz/feat/satin-w2` with #407 merged into it and Satin is a new spec: simpler semantics win over parity with the legacy engine. - Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates. Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code. -- Fork code: the `megaeth-labs/revm` fork at `fd230a3427d1b96c88e0b581bab8a7763c8ec298` and the `megaeth-labs/op-revm` fork at `2ecb7dceed1c458a2b59ca4d8993a073968cb111`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. +- Fork code: the `megaeth-labs/revm` fork at `b370b53852507dfedd342e062e96dba896cb30df` and the `megaeth-labs/op-revm` fork at `589c5078569d93d1e7293ae0d33c59efa87b1089`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. Their diff is not part of this pull request. A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour. The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks). diff --git a/Cargo.lock b/Cargo.lock index 1eeebca2c..1e95fe05d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?rev=2ecb7dceed1c458a2b59ca4d8993a073968cb111#2ecb7dceed1c458a2b59ca4d8993a073968cb111" +source = "git+https://github.com/megaeth-labs/op-revm?rev=589c5078569d93d1e7293ae0d33c59efa87b1089#589c5078569d93d1e7293ae0d33c59efa87b1089" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "revm-bytecode 11.0.1", "revm-context 18.0.3", @@ -5227,7 +5227,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "alloy-eips 2.1.1", "alloy-provider 2.1.1", @@ -5349,7 +5349,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "revm-bytecode 11.0.1", "revm-context-interface 19.0.3", @@ -5523,7 +5523,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "alloy-eip7928 0.4.11", "bitflags 2.11.1", @@ -5594,7 +5594,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" +source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index bf2738ac7..2a71e772e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,20 +232,20 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built # against the revm pin above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "2ecb7dceed1c458a2b59ca4d8993a073968cb111" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "589c5078569d93d1e7293ae0d33c59efa87b1089" } diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 7e1763185..86154ed6a 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -51,7 +51,7 @@ For the current stable behavior as a single reference, see the [MegaEVM Overview Satin (unstable): base layer and reference implementation Satin inherits standard EVM semantics from Optimism Karst (Ethereum Osaka) unless explicitly overridden, and every transaction but a deposit or one of the protocol's own pays history gas, so no transaction that pays it behaves identically to Optimism under Satin. -Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `fd230a3427d1b96c88e0b581bab8a7763c8ec298` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `2ecb7dceed1c458a2b59ca4d8993a073968cb111` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. +Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `b370b53852507dfedd342e062e96dba896cb30df` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `589c5078569d93d1e7293ae0d33c59efa87b1089` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. See the [Satin Network Upgrade](upgrades/satin.md). From 2b8922914287b9f36e980e9f71a8cde1cfa78914 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 22:08:28 +0800 Subject: [PATCH 38/83] perf(limit): compare an account with its original info by reference `Accounts::is_changed` and `changed_with_balance` compared the account's info with `Account::original_info()`, which clones the original info and with it the code's reference count, on every frame start's reads and every value transfer's records. The fork's `Account::original_info_ref()` lends the same info by reference. --- crates/mega-evm/src/limit/record.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 8ea773fd9..32e9e7b9b 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -183,7 +183,7 @@ fn differs_with_balance(info: &AccountInfo, balance: U256, original: &AccountInf /// Whether the transaction changed `account`, which it loaded, from what it loaded: its nonce, /// balance or code differs from its original info. fn changed(account: &Account) -> bool { - differs(&account.info, &account.original_info()) + differs(&account.info, account.original_info_ref()) } /// Whether the account `account` — the transaction's load of it, `None` for one it has not loaded @@ -193,8 +193,8 @@ fn changed(account: &Account) -> bool { /// The account's original info is read once for both. fn changed_now_and_with_balance(account: Option<&Account>, balance: U256) -> (bool, bool) { let Some(account) = account else { return (false, balance != U256::ZERO) }; - let original = account.original_info(); - (differs(&account.info, &original), differs_with_balance(&account.info, balance, &original)) + let original = account.original_info_ref(); + (differs(&account.info, original), differs_with_balance(&account.info, balance, original)) } /// The balance of `account`, the transaction's load of it; nothing for one it has not loaded. From 7646bae4a8ca0ea98505305391f831155f3cd7e0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 11:11:33 +0800 Subject: [PATCH 39/83] chore: bump Rust nightly to fix closure-call miscompilation Use nightly-2026-04-23, the first nightly with rust-lang/rust#155343, which fixes the indirect closure argument miscompilation in rust-lang/rust#155241. --- rust-toolchain.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 0ab2994b3..8633cbb6c 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2026-04-14" +channel = "nightly-2026-04-23" components = ["rustfmt", "clippy", "rust-src", "miri", "rust-analyzer"] From 98a1848d600ab48e241afe83d2d21c90da397e85 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 15:07:17 +0800 Subject: [PATCH 40/83] chore(deps): pin the revm and op-revm forks at the heads of their pull requests The revm fork's pull request adds a start lifecycle that its runners keep; the op-revm fork's pull request calls it from its handler's boundaries. The engine names the outcomes' new start mark in its literals, and a test that drives a transaction's frame by hand opens the transaction's start first, as the fork now requires. No execution result changes. --- .claude/skills/satin-review/SKILL.md | 2 +- Cargo.lock | 28 +++++++++---------- Cargo.toml | 26 ++++++++--------- crates/mega-evm/src/evm/frame.rs | 4 ++- .../tests/system/keyless/differential.rs | 1 + crates/mega-evm/tests/system/keyless/frame.rs | 6 +++- .../tests/system/keyless/inspector.rs | 2 ++ docs/spec/overview.md | 2 +- 8 files changed, 40 insertions(+), 31 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index dd195b230..2c5f3b79c 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -32,7 +32,7 @@ The guide describes the code at `cz/feat/satin-w2` with #407 merged into it and Satin is a new spec: simpler semantics win over parity with the legacy engine. - Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates. Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code. -- Fork code: the `megaeth-labs/revm` fork at `b370b53852507dfedd342e062e96dba896cb30df` and the `megaeth-labs/op-revm` fork at `589c5078569d93d1e7293ae0d33c59efa87b1089`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. +- Fork code: the `megaeth-labs/revm` fork at `426217bb2e76c0a41d46907eb788250e8efa107c` and the `megaeth-labs/op-revm` fork at `3d43e32029fc5cd293ab70eb0929d70e37337966`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. Their diff is not part of this pull request. A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour. The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks). diff --git a/Cargo.lock b/Cargo.lock index 1e95fe05d..2c9548057 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?rev=589c5078569d93d1e7293ae0d33c59efa87b1089#589c5078569d93d1e7293ae0d33c59efa87b1089" +source = "git+https://github.com/megaeth-labs/op-revm?rev=3d43e32029fc5cd293ab70eb0929d70e37337966#3d43e32029fc5cd293ab70eb0929d70e37337966" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "revm-bytecode 11.0.1", "revm-context 18.0.3", @@ -5227,7 +5227,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "alloy-eips 2.1.1", "alloy-provider 2.1.1", @@ -5349,7 +5349,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "revm-bytecode 11.0.1", "revm-context-interface 19.0.3", @@ -5523,7 +5523,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "alloy-eip7928 0.4.11", "bitflags 2.11.1", @@ -5594,7 +5594,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=b370b53852507dfedd342e062e96dba896cb30df#b370b53852507dfedd342e062e96dba896cb30df" +source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index 2a71e772e..e47b7c840 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,20 +232,20 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "b370b53852507dfedd342e062e96dba896cb30df" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built # against the revm pin above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "589c5078569d93d1e7293ae0d33c59efa87b1089" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "3d43e32029fc5cd293ab70eb0929d70e37337966" } diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index e2dc505d1..16db4e6f3 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -25,7 +25,7 @@ use revm::{ handler::FrameResult, interpreter::{ CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, - InterpreterResult, + InterpreterResult, OutcomeMark, }, }; @@ -66,6 +66,7 @@ pub fn synthetic_frame_result( charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), charged_start: inputs.charged_start(), + start_mark: OutcomeMark::NONE, }), FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), } @@ -87,6 +88,7 @@ pub fn synthetic_call_result( charged_new_account_state_gas: inputs.charged_new_account_state_gas, charged_state_gas_address: inputs.target_address, charged_start: inputs.charged_start, + start_mark: OutcomeMark::NONE, }) } diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index 066a53282..d3507a816 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -960,6 +960,7 @@ impl Inspector, EthInterpreter> for Recorder { charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), charged_start: Default::default(), + start_mark: Default::default(), }) } diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 88db12ced..5ca3642ba 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -55,7 +55,8 @@ fn call_frame(code: revm::state::Bytecode, data: Bytes, gas_limit: u64) -> Frame } /// The call is a frame on revm's stack, driven through revm's frame lifecycle by hand, as revm's -/// loop drives it, a frame's run result handed over before it returns: revm builds it at depth 0; +/// loop drives it, from the transaction's start, a frame's run result handed over before it +/// returns: revm builds it at depth 0; /// its first run starts the creation as its child, at depth 1, which revm builds above it on the /// stack; the creation returns into it; and on its resume it answers in the ABI, as the outermost /// frame. @@ -67,6 +68,9 @@ fn test_the_call_is_a_frame_on_revms_stack() { journal.load_account(CALLER).unwrap(); let code = journal.load_account_with_code(KEYLESS_DEPLOY_ADDRESS).unwrap().info.code.clone(); let init = call_frame(code.unwrap(), deployment.call_data(LARGE_OVERRIDE), 10_000_000); + // A runner that drives the transaction's frame by hand opens the transaction's start first, + // as revm's `Handler::execution` does. + revm::handler::lifecycle::open_frame_start(&mut evm, &init).unwrap(); let ItemOrResult::Item(call) = EvmTr::frame_init(&mut evm, init).unwrap() else { panic!("revm builds the call's frame"); diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index cbf0fee57..8250b3d48 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -76,6 +76,7 @@ impl Inspector, EthInterpreter> for Recorder { charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), charged_start: Default::default(), + start_mark: Default::default(), }) } @@ -236,6 +237,7 @@ impl Inspector for AnswersCreations { charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), charged_start: Default::default(), + start_mark: Default::default(), }) } } diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 86154ed6a..d7dfcde65 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -51,7 +51,7 @@ For the current stable behavior as a single reference, see the [MegaEVM Overview Satin (unstable): base layer and reference implementation Satin inherits standard EVM semantics from Optimism Karst (Ethereum Osaka) unless explicitly overridden, and every transaction but a deposit or one of the protocol's own pays history gas, so no transaction that pays it behaves identically to Optimism under Satin. -Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `b370b53852507dfedd342e062e96dba896cb30df` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `589c5078569d93d1e7293ae0d33c59efa87b1089` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. +Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `426217bb2e76c0a41d46907eb788250e8efa107c` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `3d43e32029fc5cd293ab70eb0929d70e37337966` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. See the [Satin Network Upgrade](upgrades/satin.md). From 2c4822a38693fdcfd5ed9e3d6095a68385e8d84d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 16:53:38 +0800 Subject: [PATCH 41/83] feat(evm): forward the start lifecycle hooks to the inner context in debug builds --- crates/mega-evm/src/evm/host.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index ccb6554bc..15b64e9eb 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -67,6 +67,12 @@ //! destroyed it. A database that answers an empty account for an address it holds none for gives //! that leaf back to no destruction: an empty account is a leaf the state holds. //! +//! # The start lifecycle +//! +//! The three lifecycle hooks — a start revm opened, one it settled, the lifecycle's end — reach the +//! inner context in a debug build, whose mirror checks their order over every engine path. A release +//! build takes the trait's defaults, which do nothing. +//! //! Every other Host method delegates to op-revm's context. #[cfg(not(feature = "std"))] @@ -89,6 +95,9 @@ use revm::{ Database, }; +#[cfg(debug_assertions)] +use revm::context_interface::host::{FrameSettle, FrameSplit, LifecycleEnd}; + use crate::{ charge_write_records_history, history_gas, limit::{DestroyedParts, HistoryBytes}, @@ -432,6 +441,25 @@ impl revm::context_interface::Host start.charge = StartCharge::new(charge, PoolAmounts::ZERO); true } + + /// Hands the inner context the start revm opened, so its debug mirror checks the lifecycle's + /// order over the engine. + #[cfg(debug_assertions)] + fn frame_split(&mut self, split: &FrameSplit) { + self.inner.frame_split(split); + } + + /// Hands the inner context the start revm settled into `gas`, its caller's. + #[cfg(debug_assertions)] + fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { + self.inner.frame_settle(settle, gas); + } + + /// Hands the inner context the lifecycle's end. + #[cfg(debug_assertions)] + fn frame_lifecycle_end(&mut self, end: LifecycleEnd) { + self.inner.frame_lifecycle_end(end); + } } impl MegaContext { From 60238bfbed392bf869889296538bc97963f3050c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 17:03:27 +0800 Subject: [PATCH 42/83] feat(limit): a start ledger checked against the fork's figures in debug builds The engine keeps its own per-start ledger of the four figures the revm fork carries on a frame's gas: the three pools with their nets and crossings, the reservoir a caller keeps, the start charge and the history allowance. It is driven only by the start lifecycle hooks: an entry opens at the split with what the frame-start hook, the keylessDeploy builder or the first frame's input parked for it, draws go to the top entry, and a settlement merges by the engine's rules, applying the inspector rules for an answer, a replaced tracker and a rebuilt outcome. Every settlement compares the ledger with the fork's figures, and a difference panics. The engine still reads the fork's figures for every result, and release builds carry none of it. Tests that run an inspector shape whose figures are accepted to change record the differences and assert each. --- crates/mega-evm/src/evm/context.rs | 28 + crates/mega-evm/src/evm/execution.rs | 117 +++ crates/mega-evm/src/evm/host.rs | 43 +- crates/mega-evm/src/limit/ledger.rs | 981 ++++++++++++++++++ crates/mega-evm/src/limit/limit.rs | 20 + crates/mega-evm/src/limit/mod.rs | 6 + .../mega-evm/src/system/keyless/dispatch.rs | 6 + crates/mega-evm/src/test_utils/ledger.rs | 29 + crates/mega-evm/src/test_utils/mod.rs | 4 + crates/mega-evm/tests/satin/common.rs | 41 + crates/mega-evm/tests/satin/history_bytes.rs | 21 +- .../tests/satin/inspector_cheatcodes.rs | 38 +- .../mega-evm/tests/satin/inspector_limits.rs | 27 +- .../tests/satin/inspector_settlement.rs | 53 +- 14 files changed, 1394 insertions(+), 20 deletions(-) create mode 100644 crates/mega-evm/src/limit/ledger.rs create mode 100644 crates/mega-evm/src/test_utils/ledger.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index a6c71484a..6b23c1246 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -496,6 +496,34 @@ impl MegaContext { !self.runs_neutral() && self.system_call } + /// The part of its pools and of its EIP-8037 reservoir, in per cent, a caller keeps when it + /// starts a frame, by the engine's own rule: [`FRAME_KEPT_PERCENT`] on the spec's + /// configuration, and nothing on the neutral one, which forwards the whole of each as Ethereum + /// does. A debug build's start ledger computes a start's shares by it. + /// + /// [`FRAME_KEPT_PERCENT`]: crate::evm::schedule::FRAME_KEPT_PERCENT + #[cfg(debug_assertions)] + pub(crate) const fn frame_kept_percent(&self) -> u64 { + if self.runs_neutral() { + 0 + } else { + super::schedule::FRAME_KEPT_PERCENT + } + } + + /// The history allowance a value-transferring `CALL` or `CALLCODE` gives the frame it starts, + /// by the engine's own rule: [`history_allowance_gas`](crate::history_allowance_gas) on the + /// spec's configuration, and none on the neutral one, which prices no history. A debug build's + /// start ledger keeps it. + #[cfg(debug_assertions)] + pub(crate) fn value_call_allowance(&self) -> u64 { + if self.runs_neutral() { + 0 + } else { + super::history::history_allowance_gas() + } + } + /// Whether the destruction table prices state gas: a destruction of an account created in the /// transaction gives back the state gas of the parts the transaction made, and from that mark /// the account keeps no further state gas. The spec's configuration does: it always charges diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9e8520767..c41944649 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -347,6 +347,11 @@ where None => repriced(), }; let charge = StartCharge::new(history, PoolAmounts::ZERO); + #[cfg(debug_assertions)] + let owed = crate::limit::Parked::transaction( + evm.ctx_ref().additional_limit.first_frame_pools(), + history, + ); gas.set_pools_remaining(evm.ctx_ref().additional_limit.first_frame_pools()); let Some(mut frame) = self.op.first_frame_input(evm, gas)? else { // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge @@ -358,8 +363,12 @@ where // rebuilding the transaction's gas from its intrinsic cost, the history charged for // the first frame's write record included, which no frame carries back. evm.ctx_mut().additional_limit.take_back_authorities(); + #[cfg(debug_assertions)] + evm.ctx_mut().additional_limit.ledger_mut().park_transaction(None); return Ok(None); }; + #[cfg(debug_assertions)] + evm.ctx_mut().additional_limit.ledger_mut().park_transaction(Some(owed)); match &mut frame.frame_input { FrameInput::Call(inputs) => inputs.charged_start = charge, FrameInput::Create(inputs) => inputs.set_charged_start(charge), @@ -392,6 +401,8 @@ where let layer = &mut evm.ctx_mut().additional_limit; layer.close_start(0, frame_result.instruction_result().is_ok()); layer.take_frame_stop(frame_result, true); + #[cfg(debug_assertions)] + layer.ledger_mut().returning(fork_figures(frame_result)); self.op.last_frame_result(evm, frame_result, parent_gas)?; let priced = evm.ctx_ref().prices_history(); let history = 0_u64.saturating_add_signed(frame_result.gas().history_gas_spent()); @@ -649,6 +660,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm( ctx.detention.on_frame_suspend(&caller.interpreter.gas, caller.depth, stipend); let caps = ctx.additional_limit.frame_caps(); cap_the_shares(ctx.gas_params(), caps, &mut caller.interpreter.gas, child); + #[cfg(debug_assertions)] + { + let kept = ctx.frame_kept_percent(); + ctx.additional_limit.ledger_mut().cap_child(caps, kept); + } } /// The action of `frame` that stops it at the limit `verdict` names before it runs another @@ -1231,6 +1253,30 @@ fn take_back_a_stopped_answer( } } +/// The fork's figures of `result`, about to settle into its caller, for the start ledger: the +/// history of the start charge it gives back, and what the result holds of its frame's history +/// allowance. +#[cfg(debug_assertions)] +fn fork_figures(result: &FrameResult) -> crate::limit::Returning { + let refund = result.refundable_start_charge().map_or(0, |charge| charge.history); + crate::limit::Returning::new(refund, result.gas().history_allowance()) +} + +/// Has the start ledger adopt what a precompile's provider drew on the pools of `answer`, revm's +/// answer to the start on top: the net draws its gas holds. A start revm refused, or answered +/// without a provider, drew nothing. The engine's provider draws no pool, so the draws are none. +#[cfg(debug_assertions)] +fn adopt_provider_draws( + ctx: &mut MegaContext, + answer: &FrameResult, +) { + let FrameResult::Call(outcome) = answer else { return }; + if outcome.was_precompile_called { + let draws = PoolId::ALL.map(|pool| outcome.result.gas.pool_spent(pool)); + ctx.additional_limit.ledger_mut().adopt_provider_draws(draws); + } +} + /// Whether revm's start of the frame `input` asks for leaves the accounts it starts on as the /// transaction held them and journals no transfer log, so that reading them before and after the /// start ([`FrameStart::of`], [`FrameStart::count`]) would find no write record, no new account and @@ -1412,6 +1458,8 @@ fn stop_the_answer_at( if verdict.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&verdict); stop_the_answer(answer, start, output); + #[cfg(debug_assertions)] + ctx.additional_limit.ledger_mut().rebuild_on_shares(); } } @@ -2133,6 +2181,75 @@ mod tests { } } + /// The start ledger holds a child's shares as the engine's `cap_the_shares` holds them, on the + /// fork's forward: to the frame cap, and, for a caller whose net is negative, to the share of + /// the caller's budget, the excess given back to the caller. Each case runs both on the same + /// caller: pools limited, unlimited or empty; a net of nothing, positive or negative; and a + /// data-size cap above, at or below the share, or none. + #[test] + #[cfg(debug_assertions)] + fn test_the_start_ledger_holds_a_childs_shares_as_cap_the_shares_does() { + use crate::{ + evm::FRAME_KEPT_PERCENT, + limit::{Counted, Parked, StartLedger, DATA_SIZE_POOL}, + satin_gas_params, + }; + let pools = [ + PoolAmounts::ZERO.with(PoolId::new(0), 10_000).with(PoolId::new(1), 250), + PoolAmounts::UNLIMITED, + PoolAmounts::ZERO, + ]; + // What the caller draws and takes back before the start, on every pool. + let moves = [(0, 0), (100, 0), (0, 4_000), (100, 37)]; + let caps = [u64::MAX, 9_800, 5_000, 0]; + for pools in pools { + for (drawn, taken) in moves { + for cap in caps { + let case = format!("{pools:?}, drawn {drawn}, taken {taken}, cap {cap}"); + let counted = Counted { + added: PoolAmounts::ZERO + .with(PoolId::new(0), drawn) + .with(PoolId::new(1), drawn.min(pools.get(PoolId::new(1)))) + .with(PoolId::new(2), drawn.min(pools.get(PoolId::new(2)))), + taken: PoolAmounts::ZERO.with(PoolId::new(0), taken), + transfer_log: false, + }; + if counted.added.get(PoolId::new(0)) > + pools.get(PoolId::new(0)).saturating_add(taken) + { + continue; + } + let mut caller = Gas::new_with_regular_gas_and_reservoir(1_000_000, 0); + caller.tracker_mut().set_pools_remaining(pools); + for pool in PoolId::ALL { + caller.tracker_mut().refill_pool(pool, counted.taken.get(pool)); + assert!(caller.tracker_mut().record_pool(pool, counted.added.get(pool))); + } + let mut ledger = StartLedger::default(); + ledger.park_transaction(Some(Parked::transaction(pools, 0))); + ledger.split(1, None, 0); + ledger.draw(&counted); + + let shares = caller.tracker_mut().forward_to_child(&satin_gas_params()).pools; + ledger.park(FRAME_KEPT_PERCENT, 0, 0, 0); + ledger.split(2, Some(1), 1); + let mut child = static_call(TARGET, &[], 100_000); + child.depth = 1; + let FrameInput::Call(inputs) = &mut child.frame_input else { unreachable!() }; + inputs.pool_shares = shares; + let caps = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, cap); + cap_the_shares(&satin_gas_params(), caps, &mut caller, &mut child); + ledger.cap_child(caps, FRAME_KEPT_PERCENT); + + let FrameInput::Call(inputs) = &child.frame_input else { unreachable!() }; + let caller_pools = caller.tracker().pools_remaining(); + let held = ledger.top_shares_and_caller_pools(); + assert_eq!(held, (inputs.pool_shares, caller_pools), "{case}"); + } + } + } + } + /// The frame start skips its reads exactly for a call that moves no value and runs no /// precompile: every call scheme, with no value and with value, to an account and to a /// precompile of the set, and a creation, with and without an endowment. diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 15b64e9eb..92731bb99 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -70,7 +70,9 @@ //! # The start lifecycle //! //! The three lifecycle hooks — a start revm opened, one it settled, the lifecycle's end — reach the -//! inner context in a debug build, whose mirror checks their order over every engine path. A release +//! inner context in a debug build, whose mirror checks their order over every engine path, and +//! drive the engine's start ledger, which keeps what each start owes and holds beside the fork's +//! figures and compares the two at every settlement (the `limit` module's `ledger`). A release //! build takes the trait's defaults, which do nothing. //! //! Every other Host method delegates to op-revm's context. @@ -96,7 +98,7 @@ use revm::{ }; #[cfg(debug_assertions)] -use revm::context_interface::host::{FrameSettle, FrameSplit, LifecycleEnd}; +use revm::context_interface::host::{FrameSettle, FrameSplit, FrameStartKind, LifecycleEnd}; use crate::{ charge_write_records_history, history_gas, @@ -364,7 +366,13 @@ impl revm::context_interface::Host } if appended != 0 { let Some(cost) = history_gas(appended) else { return WriteVerdict::OutOfGas }; - let cost = if from_allowance { gas.draw_history_allowance(cost) } else { cost }; + let cost = if from_allowance { + #[cfg(debug_assertions)] + let _ = self.additional_limit.ledger_mut().draw_allowance(cost); + gas.draw_history_allowance(cost) + } else { + cost + }; if !gas.record_history_cost(cost) { return WriteVerdict::OutOfGas; } @@ -439,30 +447,51 @@ impl revm::context_interface::Host 0 }; start.charge = StartCharge::new(charge, PoolAmounts::ZERO); + #[cfg(debug_assertions)] + self.park_start(start, gas.reservoir(), charge); true } - /// Hands the inner context the start revm opened, so its debug mirror checks the lifecycle's - /// order over the engine. + /// Hands the inner context, whose debug mirror checks the lifecycle's order, the start revm + /// opened, and opens it on the start ledger with what was parked for it. #[cfg(debug_assertions)] fn frame_split(&mut self, split: &FrameSplit) { self.inner.frame_split(split); + self.additional_limit.ledger_mut().split(split.id, split.parent, split.depth); } - /// Hands the inner context the start revm settled into `gas`, its caller's. + /// Hands the inner context the start revm settled into `gas`, its caller's, and settles it on + /// the start ledger, which compares its figures with the fork's. #[cfg(debug_assertions)] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); + self.additional_limit.ledger_mut().settle(&settle.into(), gas); } - /// Hands the inner context the lifecycle's end. + /// Hands the inner context the lifecycle's end, and ends the start ledger with it: every start + /// settled, or what is open discarded. #[cfg(debug_assertions)] fn frame_lifecycle_end(&mut self, end: LifecycleEnd) { self.inner.frame_lifecycle_end(end); + self.additional_limit.ledger_mut().end(end == LifecycleEnd::Settled); } } impl MegaContext { + /// Parks on the start ledger what the start the running frame is making owes, as the + /// frame-start hook decided it: the shares of the frame's pools and the part of its reservoir, + /// `reservoir` once the hook charged it, the frame keeps, by the engine's rule + /// ([`frame_kept_percent`](Self::frame_kept_percent)); the start `charge` the hook declared; + /// and the allowance a value-transferring `CALL` or `CALLCODE` gives its frame. + #[cfg(debug_assertions)] + fn park_start(&mut self, start: &FrameStart, reservoir: u64, charge: u64) { + let value_call = matches!(start.kind, FrameStartKind::Call | FrameStartKind::CallCode) && + !start.value.is_zero(); + let allowance = if value_call { self.value_call_allowance() } else { 0 }; + let kept = self.frame_kept_percent(); + self.additional_limit.ledger_mut().park(kept, reservoir, charge, allowance); + } + /// Prices one EIP-8037 state gas unit `id` at `site`, scaling the schedule's entry by the SALT /// bucket capacity of the account — or, for a slot-scoped entry, of the storage slot — the /// charge lands on. diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs new file mode 100644 index 000000000..deedfb506 --- /dev/null +++ b/crates/mega-evm/src/limit/ledger.rs @@ -0,0 +1,981 @@ +//! The engine's ledger of what each frame start owes and holds, kept in a debug build beside the +//! figures the revm fork carries, and checked against them. +//! +//! The revm fork carries four figures of a frame's start on the frame's gas: the shares of its +//! caller's three pools — data size, KV updates, state growth — with their nets and crossings; the +//! part of its caller's EIP-8037 reservoir the caller keeps while it runs; the start charge its +//! failure gives back to the caller; and the history allowance a value call gives it. The ledger +//! keeps the same four for every start, computed by the engine's own rules, in an entry per open +//! start. +//! +//! It is driven by the start lifecycle revm owns and by nothing else: an entry opens when revm +//! opens the start (`Host::frame_split`), settles when revm settles it (`Host::frame_settle`), and +//! the ledger is dropped when the lifecycle ends, settled or discarded +//! (`Host::frame_lifecycle_end`). The transaction's start resets it, so nothing a context's ledger +//! held carries into the next transaction. The ledger pairs nothing: revm's record says which start +//! settles, and the ledger asserts it is the one on top. +//! +//! # The rules +//! +//! - **What a start owes is parked where it is made**, on the entry of the frame that makes it, and +//! the split that opens the start takes it ([`park`](StartLedger::park)): an instruction's start +//! at the frame-start hook, after the hook's charge; a `keylessDeploy` call's creation where its +//! builder takes the creation's shares; the transaction's start where its first frame's input is +//! built ([`park_transaction`](StartLedger::park_transaction)). A start dropped before revm +//! consumes it loses what was parked for it, and the frame's next start parks over it. The +//! stand-in revm settles for a transaction whose runtime gas phase ran out of gas has nothing +//! parked: it starts with unlimited pools, as the transaction's rebuilt gas holds them. +//! - **A child's share of each pool** is all but `kept` per cent of what its caller has left, +//! rounded down, taken out of the caller's entry where it is parked; the caller keeps `kept` per +//! cent of its reservoir, rounded down. `kept` is the engine's +//! ([`frame_kept_percent`](crate::MegaContext)): two on the spec's configuration, none on the +//! neutral one, which forwards the whole of each as Ethereum does. When the child's frame starts, +//! its shares are held to the frame cap and, for a caller whose net is negative, to the share of +//! the caller's budget, and the excess goes back to the caller +//! ([`cap_child`](StartLedger::cap_child)). +//! - **A draw goes to the top entry**, the running frame's start: a completed write, a frame +//! start's records on the started frame, a deposit's code on the creating frame, a creator's +//! nonce record on the creator once its creation returned ([`draw`](StartLedger::draw)); a log's +//! history draws the top entry's allowance first +//! ([`draw_allowance`](StartLedger::draw_allowance)). +//! - **A precompile's draws are adopted when it answers**, fail-closed: a draw past the share +//! empties the pool, caps the net at the share and sets the crossing, whatever the answer's +//! status ([`adopt_provider_draws`](StartLedger::adopt_provider_draws)). +//! - **A settlement** merges the child's entry into its caller's ([`settle`](StartLedger::settle)), +//! as the fork settles a frame's gas: on success the child's remaining pools join what the caller +//! kept and its nets the caller's; on a revert or a halt its draws are undone, and its whole +//! share comes back. The start charge comes back on a failure, and for a creation also when it +//! took no address. An inspector's answer, and a result whose gas an inspector replaced, settle +//! as unlimited pools with no net; neither an inspector's answer nor an outcome an inspector +//! rebuilt gives the start charge back. +//! +//! # The comparison +//! +//! At every settlement the ledger compares what it computed with the fork's figures for the same +//! start: each of the caller's pools, nets and crossings once the child merged into it; the +//! reservoir the caller kept, with the reservoir revm says the caller held before it settled the +//! child; the start charge the fork gave back; and, for a frame revm built whose gas no inspector +//! replaced, the allowance the frame returns. At the lifecycle's successful end the ledger holds no +//! entry. +//! +//! A difference is a panic. The inspector shapes whose figures the owner accepted to change when +//! the ledger becomes what the engine reads differ by design: a tracker restored from a snapshot, +//! an interpreter replaced, an answer, an input or a result built with pools, an allowance or a +//! charge an inspector set, a tracker or an outcome copied from another start. A test that runs +//! one has the context record the differences instead, and asserts each +//! (`test_utils::tolerate_start_ledger_divergences`). After a recorded difference in a caller's +//! pools the ledger takes the fork's, so what it records is where the two part, not what follows. + +#![cfg_attr(not(any(test, feature = "test-utils")), allow(unreachable_pub))] + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + +use revm::context_interface::{ + cfg::gas::{GasTracker, PoolAmounts, PoolId}, + host::{FrameSettle, SettleStatus}, +}; + +use super::Counted; + +/// A figure of a settled start the ledger compares with the fork's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LedgerFigure { + /// What the start's caller may still draw on a pool, once the start settled into it. + PoolRemaining(PoolId), + /// The caller's net draw on a pool, once the start settled into it. + PoolNet(PoolId), + /// Whether a draw on the caller's pool was refused (`1`) or not (`0`). + PoolCrossing(PoolId), + /// The part of its reservoir the caller kept while the start ran. + KeptReservoir, + /// The history gas the start's settlement gave back to its caller. + StartChargeRefund, + /// What the frame returned of its history allowance. + Allowance, +} + +/// A figure of a settled start in which the ledger and the fork differ. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LedgerDivergence { + /// The identity revm gave the start. + pub start: u32, + /// The started frame's depth. + pub depth: usize, + /// The figure. + pub figure: LedgerFigure, + /// The ledger's value. + pub ledger: i128, + /// The fork's value. + pub fork: i128, +} + +/// What a start owes, decided where it is made and taken by the split that opens it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Parked { + /// The child's share of each of its caller's pools. + shares: PoolAmounts, + /// The part of its reservoir the caller keeps while the child runs. + kept_reservoir: u64, + /// The history gas the start charged its caller for the records on the child, which the + /// child's failure gives back. + charge: u64, + /// The history gas the child may spend on logs before it charges its gas. + allowance: u64, +} + +impl Parked { + /// What the transaction's start owes: its pools, `pools`, the start `charge` of the record its + /// frame makes, and no kept reservoir and no allowance, its frame taking the transaction's + /// whole reservoir and making no value call. + pub(crate) const fn transaction(pools: PoolAmounts, charge: u64) -> Self { + Self { shares: pools, kept_reservoir: 0, charge, allowance: 0 } + } +} + +/// What a transaction's start owes when nothing was parked for it: the stand-in revm settles for a +/// transaction whose runtime gas phase ran out of gas, which carries every pool of the rebuilt +/// gas, unlimited, and owes nothing else. +const STAND_IN: Parked = Parked::transaction(PoolAmounts::UNLIMITED, 0); + +/// What a start owes when an inspector consumed an input it built itself, which no start parked +/// anything for: nothing, and no pool. +const UNPARKED: Parked = Parked::transaction(PoolAmounts::ZERO, 0); + +/// A frame's three pools as the engine keeps them: what it may still draw, its signed net draw, +/// and whether a draw it could not pay was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Pools { + remaining: PoolAmounts, + net: [i64; PoolId::COUNT], + crossings: [bool; PoolId::COUNT], +} + +impl Pools { + /// Pools that start at `shares`, undrawn. + const fn of(shares: PoolAmounts) -> Self { + Self { remaining: shares, net: [0; PoolId::COUNT], crossings: [false; PoolId::COUNT] } + } + + /// The pools `gas` holds. + fn on(gas: &GasTracker) -> Self { + Self { + remaining: gas.pools_remaining(), + net: PoolId::ALL.map(|pool| gas.pool_spent(pool)), + crossings: PoolId::ALL.map(|pool| gas.pool_crossing(pool)), + } + } + + /// Draws `amount` on `pool`; a draw the pool cannot pay takes nothing and sets its crossing. + fn record(&mut self, pool: PoolId, amount: u64) -> bool { + let index = pool.index(); + let Some(left) = self.remaining.get(pool).checked_sub(amount) else { + self.crossings[index] = true; + return false; + }; + self.remaining.set(pool, left); + self.net[index] = self.net[index].saturating_add(signed(amount)); + true + } + + /// Gives `amount` back to `pool`, lowering its net, below zero for a draw a caller made. + fn refill(&mut self, pool: PoolId, amount: u64) { + let index = pool.index(); + self.remaining.set(pool, self.remaining.get(pool).saturating_add(amount)); + self.net[index] = self.net[index].saturating_sub(signed(amount)); + } + + /// Undoes every draw, for a frame that failed: each pool back at what it started with. + fn roll_back(&mut self) { + for pool in PoolId::ALL { + let index = pool.index(); + let remaining = self.remaining.get(pool).saturating_add_signed(self.net[index]); + self.remaining.set(pool, remaining); + self.net[index] = 0; + } + } + + /// Takes back what a child that `succeeded`, or failed, returns: its remaining pools join what + /// this frame kept, and its nets this frame's when it succeeded. A failed child's draws are + /// undone first. A child's crossings stay the child's. + fn absorb(&mut self, mut child: Self, succeeded: bool) { + if !succeeded { + child.roll_back(); + } + for pool in PoolId::ALL { + let index = pool.index(); + if succeeded { + self.net[index] = self.net[index].saturating_add(child.net[index]); + } + let remaining = self.remaining.get(pool).saturating_add(child.remaining.get(pool)); + self.remaining.set(pool, remaining); + } + } +} + +/// `amount` as a signed net, saturating. +const fn signed(amount: u64) -> i64 { + if amount > i64::MAX as u64 { + i64::MAX + } else { + amount as i64 + } +} + +/// `kept` per cent of `amount`, rounded down: the part of its reservoir a caller keeps when it +/// starts a frame. +const fn kept_part(amount: u64, kept: u64) -> u64 { + if kept >= 100 { + return amount; + } + (amount as u128 * kept as u128 / 100) as u64 +} + +/// The share of a pool holding `remaining` a child starts with: `100 − kept` per cent of it, +/// rounded down. +const fn pool_share(remaining: u64, kept: u64) -> u64 { + if kept >= 100 { + return 0; + } + (remaining as u128 * (100 - kept) as u128 / 100) as u64 +} + +/// One open start. +#[derive(Clone, Copy, Debug)] +struct Entry { + /// The identity revm gave the start. + id: u32, + /// The started frame's depth. + depth: usize, + /// The shares its frame started with, once its start held them to the frame cap: what an + /// answer rebuilt on its untouched gas carries. + shares: PoolAmounts, + /// Its pools as its frame draws them. + pools: Pools, + /// The part of its reservoir the start's caller kept. + kept_reservoir: u64, + /// The start charge its failure gives back. + charge: u64, + /// What is left of its history allowance. + allowance: u64, + /// Whether revm built a frame for it, which ran or ended before it ran; an answer has none. + built: bool, + /// What the next start its frame makes owes. + parked: Option, +} + +impl Entry { + const fn open(id: u32, depth: usize, owed: Parked) -> Self { + Self { + id, + depth, + shares: owed.shares, + pools: Pools::of(owed.shares), + kept_reservoir: owed.kept_reservoir, + charge: owed.charge, + allowance: owed.allowance, + built: false, + parked: None, + } + } +} + +/// A start's settlement as revm reports it ([`FrameSettle`]), in the ledger's own terms. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Settlement { + id: u32, + depth: usize, + status: SettleStatus, + created: Option, + inspector_answer: bool, + gas_replaced: bool, + outcome_rebuilt: bool, + held_reservoir: u64, +} + +impl From<&FrameSettle> for Settlement { + fn from(settle: &FrameSettle) -> Self { + Self { + id: settle.id, + depth: settle.depth, + status: settle.status, + created: settle.created, + inspector_answer: settle.inspector_answer, + gas_replaced: settle.gas_replaced, + outcome_rebuilt: settle.outcome_rebuilt, + held_reservoir: settle.held_reservoir, + } + } +} + +/// The fork's figures of the result about to settle, read before revm consumes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Returning { + /// The history the fork gives back to the caller for the start. + refund: u64, + /// What the result's gas holds of the frame's history allowance. + allowance: u64, +} + +impl Returning { + /// `refund`, the history of the start charge the fork gives back, and `allowance`, what the + /// result's gas holds of the frame's history allowance. + pub(crate) const fn new(refund: u64, allowance: u64) -> Self { + Self { refund, allowance } + } +} + +/// The engine's ledger of the open starts of the running transaction. See the module +/// documentation. +#[derive(Clone, Debug, Default)] +pub(crate) struct StartLedger { + /// One entry per open start, the transaction's first and the innermost last. + entries: Vec, + /// What the transaction's start owes, parked where its first frame's input is built. + transaction: Option, + /// The fork's figures of the result settling next. + returning: Option, + /// The differences found, when the ledger records them rather than panics. + divergences: Option>, +} + +impl StartLedger { + /* The lifecycle */ + + /// Parks what the transaction's start owes, or forgets what was parked when the first frame's + /// input could not be built (`None`), whose stand-in owes nothing. + pub(crate) const fn park_transaction(&mut self, owed: Option) { + self.transaction = owed; + } + + /// Opens the start revm just opened, `id` at `depth` under `parent`, with what was parked for + /// it. The transaction's start, with no parent, resets the ledger. + pub(crate) fn split(&mut self, id: u32, parent: Option, depth: usize) { + let owed = match parent { + None => { + self.entries.clear(); + self.returning = None; + self.transaction.take().unwrap_or(STAND_IN) + } + Some(parent) => { + let caller = self.entries.last_mut(); + let Some(caller) = + caller.filter(|caller| caller.id == parent && caller.depth + 1 == depth) + else { + panic!( + "start {id} at depth {depth} opened under {parent}, not the ledger's top" + ) + }; + caller.parked.take().unwrap_or(UNPARKED) + } + }; + self.entries.push(Entry::open(id, depth, owed)); + } + + /// Ends the lifecycle: every start settled when it `settled`, or what is open discarded. + pub(crate) fn end(&mut self, settled: bool) { + if settled { + assert!( + self.entries.is_empty(), + "the lifecycle settled with starts open in the ledger: {:?}", + self.entries + ); + } + self.entries.clear(); + self.returning = None; + self.transaction = None; + } + + /* What a start owes */ + + /// Parks on the running frame's entry what the start it is making owes: the share of each of + /// its pools, taken out of them, and the part of `reservoir` it keeps, all by `kept`; the + /// start's `charge`; and the child's `allowance`. `reservoir` is what the caller holds once the + /// start's charges are made. Overwrites what an earlier start of the frame parked and no split + /// took. + pub(crate) fn park(&mut self, kept: u64, reservoir: u64, charge: u64, allowance: u64) { + let Some(caller) = self.entries.last_mut() else { return }; + let mut shares = PoolAmounts::ZERO; + for pool in PoolId::ALL { + let remaining = caller.pools.remaining.get(pool); + let share = pool_share(remaining, kept); + caller.pools.remaining.set(pool, remaining - share); + shares.set(pool, share); + } + let kept_reservoir = kept_part(reservoir, kept); + caller.parked = Some(Parked { shares, kept_reservoir, charge, allowance }); + } + + /// Holds the shares of the start on top, which its caller below it is suspended on, to `caps` + /// and, for a caller whose net is negative, to the share of its budget by `kept`, and gives the + /// excess back to the caller. The caller's budget is what it holds with the share and its net + /// together, so a negative net never enlarges a child's share. + pub(crate) fn cap_child(&mut self, caps: PoolAmounts, kept: u64) { + let [.., caller, child] = self.entries.as_mut_slice() else { return }; + for pool in PoolId::ALL { + let share = child.shares.get(pool); + let mut allowed = caps.get(pool); + let net = caller.pools.net[pool.index()]; + if net < 0 { + let had = caller.pools.remaining.get(pool).saturating_add(share); + allowed = allowed.min(pool_share(had.saturating_add_signed(net), kept)); + } + let Some(excess) = share.checked_sub(allowed).filter(|excess| *excess != 0) else { + continue; + }; + let remaining = caller.pools.remaining.get(pool).saturating_add(excess); + caller.pools.remaining.set(pool, remaining); + child.shares.set(pool, allowed); + child.pools.remaining.set(pool, allowed); + } + } + + /// Notes that revm built a frame for the start on top. + pub(crate) fn built(&mut self) { + if let Some(entry) = self.entries.last_mut() { + entry.built = true; + } + } + + /* Draws */ + + /// Draws `counted` on the top entry's pools, which the limits admitted: what it takes back goes + /// back to each pool first, then what it adds is drawn. + pub(crate) fn draw(&mut self, counted: &Counted) { + let Some(entry) = self.entries.last_mut() else { return }; + for pool in PoolId::ALL { + let (added, taken) = (counted.added.get(pool), counted.taken.get(pool)); + if added == 0 && taken == 0 { + continue; + } + entry.pools.refill(pool, taken); + if !entry.pools.record(pool, added) { + // Admitted by the limits, so refused only past a saturated unlimited pool, which is + // no crossing. + entry.pools.crossings[pool.index()] = false; + } + } + } + + /// Draws `cost` of history on the top entry's allowance first, and answers the part it did not + /// cover. + pub(crate) fn draw_allowance(&mut self, cost: u64) -> u64 { + let Some(entry) = self.entries.last_mut() else { return cost }; + let drawn = cost.min(entry.allowance); + entry.allowance -= drawn; + cost - drawn + } + + /// Adopts `draws`, what a precompile's provider drew on each pool of its answer to the start on + /// top, fail-closed: a draw within the share is drawn, and one past it empties the pool, caps + /// the net at the share and sets the crossing. The answer's status is the provider's either + /// way. + pub(crate) fn adopt_provider_draws(&mut self, draws: [i64; PoolId::COUNT]) { + let Some(entry) = self.entries.last_mut() else { return }; + for pool in PoolId::ALL { + let (index, share, drawn) = (pool.index(), entry.shares.get(pool), draws[pool.index()]); + if drawn > 0 && drawn as u64 > share { + entry.pools.remaining.set(pool, 0); + entry.pools.net[index] = signed(share); + entry.pools.crossings[index] = true; + } else { + entry + .pools + .remaining + .set(pool, share.saturating_add_signed(drawn.saturating_neg())); + entry.pools.net[index] = drawn; + } + } + } + + /// Puts the start on top back at its shares, undrawn: its answer was rebuilt on the gas its + /// caller forwarded, untouched. + pub(crate) fn rebuild_on_shares(&mut self) { + if let Some(entry) = self.entries.last_mut() { + entry.pools = Pools::of(entry.shares); + } + } + + /* Settlement */ + + /// Notes the fork's figures of the result about to settle. + pub(crate) const fn returning(&mut self, figures: Returning) { + self.returning = Some(figures); + } + + /// Settles the start on top, which revm just settled into `gas`, its caller's — the + /// transaction's gas, for the transaction's start — and compares the caller's pools, what the + /// caller kept of its reservoir, the start charge given back and the allowance the frame + /// returned with the fork's. + pub(crate) fn settle(&mut self, settlement: &Settlement, gas: &GasTracker) { + let Some(child) = self.entries.pop() else { + panic!("start {} settled with no start open in the ledger", settlement.id) + }; + assert_eq!( + (child.id, child.depth), + (settlement.id, settlement.depth), + "the start on top of the ledger is not the one revm settled" + ); + let Some(fork) = self.returning.take() else { + panic!("start {} settled without the fork's figures of its result", settlement.id) + }; + let inspected = settlement.inspector_answer || settlement.gas_replaced; + let pools = if inspected { Pools::of(PoolAmounts::UNLIMITED) } else { child.pools }; + let succeeded = settlement.status == SettleStatus::Ok; + let failed = !succeeded || settlement.created == Some(false); + let refunds = failed && !settlement.inspector_answer && !settlement.outcome_rebuilt; + let refund = if refunds { child.charge } else { 0 }; + let returned = child.built && !inspected; + + // The transaction's gas holds none of its pools while its frame runs, which took them + // whole. + let mut transaction = Pools::of(PoolAmounts::ZERO); + let caller = match self.entries.last_mut() { + Some(caller) => &mut caller.pools, + None => &mut transaction, + }; + caller.absorb(pools, succeeded); + let ledger = *caller; + let on_gas = Pools::on(gas); + + let mut differences = Vec::new(); + for pool in PoolId::ALL { + let index = pool.index(); + differences.extend([ + ( + LedgerFigure::PoolRemaining(pool), + i128::from(ledger.remaining.get(pool)), + i128::from(on_gas.remaining.get(pool)), + ), + (LedgerFigure::PoolNet(pool), ledger.net[index].into(), on_gas.net[index].into()), + ( + LedgerFigure::PoolCrossing(pool), + ledger.crossings[index].into(), + on_gas.crossings[index].into(), + ), + ]); + } + differences.extend([ + ( + LedgerFigure::KeptReservoir, + child.kept_reservoir.into(), + settlement.held_reservoir.into(), + ), + (LedgerFigure::StartChargeRefund, refund.into(), fork.refund.into()), + ]); + if returned { + differences.push(( + LedgerFigure::Allowance, + child.allowance.into(), + fork.allowance.into(), + )); + } + differences.retain(|(_, ledger, fork)| ledger != fork); + if differences.is_empty() { + return; + } + let pools_differ = differences.iter().any(|(figure, ..)| { + matches!( + figure, + LedgerFigure::PoolRemaining(_) | + LedgerFigure::PoolNet(_) | + LedgerFigure::PoolCrossing(_) + ) + }); + let Some(recorded) = &mut self.divergences else { + panic!( + "the start ledger parts from the fork at start {} (depth {}), settled {:?}: \ + (figure, ledger, fork) {differences:?}", + child.id, child.depth, settlement + ) + }; + recorded.extend(differences.into_iter().map(|(figure, ledger, fork)| LedgerDivergence { + start: child.id, + depth: child.depth, + figure, + ledger, + fork, + })); + if pools_differ { + if let Some(caller) = self.entries.last_mut() { + caller.pools = on_gas; + } + } + } + + /// The shares the start on top started with and the pools of the start below it. + #[cfg(test)] + pub(crate) fn top_shares_and_caller_pools(&self) -> (PoolAmounts, PoolAmounts) { + let [.., caller, child] = self.entries.as_slice() else { panic!("two starts are open") }; + (child.shares, caller.pools.remaining) + } + + /* The differences an inspector's shape makes */ + + /// Records every difference from now on rather than panicking on it. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) fn tolerate_divergences(&mut self) { + self.divergences.get_or_insert_with(Vec::new); + } + + /// The differences recorded since the last were taken; `None` unless they are recorded. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) fn take_divergences(&mut self) -> Option> { + self.divergences.as_mut().map(core::mem::take) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + limit::{DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL}, + satin_gas_params, + }; + use revm::{ + context_interface::cfg::GasParams, handler::handle_reservoir_remaining_gas, + interpreter::InstructionResult, primitives::hardfork::SpecId, + }; + + /// The part of its pools and reservoir the spec's configuration has a caller keep. + const KEPT: u64 = crate::evm::FRAME_KEPT_PERCENT; + + /// A settlement of start `id` at `depth` with `status`, which no inspector touched, of a call. + fn settled(id: u32, depth: usize, status: SettleStatus, held_reservoir: u64) -> Settlement { + Settlement { + id, + depth, + status, + created: None, + inspector_answer: false, + gas_replaced: false, + outcome_rebuilt: false, + held_reservoir, + } + } + + /// The status a settlement reports of `result`, as revm's record reports it. + fn status_of(result: InstructionResult) -> SettleStatus { + if result.is_ok() { + SettleStatus::Ok + } else if result.is_revert() { + SettleStatus::Revert + } else { + SettleStatus::Halt + } + } + + /// A tracker with `pools`, regular gas and `reservoir`. + fn tracker(pools: PoolAmounts, reservoir: u64) -> GasTracker { + let mut gas = GasTracker::new(10_000_000, 10_000_000, reservoir); + gas.set_pools_remaining(pools); + gas + } + + /// A ledger whose transaction's start, 1, has `pools`, open. + fn opened(pools: PoolAmounts) -> StartLedger { + let mut ledger = StartLedger::default(); + ledger.park_transaction(Some(Parked::transaction(pools, 0))); + ledger.split(1, None, 0); + ledger + } + + /// The pools of the open start on top. + fn top(ledger: &StartLedger) -> Pools { + ledger.entries.last().expect("a start is open").pools + } + + const POOLS: PoolAmounts = PoolAmounts::ZERO + .with(DATA_SIZE_POOL, 10_000) + .with(KV_UPDATE_POOL, 250) + .with(STATE_GROWTH_POOL, 49); + + /// A child's share of each pool is what the fork forwards on the spec's schedule, the floor of + /// 98 per cent, and the caller keeps the rest; the caller keeps the part of its reservoir the + /// fork leaves it, the floor of 2 per cent, so nothing below 50. On the neutral configuration + /// the caller keeps nothing of either, as the fork forwards on a schedule that keeps nothing. + #[test] + fn test_a_start_takes_the_forks_shares_and_leaves_the_caller_its_part() { + let amsterdam = GasParams::new_spec(SpecId::AMSTERDAM); + for (kept, params) in [(KEPT, satin_gas_params()), (0, amsterdam)] { + for reservoir in [0, 1, 49, 50, 99, 100, 12_345, u64::MAX] { + for pools in [POOLS, PoolAmounts::UNLIMITED, PoolAmounts::ZERO] { + let case = format!("kept {kept}, reservoir {reservoir}, pools {pools:?}"); + let mut ledger = opened(pools); + ledger.park(kept, reservoir, 7, 9); + let mut caller = tracker(pools, reservoir); + let shares = caller.forward_to_child(¶ms); + assert_eq!(top(&ledger).remaining, caller.pools_remaining(), "{case}"); + let parked = ledger.entries[0].parked.expect("parked"); + assert_eq!(parked.shares, shares.pools, "{case}"); + assert_eq!(parked.kept_reservoir, caller.reservoir(), "{case}"); + assert_eq!((parked.charge, parked.allowance), (7, 9), "{case}"); + } + } + } + } + + /// What a start owes is the frame's own scratch: the split that opens it takes it, a start + /// dropped before revm consumed it loses its shares — the caller keeps only its part — and the + /// frame's next start parks over it. + #[test] + fn test_a_dropped_start_loses_its_shares_and_the_next_start_parks_over_it() { + let mut ledger = opened(POOLS); + ledger.park(KEPT, 0, 1, 0); + let after_first = top(&ledger).remaining; + ledger.park(KEPT, 0, 2, 0); + let parked = ledger.entries[0].parked.expect("parked"); + assert_eq!(parked.charge, 2, "the second start's"); + for pool in PoolId::ALL { + let (first, second) = (after_first.get(pool), top(&ledger).remaining.get(pool)); + assert_eq!(parked.shares.get(pool), pool_share(first, KEPT), "{pool:?}"); + assert_eq!(second, first - pool_share(first, KEPT), "{pool:?}: the first share lost"); + } + ledger.split(2, Some(1), 1); + assert_eq!(ledger.entries[0].parked, None, "taken"); + assert_eq!(ledger.entries[1].shares, parked.shares); + assert_eq!(ledger.entries[1].charge, 2); + } + + /// A child's draws settle into its caller as the fork settles them: a success hands its + /// remaining pools and its nets to the caller, a revert and a halt give its whole share back + /// and leave the caller's nets alone; a child's take-back of a caller's draw nets out on + /// success. The comparison finds nothing to part on. + #[test] + fn test_a_settlement_merges_as_the_fork_does() { + let results = + [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas]; + for result in results { + let case = format!("{result:?}"); + let mut ledger = opened(POOLS); + let mut caller = tracker(POOLS, 0); + // The caller draws, then starts a child, which draws and takes back. + let caller_draw = Counted::records(3, 0, false).with_growth(2, 0); + ledger.draw(&caller_draw); + for pool in PoolId::ALL { + assert!(caller.record_pool(pool, caller_draw.added.get(pool))); + } + ledger.park(KEPT, 0, 0, 0); + ledger.split(2, Some(1), 1); + let mut child = tracker(caller.forward_to_child(&satin_gas_params()).pools, 0); + let child_draw = Counted::records(5, 2, true).with_growth(1, 2); + ledger.draw(&child_draw); + for pool in PoolId::ALL { + child.refill_pool(pool, child_draw.taken.get(pool)); + assert!(child.record_pool(pool, child_draw.added.get(pool))); + } + assert_eq!(top(&ledger), Pools::on(&child), "{case}: the child's draws"); + handle_reservoir_remaining_gas(result, &mut caller, &mut child); + ledger.returning(Returning::new(0, 0)); + ledger.settle(&settled(2, 1, status_of(result), 0), &caller); + assert_eq!(top(&ledger), Pools::on(&caller), "{case}: the caller's"); + } + } + + /// The start charge comes back on a call's failure, and on a creation's too when it took no + /// address; never on a success, an inspector's answer or an outcome an inspector rebuilt. + #[test] + fn test_the_start_charge_comes_back_on_failure() { + // (status, created, inspector answer, outcome rebuilt, refunded) + let cases = [ + (SettleStatus::Ok, None, false, false, false), + (SettleStatus::Revert, None, false, false, true), + (SettleStatus::Halt, None, false, false, true), + (SettleStatus::Ok, Some(true), false, false, false), + (SettleStatus::Ok, Some(false), false, false, true), + (SettleStatus::Revert, Some(false), false, false, true), + (SettleStatus::Revert, None, true, false, false), + (SettleStatus::Revert, None, false, true, false), + (SettleStatus::Ok, Some(false), false, true, false), + ]; + for (status, created, inspector_answer, outcome_rebuilt, refunded) in cases { + let case = format!("{status:?}, {created:?}, {inspector_answer}, {outcome_rebuilt}"); + let mut ledger = opened(PoolAmounts::UNLIMITED); + ledger.tolerate_divergences(); + ledger.park(KEPT, 0, 123, 0); + ledger.split(2, Some(1), 1); + ledger.returning(Returning::new(0, 0)); + let settlement = Settlement { + created, + inspector_answer, + outcome_rebuilt, + ..settled(2, 1, status, 0) + }; + ledger.settle(&settlement, &tracker(PoolAmounts::UNLIMITED, 0)); + let refund = ledger + .take_divergences() + .unwrap_or_default() + .into_iter() + .find(|divergence| divergence.figure == LedgerFigure::StartChargeRefund) + .map(|divergence| divergence.ledger); + assert_eq!(refund, refunded.then_some(123), "{case}"); + } + } + + /// An inspector's answer and a result whose tracker an inspector replaced settle as unlimited + /// pools with no net, as the fork settles one built with `Gas::new`; an outcome an inspector + /// rebuilt around the frame's own tracker settles on the frame's pools. + #[test] + fn test_an_inspectors_answer_and_a_replaced_tracker_settle_as_unlimited_pools() { + for (inspector_answer, gas_replaced, outcome_rebuilt) in + [(true, false, false), (false, true, false), (false, false, true)] + { + let case = format!("{inspector_answer}, {gas_replaced}, {outcome_rebuilt}"); + let mut ledger = opened(POOLS); + let mut caller = tracker(POOLS, 0); + ledger.park(KEPT, 0, 0, 0); + ledger.split(2, Some(1), 1); + let mut child = tracker(caller.forward_to_child(&satin_gas_params()).pools, 0); + ledger.draw(&Counted::records(1, 0, false)); + for pool in [DATA_SIZE_POOL, KV_UPDATE_POOL] { + assert!(child.record_pool(pool, ledger.entries[1].pools.net[pool.index()] as u64)); + } + let mut returned = if outcome_rebuilt { child } else { GasTracker::new(0, 0, 0) }; + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut caller, &mut returned); + ledger.returning(Returning::new(0, 0)); + let settlement = Settlement { + inspector_answer, + gas_replaced, + outcome_rebuilt, + ..settled(2, 1, SettleStatus::Ok, 0) + }; + ledger.settle(&settlement, &caller); + assert_eq!(top(&ledger), Pools::on(&caller), "{case}"); + } + } + + /// A precompile's draws are adopted fail-closed, as the fork adopts them: within the share they + /// are drawn, and past it the pool is emptied, the net capped at the share and the crossing + /// set — share 10, draw 11 — whatever the answer's status. + #[test] + fn test_a_precompiles_draws_past_its_share_are_adopted_fail_closed() { + for drawn in [0_i64, 4, 10, 11, -3] { + let pools = PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10); + let mut ledger = opened(PoolAmounts::UNLIMITED); + ledger.park(0, 0, 0, 0); + ledger.split(2, Some(1), 1); + ledger.entries[1].shares = pools; + ledger.adopt_provider_draws([drawn, 0, 0]); + let mut answer = GasTracker::new(0, 0, 0); + answer.set_pool_spent(DATA_SIZE_POOL, drawn); + answer.adopt_pool_shares(pools); + assert_eq!(top(&ledger), Pools::on(&answer), "drawn {drawn}"); + } + let mut ledger = opened(PoolAmounts::UNLIMITED); + ledger.park(0, 0, 0, 0); + ledger.split(2, Some(1), 1); + ledger.entries[1].shares = PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10); + ledger.adopt_provider_draws([11, 0, 0]); + let pools = top(&ledger); + assert_eq!( + (pools.remaining.get(DATA_SIZE_POOL), pools.net[0], pools.crossings[0]), + (0, 10, true), + "share 10, draw 11" + ); + } + + /// A log's history draws the allowance first and pays the rest, and what the frame returns of + /// it is compared for a frame revm built; an answer's allowance is never drawn or compared. + #[test] + fn test_the_allowance_is_drawn_first_and_compared_for_a_built_frame() { + for built in [false, true] { + let mut ledger = opened(PoolAmounts::UNLIMITED); + ledger.tolerate_divergences(); + ledger.park(KEPT, 0, 0, 100); + ledger.split(2, Some(1), 1); + if built { + ledger.built(); + } + assert_eq!(ledger.draw_allowance(30), 0, "within it"); + assert_eq!(ledger.draw_allowance(80), 10, "past it"); + assert_eq!(ledger.draw_allowance(5), 5, "spent"); + ledger.returning(Returning::new(0, 1)); + ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &tracker(PoolAmounts::UNLIMITED, 0)); + let divergences = ledger.take_divergences().unwrap_or_default(); + let expected = built.then_some(LedgerDivergence { + start: 2, + depth: 1, + figure: LedgerFigure::Allowance, + ledger: 0, + fork: 1, + }); + assert_eq!(divergences.first().copied(), expected, "built {built}"); + } + } + + /// The transaction's start resets the ledger, takes what its first frame's input parked or the + /// stand-in's unlimited pools, and settles into the transaction's gas, which holds none of its + /// pools while it runs. The lifecycle's end drops what is open. + #[test] + fn test_the_transactions_start_resets_the_ledger() { + let mut ledger = opened(POOLS); + ledger.park(KEPT, 0, 0, 0); + ledger.split(2, Some(1), 1); + ledger.end(false); + assert!(ledger.entries.is_empty(), "discarded"); + + ledger.split(1, None, 0); + assert_eq!(top(&ledger).remaining, PoolAmounts::UNLIMITED, "the stand-in's"); + ledger.park(KEPT, 0, 0, 0); + ledger.split(1, None, 0); + assert_eq!(ledger.entries.len(), 1, "a transaction's start resets"); + ledger.returning(Returning::new(0, 0)); + let mut transaction = tracker(PoolAmounts::UNLIMITED, 0); + let mut frame = tracker(transaction.forward_all_to_child().pools, 0); + handle_reservoir_remaining_gas(InstructionResult::Stop, &mut transaction, &mut frame); + ledger.settle(&settled(1, 0, SettleStatus::Ok, 0), &transaction); + ledger.end(true); + } + + /// A settled lifecycle with a start open in the ledger is a broken pairing. + #[test] + #[should_panic(expected = "the lifecycle settled with starts open in the ledger")] + fn test_a_settled_end_with_a_start_open_panics() { + opened(POOLS).end(true); + } + + /// A start that opens under another start than the ledger's top is a broken pairing. + #[test] + #[should_panic(expected = "not the ledger's top")] + fn test_a_start_under_another_than_the_top_panics() { + let mut ledger = opened(POOLS); + ledger.split(3, Some(2), 1); + } + + /// A difference panics, naming the start and every figure that parts. + #[test] + #[should_panic(expected = "the start ledger parts from the fork at start 2 (depth 1)")] + fn test_a_difference_panics() { + let mut ledger = opened(POOLS); + ledger.park(KEPT, 1_000, 0, 0); + ledger.split(2, Some(1), 1); + ledger.returning(Returning::new(0, 0)); + ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &tracker(POOLS, 0)); + } + + /// A ledger that tolerates differences records each, in the order of the figures, and takes the + /// fork's pools for the caller, so the next settlement compares from where the two parted. + #[test] + fn test_a_tolerated_difference_is_recorded_and_the_caller_takes_the_forks_pools() { + let mut ledger = opened(POOLS); + ledger.tolerate_divergences(); + ledger.park(KEPT, 1_000, 0, 0); + ledger.split(2, Some(1), 1); + ledger.returning(Returning::new(5, 0)); + let fork = tracker(POOLS.with(DATA_SIZE_POOL, 1), 0); + ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &fork); + let at = + |figure, ledger, fork| LedgerDivergence { start: 2, depth: 1, figure, ledger, fork }; + assert_eq!( + ledger.take_divergences(), + Some(std::vec![ + at(LedgerFigure::PoolRemaining(DATA_SIZE_POOL), 10_000, 1), + at(LedgerFigure::KeptReservoir, 20, 0), + at(LedgerFigure::StartChargeRefund, 0, 5), + ]) + ); + assert_eq!(top(&ledger), Pools::on(&fork), "the fork's pools taken"); + assert_eq!(ledger.take_divergences(), Some(std::vec![]), "taken once"); + } +} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 699a2c122..6f917d0b3 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -11,6 +11,8 @@ use revm::{ use alloc as std; use std::vec::Vec; +#[cfg(debug_assertions)] +use super::StartLedger; use super::{ CreatorBefore, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, COUNTED, DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, @@ -120,6 +122,11 @@ pub struct AdditionalLimit { /// The EIP-8037 reservoir the settled transaction or system call left unspent: none from where /// an execution builds its gas until it reports what it settled with. reservoir_remaining: Option, + /// In a debug build, the engine's own ledger of what each open start owes and holds, checked + /// against the fork's figures at every settlement. It is not begun with the transaction: the + /// start lifecycle drives it, from the transaction's start to the lifecycle's end. + #[cfg(debug_assertions)] + ledger: StartLedger, } /// What the running execution is, decided when the layer begins it from what the transaction is @@ -621,6 +628,8 @@ impl AdditionalLimit { } Self::apply(gas, counted); self.count(counted); + #[cfg(debug_assertions)] + self.ledger.draw(counted); LimitCheck::WithinLimit } @@ -713,6 +722,8 @@ impl AdditionalLimit { } Self::apply(gas, counted); self.count(counted); + #[cfg(debug_assertions)] + self.ledger.draw(counted); if let Some(start) = self.decided.last_mut() { start.credit = credit; } @@ -827,6 +838,15 @@ impl AdditionalLimit { } } + /* The start ledger */ + + /// The engine's own ledger of what each open start owes and holds, which a debug build keeps + /// beside the fork's figures and checks against them. + #[cfg(debug_assertions)] + pub(crate) const fn ledger_mut(&mut self) -> &mut StartLedger { + &mut self.ledger + } + /* What the settled transaction reports */ /// The history gas the last settled transaction spent. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 8026528c7..3c4b98d4a 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -179,10 +179,16 @@ //! recipient is the block beneficiary or a fee vault pays a record the body already bound. It is //! an over-charge, never an under-charge. +#[cfg(debug_assertions)] +mod ledger; #[allow(clippy::module_inception)] mod limit; mod record; +#[cfg(all(debug_assertions, any(test, feature = "test-utils")))] +pub use ledger::{LedgerDivergence, LedgerFigure}; +#[cfg(debug_assertions)] +pub(crate) use ledger::{Parked, Returning, StartLedger}; pub use limit::AdditionalLimit; pub(crate) use limit::{Counted, TxClass}; #[cfg(test)] diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index aa6d914e2..054a09a43 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -190,6 +190,12 @@ pub(crate) fn start( }; // The creation's shares of the call's reservoir and pools are taken out of the call, as a // `CREATE` opcode's are: the creation's return adds what it left back to what the call kept. + #[cfg(debug_assertions)] + { + let (kept, reservoir) = (ctx.frame_kept_percent(), gas.reservoir()); + let charge = deployment.on_frame_record_charge; + ctx.additional_limit.ledger_mut().park(kept, reservoir, charge, 0); + } let shares = gas.tracker_mut().forward_to_child(ctx.gas_params()); let mut create = CreateInputs::new( deployment.signer, diff --git a/crates/mega-evm/src/test_utils/ledger.rs b/crates/mega-evm/src/test_utils/ledger.rs new file mode 100644 index 000000000..b868b1d70 --- /dev/null +++ b/crates/mega-evm/src/test_utils/ledger.rs @@ -0,0 +1,29 @@ +//! The differences a debug build's start ledger finds between its figures and the fork's, for a +//! test that runs an inspector shape whose figures are accepted to change. +//! +//! The start ledger panics on any difference. An inspector that restores a snapshot of a running +//! tracker, replaces an interpreter, answers or rewrites with pools, an allowance or a start charge +//! it set, copies a tracker or an outcome from another start, or builds an input itself, moves the +//! fork's figures where the ledger, which keeps them off the tracker, does not follow: a test that +//! runs one tolerates the differences, then asserts each of them. + +use crate::{ExternalEnvTypes, MegaContext}; +use revm::Database; + +pub use crate::limit::{LedgerDivergence, LedgerFigure}; + +/// Has `ctx`'s start ledger record every difference from now on rather than panic on it, and take +/// the fork's pools where a caller's differ. +pub fn tolerate_start_ledger_divergences( + ctx: &mut MegaContext, +) { + ctx.additional_limit.ledger_mut().tolerate_divergences(); +} + +/// The differences `ctx`'s start ledger recorded since they were last taken, in the order it found +/// them; none when it was not told to tolerate them. +pub fn take_start_ledger_divergences( + ctx: &mut MegaContext, +) -> Vec { + ctx.additional_limit.ledger_mut().take_divergences().unwrap_or_default() +} diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index 5e46a06a6..432c88bc6 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -4,6 +4,8 @@ mod bytes; mod database; mod evm; mod inspectors; +#[cfg(debug_assertions)] +mod ledger; mod logs; mod neutral; mod opcode_gen; @@ -16,6 +18,8 @@ pub use bytes::*; pub use database::*; pub use evm::*; pub use inspectors::*; +#[cfg(debug_assertions)] +pub use ledger::*; pub use logs::*; pub use neutral::*; pub use opcode_gen::*; diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index c8123427a..0943b3ba9 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -3,12 +3,16 @@ use alloy_evm::Evm; use alloy_op_evm::OpTx; use alloy_primitives::{Address, Bytes, TxKind, B256, U256}; +#[cfg(debug_assertions)] +use mega_evm::test_utils::{LedgerDivergence, LedgerFigure}; use mega_evm::{ active_satin_prices, test_utils::{note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder}, EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionOutcome, }; +#[cfg(debug_assertions)] +use revm::interpreter::{PoolAmounts, PoolId}; use revm::{ bytecode::opcode::{PUSH0, RETURN}, context::{result::ResultAndState, BlockEnv, TxEnv}, @@ -296,3 +300,40 @@ pub(crate) const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { pub(crate) fn body_history(calldata_len: u64) -> u64 { history(mega_evm::TX_BODY_SIZE + calldata_len) } + +/// The pools the transaction's own frame starts with under `limits` when `tx` counts nothing +/// before it but its body: what each limit leaves once the body is counted, the data size under the +/// frame cap. +#[cfg(debug_assertions)] +pub(crate) fn first_frame_pools(limits: &EvmTxRuntimeLimits, tx: &MegaTransaction) -> PoolAmounts { + let data_size = limits.tx_data_size_limit.saturating_sub(mega_evm::transaction_body_bytes(tx)); + PoolAmounts::ZERO + .with(PoolId::new(0), data_size.min(limits.frame_data_size_limit)) + .with(PoolId::new(1), limits.tx_kv_update_limit) + .with(PoolId::new(2), limits.tx_state_growth_limit) +} + +/// What a debug build's start ledger records where an inspector answered start `start`, at +/// `depth`, on gas that carries the shares its input was forwarded, as the engine's +/// `untouched_call_gas` and `untouched_create_gas` build it: an answer with pools the inspector +/// set, which the owner accepted as an API removal. The fork returns the shares to the caller, +/// which then holds what it held before the start, `caller`; the ledger settles an inspector's +/// answer at unlimited pools. A pool the caller held unlimited parts nowhere. +#[cfg(debug_assertions)] +pub(crate) fn answered_on_its_shares( + start: u32, + depth: usize, + caller: PoolAmounts, +) -> Vec { + PoolId::ALL + .into_iter() + .filter(|pool| caller.get(*pool) != u64::MAX) + .map(|pool| LedgerDivergence { + start, + depth, + figure: LedgerFigure::PoolRemaining(pool), + ledger: u64::MAX.into(), + fork: caller.get(pool).into(), + }) + .collect() +} diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 62dc80525..ef220b75e 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -44,7 +44,11 @@ use revm::{ Inspector, }; +#[cfg(debug_assertions)] +use crate::common::{answered_on_its_shares, first_frame_pools}; use crate::common::{call, call_with_data, context, create, execute, runs_at_measurement_prices}; +#[cfg(debug_assertions)] +use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; const CALLER: Address = address!("0000000000000000000000000000000000a00000"); const CALLEE: Address = address!("0000000000000000000000000000000000a00001"); @@ -252,10 +256,19 @@ fn test_a_creation_answered_without_running_appends_no_code() { } for gas_limit in GAS_LIMITS { let db = callee_running(creating(BytecodeBuilder::default(), &deploying())); - let outcome = MegaEvm::new(context(db)) - .with_inspector(AnswersCreations) - .execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)) - .expect("the transaction is valid"); + let tx = call(CALLER, CALLEE, U256::ZERO, gas_limit); + let mut evm = MegaEvm::new(context(db)).with_inspector(AnswersCreations); + #[cfg(debug_assertions)] + tolerate_start_ledger_divergences(evm.ctx_mut()); + let outcome = evm.execute_transaction(tx.clone()).expect("the transaction is valid"); + // The answer carries the creation's shares, pools the inspector set: an API removal of the + // inspector table, where a debug build's start ledger, which settles an inspector's answer + // at unlimited pools, parts from the fork. + #[cfg(debug_assertions)] + assert_eq!( + take_start_ledger_divergences(evm.ctx_mut()), + answered_on_its_shares(2, 1, first_frame_pools(&EvmTxRuntimeLimits::default(), &tx)), + ); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.usage.write_records, 0, "no bump, no record"); diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 697fbf8a7..d3b4caa41 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -42,6 +42,13 @@ use crate::{ common::{body_history, call, context, reservoir_share}, salt::entry, }; +#[cfg(debug_assertions)] +use mega_evm::test_utils::{ + take_start_ledger_divergences, tolerate_start_ledger_divergences, LedgerDivergence, + LedgerFigure, +}; +#[cfg(debug_assertions)] +use revm::interpreter::PoolId; sol! { /// The cheatcodes these tests drive, as Foundry's `Vm` interface declares them. @@ -304,7 +311,36 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { }; let db = |code: Bytes| MemoryDatabase::default().account_code(TEST, code); - let (worked, answered) = run(db(paused(true)), true); + let (worked, answered) = { + let tx = call(CALLER, TEST, U256::ZERO, GAS_LIMIT); + let mut evm = MegaEvm::new(context(db(paused(true)))).with_inspector(Cheatcodes::default()); + #[cfg(debug_assertions)] + tolerate_start_ledger_divergences(evm.ctx_mut()); + let outcome = evm.execute_transaction(tx).expect("valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + // The paused region's slot is drawn on the frame's pools, and the snapshot `step` puts + // back before the next instruction takes the draw back off the frame's gas: a tracker + // restored from a snapshot, a behaviour change of the inspector table. A debug build's + // start ledger keeps the pools off the tracker and keeps the record's draw, and parts from + // the fork in `TEST`'s nets where the call to `resumeGasMetering`, start 3, settles; the + // pools themselves both read unlimited, the cheatcode's answer on `Gas::new` having + // carried unlimited pools back to `TEST` at the pause. + #[cfg(debug_assertions)] + { + let net = |pool, drawn: u64| LedgerDivergence { + start: 3, + depth: 1, + figure: LedgerFigure::PoolNet(PoolId::new(pool)), + ledger: drawn.into(), + fork: 0, + }; + assert_eq!( + take_start_ledger_divergences(evm.ctx_mut()), + [net(0, WRITE_RECORD_SIZE), net(1, 1), net(2, 1)] + ); + } + (outcome, evm.inspector().answered) + }; assert_eq!(answered, 2); let (idle, _) = run(db(paused(false)), true); assert_eq!(slot(&worked, TEST, 9), U256::from(1), "the slot was written"); diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index 23a77a7aa..1955fcc2d 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -29,7 +29,11 @@ use revm::{ Database, Inspector, }; +#[cfg(debug_assertions)] +use crate::common::{answered_on_its_shares, first_frame_pools}; use crate::common::{body_history, call, context, reservoir_share}; +#[cfg(debug_assertions)] +use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; const CALLER: Address = address!("0000000000000000000000000000000000e00000"); const A: Address = address!("0000000000000000000000000000000000e00001"); @@ -390,7 +394,28 @@ fn test_an_answer_settles_on_the_gas_it_is_built_on() { { let answer = |gas| { let inspector = AnswersB { result, gas }; - run(a_calls_b(), limits, gas_limit, Some(inspector)).0 + let tx = call(CALLER, A, U256::ZERO, gas_limit); + let mut evm = MegaEvm::new(context(a_calls_b()).with_tx_runtime_limits(limits)) + .with_inspector(inspector); + #[cfg(debug_assertions)] + tolerate_start_ledger_divergences(evm.ctx_mut()); + let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); + // An answer on `Gas::new` carries unlimited pools, as the start ledger settles an + // inspector's answer; one on the call's shares carries pools the inspector set, an API + // removal of the inspector table, and the ledger parts from the fork where `A`'s pool + // is limited. + #[cfg(debug_assertions)] + { + let expected = match gas { + AnswerGas::Fresh => Vec::new(), + AnswerGas::Untouched | AnswerGas::Charged => { + answered_on_its_shares(2, 1, first_frame_pools(&limits, &tx)) + } + }; + let divergences = take_start_ledger_divergences(evm.ctx_mut()); + assert_eq!(divergences, expected, "{result:?}, {gas:?}"); + } + outcome }; let untouched = answer(AnswerGas::Untouched); assert!(untouched.result.is_success(), "{result:?}: `A` ignores the answer"); diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index bd0d6ddbb..c95813dd8 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -38,10 +38,14 @@ use revm::{ Inspector, }; +#[cfg(debug_assertions)] +use crate::common::{answered_on_its_shares, first_frame_pools}; use crate::salt::{ create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, value_call, SaltEnvs, CALLER, CONTRACT, EMPTY, }; +#[cfg(debug_assertions)] +use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; /// A contract `CONTRACT` calls. const CALLEE: Address = address!("0000000000000000000000000000000000c00010"); @@ -127,6 +131,41 @@ where .expect("a valid transaction") } +/// [`inspected`] under `inspector`, which answers start `start`, at `depth`, on the gas its input +/// carries, the shares of its caller's pools included: an answer with pools the inspector set, an +/// API removal of the inspector table. A debug build's start ledger, which settles an inspector's +/// answer at unlimited pools, records where it parts from the fork, and each part is asserted +/// ([`answered_on_its_shares`]): the caller is the transaction's own frame, or the transaction, +/// which holds its first frame's pools when the start is made. +fn answered( + db: MemoryDatabase, + envs: SaltEnvs, + tx: MegaTransaction, + inspector: I, + (start, depth): (u32, usize), +) -> MegaTransactionOutcome +where + I: Inspector, EthInterpreter>, +{ + let mut evm = MegaEvm::new(salt_context(db, envs)).with_inspector(inspector); + #[cfg(debug_assertions)] + tolerate_start_ledger_divergences(evm.ctx_mut()); + let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); + #[cfg(debug_assertions)] + assert_eq!( + take_start_ledger_divergences(evm.ctx_mut()), + answered_on_its_shares( + start, + depth, + first_frame_pools(&EvmTxRuntimeLimits::default(), &tx) + ), + "start {start} at depth {depth}" + ); + #[cfg(not(debug_assertions))] + let _ = (start, depth); + outcome +} + /// A call from `CALLER` to `to` carrying `value` and `data`, at `gas_limit`. fn to(to: Address, value: u64, data: Bytes, gas_limit: u64) -> MegaTransaction { tx_with_gas(TxKind::Call(to), data, U256::from(value), gas_limit) @@ -377,8 +416,8 @@ fn test_a_value_call_an_inspector_answers_keeps_what_its_opcode_was_charged() { [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] { let case = format!("answered with {result:?}, gas limit {gas_limit}"); - let answered = - inspected(db(caller()), envs(), tx.clone(), Answers::call(EMPTY, result)); + let answers = Answers::call(EMPTY, result); + let answered = answered(db(caller()), envs(), tx.clone(), answers, (2, 1)); assert!(answered.result.is_success(), "{case}: {:?}", answered.result); assert!(!holds_something(&answered, EMPTY), "{case}: no account"); assert_bills_as(&case, &answered, &ran); @@ -401,8 +440,8 @@ fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_its_charg for result in [InstructionResult::Stop, InstructionResult::Revert] { let case = format!("answered with {result:?}, gas limit {gas_limit}"); - let answered = - inspected(db(Bytes::new()), envs(), tx.clone(), Answers::call(EMPTY, result)); + let answers = Answers::call(EMPTY, result); + let answered = answered(db(Bytes::new()), envs(), tx.clone(), answers, (1, 0)); assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); assert!(!holds_something(&answered, EMPTY), "{case}: no account"); assert_bills_as(&case, &answered, &ran); @@ -436,7 +475,7 @@ fn test_a_creation_an_inspector_answers_keeps_what_its_opcode_was_charged() { .map(|(result, address)| { let case = format!("answered with {result:?}, gas limit {gas_limit}"); let answers = Answers::creation(result, address); - let answered = inspected(db(caller()), envs(), tx.clone(), answers); + let answered = answered(db(caller()), envs(), tx.clone(), answers, (2, 1)); assert!(answered.result.is_success(), "{case}: {:?}", answered.result); assert!(!holds_something(&answered, created), "{case}: no account"); assert_eq!(answered.state[&CONTRACT].info.nonce, nonce - 1, "{case}: no bump"); @@ -469,7 +508,7 @@ fn test_the_transactions_own_creation_an_inspector_answers_keeps_its_charges() { ] { let case = format!("answered with {result:?}, gas limit {gas_limit}"); let answers = Answers::creation(result, address); - let answered = inspected(db(Bytes::new()), envs(), tx.clone(), answers); + let answered = answered(db(Bytes::new()), envs(), tx.clone(), answers, (1, 0)); assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); assert!(!holds_something(&answered, created), "{case}: no account"); assert_bills_as(&case, &answered, &ran); @@ -540,7 +579,7 @@ fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_new_targets_pr let case = format!("m {account_m}/{retarget_m}, gas limit {gas_limit}"); let answer = Some(InstructionResult::Stop); let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer }; - let answered = inspected(db(), envs(), tx.clone(), inspector); + let answered = answered(db(), envs(), tx.clone(), inspector, (2, 1)); assert!(answered.result.is_success(), "{case}: {:?}", answered.result); assert_eq!(answered.gas.state, account_m * account, "{case}: answered, kept whole"); From 3f3d5250251344fde3668e2585720799f4e710b7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 17:15:47 +0800 Subject: [PATCH 43/83] fix(limit): the start ledger compares the settling frame's own pools too A settlement compared only the caller's pools once the child merged into them, which a misallocation between the two cannot move: a share the ledger did not hold to the frame cap came back whole either way. The comparison now also reads the frame's own pools as its result returns them, before the fork settles it. --- crates/mega-evm/src/evm/execution.rs | 2 +- crates/mega-evm/src/limit/ledger.rs | 106 ++++++++++++------ crates/mega-evm/tests/satin/common.rs | 45 +++++--- crates/mega-evm/tests/satin/history_bytes.rs | 11 +- .../tests/satin/inspector_cheatcodes.rs | 2 +- .../mega-evm/tests/satin/inspector_limits.rs | 5 +- .../tests/satin/inspector_settlement.rs | 20 ++-- 7 files changed, 123 insertions(+), 68 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index c41944649..aab2af81c 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1259,7 +1259,7 @@ fn take_back_a_stopped_answer( #[cfg(debug_assertions)] fn fork_figures(result: &FrameResult) -> crate::limit::Returning { let refund = result.refundable_start_charge().map_or(0, |charge| charge.history); - crate::limit::Returning::new(refund, result.gas().history_allowance()) + crate::limit::Returning::of(result.gas().tracker(), refund) } /// Has the start ledger adopt what a precompile's provider drew on the pools of `answer`, revm's diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index deedfb506..d6fc8b124 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -82,12 +82,19 @@ use super::Counted; /// A figure of a settled start the ledger compares with the fork's. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LedgerFigure { + /// What the started frame may still draw on a pool, as its result returns it. + FrameRemaining(PoolId), + /// The started frame's net draw on a pool, as its result returns it. + FrameNet(PoolId), + /// Whether a draw on the started frame's pool was refused (`1`) or not (`0`), as its result + /// returns it. + FrameCrossing(PoolId), /// What the start's caller may still draw on a pool, once the start settled into it. - PoolRemaining(PoolId), + CallerRemaining(PoolId), /// The caller's net draw on a pool, once the start settled into it. - PoolNet(PoolId), + CallerNet(PoolId), /// Whether a draw on the caller's pool was refused (`1`) or not (`0`). - PoolCrossing(PoolId), + CallerCrossing(PoolId), /// The part of its reservoir the caller kept while the start ran. KeptReservoir, /// The history gas the start's settlement gave back to its caller. @@ -96,6 +103,9 @@ pub enum LedgerFigure { Allowance, } +/// One of a pool's figures, named by the pool. +type PoolFigure = fn(PoolId) -> LedgerFigure; + /// A figure of a settled start in which the ledger and the fork differ. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LedgerDivergence { @@ -312,6 +322,8 @@ impl From<&FrameSettle> for Settlement { /// The fork's figures of the result about to settle, read before revm consumes it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Returning { + /// The frame's pools as its result's gas holds them. + pools: Pools, /// The history the fork gives back to the caller for the start. refund: u64, /// What the result's gas holds of the frame's history allowance. @@ -319,10 +331,10 @@ pub(crate) struct Returning { } impl Returning { - /// `refund`, the history of the start charge the fork gives back, and `allowance`, what the - /// result's gas holds of the frame's history allowance. - pub(crate) const fn new(refund: u64, allowance: u64) -> Self { - Self { refund, allowance } + /// The figures of a result whose gas is `gas`: its pools and what it holds of its frame's + /// history allowance; and `refund`, the history of the start charge the fork gives back. + pub(crate) fn of(gas: &GasTracker, refund: u64) -> Self { + Self { pools: Pools::on(gas), refund, allowance: gas.history_allowance() } } } @@ -540,21 +552,35 @@ impl StartLedger { let on_gas = Pools::on(gas); let mut differences = Vec::new(); - for pool in PoolId::ALL { - let index = pool.index(); - differences.extend([ - ( - LedgerFigure::PoolRemaining(pool), - i128::from(ledger.remaining.get(pool)), - i128::from(on_gas.remaining.get(pool)), - ), - (LedgerFigure::PoolNet(pool), ledger.net[index].into(), on_gas.net[index].into()), - ( - LedgerFigure::PoolCrossing(pool), - ledger.crossings[index].into(), - on_gas.crossings[index].into(), - ), - ]); + let figures: [(Pools, Pools, [PoolFigure; 3]); 2] = [ + ( + pools, + fork.pools, + [LedgerFigure::FrameRemaining, LedgerFigure::FrameNet, LedgerFigure::FrameCrossing], + ), + ( + ledger, + on_gas, + [ + LedgerFigure::CallerRemaining, + LedgerFigure::CallerNet, + LedgerFigure::CallerCrossing, + ], + ), + ]; + for (ledger, fork, [remaining, net, crossing]) in figures { + for pool in PoolId::ALL { + let index = pool.index(); + differences.extend([ + ( + remaining(pool), + i128::from(ledger.remaining.get(pool)), + i128::from(fork.remaining.get(pool)), + ), + (net(pool), ledger.net[index].into(), fork.net[index].into()), + (crossing(pool), ledger.crossings[index].into(), fork.crossings[index].into()), + ]); + } } differences.extend([ ( @@ -578,9 +604,9 @@ impl StartLedger { let pools_differ = differences.iter().any(|(figure, ..)| { matches!( figure, - LedgerFigure::PoolRemaining(_) | - LedgerFigure::PoolNet(_) | - LedgerFigure::PoolCrossing(_) + LedgerFigure::CallerRemaining(_) | + LedgerFigure::CallerNet(_) | + LedgerFigure::CallerCrossing(_) ) }); let Some(recorded) = &mut self.divergences else { @@ -766,8 +792,8 @@ mod tests { assert!(child.record_pool(pool, child_draw.added.get(pool))); } assert_eq!(top(&ledger), Pools::on(&child), "{case}: the child's draws"); + ledger.returning(Returning::of(&child, 0)); handle_reservoir_remaining_gas(result, &mut caller, &mut child); - ledger.returning(Returning::new(0, 0)); ledger.settle(&settled(2, 1, status_of(result), 0), &caller); assert_eq!(top(&ledger), Pools::on(&caller), "{case}: the caller's"); } @@ -795,7 +821,7 @@ mod tests { ledger.tolerate_divergences(); ledger.park(KEPT, 0, 123, 0); ledger.split(2, Some(1), 1); - ledger.returning(Returning::new(0, 0)); + ledger.returning(Returning::of(&tracker(PoolAmounts::UNLIMITED, 0), 0)); let settlement = Settlement { created, inspector_answer, @@ -832,8 +858,8 @@ mod tests { assert!(child.record_pool(pool, ledger.entries[1].pools.net[pool.index()] as u64)); } let mut returned = if outcome_rebuilt { child } else { GasTracker::new(0, 0, 0) }; + ledger.returning(Returning::of(&returned, 0)); handle_reservoir_remaining_gas(InstructionResult::Stop, &mut caller, &mut returned); - ledger.returning(Returning::new(0, 0)); let settlement = Settlement { inspector_answer, gas_replaced, @@ -890,9 +916,15 @@ mod tests { assert_eq!(ledger.draw_allowance(30), 0, "within it"); assert_eq!(ledger.draw_allowance(80), 10, "past it"); assert_eq!(ledger.draw_allowance(5), 5, "spent"); - ledger.returning(Returning::new(0, 1)); + let mut returned = tracker(PoolAmounts::UNLIMITED, 0); + returned.set_history_allowance(1); + ledger.returning(Returning::of(&returned, 0)); ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &tracker(PoolAmounts::UNLIMITED, 0)); - let divergences = ledger.take_divergences().unwrap_or_default(); + let allowance = ledger + .take_divergences() + .unwrap_or_default() + .into_iter() + .find(|divergence| divergence.figure == LedgerFigure::Allowance); let expected = built.then_some(LedgerDivergence { start: 2, depth: 1, @@ -900,7 +932,7 @@ mod tests { ledger: 0, fork: 1, }); - assert_eq!(divergences.first().copied(), expected, "built {built}"); + assert_eq!(allowance, expected, "built {built}"); } } @@ -920,9 +952,9 @@ mod tests { ledger.park(KEPT, 0, 0, 0); ledger.split(1, None, 0); assert_eq!(ledger.entries.len(), 1, "a transaction's start resets"); - ledger.returning(Returning::new(0, 0)); let mut transaction = tracker(PoolAmounts::UNLIMITED, 0); let mut frame = tracker(transaction.forward_all_to_child().pools, 0); + ledger.returning(Returning::of(&frame, 0)); handle_reservoir_remaining_gas(InstructionResult::Stop, &mut transaction, &mut frame); ledger.settle(&settled(1, 0, SettleStatus::Ok, 0), &transaction); ledger.end(true); @@ -950,7 +982,7 @@ mod tests { let mut ledger = opened(POOLS); ledger.park(KEPT, 1_000, 0, 0); ledger.split(2, Some(1), 1); - ledger.returning(Returning::new(0, 0)); + ledger.returning(Returning::of(&tracker(ledger.entries[1].shares, 0), 0)); ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &tracker(POOLS, 0)); } @@ -962,15 +994,19 @@ mod tests { ledger.tolerate_divergences(); ledger.park(KEPT, 1_000, 0, 0); ledger.split(2, Some(1), 1); - ledger.returning(Returning::new(5, 0)); + let shares = ledger.entries[1].shares; + let returned = tracker(shares.with(KV_UPDATE_POOL, 7), 0); + ledger.returning(Returning::of(&returned, 5)); let fork = tracker(POOLS.with(DATA_SIZE_POOL, 1), 0); ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &fork); let at = |figure, ledger, fork| LedgerDivergence { start: 2, depth: 1, figure, ledger, fork }; + let shared = i128::from(shares.get(KV_UPDATE_POOL)); assert_eq!( ledger.take_divergences(), Some(std::vec![ - at(LedgerFigure::PoolRemaining(DATA_SIZE_POOL), 10_000, 1), + at(LedgerFigure::FrameRemaining(KV_UPDATE_POOL), shared, 7), + at(LedgerFigure::CallerRemaining(DATA_SIZE_POOL), 10_000, 1), at(LedgerFigure::KeptReservoir, 20, 0), at(LedgerFigure::StartChargeRefund, 0, 5), ]) diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 0943b3ba9..33d77bdc3 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -313,27 +313,44 @@ pub(crate) fn first_frame_pools(limits: &EvmTxRuntimeLimits, tx: &MegaTransactio .with(PoolId::new(2), limits.tx_state_growth_limit) } +/// The share of each of `caller`'s pools a frame it starts begins with: 98/100 of each, rounded +/// down. +#[cfg(debug_assertions)] +pub(crate) fn frame_shares(caller: PoolAmounts) -> PoolAmounts { + let share = |amount: u64| { + let share = u128::from(amount) * u128::from(mega_evm::FRAME_DATA_SHARE_NUMERATOR) / + u128::from(mega_evm::FRAME_DATA_SHARE_DENOMINATOR); + u64::try_from(share).expect("a share is less than the pool") + }; + PoolId::ALL.into_iter().fold(caller, |shares, pool| shares.with(pool, share(caller.get(pool)))) +} + /// What a debug build's start ledger records where an inspector answered start `start`, at -/// `depth`, on gas that carries the shares its input was forwarded, as the engine's +/// `depth`, on gas that carries the shares its input was forwarded, `shares`, as the engine's /// `untouched_call_gas` and `untouched_create_gas` build it: an answer with pools the inspector -/// set, which the owner accepted as an API removal. The fork returns the shares to the caller, -/// which then holds what it held before the start, `caller`; the ledger settles an inspector's -/// answer at unlimited pools. A pool the caller held unlimited parts nowhere. +/// set, which the owner accepted as an API removal. The ledger settles an inspector's answer at +/// unlimited pools, so it parts from the fork on the answer's own pools wherever a share is +/// limited, and on its caller's once it settled, wherever the caller, which the fork gives back +/// the shares and so leaves with what it held before the start, `caller`, is limited. #[cfg(debug_assertions)] pub(crate) fn answered_on_its_shares( start: u32, depth: usize, caller: PoolAmounts, + shares: PoolAmounts, ) -> Vec { - PoolId::ALL - .into_iter() - .filter(|pool| caller.get(*pool) != u64::MAX) - .map(|pool| LedgerDivergence { - start, - depth, - figure: LedgerFigure::PoolRemaining(pool), - ledger: u64::MAX.into(), - fork: caller.get(pool).into(), - }) + let parts = |amounts: PoolAmounts, figure: fn(PoolId) -> LedgerFigure| { + PoolId::ALL.into_iter().filter(move |pool| amounts.get(*pool) != u64::MAX).map( + move |pool| LedgerDivergence { + start, + depth, + figure: figure(pool), + ledger: u64::MAX.into(), + fork: amounts.get(pool).into(), + }, + ) + }; + parts(shares, LedgerFigure::FrameRemaining) + .chain(parts(caller, LedgerFigure::CallerRemaining)) .collect() } diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index ef220b75e..60f308e86 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -45,7 +45,7 @@ use revm::{ }; #[cfg(debug_assertions)] -use crate::common::{answered_on_its_shares, first_frame_pools}; +use crate::common::{answered_on_its_shares, first_frame_pools, frame_shares}; use crate::common::{call, call_with_data, context, create, execute, runs_at_measurement_prices}; #[cfg(debug_assertions)] use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; @@ -265,10 +265,11 @@ fn test_a_creation_answered_without_running_appends_no_code() { // inspector table, where a debug build's start ledger, which settles an inspector's answer // at unlimited pools, parts from the fork. #[cfg(debug_assertions)] - assert_eq!( - take_start_ledger_divergences(evm.ctx_mut()), - answered_on_its_shares(2, 1, first_frame_pools(&EvmTxRuntimeLimits::default(), &tx)), - ); + { + let caller = first_frame_pools(&EvmTxRuntimeLimits::default(), &tx); + let expected = answered_on_its_shares(2, 1, caller, frame_shares(caller)); + assert_eq!(take_start_ledger_divergences(evm.ctx_mut()), expected); + } assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.usage.write_records, 0, "no bump, no record"); diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index d3b4caa41..1c56861a1 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -330,7 +330,7 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { let net = |pool, drawn: u64| LedgerDivergence { start: 3, depth: 1, - figure: LedgerFigure::PoolNet(PoolId::new(pool)), + figure: LedgerFigure::CallerNet(PoolId::new(pool)), ledger: drawn.into(), fork: 0, }; diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index 1955fcc2d..4b99acc5e 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -30,7 +30,7 @@ use revm::{ }; #[cfg(debug_assertions)] -use crate::common::{answered_on_its_shares, first_frame_pools}; +use crate::common::{answered_on_its_shares, first_frame_pools, frame_shares}; use crate::common::{body_history, call, context, reservoir_share}; #[cfg(debug_assertions)] use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; @@ -409,7 +409,8 @@ fn test_an_answer_settles_on_the_gas_it_is_built_on() { let expected = match gas { AnswerGas::Fresh => Vec::new(), AnswerGas::Untouched | AnswerGas::Charged => { - answered_on_its_shares(2, 1, first_frame_pools(&limits, &tx)) + let caller = first_frame_pools(&limits, &tx); + answered_on_its_shares(2, 1, caller, frame_shares(caller)) } }; let divergences = take_start_ledger_divergences(evm.ctx_mut()); diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index c95813dd8..8f34b25b7 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -39,7 +39,7 @@ use revm::{ }; #[cfg(debug_assertions)] -use crate::common::{answered_on_its_shares, first_frame_pools}; +use crate::common::{answered_on_its_shares, first_frame_pools, frame_shares}; use crate::salt::{ create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, value_call, SaltEnvs, CALLER, CONTRACT, EMPTY, @@ -152,15 +152,15 @@ where tolerate_start_ledger_divergences(evm.ctx_mut()); let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); #[cfg(debug_assertions)] - assert_eq!( - take_start_ledger_divergences(evm.ctx_mut()), - answered_on_its_shares( - start, - depth, - first_frame_pools(&EvmTxRuntimeLimits::default(), &tx) - ), - "start {start} at depth {depth}" - ); + { + let caller = first_frame_pools(&EvmTxRuntimeLimits::default(), &tx); + let shares = if depth == 0 { caller } else { frame_shares(caller) }; + assert_eq!( + take_start_ledger_divergences(evm.ctx_mut()), + answered_on_its_shares(start, depth, caller, shares), + "start {start} at depth {depth}" + ); + } #[cfg(not(debug_assertions))] let _ = (start, depth); outcome From 8a375a4de4eb8b685ebdbd610ba9e21692b64326 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 17:22:23 +0800 Subject: [PATCH 44/83] test(satin): the start ledger over the depth guard, a fatal error and reuse, a nested EVM and inspector rewrites --- crates/mega-evm/tests/satin/main.rs | 3 + crates/mega-evm/tests/satin/start_ledger.rs | 344 ++++++++++++++++++++ 2 files changed, 347 insertions(+) create mode 100644 crates/mega-evm/tests/satin/start_ledger.rs diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index dca186240..5173fa9d0 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -49,6 +49,9 @@ mod schedule; #[path = "../shared/snapshot.rs"] mod snapshot; mod spec_numbers; +// The start ledger runs in a debug build alone. +#[cfg(debug_assertions)] +mod start_ledger; mod state; mod state_growth; mod static_callee; diff --git a/crates/mega-evm/tests/satin/start_ledger.rs b/crates/mega-evm/tests/satin/start_ledger.rs new file mode 100644 index 000000000..4e5fc4d4a --- /dev/null +++ b/crates/mega-evm/tests/satin/start_ledger.rs @@ -0,0 +1,344 @@ +//! The start ledger over the engine's paths no other test drives through a transaction's start +//! lifecycle. +//! +//! A debug build keeps the engine's own ledger of what each frame start owes and holds beside the +//! fork's figures, and compares the two at every settlement, panicking on a difference. Every test +//! of the crate runs under it, so a path the suite drives is a path the comparison holds on. These +//! tests drive the ones it does not: the depth guard's answer inside a running transaction, a +//! fatal error with starts open and the reuse of the EVM after it, an EVM run inside an inspector's +//! callback, an inspector's answer to the transaction's own frame, and the end-callback rewrites +//! whose figures the ledger settles exactly. Each reads the starts revm settled off its debug +//! mirror of the lifecycle, so the path is shown taken, and passes only if the ledger agreed with +//! the fork at each of them. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{ + neutral_cfg, neutralize_evm, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, + }, + EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, +}; +use revm::{ + bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, REVERT}, + context::{BlockEnv, ContextTr}, + context_interface::{ + host::{FrameSettle, LifecycleEnd, SettleStatus}, + LifecycleEvent, LocalContextTr, + }, + handler::FrameResult, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + FrameInput, Gas, InstructionResult, InterpreterResult, + }, + primitives::CALL_STACK_LIMIT, + Database, Inspector, +}; + +use crate::common::{block, call, context, create}; + +const CALLER: Address = address!("0000000000000000000000000000000000d00000"); +const OUTER: Address = address!("0000000000000000000000000000000000d00001"); +const CHILD: Address = address!("0000000000000000000000000000000000d00002"); +/// Calls a contract whose storage read the database fails. +const CALLS_FAILS: Address = address!("0000000000000000000000000000000000d00005"); +const GAS_LIMIT: u64 = 10_000_000; + +/// The settlements of the last transaction's start lifecycle, as revm's debug mirror recorded +/// them, and how it ended: each settlement is one the start ledger compared with the fork's +/// figures. +fn settlements(ctx: &mut MegaContext) -> (Vec, LifecycleEnd) { + let mirror = ctx.local_mut().lifecycle_mirror().expect("a debug build's mirror"); + let mut settled = Vec::new(); + let mut end = None; + for event in mirror.events() { + match event { + LifecycleEvent::Settle(settle) => settled.push(*settle), + LifecycleEvent::End(ended) => end = Some(*ended), + LifecycleEvent::Split(_) => {} + } + } + (settled, end.expect("the lifecycle ended")) +} + +/// `(start, depth, status)` of each settlement, innermost first. +fn shape(settled: &[FrameSettle]) -> Vec<(u32, usize, SettleStatus)> { + settled.iter().map(|settle| (settle.id, settle.depth, settle.status)).collect() +} + +/// `OUTER` sends one wei to `CHILD`, which writes a fresh slot and then returns or reverts as +/// `reverts` says; `OUTER` stops either way. The child's start makes two write records, which its +/// caller is charged for at the `CALL` and which its failure gives back. +fn value_call_to_a_writer(reverts: bool) -> MemoryDatabase { + let outer = BytecodeBuilder::default().call(CHILD, U256::from(1)).append(POP).stop().build(); + let child = BytecodeBuilder::default().sstore(U256::from(7), U256::from(1)); + let child = if reverts { child.append_many([PUSH0, PUSH0, REVERT]) } else { child.stop() }; + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(OUTER, U256::from(10)) + .account_code(OUTER, outer) + .account_code(CHILD, child.build()) +} + +/// A frame past the call-stack limit is answered by the depth guard inside a running transaction: +/// a contract that calls itself with all its gas reaches depth 1,024, whose call is answered +/// `CallTooDeep` at depth 1,025 without a frame, and the guard's answer settles on the start revm +/// opened for it as every frame below it settles. No Satin transaction reaches that depth, a +/// child taking 98/100 of its caller's gas under an execution cap, so this one runs on the neutral +/// configuration, EIP-150's 63/64, without a cap. +#[test] +fn test_the_depth_guards_answer_settles_on_its_start() { + const RECURSES: Address = address!("0000000000000000000000000000000000d00003"); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, ADDRESS, GAS, CALL]) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(RECURSES, code); + let mut cfg = neutral_cfg(EthSpecId::OSAKA).expect("Osaka has a neutral configuration"); + cfg.tx_gas_limit_cap = Some(u64::MAX); + let ctx = context(db) + .with_block(BlockEnv { gas_limit: u64::MAX, ..block() }) + .with_neutral_cfg(cfg) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(ctx); + neutralize_evm(&mut evm, EthSpecId::OSAKA).expect("Osaka neutralizes"); + let outcome = evm + .execute_transaction(call(CALLER, RECURSES, U256::ZERO, 1_000_000_000_000)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + let (settled, end) = settlements(evm.ctx_mut()); + assert_eq!(end, LifecycleEnd::Settled); + let past = CALL_STACK_LIMIT as usize + 1; + assert_eq!(settled.len(), past + 1, "a start for every frame and the guard's answer"); + // revm counts `CallTooDeep` among its revert results. + let guards = [(past as u32 + 1, past, SettleStatus::Revert)]; + assert_eq!(shape(&settled[..1]), guards, "the guard's answer"); + assert!(settled[1..].iter().all(|settle| settle.status == SettleStatus::Ok), "the frames'"); +} + +/// A database error in a frame two starts deep fails the transaction with both starts open: the +/// lifecycle is discarded and the start ledger dropped with it, and the same EVM runs the next +/// transaction from a ledger its own transaction's start resets, every start compared. +#[test] +fn test_a_fatal_error_with_starts_open_discards_the_ledger_and_the_evm_runs_on() { + const FAILS: Address = address!("0000000000000000000000000000000000d00004"); + let key = U256::from(0x42); + let outer = BytecodeBuilder::default().call(FAILS, U256::ZERO).append(POP).stop().build(); + let fails = BytecodeBuilder::default().sstore(key, U256::from(1)).stop().build(); + let db = + value_call_to_a_writer(false).account_code(FAILS, fails).account_code(CALLS_FAILS, outer); + let mut db = ErrorInjectingDatabase::new(db); + db.fail_on_storage = Some((FAILS, key)); + let mut evm = MegaEvm::new(context(db)); + + let failing = call(CALLER, CALLS_FAILS, U256::ZERO, GAS_LIMIT); + let error = evm.execute_transaction(failing).expect_err("the storage read fails"); + assert!(format!("{error:?}").contains("injected storage()"), "{error:?}"); + let (settled, end) = settlements(evm.ctx_mut()); + assert_eq!((settled.len(), end), (0, LifecycleEnd::Discarded), "both starts discarded"); + + let outcome = evm + .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (settled, end) = settlements(evm.ctx_mut()); + assert_eq!(end, LifecycleEnd::Settled); + assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); +} + +/// Runs a transaction on an EVM of its own, over a copy of the state, in its `call` callback for +/// `CHILD`: a simulation a tool makes while the outer transaction runs. +struct Simulates { + db: MemoryDatabase, + simulated: usize, +} + +impl Inspector, EthInterpreter> for Simulates { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + if inputs.target_address == CHILD { + let mut nested = MegaEvm::new(context(self.db.clone())); + let outcome = nested + .execute_transaction(call(CALLER, OUTER, U256::from(1), GAS_LIMIT)) + .expect("the simulation is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (settled, end) = settlements(nested.ctx_mut()); + assert_eq!(end, LifecycleEnd::Settled); + assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + self.simulated += 1; + } + None + } +} + +/// An EVM a tool runs inside an inspector's callback keeps a start ledger of its own, which its +/// transaction's start resets and every start of which it compares; the outer transaction's ledger, +/// with a start open in it, goes on as if nothing ran, and compares every start of its own. +/// `MegaContext` is not `Clone`, so a simulation always runs on a context of its own. +#[test] +fn test_an_evm_run_inside_a_callback_keeps_a_ledger_of_its_own() { + let db = value_call_to_a_writer(false); + let inspector = Simulates { db: db.clone(), simulated: 0 }; + let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); + let outcome = evm + .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(evm.inspector().simulated, 1); + let (settled, end) = settlements(evm.ctx_mut()); + assert_eq!(end, LifecycleEnd::Settled); + assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); +} + +/// Answers the transaction's own frame on `Gas::new`, as Foundry answers a cheatcode: in +/// `frame_start` when `at_frame_start`, otherwise in `call` or `create`. +struct AnswersTheTransaction { + result: InstructionResult, + at_frame_start: bool, +} + +impl AnswersTheTransaction { + fn answer_call(&self, inputs: &CallInputs) -> CallOutcome { + let gas = Gas::new(inputs.gas_limit); + let result = InterpreterResult::new(self.result, Bytes::new(), gas); + CallOutcome::new(result, inputs.return_memory_offset.clone()) + } + + fn answer_create(&self, inputs: &CreateInputs) -> CreateOutcome { + let gas = Gas::new(inputs.gas_limit()); + CreateOutcome::new(InterpreterResult::new(self.result, Bytes::new(), gas), None) + } +} + +impl Inspector, EthInterpreter> for AnswersTheTransaction { + fn frame_start( + &mut self, + _: &mut MegaContext, + input: &mut FrameInput, + ) -> Option { + if !self.at_frame_start { + return None; + } + match input { + FrameInput::Call(inputs) => Some(FrameResult::Call(self.answer_call(inputs))), + FrameInput::Create(inputs) => Some(FrameResult::Create(self.answer_create(inputs))), + FrameInput::Empty => None, + } + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + (!self.at_frame_start).then(|| self.answer_call(inputs)) + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + (!self.at_frame_start).then(|| self.answer_create(inputs)) + } +} + +/// An inspector's answer to the transaction's own frame, on `Gas::new`, settles as the start +/// ledger settles an inspector's answer — unlimited pools, no start charge back — and the fork +/// settles it the same: a value transfer and a creation, answered with a success, a revert and a +/// halt, in `frame_start` and in `call` or `create`. +#[test] +fn test_an_inspectors_answer_to_the_transactions_frame_settles_as_unlimited_pools() { + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let results = [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas]; + for at_frame_start in [false, true] { + for result in results { + for transaction in [ + call(CALLER, CHILD, U256::from(1), GAS_LIMIT), + create(CALLER, Bytes::from_static(&[0x00]), GAS_LIMIT), + ] { + let case = format!( + "{result:?}, frame start {at_frame_start}, {:?}", + transaction.0.base.kind + ); + let inspector = AnswersTheTransaction { result, at_frame_start }; + let mut evm = MegaEvm::new(context(db())).with_inspector(inspector); + let outcome = evm.execute_transaction(transaction).expect("valid"); + assert_eq!(outcome.result.is_success(), result.is_ok(), "{case}"); + let (settled, end) = settlements(evm.ctx_mut()); + assert_eq!(end, LifecycleEnd::Settled, "{case}"); + assert_eq!(settled.len(), 1, "{case}"); + assert!(settled[0].inspector_answer, "{case}: flagged"); + } + } + } +} + +/// How [`Rewrites`] rewrites `CHILD`'s result in `call_end`. +#[derive(Clone, Copy, Debug)] +enum Rewrite { + /// The status alone, a success into a revert and a failure into a success. + Status, + /// The tracker, replaced with `Gas::new` of the call's gas limit. + Tracker, + /// The outcome, rebuilt around the same result with `CallOutcome::new`. + Outcome, + /// The outcome, rebuilt keeping every other field of it. + KeepingTheOutcome, +} + +/// Rewrites `CHILD`'s result in `call_end` as its [`Rewrite`] says. +struct Rewrites(Rewrite); + +impl Inspector, EthInterpreter> for Rewrites { + fn call_end(&mut self, _: &mut MegaContext, inputs: &CallInputs, out: &mut CallOutcome) { + if inputs.target_address != CHILD { + return; + } + match self.0 { + Rewrite::Status => { + out.result.result = if out.result.result.is_ok() { + InstructionResult::Revert + } else { + InstructionResult::Stop + } + } + Rewrite::Tracker => out.result.gas = Gas::new(inputs.gas_limit), + Rewrite::Outcome => { + *out = CallOutcome::new(out.result.clone(), out.memory_offset.clone()); + } + Rewrite::KeepingTheOutcome => { + *out = CallOutcome { result: out.result.clone(), ..out.clone() }; + } + } + } +} + +/// The end-callback rewrites the start ledger settles exactly settle as the fork settles them: +/// a status rewritten either way settles by the new status; a tracker replaced with `Gas::new` +/// settles as unlimited pools, and its start charge comes back by the status; an outcome rebuilt +/// around the same result settles on the frame's pools and gives no start charge back, the +/// constructor having dropped it; one rebuilt keeping the outcome is no rewrite at all. Each on a +/// value call to a child that writes a fresh slot and then succeeds or reverts. +#[test] +fn test_end_callback_rewrites_settle_as_the_fork_settles_them() { + for rewrite in [Rewrite::Status, Rewrite::Tracker, Rewrite::Outcome, Rewrite::KeepingTheOutcome] + { + for reverts in [false, true] { + let case = format!("{rewrite:?}, the child reverts {reverts}"); + let mut evm = MegaEvm::new(context(value_call_to_a_writer(reverts))) + .with_inspector(Rewrites(rewrite)); + let outcome = evm + .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + let (settled, end) = settlements(evm.ctx_mut()); + assert_eq!(end, LifecycleEnd::Settled, "{case}"); + let child = settled[0]; + let ok = matches!(rewrite, Rewrite::Status) == reverts; + assert_eq!(child.status == SettleStatus::Ok, ok, "{case}: the settled status"); + let flags = (child.inspector_answer, child.gas_replaced, child.outcome_rebuilt); + let expected = match rewrite { + Rewrite::Status | Rewrite::KeepingTheOutcome => (false, false, false), + Rewrite::Tracker => (false, true, false), + Rewrite::Outcome => (false, false, true), + }; + assert_eq!(flags, expected, "{case}: the flags"); + } + } +} From c973c2c4f8bda1a75d11d601a0a6eafcca410ca2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 17:25:56 +0800 Subject: [PATCH 45/83] docs: the start ledger a debug build checks against the fork's figures, in AGENTS.md and the review guide --- .claude/skills/satin-review/SKILL.md | 9 ++++++++- AGENTS.md | 10 ++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 2c5f3b79c..b3edff9b3 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -69,6 +69,12 @@ Each change is stated here in plain words with its reason; the specification has revm's frame run returns an action set on a frame before it runs, without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`: a `keylessDeploy` call's creation and answer, and the stop of a caller a child left over a limit, come back through revm's own run. The run-result hook (`EvmTr::frame_run_result`) is called once a frame's run returns, before the inspector's `call_end`, `create_end` and `frame_end` and before `frame_return_result`; gas detention turns a crossing into the stop there, so inspectors and tracers see the stop the caller gets. Why: both are points in the middle of revm's own loop that mega-evm cannot reach from outside, which is what the fork is for, and with them the engine has no frame run of its own. +- **A debug build keeps its own ledger of every frame start and checks it against the fork's figures.** + The fork carries four figures of a start on the frame's gas: the three pools with their nets and crossings, the part of the reservoir the caller keeps, the start charge and the history allowance. + The engine keeps the same four in an entry per start (`src/limit/ledger.rs`), computed by its own rules and driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and compares them with the fork's at every settlement, panicking on a difference; every result still reads the fork's figures, and a release build carries none of it. + A test of an inspector that answers or rewrites with pools or a start charge it set, or restores a snapshot of a running tracker, records the differences and asserts each, since those figures are accepted to change once the engine reads its own ledger. + This was added after #407 merged. + Why: the figures are to leave the fork for the engine, and the ledger that will replace them is proved against them, on every engine path, before anything reads it. - **Writes and frame starts are metered in the fork's instruction hooks.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, and the frame's own part is declared on the start (`FrameStart::charge`) for the fork to refund when the frame fails. @@ -232,7 +238,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. ### Limits: data size, KV updates, state growth, the stop -- **Where:** `src/limit/` (the byte table, `LimitKind`, `LimitCheck`, `MegaLimitExceeded` and `EvmTxRuntimeLimits` in `mod.rs`; the write records and the state growth a write and a frame start make in `record.rs`; `AdditionalLimit` in `limit.rs`), `src/block/limit.rs` (`ProtocolLimits::for_spec`, `BlockLimits`, `BlockLimiter`), `src/constants.rs`. +- **Where:** `src/limit/` (the byte table, `LimitKind`, `LimitCheck`, `MegaLimitExceeded` and `EvmTxRuntimeLimits` in `mod.rs`; the write records and the state growth a write and a frame start make in `record.rs`; `AdditionalLimit` in `limit.rs`; the debug build's start ledger in `ledger.rs`), `src/block/limit.rs` (`ProtocolLimits::for_spec`, `BlockLimits`, `BlockLimiter`), `src/constants.rs`. - **Read first:** the module doc of `src/limit/mod.rs` and the doc of `AdditionalLimit` in `src/limit/limit.rs`. - **Check:** - A count is drawn where it is made, on the pool of the frame that makes it (`AdditionalLimit::draw`), and a failed frame's draws go back with its gas. @@ -354,6 +360,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing (a frame that fails, or a start revm refuses before it bumps a nonce or moves a value), and its records are those revm then made. - A pre-block system call runs on the plain system-call path, with no callback. - `test_utils::ReadOnlyObserver` checks, in debug builds, that an inspector a test declares an observer writes nothing back: a tripwire for tests, not a proof. + - A debug build's start ledger settles an inspector's answer and a replaced tracker at unlimited pools, and gives no start charge back for an answer or a rebuilt outcome; a test whose inspector builds an answer or a result with pools or a charge of its own, or restores a snapshot of a running tracker, records the ledger's differences from the fork and asserts each, and every other test fails on any difference. - **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer), the entries on inspectors. ### Node surface, validation and the stateless witness diff --git a/AGENTS.md b/AGENTS.md index 4d9441d61..4047c5508 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,6 +106,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `cargo tree -i revm` must show exactly one revm, from the fork: the engine's graph (the default member) never reaches another. The workspace also locks revm 27.1.0, linked only by `mega-evme`: its `legacy` feature, and its `mega-state-test` 1.7.1 dev-dependency, which is unconditional, so a test build without `legacy` links it too (`cargo tree --workspace -i revm@27.1.0`). - The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. +- The engine implements the fork's start lifecycle hooks (`Host::frame_split`, `frame_settle`, `frame_lifecycle_end`) in a debug build alone: each reaches the inner context, whose mirror checks the lifecycle's order, and drives the engine's start ledger (`limit/ledger.rs`), which pairs nothing itself; a release build takes the hooks' defaults, which do nothing. - Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), whose crossing record holds the regular gas the frame had before the charge that crossed (`WithheldCrossing::remaining`), on the fork's failed-charge record, the regular gas a frame had before every deduction that failed and before a halt on a cold access it could not pay (`failed_charge_remaining`, `set_failed_charge_remaining`), which tells what a halting frame burned, and on the fork's precompile price (`Precompile::required_gas`), none of which upstream revm has. - Writes and frame starts are metered inside revm's instructions, through the fork's two instruction hooks on `Host`, which upstream revm does not have: `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge they make has been made, and the four calls and two creations call `frame_starting` once the forward is taken and before the frame's input is built. `CompletedWrite` and `FrameStartKind` are exhaustive on purpose, so the engine's matches over them carry no wildcard arm and a new kind is a compile error here. @@ -140,12 +141,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | | `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | | `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); in a debug build, the start ledger beside it: what each open frame start owes and holds of the four figures the fork carries — the three pools with their nets and crossings, the reservoir its caller keeps, its start charge and its history allowance — computed by the engine's own rules, driven by the start lifecycle hooks alone, and compared with the fork's figures at every settlement (`ledger.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | | `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | | `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | | `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | | `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | -| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | +| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); in a debug build, the start ledger's differences from the fork that a test of an inspector shape accepted to change records and asserts (`tolerate_start_ledger_divergences`, `take_start_ledger_divergences`, `LedgerDivergence`, `LedgerFigure`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | ### How Satin executes today @@ -488,6 +489,11 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **A per-frame gas cap stays inside the frame's tracker.** Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame's run returns (`frame_run_result`). A later mechanism that caps a frame's gas uses the same part; it limits the frame at its start and again after every credit — a child's return, `SSTORE`'s refill — and never releases a creating frame's withheld part before `return_create`, whose charges are the frame's own regular charges. +- **A debug build checks every start's figures against a ledger of the engine's own.** + The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding the four figures the fork carries on the frame's gas — its pools, the reservoir its caller keeps, its start charge and its history allowance — computed by the engine's own rules: what a start owes is parked where it is decided (`frame_starting`, the keyless builder, the first frame's input) and taken by the split, every draw `AdditionalLimit` applies is mirrored on the top entry, the frame cap is applied as `cap_the_shares` applies it, and a settlement merges by status and the inspector flags. + At every settlement it compares the frame's pools as its result returns them, its caller's once settled, the kept reservoir with `held_reservoir`, the start-charge refund and the allowance with the fork's figures, and panics on a difference; the lifecycle's successful end finds it empty. + The engine still reads the fork's figures for every result. + The inspector shapes accepted to change when the engine reads its ledger instead — an answer or a result built with pools or a charge the inspector set, a restored snapshot, a replaced interpreter, a copied tracker or outcome, an input the inspector built — differ by design: a test that runs one records the differences and asserts each (`test_utils::tolerate_start_ledger_divergences`). - **Synthetic frame results carry the caller's pools.** A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir and byte share (`untouched_call_gas`, `untouched_create_gas`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags and start charge, so revm's own frame return settles it exactly like a result of its own. - **Inspectors in block execution.** From eb298946b90d3bc65579aff1c837555b0a7de087 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 17:34:05 +0800 Subject: [PATCH 46/83] refactor(limit): one park for the start ledger, a lint allow on the two items it concerns, and comments that state their reasons --- crates/mega-evm/src/evm/execution.rs | 18 +++++---- crates/mega-evm/src/evm/host.rs | 12 ++++++ crates/mega-evm/src/limit/ledger.rs | 37 +++++++++++++------ .../mega-evm/src/system/keyless/dispatch.rs | 6 +-- crates/mega-evm/src/test_utils/ledger.rs | 4 ++ crates/mega-evm/tests/satin/common.rs | 3 +- crates/mega-evm/tests/satin/history_bytes.rs | 6 +-- .../tests/satin/inspector_cheatcodes.rs | 2 +- .../mega-evm/tests/satin/inspector_limits.rs | 5 +-- .../tests/satin/inspector_settlement.rs | 4 +- 10 files changed, 62 insertions(+), 35 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index aab2af81c..29de70b34 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -2191,11 +2191,13 @@ mod tests { fn test_the_start_ledger_holds_a_childs_shares_as_cap_the_shares_does() { use crate::{ evm::FRAME_KEPT_PERCENT, - limit::{Counted, Parked, StartLedger, DATA_SIZE_POOL}, + limit::{ + Counted, Parked, StartLedger, DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL, + }, satin_gas_params, }; let pools = [ - PoolAmounts::ZERO.with(PoolId::new(0), 10_000).with(PoolId::new(1), 250), + PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10_000).with(KV_UPDATE_POOL, 250), PoolAmounts::UNLIMITED, PoolAmounts::ZERO, ]; @@ -2208,14 +2210,14 @@ mod tests { let case = format!("{pools:?}, drawn {drawn}, taken {taken}, cap {cap}"); let counted = Counted { added: PoolAmounts::ZERO - .with(PoolId::new(0), drawn) - .with(PoolId::new(1), drawn.min(pools.get(PoolId::new(1)))) - .with(PoolId::new(2), drawn.min(pools.get(PoolId::new(2)))), - taken: PoolAmounts::ZERO.with(PoolId::new(0), taken), + .with(DATA_SIZE_POOL, drawn) + .with(KV_UPDATE_POOL, drawn.min(pools.get(KV_UPDATE_POOL))) + .with(STATE_GROWTH_POOL, drawn.min(pools.get(STATE_GROWTH_POOL))), + taken: PoolAmounts::ZERO.with(DATA_SIZE_POOL, taken), transfer_log: false, }; - if counted.added.get(PoolId::new(0)) > - pools.get(PoolId::new(0)).saturating_add(taken) + if counted.added.get(DATA_SIZE_POOL) > + pools.get(DATA_SIZE_POOL).saturating_add(taken) { continue; } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 92731bb99..632c4e4d4 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -367,6 +367,7 @@ impl revm::context_interface::Host if appended != 0 { let Some(cost) = history_gas(appended) else { return WriteVerdict::OutOfGas }; let cost = if from_allowance { + // The ledger draws its own allowance; the settlement compares what is left. #[cfg(debug_assertions)] let _ = self.additional_limit.ledger_mut().draw_allowance(cost); gas.draw_history_allowance(cost) @@ -488,6 +489,17 @@ impl MegaContext { let value_call = matches!(start.kind, FrameStartKind::Call | FrameStartKind::CallCode) && !start.value.is_zero(); let allowance = if value_call { self.value_call_allowance() } else { 0 }; + self.park_owed(reservoir, charge, allowance); + } + + /// Parks on the start ledger what the start the running frame is making owes: the shares of + /// the frame's pools and the part of `reservoir`, what it holds once the start's charges are + /// made, the frame keeps, by the engine's rule + /// ([`frame_kept_percent`](Self::frame_kept_percent)); the start's `charge`; and the + /// child's `allowance`. The frame-start hook parks an instruction's start, and a + /// `keylessDeploy` call's builder its creation. + #[cfg(debug_assertions)] + pub(crate) fn park_owed(&mut self, reservoir: u64, charge: u64, allowance: u64) { let kept = self.frame_kept_percent(); self.additional_limit.ledger_mut().park(kept, reservoir, charge, allowance); } diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index d6fc8b124..163d5c98c 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -58,15 +58,15 @@ //! replaced, the allowance the frame returns. At the lifecycle's successful end the ledger holds no //! entry. //! -//! A difference is a panic. The inspector shapes whose figures the owner accepted to change when -//! the ledger becomes what the engine reads differ by design: a tracker restored from a snapshot, -//! an interpreter replaced, an answer, an input or a result built with pools, an allowance or a -//! charge an inspector set, a tracker or an outcome copied from another start. A test that runs -//! one has the context record the differences instead, and asserts each -//! (`test_utils::tolerate_start_ledger_divergences`). After a recorded difference in a caller's -//! pools the ledger takes the fork's, so what it records is where the two part, not what follows. - -#![cfg_attr(not(any(test, feature = "test-utils")), allow(unreachable_pub))] +//! A difference is a panic. Some inspector shapes differ by design, because they move a figure +//! the ledger keeps off the tracker, which a tracker copy or a field an inspector writes cannot +//! reach: a tracker restored from a snapshot, an interpreter replaced, an answer, an input or a +//! result built with pools, an allowance or a charge an inspector set, a tracker or an outcome +//! copied from another start. Once the engine reads its ledger, those figures are the ledger's, and +//! such an inspector's values are not taken. A test that runs one has the context record the +//! differences instead, and asserts each (`test_utils::tolerate_start_ledger_divergences`). After a +//! recorded difference in a caller's pools the ledger takes the fork's, so what it records is where +//! the two part, not what follows. #[cfg(not(feature = "std"))] use alloc as std; @@ -80,7 +80,11 @@ use revm::context_interface::{ use super::Counted; /// A figure of a settled start the ledger compares with the fork's. +/// +/// Public to the test tools, which record and assert a difference; a debug build without them +/// reaches it only through the ledger's panic. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(any(test, feature = "test-utils")), allow(unreachable_pub))] pub enum LedgerFigure { /// What the started frame may still draw on a pool, as its result returns it. FrameRemaining(PoolId), @@ -107,7 +111,10 @@ pub enum LedgerFigure { type PoolFigure = fn(PoolId) -> LedgerFigure; /// A figure of a settled start in which the ledger and the fork differ. +/// +/// Public to the test tools, as [`LedgerFigure`] is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(any(test, feature = "test-utils")), allow(unreachable_pub))] pub struct LedgerDivergence { /// The identity revm gave the start. pub start: u32, @@ -151,7 +158,8 @@ const STAND_IN: Parked = Parked::transaction(PoolAmounts::UNLIMITED, 0); /// What a start owes when an inspector consumed an input it built itself, which no start parked /// anything for: nothing, and no pool. -const UNPARKED: Parked = Parked::transaction(PoolAmounts::ZERO, 0); +const UNPARKED: Parked = + Parked { shares: PoolAmounts::ZERO, kept_reservoir: 0, charge: 0, allowance: 0 }; /// A frame's three pools as the engine keeps them: what it may still draw, its signed net draw, /// and whether a draw it could not pay was refused. @@ -291,7 +299,8 @@ impl Entry { } } -/// A start's settlement as revm reports it ([`FrameSettle`]), in the ledger's own terms. +/// A start's settlement as revm reports it: the fields of [`FrameSettle`], which only revm's record +/// can build, so the ledger's unit tests can settle a start without one. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Settlement { id: u32, @@ -895,7 +904,11 @@ mod tests { ledger.adopt_provider_draws([11, 0, 0]); let pools = top(&ledger); assert_eq!( - (pools.remaining.get(DATA_SIZE_POOL), pools.net[0], pools.crossings[0]), + ( + pools.remaining.get(DATA_SIZE_POOL), + pools.net[DATA_SIZE_POOL.index()], + pools.crossings[DATA_SIZE_POOL.index()], + ), (0, 10, true), "share 10, draw 11" ); diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 054a09a43..ff5e16ff2 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -191,11 +191,7 @@ pub(crate) fn start( // The creation's shares of the call's reservoir and pools are taken out of the call, as a // `CREATE` opcode's are: the creation's return adds what it left back to what the call kept. #[cfg(debug_assertions)] - { - let (kept, reservoir) = (ctx.frame_kept_percent(), gas.reservoir()); - let charge = deployment.on_frame_record_charge; - ctx.additional_limit.ledger_mut().park(kept, reservoir, charge, 0); - } + ctx.park_owed(gas.reservoir(), deployment.on_frame_record_charge, 0); let shares = gas.tracker_mut().forward_to_child(ctx.gas_params()); let mut create = CreateInputs::new( deployment.signer, diff --git a/crates/mega-evm/src/test_utils/ledger.rs b/crates/mega-evm/src/test_utils/ledger.rs index b868b1d70..f3bd7301a 100644 --- a/crates/mega-evm/src/test_utils/ledger.rs +++ b/crates/mega-evm/src/test_utils/ledger.rs @@ -7,6 +7,10 @@ //! fork's figures where the ledger, which keeps them off the tracker, does not follow: a test that //! runs one tolerates the differences, then asserts each of them. +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + use crate::{ExternalEnvTypes, MegaContext}; use revm::Database; diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 33d77bdc3..487e7da7f 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -328,7 +328,8 @@ pub(crate) fn frame_shares(caller: PoolAmounts) -> PoolAmounts { /// What a debug build's start ledger records where an inspector answered start `start`, at /// `depth`, on gas that carries the shares its input was forwarded, `shares`, as the engine's /// `untouched_call_gas` and `untouched_create_gas` build it: an answer with pools the inspector -/// set, which the owner accepted as an API removal. The ledger settles an inspector's answer at +/// set, whose pools stop being taken once the engine reads its ledger, the pool fields leaving the +/// frame's input and gas. The ledger settles an inspector's answer at /// unlimited pools, so it parts from the fork on the answer's own pools wherever a share is /// limited, and on its caller's once it settled, wherever the caller, which the fork gives back /// the shares and so leaves with what it held before the start, `caller`, is limited. diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 60f308e86..0598b1c60 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -261,9 +261,9 @@ fn test_a_creation_answered_without_running_appends_no_code() { #[cfg(debug_assertions)] tolerate_start_ledger_divergences(evm.ctx_mut()); let outcome = evm.execute_transaction(tx.clone()).expect("the transaction is valid"); - // The answer carries the creation's shares, pools the inspector set: an API removal of the - // inspector table, where a debug build's start ledger, which settles an inspector's answer - // at unlimited pools, parts from the fork. + // The answer carries the creation's shares, pools the inspector set, which a debug build's + // start ledger does not take: it settles an inspector's answer at unlimited pools, and + // parts from the fork. #[cfg(debug_assertions)] { let caller = first_frame_pools(&EvmTxRuntimeLimits::default(), &tx); diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 1c56861a1..fc70f3a66 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -320,7 +320,7 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { assert!(outcome.result.is_success(), "{:?}", outcome.result); // The paused region's slot is drawn on the frame's pools, and the snapshot `step` puts // back before the next instruction takes the draw back off the frame's gas: a tracker - // restored from a snapshot, a behaviour change of the inspector table. A debug build's + // restored from a snapshot, which cannot restore a figure kept off it. A debug build's // start ledger keeps the pools off the tracker and keeps the record's draw, and parts from // the fork in `TEST`'s nets where the call to `resumeGasMetering`, start 3, settles; the // pools themselves both read unlimited, the cheatcode's answer on `Gas::new` having diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index 4b99acc5e..ac1bc2519 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -401,9 +401,8 @@ fn test_an_answer_settles_on_the_gas_it_is_built_on() { tolerate_start_ledger_divergences(evm.ctx_mut()); let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); // An answer on `Gas::new` carries unlimited pools, as the start ledger settles an - // inspector's answer; one on the call's shares carries pools the inspector set, an API - // removal of the inspector table, and the ledger parts from the fork where `A`'s pool - // is limited. + // inspector's answer; one on the call's shares carries pools the inspector set, which + // the ledger does not take, and it parts from the fork where `A`'s pool is limited. #[cfg(debug_assertions)] { let expected = match gas { diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index 8f34b25b7..753d2f967 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -132,8 +132,8 @@ where } /// [`inspected`] under `inspector`, which answers start `start`, at `depth`, on the gas its input -/// carries, the shares of its caller's pools included: an answer with pools the inspector set, an -/// API removal of the inspector table. A debug build's start ledger, which settles an inspector's +/// carries, the shares of its caller's pools included: an answer with pools the inspector set, +/// which a debug build's start ledger does not take. The ledger, which settles an inspector's /// answer at unlimited pools, records where it parts from the fork, and each part is asserted /// ([`answered_on_its_shares`]): the caller is the transaction's own frame, or the transaction, /// which holds its first frame's pools when the start is made. From 4f431170e304bb7ba249fba6fb5d34df7f62372f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 26 Oct 2026 17:41:35 +0800 Subject: [PATCH 47/83] fix(evm): the start ledger reads a precompile's overdraw back as one The fork adopts a provider's draws before the engine sees the answer, capping a draw past the share at the share and marking the pool's crossing. The ledger read back the capped net alone, so a provider that overdrew would have been adopted as a draw of exactly its share, without the crossing. A pool whose crossing the adoption set is now read as a draw past the share. No provider of the engine draws. --- crates/mega-evm/src/evm/execution.rs | 60 ++++++++++++++++++++++++++-- crates/mega-evm/src/limit/ledger.rs | 10 +++++ 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 29de70b34..1752a5182 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1263,8 +1263,12 @@ fn fork_figures(result: &FrameResult) -> crate::limit::Returning { } /// Has the start ledger adopt what a precompile's provider drew on the pools of `answer`, revm's -/// answer to the start on top: the net draws its gas holds. A start revm refused, or answered -/// without a provider, drew nothing. The engine's provider draws no pool, so the draws are none. +/// answer to the start on top. A start revm refused, or answered without a provider, drew nothing. +/// +/// The fork adopts the provider's draws before the engine sees the answer, so they are read back +/// off the answer's gas: each pool's net, and, for a pool whose crossing the adoption set, a draw +/// past the share, which the adoption capped at it. The engine's provider draws no pool, so the +/// draws are none. #[cfg(debug_assertions)] fn adopt_provider_draws( ctx: &mut MegaContext, @@ -1272,7 +1276,17 @@ fn adopt_provider_draws( ) { let FrameResult::Call(outcome) = answer else { return }; if outcome.was_precompile_called { - let draws = PoolId::ALL.map(|pool| outcome.result.gas.pool_spent(pool)); + let gas = outcome.result.gas.tracker(); + let draws = + PoolId::ALL.map( + |pool| { + if gas.pool_crossing(pool) { + i64::MAX + } else { + gas.pool_spent(pool) + } + }, + ); ctx.additional_limit.ledger_mut().adopt_provider_draws(draws); } } @@ -2252,6 +2266,46 @@ mod tests { } } + /// A precompile's draws reach the start ledger as the provider made them, though the fork + /// adopted them first: a draw within the share as its net, and a draw past it, which the + /// adoption capped at the share and marked with the pool's crossing, as a draw past the + /// share. The ledger then holds the pool as the fork's adoption left it — share 10 and a + /// draw of 11 included. + #[test] + #[cfg(debug_assertions)] + fn test_a_precompiles_draws_reach_the_start_ledger_as_the_provider_made_them() { + use crate::limit::{Parked, DATA_SIZE_POOL}; + use revm::interpreter::CallOutcome; + let shares = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, 10); + for drawn in [0_i64, 4, 10, 11, 25, -3] { + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let ledger = ctx.additional_limit.ledger_mut(); + ledger.park_transaction(Some(Parked::transaction(shares, 0))); + ledger.split(1, None, 0); + ledger.park(0, 0, 0, 0); + ledger.split(2, Some(1), 1); + + let mut gas = Gas::new(100_000); + gas.tracker_mut().set_pool_spent(DATA_SIZE_POOL, drawn); + gas.tracker_mut().adopt_pool_shares(shares); + let mut answer = CallOutcome::new( + InterpreterResult::new(InstructionResult::Return, Bytes::new(), gas), + 0..0, + ); + answer.was_precompile_called = true; + adopt_provider_draws(&mut ctx, &FrameResult::Call(answer)); + let tracker = gas.tracker(); + let fork = PoolId::ALL.map(|pool| { + ( + tracker.pool_remaining(pool), + tracker.pool_spent(pool), + tracker.pool_crossing(pool), + ) + }); + assert_eq!(ctx.additional_limit.ledger_mut().top_pools(), fork, "drawn {drawn}"); + } + } + /// The frame start skips its reads exactly for a call that moves no value and runs no /// precompile: every call scheme, with no value and with value, to an account and to a /// precompile of the set, and a creation, with and without an endowment. diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 163d5c98c..dfedec2a6 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -639,6 +639,16 @@ impl StartLedger { } } + /// Each pool of the start on top: what it may still draw, its net and its crossing. + #[cfg(test)] + pub(crate) fn top_pools(&self) -> [(u64, i64, bool); PoolId::COUNT] { + let pools = self.entries.last().expect("a start is open").pools; + PoolId::ALL.map(|pool| { + let index = pool.index(); + (pools.remaining.get(pool), pools.net[index], pools.crossings[index]) + }) + } + /// The shares the start on top started with and the pools of the start below it. #[cfg(test)] pub(crate) fn top_shares_and_caller_pools(&self) -> (PoolAmounts, PoolAmounts) { From 99a3602df72077df857fe3664403ebce5ed99727 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 09:56:36 +0800 Subject: [PATCH 48/83] fix(limit): a precompile's draw past a share reaches the start ledger as a flag, not as an amount --- crates/mega-evm/src/evm/execution.rs | 23 +++++----- crates/mega-evm/src/limit/ledger.rs | 63 +++++++++++++++++++++------- crates/mega-evm/src/limit/mod.rs | 2 +- 3 files changed, 59 insertions(+), 29 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 1752a5182..9c72bc930 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1266,9 +1266,12 @@ fn fork_figures(result: &FrameResult) -> crate::limit::Returning { /// answer to the start on top. A start revm refused, or answered without a provider, drew nothing. /// /// The fork adopts the provider's draws before the engine sees the answer, so they are read back -/// off the answer's gas: each pool's net, and, for a pool whose crossing the adoption set, a draw -/// past the share, which the adoption capped at it. The engine's provider draws no pool, so the -/// draws are none. +/// off the answer's gas: each pool's net, and, for a pool whose crossing the adoption set, that +/// the provider drew past the share, which the adoption capped its net at. The engine's provider +/// draws no pool, so the draws are none. +/// +/// It runs before the start's records are counted on the answer: the adoption replaces the +/// entry's pools. #[cfg(debug_assertions)] fn adopt_provider_draws( ctx: &mut MegaContext, @@ -1277,16 +1280,10 @@ fn adopt_provider_draws( let FrameResult::Call(outcome) = answer else { return }; if outcome.was_precompile_called { let gas = outcome.result.gas.tracker(); - let draws = - PoolId::ALL.map( - |pool| { - if gas.pool_crossing(pool) { - i64::MAX - } else { - gas.pool_spent(pool) - } - }, - ); + let draws = PoolId::ALL.map(|pool| crate::limit::ProviderDraw { + net: gas.pool_spent(pool), + past_a_share: gas.pool_crossing(pool), + }); ctx.additional_limit.ledger_mut().adopt_provider_draws(draws); } } diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index dfedec2a6..055243597 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -259,6 +259,24 @@ const fn pool_share(remaining: u64, kept: u64) -> u64 { (remaining as u128 * (100 - kept) as u128 / 100) as u64 } +/// What a precompile's provider drew on one pool of its answer: its signed `net` draw, and whether +/// it drew past a share it was held to, which the net alone cannot tell once that share capped it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ProviderDraw { + /// The net draw. + pub(crate) net: i64, + /// Whether the draw went past a share it was held to. + pub(crate) past_a_share: bool, +} + +impl ProviderDraw { + /// A net draw of `net`, within any share it was held to. + #[cfg(test)] + pub(crate) const fn of(net: i64) -> Self { + Self { net, past_a_share: false } + } +} + /// One open start. #[derive(Clone, Copy, Debug)] struct Entry { @@ -492,11 +510,16 @@ impl StartLedger { /// top, fail-closed: a draw within the share is drawn, and one past it empties the pool, caps /// the net at the share and sets the crossing. The answer's status is the provider's either /// way. - pub(crate) fn adopt_provider_draws(&mut self, draws: [i64; PoolId::COUNT]) { + /// + /// The adoption replaces the entry's pools with the share less the provider's draw, so it runs + /// before anything else is drawn on the answer: the start's own records, which the frame start + /// counts on the answer once it was adopted, would otherwise be overwritten. + pub(crate) fn adopt_provider_draws(&mut self, draws: [ProviderDraw; PoolId::COUNT]) { let Some(entry) = self.entries.last_mut() else { return }; for pool in PoolId::ALL { - let (index, share, drawn) = (pool.index(), entry.shares.get(pool), draws[pool.index()]); - if drawn > 0 && drawn as u64 > share { + let (index, share) = (pool.index(), entry.shares.get(pool)); + let ProviderDraw { net: drawn, past_a_share } = draws[index]; + if past_a_share || (drawn > 0 && drawn as u64 > share) { entry.pools.remaining.set(pool, 0); entry.pools.net[index] = signed(share); entry.pools.crossings[index] = true; @@ -892,35 +915,45 @@ mod tests { /// A precompile's draws are adopted fail-closed, as the fork adopts them: within the share they /// are drawn, and past it the pool is emptied, the net capped at the share and the crossing - /// set — share 10, draw 11 — whatever the answer's status. + /// set — share 10, draw 11 — whatever the answer's status. A draw marked past a share is + /// adopted as one past the entry's, whatever its net: an unlimited share included, which no + /// net can pass. #[test] fn test_a_precompiles_draws_past_its_share_are_adopted_fail_closed() { + let none = ProviderDraw::default(); for drawn in [0_i64, 4, 10, 11, -3] { let pools = PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10); let mut ledger = opened(PoolAmounts::UNLIMITED); ledger.park(0, 0, 0, 0); ledger.split(2, Some(1), 1); ledger.entries[1].shares = pools; - ledger.adopt_provider_draws([drawn, 0, 0]); + ledger.adopt_provider_draws([ProviderDraw::of(drawn), none, none]); let mut answer = GasTracker::new(0, 0, 0); answer.set_pool_spent(DATA_SIZE_POOL, drawn); answer.adopt_pool_shares(pools); assert_eq!(top(&ledger), Pools::on(&answer), "drawn {drawn}"); } - let mut ledger = opened(PoolAmounts::UNLIMITED); - ledger.park(0, 0, 0, 0); - ledger.split(2, Some(1), 1); - ledger.entries[1].shares = PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10); - ledger.adopt_provider_draws([11, 0, 0]); - let pools = top(&ledger); - assert_eq!( + let past = |share: u64, net: i64, past_a_share: bool| { + let mut ledger = opened(PoolAmounts::UNLIMITED); + ledger.park(0, 0, 0, 0); + ledger.split(2, Some(1), 1); + ledger.entries[1].shares = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, share); + ledger.adopt_provider_draws([ProviderDraw { net, past_a_share }, none, none]); + let pools = top(&ledger); ( pools.remaining.get(DATA_SIZE_POOL), pools.net[DATA_SIZE_POOL.index()], pools.crossings[DATA_SIZE_POOL.index()], - ), - (0, 10, true), - "share 10, draw 11" + ) + }; + assert_eq!(past(10, 11, false), (0, 10, true), "share 10, draw 11"); + assert_eq!(past(10, 10, true), (0, 10, true), "a draw a share of 10 capped at it"); + let unlimited = u64::MAX; + assert_eq!(past(unlimited, 7, false), (unlimited - 7, 7, false), "an unlimited share"); + assert_eq!( + past(unlimited, i64::MAX, true), + (0, i64::MAX, true), + "an unlimited share, a draw marked past a share" ); } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 3c4b98d4a..95f1dc9cd 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -188,7 +188,7 @@ mod record; #[cfg(all(debug_assertions, any(test, feature = "test-utils")))] pub use ledger::{LedgerDivergence, LedgerFigure}; #[cfg(debug_assertions)] -pub(crate) use ledger::{Parked, Returning, StartLedger}; +pub(crate) use ledger::{Parked, ProviderDraw, Returning, StartLedger}; pub use limit::AdditionalLimit; pub(crate) use limit::{Counted, TxClass}; #[cfg(test)] From 33cc88fc09984031946286d434b692729d18f463 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 09:58:11 +0800 Subject: [PATCH 49/83] test(satin): a creation that takes no address settles as one, cleared by an end callback or answered without one --- crates/mega-evm/tests/satin/start_ledger.rs | 102 +++++++++++++++++++- 1 file changed, 99 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/start_ledger.rs b/crates/mega-evm/tests/satin/start_ledger.rs index 4e5fc4d4a..2d5eefa47 100644 --- a/crates/mega-evm/tests/satin/start_ledger.rs +++ b/crates/mega-evm/tests/satin/start_ledger.rs @@ -16,10 +16,10 @@ use mega_evm::{ test_utils::{ neutral_cfg, neutralize_evm, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, }, - EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, + EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, REVERT}, + bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, REVERT, STOP}, context::{BlockEnv, ContextTr}, context_interface::{ host::{FrameSettle, LifecycleEnd, SettleStatus}, @@ -34,7 +34,7 @@ use revm::{ Database, Inspector, }; -use crate::common::{block, call, context, create}; +use crate::common::{block, call, context, create, history}; const CALLER: Address = address!("0000000000000000000000000000000000d00000"); const OUTER: Address = address!("0000000000000000000000000000000000d00001"); @@ -342,3 +342,99 @@ fn test_end_callback_rewrites_settle_as_the_fork_settles_them() { } } } + +/// `OUTER` creates a contract whose init code stops, deploying no code, and stops. The creation's +/// start makes one write record on the creation, the created account's, which its caller is +/// charged for at the `CREATE` and which the creation's start charge gives back when it fails or +/// takes no address; the creator's nonce record is charged there too and is not given back. +fn creates_an_empty_contract() -> MemoryDatabase { + let outer = BytecodeBuilder::default().create(U256::ZERO, [STOP]).append(POP).stop().build(); + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(OUTER, outer) +} + +/// How [`CreationRewrites`] takes the creation `OUTER` makes its address. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum AddressRewrite { + /// `create_end` clears the address of the creation, which succeeded. + Cleared, + /// `create` answers the creation with a success that took no address, on `Gas::new`. + AnsweredWithout, +} + +/// Takes the creation `OUTER` makes its address as its [`AddressRewrite`] says. +struct CreationRewrites(AddressRewrite); + +impl Inspector, EthInterpreter> for CreationRewrites { + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + (self.0 == AddressRewrite::AnsweredWithout && inputs.caller() == OUTER).then(|| { + let gas = Gas::new(inputs.gas_limit()); + CreateOutcome::new( + InterpreterResult::new(InstructionResult::Stop, Bytes::new(), gas), + None, + ) + }) + } + + fn create_end( + &mut self, + _: &mut MegaContext, + inputs: &CreateInputs, + out: &mut CreateOutcome, + ) { + if self.0 == AddressRewrite::Cleared && inputs.caller() == OUTER { + assert!(out.result.is_ok() && out.address.is_some(), "the creation took its address"); + out.address = None; + } + } +} + +/// A creation that took no address settles as one, whoever took it: an end callback that clears a +/// successful creation's address has its start charge given back, the created account's record, +/// whose history the transaction no longer pays, as revm reports the creation took no address; an +/// inspector's success answered without an address gives nothing back, an inspector's answer +/// carrying no start charge, and the transaction pays what the creation's opcode was charged, as +/// it pays when the creation runs and keeps it. +#[test] +fn test_a_creation_that_takes_no_address_settles_as_one() { + let run = |inspector: Option| { + let tx = call(CALLER, OUTER, U256::ZERO, GAS_LIMIT); + let outcome = match inspector { + Some(inspector) => MegaEvm::new(context(creates_an_empty_contract())) + .with_inspector(inspector) + .execute_transaction(tx), + None => MegaEvm::new(context(creates_an_empty_contract())).execute_transaction(tx), + }; + let outcome = outcome.expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome + }; + let kept = run(None); + for rewrite in [AddressRewrite::Cleared, AddressRewrite::AnsweredWithout] { + let mut evm = MegaEvm::new(context(creates_an_empty_contract())) + .with_inspector(CreationRewrites(rewrite)); + let outcome = evm + .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{rewrite:?}: {:?}", outcome.result); + let (settled, end) = settlements(evm.ctx_mut()); + assert_eq!(end, LifecycleEnd::Settled, "{rewrite:?}"); + let creation = settled[0]; + assert_eq!((creation.id, creation.depth), (2, 1), "{rewrite:?}: the creation's start"); + assert_eq!( + (creation.status, creation.created, creation.inspector_answer), + (SettleStatus::Ok, Some(false), rewrite == AddressRewrite::AnsweredWithout), + "{rewrite:?}: a success that took no address" + ); + let given_back = match rewrite { + AddressRewrite::Cleared => history(WRITE_RECORD_SIZE), + AddressRewrite::AnsweredWithout => 0, + }; + assert_eq!(outcome.gas.history, kept.gas.history - given_back, "{rewrite:?}"); + } +} From 3bb1f7d06a3c048c56e08e6fabe4f90adfb0573b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 09:58:38 +0800 Subject: [PATCH 50/83] docs: the start ledger compares the allowance of a frame revm built that no inspector answered or replaced --- .claude/skills/satin-review/SKILL.md | 1 - AGENTS.md | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index b3edff9b3..d085132d4 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -73,7 +73,6 @@ Each change is stated here in plain words with its reason; the specification has The fork carries four figures of a start on the frame's gas: the three pools with their nets and crossings, the part of the reservoir the caller keeps, the start charge and the history allowance. The engine keeps the same four in an entry per start (`src/limit/ledger.rs`), computed by its own rules and driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and compares them with the fork's at every settlement, panicking on a difference; every result still reads the fork's figures, and a release build carries none of it. A test of an inspector that answers or rewrites with pools or a start charge it set, or restores a snapshot of a running tracker, records the differences and asserts each, since those figures are accepted to change once the engine reads its own ledger. - This was added after #407 merged. Why: the figures are to leave the fork for the engine, and the ledger that will replace them is proved against them, on every engine path, before anything reads it. - **Writes and frame starts are metered in the fork's instruction hooks.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. diff --git a/AGENTS.md b/AGENTS.md index 4047c5508..1994e9e1d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -491,7 +491,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer A later mechanism that caps a frame's gas uses the same part; it limits the frame at its start and again after every credit — a child's return, `SSTORE`'s refill — and never releases a creating frame's withheld part before `return_create`, whose charges are the frame's own regular charges. - **A debug build checks every start's figures against a ledger of the engine's own.** The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding the four figures the fork carries on the frame's gas — its pools, the reservoir its caller keeps, its start charge and its history allowance — computed by the engine's own rules: what a start owes is parked where it is decided (`frame_starting`, the keyless builder, the first frame's input) and taken by the split, every draw `AdditionalLimit` applies is mirrored on the top entry, the frame cap is applied as `cap_the_shares` applies it, and a settlement merges by status and the inspector flags. - At every settlement it compares the frame's pools as its result returns them, its caller's once settled, the kept reservoir with `held_reservoir`, the start-charge refund and the allowance with the fork's figures, and panics on a difference; the lifecycle's successful end finds it empty. + At every settlement it compares the frame's pools as its result returns them, its caller's once settled, the kept reservoir with `held_reservoir` and the start-charge refund with the fork's figures, and the allowance the frame returns for a frame revm built whose result no inspector answered or replaced the tracker of (an answer's allowance is never drawn), and panics on a difference; the lifecycle's successful end finds it empty. The engine still reads the fork's figures for every result. The inspector shapes accepted to change when the engine reads its ledger instead — an answer or a result built with pools or a charge the inspector set, a restored snapshot, a replaced interpreter, a copied tracker or outcome, an input the inspector built — differ by design: a test that runs one records the differences and asserts each (`test_utils::tolerate_start_ledger_divergences`). - **Synthetic frame results carry the caller's pools.** From 34a778c1e43d2a7cbd85ece84eff0bcbe32fb4fc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 10:16:26 +0800 Subject: [PATCH 51/83] feat(evm): a frame start's budgets, start charge, allowance and reservoir share are decided on the engine's start ledger --- crates/mega-evm/src/evm/context.rs | 22 +- crates/mega-evm/src/evm/execution.rs | 292 +++--- crates/mega-evm/src/evm/frame.rs | 44 +- crates/mega-evm/src/evm/host.rs | 107 ++- crates/mega-evm/src/evm/schedule.rs | 122 +-- crates/mega-evm/src/limit/ledger.rs | 908 +++++++----------- crates/mega-evm/src/limit/limit.rs | 199 ++-- crates/mega-evm/src/limit/mod.rs | 8 +- .../mega-evm/src/system/keyless/dispatch.rs | 19 +- crates/mega-evm/src/system/keyless/settle.rs | 2 +- crates/mega-evm/src/test_utils/ledger.rs | 35 +- crates/mega-evm/src/test_utils/mod.rs | 2 - crates/mega-evm/tests/satin/common.rs | 77 +- crates/mega-evm/tests/satin/history_bytes.rs | 25 +- .../tests/satin/inspector_cheatcodes.rs | 43 +- .../mega-evm/tests/satin/inspector_limits.rs | 34 +- .../tests/satin/inspector_settlement.rs | 44 +- crates/mega-evm/tests/satin/pricing-table.md | 12 +- crates/mega-evm/tests/satin/pricing_table.rs | 31 +- ...erential__keyless_differential_record.snap | 276 +++--- 20 files changed, 963 insertions(+), 1339 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 6b23c1246..9fde449d5 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -499,10 +499,9 @@ impl MegaContext { /// The part of its pools and of its EIP-8037 reservoir, in per cent, a caller keeps when it /// starts a frame, by the engine's own rule: [`FRAME_KEPT_PERCENT`] on the spec's /// configuration, and nothing on the neutral one, which forwards the whole of each as Ethereum - /// does. A debug build's start ledger computes a start's shares by it. + /// does, whatever schedule it was given. A start's shares are computed by it. /// /// [`FRAME_KEPT_PERCENT`]: crate::evm::schedule::FRAME_KEPT_PERCENT - #[cfg(debug_assertions)] pub(crate) const fn frame_kept_percent(&self) -> u64 { if self.runs_neutral() { 0 @@ -513,9 +512,8 @@ impl MegaContext { /// The history allowance a value-transferring `CALL` or `CALLCODE` gives the frame it starts, /// by the engine's own rule: [`history_allowance_gas`](crate::history_allowance_gas) on the - /// spec's configuration, and none on the neutral one, which prices no history. A debug build's - /// start ledger keeps it. - #[cfg(debug_assertions)] + /// spec's configuration, and none on the neutral one, which prices no history. The start + /// ledger keeps it, and a log the frame emits draws it first. pub(crate) fn value_call_allowance(&self) -> u64 { if self.runs_neutral() { 0 @@ -729,11 +727,13 @@ impl ContextTr for MegaContext ContextTr for MegaContext, - gas: &mut GasTracker, + _gas: &mut GasTracker, ) -> Result<(), Bytes> { // Destroyed in this transaction: the flag revm keeps for the whole journal may stand from // an earlier transaction on it. @@ -756,7 +756,7 @@ impl ContextTr for MegaContext repriced(), }; - let charge = StartCharge::new(history, PoolAmounts::ZERO); - #[cfg(debug_assertions)] let owed = crate::limit::Parked::transaction( evm.ctx_ref().additional_limit.first_frame_pools(), history, ); - gas.set_pools_remaining(evm.ctx_ref().additional_limit.first_frame_pools()); - let Some(mut frame) = self.op.first_frame_input(evm, gas)? else { + let Some(frame) = self.op.first_frame_input(evm, gas)? else { // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge // for the account the frame adds, a call's recipient or a creation's account, or the // access to the code a delegated recipient runs, warm or cold. A price of that account @@ -363,17 +361,10 @@ where // rebuilding the transaction's gas from its intrinsic cost, the history charged for // the first frame's write record included, which no frame carries back. evm.ctx_mut().additional_limit.take_back_authorities(); - #[cfg(debug_assertions)] evm.ctx_mut().additional_limit.ledger_mut().park_transaction(None); return Ok(None); }; - #[cfg(debug_assertions)] evm.ctx_mut().additional_limit.ledger_mut().park_transaction(Some(owed)); - match &mut frame.frame_input { - FrameInput::Call(inputs) => inputs.charged_start = charge, - FrameInput::Create(inputs) => inputs.set_charged_start(charge), - FrameInput::Empty => {} - } evm.ctx_mut().mark_beneficiary_delegate(); Ok(Some(frame)) } @@ -382,12 +373,12 @@ where /// revm's settlement, so revm's never runs here): a transaction whose own frame a limit stopped /// settles like an EIP-8037 revert, its unspent regular gas and reservoir back to the sender. /// - /// The write record the transaction's own frame makes was charged before execution and rides - /// on the frame's input as its start charge, which the settlement gives back when the frame - /// did not succeed, the way EIP-8037 gives back the state gas of the account that frame would - /// have created. A frame answered without returning through - /// [`frame_return_result`](EvmTr::frame_return_result) — revm's answer to the first frame, an - /// interceptor's, an inspector's — closes its start and gives up its stop here. + /// The write record the transaction's own frame makes was charged before execution and is the + /// transaction's start charge on the start ledger, which revm's settlement of the start gives + /// back when the frame did not succeed (`Host::frame_settle`), the way EIP-8037 gives back the + /// state gas of the account that frame would have created. A frame answered without returning + /// through [`frame_return_result`](EvmTr::frame_return_result) — revm's answer to the first + /// frame, an interceptor's, an inspector's — closes its start and gives up its stop here. /// /// Keeps the history gas the transaction spent, which its gas holds once the frame settled into /// it: what the body was charged, and what the frames charged net of what they gave back; and @@ -401,8 +392,6 @@ where let layer = &mut evm.ctx_mut().additional_limit; layer.close_start(0, frame_result.instruction_result().is_ok()); layer.take_frame_stop(frame_result, true); - #[cfg(debug_assertions)] - layer.ledger_mut().returning(fork_figures(frame_result)); self.op.last_frame_result(evm, frame_result, parent_gas)?; let priced = evm.ctx_ref().prices_history(); let history = 0_u64.saturating_add_signed(frame_result.gas().history_gas_spent()); @@ -613,7 +602,7 @@ impl EvmTr for MegaEvm Result, ContextDbError> { // The frame on top of the stack, if any, is the caller, which suspends on this start. if self.inner.frame_stack.index().is_some() { - suspend(&mut self.inner.ctx, self.inner.frame_stack.get(), &mut frame_init); + suspend(&mut self.inner.ctx, self.inner.frame_stack.get(), &frame_init); } if let Some(result) = call_too_deep(&frame_init) { return Ok(ItemOrResult::Result(result)); @@ -660,11 +649,9 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm { let bumped = creator.filter(|creator| ctx.accounts().bumped(creator)); - let gas = caller.interpreter.gas.tracker_mut(); - (bumped.and_then(|creator| hold_creator(ctx, gas, &creator)), None) + (bumped.and_then(|creator| hold_creator(ctx, &creator)), None) } }; let stop = stop.or_else(|| ctx.additional_limit.hold_caller()); @@ -862,8 +845,9 @@ where /// Settles `caller`, the frame on top of the stack, which suspends to start `child`: gas detention /// keeps its compute for the child's start to add to the transaction's, with the stipend revm /// gives a value call's child, which the caller did not forward -/// ([`on_frame_suspend`](Detention::on_frame_suspend)), and the share of its pool the child starts -/// with is held to the frame cap ([`cap_the_shares`]). +/// ([`on_frame_suspend`](Detention::on_frame_suspend)), and the share of each of its pools the +/// child starts with is held to the frame cap and, for a caller whose net is negative, to the share +/// of the caller's budget, on the start ledger (`StartLedger::cap_child`). /// /// It runs where the start reaches [`EvmTr::frame_init`]: under an inspector, after the /// inspector's `frame_start` saw the start. A start the inspector answers itself settles nothing: @@ -871,18 +855,14 @@ where #[inline] fn suspend( ctx: &mut MegaContext, - caller: &mut EthFrame, - child: &mut FrameInit, + caller: &EthFrame, + child: &FrameInit, ) { let stipend = value_call_stipend(&child.frame_input, ctx.gas_params().call_stipend()); ctx.detention.on_frame_suspend(&caller.interpreter.gas, caller.depth, stipend); let caps = ctx.additional_limit.frame_caps(); - cap_the_shares(ctx.gas_params(), caps, &mut caller.interpreter.gas, child); - #[cfg(debug_assertions)] - { - let kept = ctx.frame_kept_percent(); - ctx.additional_limit.ledger_mut().cap_child(caps, kept); - } + let kept = ctx.frame_kept_percent(); + ctx.additional_limit.ledger_mut().cap_child(caps, kept); } /// The action of `frame` that stops it at the limit `verdict` names before it runs another @@ -946,9 +926,9 @@ fn end_frame( } } -/// Counts on a creator whose pools `gas` holds, once a creation it started returned into it, what -/// the nonce bump revm made for the creation made of it ([`Accounts::creator_counted`]) — `before` -/// is the creator as it stood before revm decided the creation — and answers the stop the creator +/// Counts on a creator, the running frame, once a creation it started returned into it, what the +/// nonce bump revm made for the creation made of it ([`Accounts::creator_counted`]) — `before` is +/// the creator as it stood before revm decided the creation — and answers the stop the creator /// returns before it runs on, if the count crossed a limit: the record is held to the creator's /// budget, then to the transaction's limit, as any count the creator makes /// ([`draw`](crate::AdditionalLimit)). The creation's budget was taken before the record, at its @@ -958,58 +938,13 @@ fn end_frame( /// [`Accounts::creator_counted`]: crate::limit::Accounts pub(crate) fn hold_creator( ctx: &mut MegaContext, - gas: &mut GasTracker, before: &CreatorBefore, ) -> Option { let counted = ctx.accounts().creator_counted(before); - let check = ctx.additional_limit.draw(gas, &counted); + let check = ctx.additional_limit.draw(&counted); check.exceeded_limit().then_some(check) } -/// Holds the share of each of its caller's pools the frame `child` starts with to the share of what -/// the caller has left, its remaining clamped to its budget, and to that pool's frame cap in -/// `caps`, and gives what it forwarded above that back to the caller, whose pools `caller` holds. -/// -/// A frame's remaining is `min(budget, max(0, budget − net))`: a frame whose net is negative — it -/// took back a record or removed state a frame above it made — holds more in its pool than the -/// budget it was given, and the share it forwards is of that budget, not of the pool, so a negative -/// net never enlarges a child's budget. The fork forwarded the schedule's share of the pool the -/// opcode found ([`GasParams::pool_forward_share`]); the caller had that pool and the share -/// together, and its budget is that less its net draw. -#[inline] -fn cap_the_shares(params: &GasParams, caps: PoolAmounts, caller: &mut Gas, child: &mut FrameInit) { - let mut shares = match &child.frame_input { - FrameInput::Call(inputs) => inputs.pool_shares, - FrameInput::Create(inputs) => inputs.pool_shares(), - FrameInput::Empty => return, - }; - let mut capped = false; - for pool in PoolId::ALL { - let share = shares.get(pool); - let mut allowed = caps.get(pool); - let spent = caller.pool_spent(pool); - if spent < 0 { - let had = caller.pool_remaining(pool).saturating_add(share); - let budget = had.saturating_add_signed(spent); - allowed = allowed.min(params.pool_forward_share(pool, budget)); - } - let Some(excess) = share.checked_sub(allowed).filter(|excess| *excess != 0) else { - continue; - }; - caller.set_pool_remaining(pool, caller.pool_remaining(pool).saturating_add(excess)); - shares.set(pool, allowed); - capped = true; - } - if !capped { - return; - } - match &mut child.frame_input { - FrameInput::Call(inputs) => inputs.pool_shares = shares, - FrameInput::Create(inputs) => inputs.set_pool_shares(shares), - FrameInput::Empty => {} - } -} - /// Holds a frame answered without running to the compute limit: the answer to a frame of /// `gas_limit` at `depth`, which its caller forwarded. /// @@ -1253,15 +1188,6 @@ fn take_back_a_stopped_answer( } } -/// The fork's figures of `result`, about to settle into its caller, for the start ledger: the -/// history of the start charge it gives back, and what the result holds of its frame's history -/// allowance. -#[cfg(debug_assertions)] -fn fork_figures(result: &FrameResult) -> crate::limit::Returning { - let refund = result.refundable_start_charge().map_or(0, |charge| charge.history); - crate::limit::Returning::of(result.gas().tracker(), refund) -} - /// Has the start ledger adopt what a precompile's provider drew on the pools of `answer`, revm's /// answer to the start on top. A start revm refused, or answered without a provider, drew nothing. /// @@ -1272,7 +1198,7 @@ fn fork_figures(result: &FrameResult) -> crate::limit::Returning { /// /// It runs before the start's records are counted on the answer: the adoption replaces the /// entry's pools. -#[cfg(debug_assertions)] +#[inline] fn adopt_provider_draws( ctx: &mut MegaContext, answer: &FrameResult, @@ -1333,14 +1259,13 @@ struct FrameStart { /// skipped, which [`count`](Self::count) makes after all and asserts find nothing. #[cfg(debug_assertions)] skipped: Option, - /// The history gas the start's caller paid at its opcode for the records on the frame. + /// The history gas the start's caller paid at its opcode for the records on the frame: the + /// start's charge on the start ledger. charged: u64, /// The gas limit the frame's caller forwarded, before gas detention held a precompile to less. gas_limit: u64, /// The reservoir the frame inherits. reservoir: u64, - /// The shares of its caller's pools the frame starts with: its budgets. - shares: PoolAmounts, /// For a creation a frame makes, its creator as it stands before revm decides the start, which /// tells once the creation returned what revm's nonce bump made of it. The transaction's own /// creation has none: its sender's account is the transaction body's. @@ -1355,6 +1280,9 @@ impl FrameStart { /// is the creator's, counted from the bump once the creation returned. The accounts are not /// read for a start that `writes_nothing` on them ([`start_writes_nothing`]). /// + /// revm opened the start before it handed `frame_init` here, so the start ledger's top entry + /// is the start's, which holds what its caller paid at its opcode. + /// /// [`Accounts::start_before`]: crate::limit::Accounts fn of( ctx: &mut MegaContext, @@ -1362,14 +1290,10 @@ impl FrameStart { writes_nothing: bool, ) -> Result> { let mut creator = None; - let (account, other, charged, reservoir, shares) = match &frame_init.frame_input { - FrameInput::Call(inputs) => ( - inputs.caller, - Some(inputs.target_address), - inputs.charged_start.history, - inputs.reservoir, - inputs.pool_shares, - ), + let (account, other, reservoir) = match &frame_init.frame_input { + FrameInput::Call(inputs) => { + (inputs.caller, Some(inputs.target_address), inputs.reservoir) + } FrameInput::Create(inputs) => { // A creation's creator and address are loaded before revm decides the start, as // revm loads them itself, outside the creation's checkpoint, once it decides it: @@ -1388,13 +1312,7 @@ impl FrameStart { if frame_init.depth > 0 { creator = Some(ctx.accounts().creator_before(inputs.caller())); } - ( - created, - None, - inputs.charged_start().history, - inputs.reservoir(), - inputs.pool_shares(), - ) + (created, None, inputs.reservoir()) } FrameInput::Empty => unreachable!( "a frame input always names a call or a creation, as revm's frame init asserts" @@ -1411,26 +1329,24 @@ impl FrameStart { #[cfg(debug_assertions)] skipped: writes_nothing.then(read), mark, - charged, + charged: ctx.additional_limit.ledger().charge(), gas_limit: input_gas_limit(&frame_init.frame_input), reservoir, - shares, creator, }) } - /// Holds the start, which revm just decided, to the limits on the pools of its frame, which - /// `gas` holds, and counts there what it made, read off the journal — its records and their - /// bytes, its state growth and its transfer log ([`Accounts::start_made`]) — with what its - /// caller gets back once the frame returned with its start kept: what it paid for the records - /// on the frame, less the price of those the start made, and the price of those it took back - /// ([`AdditionalLimit::count_start`](crate::AdditionalLimit)). + /// Holds the start, which revm just decided, to the limits on the budgets of its frame, the + /// start ledger's top entry, and counts there what it made, read off the journal — its records + /// and their bytes, its state growth and its transfer log ([`Accounts::start_made`]) — with + /// what its caller gets back once the frame returned with its start kept: what it paid for + /// the records on the frame, less the price of those the start made, and the price of those + /// it took back ([`AdditionalLimit::count_start`](crate::AdditionalLimit)). /// /// [`Accounts::start_made`]: crate::limit::Accounts fn count( &self, ctx: &mut MegaContext, - gas: &mut GasTracker, ) -> LimitCheck { let (records, counted) = match &self.before { Some(before) => ctx.accounts().start_made(before), @@ -1452,7 +1368,7 @@ impl FrameStart { } else { 0 }; - ctx.additional_limit.count_start(gas, &counted, credit) + ctx.additional_limit.count_start(&counted, credit) } } @@ -1469,24 +1385,22 @@ fn stop_the_answer_at( if verdict.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&verdict); stop_the_answer(answer, start, output); - #[cfg(debug_assertions)] ctx.additional_limit.ledger_mut().rebuild_on_shares(); } } /// Rewrites `answer`, to the call `start` began, into the stop `output`: a revert on the gas the -/// call's caller forwarded, untouched, with the reservoir and the pools the call inherited, and no -/// precompile output, as [`synthetic_frame_result`] answers a frame that never started. +/// call's caller forwarded, untouched, with the reservoir the call inherited, and no precompile +/// output, as [`synthetic_frame_result`] answers a frame that never started. Its budgets go back +/// to the shares the call started with on the start ledger +/// (`StartLedger::rebuild_on_shares`). #[cold] #[inline(never)] fn stop_the_answer(answer: &mut FrameResult, start: &FrameStart, output: Bytes) { let FrameResult::Call(outcome) = answer else { unreachable!("only a call is held to the limits once revm answered it") }; - let mut gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); - gas.tracker_mut().set_pools_remaining(start.shares); - let allowance = outcome.result.gas.history_allowance(); - gas.set_history_allowance(allowance); + let gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); outcome.result = InterpreterResult::new(InstructionResult::Revert, output, gas); outcome.was_precompile_called = false; outcome.precompile_call_logs.clear(); @@ -1762,7 +1676,7 @@ mod tests { context_interface::journaled_state::account::JournaledAccountTr, interpreter::{ gas::WithheldCrossing, CallInput, CallInputs, CallValue, CreateInputs, CreateScheme, - SharedMemory, + PoolAmounts, SharedMemory, }, }; use std::boxed::Box; @@ -2192,14 +2106,46 @@ mod tests { } } - /// The start ledger holds a child's shares as the engine's `cap_the_shares` holds them, on the - /// fork's forward: to the frame cap, and, for a caller whose net is negative, to the share of - /// the caller's budget, the excess given back to the caller. Each case runs both on the same - /// caller: pools limited, unlimited or empty; a net of nothing, positive or negative; and a - /// data-size cap above, at or below the share, or none. + /// The engine's earlier holding of a child's shares, which ran on the fork's figures: the + /// shares revm forwarded on the input, `child`'s, held to `caps` and, for a caller whose net + /// is negative, to the share of the caller's budget by `params`, the excess given back to the + /// caller's pools, which `caller` holds. The start ledger's [`StartLedger::cap_child`] took its + /// place and is held to it. + /// + /// [`StartLedger::cap_child`]: crate::limit::StartLedger + fn cap_the_shares( + params: &revm::context_interface::cfg::GasParams, + caps: PoolAmounts, + caller: &mut Gas, + child: &mut FrameInit, + ) { + let FrameInput::Call(inputs) = &mut child.frame_input else { unreachable!() }; + for pool in PoolId::ALL { + let share = inputs.pool_shares.get(pool); + let mut allowed = caps.get(pool); + let spent = caller.pool_spent(pool); + if spent < 0 { + let had = caller.pool_remaining(pool).saturating_add(share); + let budget = had.saturating_add_signed(spent); + allowed = allowed.min(params.pool_forward_share(pool, budget)); + } + let Some(excess) = share.checked_sub(allowed).filter(|excess| *excess != 0) else { + continue; + }; + caller.set_pool_remaining(pool, caller.pool_remaining(pool).saturating_add(excess)); + inputs.pool_shares.set(pool, allowed); + } + } + + /// The start ledger holds a child's shares as the engine held them on the fork's figures + /// before the ledger decided them ([`cap_the_shares`], on a schedule that keeps 2 per cent of + /// each pool from a child, as the Satin schedule did): to the frame cap, and, for a caller + /// whose net is negative, to the share of the caller's budget, the excess given back to the + /// caller. Each case runs both on the same caller: pools limited, unlimited or empty; a net + /// of nothing, positive or negative; and a data-size cap above, at or below the share, or + /// none. #[test] - #[cfg(debug_assertions)] - fn test_the_start_ledger_holds_a_childs_shares_as_cap_the_shares_does() { + fn test_the_start_ledger_holds_a_childs_shares_as_the_engine_held_them_on_the_forks() { use crate::{ evm::FRAME_KEPT_PERCENT, limit::{ @@ -2207,6 +2153,11 @@ mod tests { }, satin_gas_params, }; + let mut params = satin_gas_params(); + params.override_gas( + [DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL] + .map(|pool| (GasId::pool_kept_percent(pool), FRAME_KEPT_PERCENT)), + ); let pools = [ PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10_000).with(KV_UPDATE_POOL, 250), PoolAmounts::UNLIMITED, @@ -2243,15 +2194,15 @@ mod tests { ledger.split(1, None, 0); ledger.draw(&counted); - let shares = caller.tracker_mut().forward_to_child(&satin_gas_params()).pools; - ledger.park(FRAME_KEPT_PERCENT, 0, 0, 0); + let shares = caller.tracker_mut().forward_to_child(¶ms).pools; + ledger.park(FRAME_KEPT_PERCENT, 0, 0); ledger.split(2, Some(1), 1); let mut child = static_call(TARGET, &[], 100_000); child.depth = 1; let FrameInput::Call(inputs) = &mut child.frame_input else { unreachable!() }; inputs.pool_shares = shares; let caps = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, cap); - cap_the_shares(&satin_gas_params(), caps, &mut caller, &mut child); + cap_the_shares(¶ms, caps, &mut caller, &mut child); ledger.cap_child(caps, FRAME_KEPT_PERCENT); let FrameInput::Call(inputs) = &child.frame_input else { unreachable!() }; @@ -2263,43 +2214,46 @@ mod tests { } } - /// A precompile's draws reach the start ledger as the provider made them, though the fork - /// adopted them first: a draw within the share as its net, and a draw past it, which the - /// adoption capped at the share and marked with the pool's crossing, as a draw past the - /// share. The ledger then holds the pool as the fork's adoption left it — share 10 and a - /// draw of 11 included. + /// A precompile's draws reach the start ledger as the provider made them on its answer's gas: + /// a draw within the ledger's share as its net, and a draw past it, capped at the share. revm + /// adopts the draws on the answer's gas first, at the shares the input carries, which revm + /// forwards whole; when a share the input carries capped them — an inspector set the caller's + /// pools — the pool's crossing says the provider drew past a share, which the ledger adopts as + /// a draw past its own. Share 10 and a draw of 11 included. #[test] - #[cfg(debug_assertions)] fn test_a_precompiles_draws_reach_the_start_ledger_as_the_provider_made_them() { use crate::limit::{Parked, DATA_SIZE_POOL}; use revm::interpreter::CallOutcome; let shares = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, 10); - for drawn in [0_i64, 4, 10, 11, 25, -3] { + for (input_shares, drawn, expected) in [ + (PoolAmounts::UNLIMITED, 0_i64, (10, 0)), + (PoolAmounts::UNLIMITED, 4, (6, 4)), + (PoolAmounts::UNLIMITED, 10, (0, 10)), + (PoolAmounts::UNLIMITED, 11, (0, 10)), + (PoolAmounts::UNLIMITED, 25, (0, 10)), + (PoolAmounts::UNLIMITED, -3, (13, -3)), + (shares, 11, (0, 10)), + (PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, 3), 4, (0, 10)), + ] { + let case = format!("{input_shares:?}, drawn {drawn}"); let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); let ledger = ctx.additional_limit.ledger_mut(); ledger.park_transaction(Some(Parked::transaction(shares, 0))); ledger.split(1, None, 0); - ledger.park(0, 0, 0, 0); + ledger.park(0, 0, 0); ledger.split(2, Some(1), 1); let mut gas = Gas::new(100_000); gas.tracker_mut().set_pool_spent(DATA_SIZE_POOL, drawn); - gas.tracker_mut().adopt_pool_shares(shares); + gas.tracker_mut().adopt_pool_shares(input_shares); let mut answer = CallOutcome::new( InterpreterResult::new(InstructionResult::Return, Bytes::new(), gas), 0..0, ); answer.was_precompile_called = true; adopt_provider_draws(&mut ctx, &FrameResult::Call(answer)); - let tracker = gas.tracker(); - let fork = PoolId::ALL.map(|pool| { - ( - tracker.pool_remaining(pool), - tracker.pool_spent(pool), - tracker.pool_crossing(pool), - ) - }); - assert_eq!(ctx.additional_limit.ledger_mut().top_pools(), fork, "drawn {drawn}"); + let pools = ctx.additional_limit.ledger().top_pools(); + assert_eq!(pools[DATA_SIZE_POOL.index()], expected, "{case}"); } } diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 16db4e6f3..24dbb9d06 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -7,18 +7,19 @@ //! //! 1. an upfront state-gas charge the calling opcode made for the frame (a new account, a creation) //! is priced for refund when the frame failed; -//! 2. the frame's gas merges into the caller's: unused regular gas back on success and revert, the -//! frame's reservoir added to what the caller kept, and the frame's pools absorbed into the -//! caller's; -//! 3. the refund is refilled into the caller's reservoir, and the start charge the frame carries — -//! what its caller paid for the records its start makes — is given back when it failed. +//! 2. the frame's gas merges into the caller's: unused regular gas back on success and revert, and +//! the frame's reservoir added to what the caller kept; +//! 3. the refund is refilled into the caller's reservoir; +//! 4. revm settles the frame's start, and the engine's start ledger merges the frame's budgets into +//! its caller's and gives back the start charge — what its caller paid for the records its start +//! makes — when it failed, by the result's status, as for a frame revm ran. //! //! The contract for a synthetic result is that it settles exactly like revm's own: its gas carries -//! the reservoir and the shares of the pools the frame inherited ([`untouched_call_gas`], -//! [`untouched_create_gas`]), never `Gas::new(limit)`, which would carry no reservoir and -//! unlimited pools, billing the sender for the whole reservoir and lifting the caller's budgets; -//! and it carries the calling opcode's upfront-charge flags and start charge, so step 1 and step 3 -//! refund them. [`synthetic_frame_result`] builds one. +//! the reservoir the frame inherited ([`untouched_call_gas`], [`untouched_create_gas`]), never +//! `Gas::new(limit)`, which would carry no reservoir, billing the sender for the whole reservoir; +//! and it carries the calling opcode's upfront-charge flags, so step 1 refunds them. The budgets +//! and the start charge are the start ledger's, which the engine's own answers settle on by +//! status, so nothing of them is carried. [`synthetic_frame_result`] builds one. use alloy_primitives::Bytes; use revm::{ @@ -30,29 +31,22 @@ use revm::{ }; /// The gas of a call result built without running the callee: the call's whole gas limit -/// unspent, the reservoir the call inherited, and the shares of its caller's pools it was given, -/// undrawn. +/// unspent, and the reservoir the call inherited. #[inline] pub const fn untouched_call_gas(inputs: &CallInputs) -> Gas { - let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); - gas.tracker_mut().set_pools_remaining(inputs.pool_shares); - gas + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir) } /// The gas of a creation result built without running the init code: its whole gas limit -/// unspent, the reservoir the creation inherited, and the shares of its creator's pools it was -/// given, undrawn. +/// unspent, and the reservoir the creation inherited. #[inline] pub const fn untouched_create_gas(inputs: &CreateInputs) -> Gas { - let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()); - gas.tracker_mut().set_pools_remaining(inputs.pool_shares()); - gas + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()) } /// A result for the frame `input` would start, built without running it: `result` with -/// `output`, the frame's gas untouched, the inherited reservoir and pool shares carried, and the -/// calling opcode's upfront state-gas flags and start charge, as revm builds the results of the -/// frames it answers itself. +/// `output`, the frame's gas untouched, the inherited reservoir carried, and the calling opcode's +/// upfront state-gas flags, as revm builds the results of the frames it answers itself. pub fn synthetic_frame_result( input: &FrameInput, result: InstructionResult, @@ -65,7 +59,7 @@ pub fn synthetic_frame_result( address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), - charged_start: inputs.charged_start(), + charged_start: Default::default(), start_mark: OutcomeMark::NONE, }), FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), @@ -87,7 +81,7 @@ pub fn synthetic_call_result( precompile_call_logs: Default::default(), charged_new_account_state_gas: inputs.charged_new_account_state_gas, charged_state_gas_address: inputs.target_address, - charged_start: inputs.charged_start, + charged_start: Default::default(), start_mark: OutcomeMark::NONE, }) } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 632c4e4d4..5ecb256f0 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -70,10 +70,11 @@ //! # The start lifecycle //! //! The three lifecycle hooks — a start revm opened, one it settled, the lifecycle's end — reach the -//! inner context in a debug build, whose mirror checks their order over every engine path, and -//! drive the engine's start ledger, which keeps what each start owes and holds beside the fork's -//! figures and compares the two at every settlement (the `limit` module's `ledger`). A release -//! build takes the trait's defaults, which do nothing. +//! inner context, whose mirror checks their order over every engine path in a debug build and does +//! nothing in a release build, and drive the engine's start ledger, which keeps what each start +//! owes and holds — its frame budgets, its start charge, its history allowance — and gives the +//! start charge back when a start's settlement does not keep its records (the `limit` module's +//! `ledger`). //! //! Every other Host method delegates to op-revm's context. @@ -85,21 +86,18 @@ use delegate::delegate; use revm::{ context::ContextTr, context_interface::{ - cfg::{ - gas::{GasTracker, PoolAmounts, StartCharge}, - GasId, GasParams, StateGasCharge, StateGasSite, - }, + cfg::{gas::GasTracker, GasId, GasParams, StateGasCharge, StateGasSite}, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, - host::{CompletedWrite, FrameStart, LoadError, WriteVerdict}, + host::{ + CompletedWrite, FrameSettle, FrameSplit, FrameStart, FrameStartKind, LifecycleEnd, + LoadError, WriteVerdict, + }, journaled_state::AccountInfoLoad, }, primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, Database, }; -#[cfg(debug_assertions)] -use revm::context_interface::host::{FrameSettle, FrameSplit, FrameStartKind, LifecycleEnd}; - use crate::{ charge_write_records_history, history_gas, limit::{DestroyedParts, HistoryBytes}, @@ -342,7 +340,7 @@ impl revm::context_interface::Host CompletedWrite::SelfDestruct { .. } => (false, false), }; let (counted, history, destroyed) = self.accounts().write_counted(&write); - let check = self.additional_limit.draw(gas, &counted); + let check = self.additional_limit.draw(&counted); if check.exceeded_limit() { return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); } @@ -367,10 +365,7 @@ impl revm::context_interface::Host if appended != 0 { let Some(cost) = history_gas(appended) else { return WriteVerdict::OutOfGas }; let cost = if from_allowance { - // The ledger draws its own allowance; the settlement compares what is left. - #[cfg(debug_assertions)] - let _ = self.additional_limit.ledger_mut().draw_allowance(cost); - gas.draw_history_allowance(cost) + self.additional_limit.ledger_mut().draw_allowance(cost) } else { cost }; @@ -398,11 +393,15 @@ impl revm::context_interface::Host /// /// The charge comes out of what the caller kept rather than out of what the callee gets, so /// the frame's allowance is free for what the recipient does. What the frame's own records - /// cost is declared on the start ([`FrameStart::charge`]), which the fork carries on the - /// frame's input and gives back to the caller when the frame fails; the creator's record - /// outlives the creation and is not declared. The frame's input copies the caller's - /// reservoir after the charge, so the frame, or the answer revm gives in its place, - /// inherits the reservoir the charge left. An opcode that starts no frame — a creation the + /// cost is the start's charge, parked on the start ledger with the frame's shares of the + /// caller's pools and, for a value-transferring `CALL` or `CALLCODE`, its history allowance + /// ([`forward_start`](MegaContext::forward_start)): the ledger gives the charge back to the + /// caller when the frame fails; the creator's record outlives the creation and is not part of + /// it. The frame's share of the caller's reservoir is taken out of the reservoir the charge + /// left and named on the start ([`FrameStart::reservoir`]), so the frame, or the answer revm + /// gives in its place, inherits it, and the caller keeps the rest while the frame runs. revm + /// adds what the frame leaves of it to what the caller kept when it returns. Nothing is + /// declared on the start for the fork to carry. An opcode that starts no frame — a creation the /// balance, the nonce or the depth refuses, an out-of-gas before the forward — never calls /// it, and makes no records; with EIP-8037 off, such a creation calls it without the address /// it would take, which makes none either. A start revm then refuses — a value the caller @@ -447,31 +446,41 @@ impl revm::context_interface::Host ); 0 }; - start.charge = StartCharge::new(charge, PoolAmounts::ZERO); - #[cfg(debug_assertions)] - self.park_start(start, gas.reservoir(), charge); + let value_call = matches!(start.kind, FrameStartKind::Call | FrameStartKind::CallCode) && + !start.value.is_zero(); + let allowance = if value_call { self.value_call_allowance() } else { 0 }; + start.reservoir = Some(self.forward_start(gas, charge, allowance)); true } /// Hands the inner context, whose debug mirror checks the lifecycle's order, the start revm /// opened, and opens it on the start ledger with what was parked for it. - #[cfg(debug_assertions)] + #[inline] fn frame_split(&mut self, split: &FrameSplit) { self.inner.frame_split(split); self.additional_limit.ledger_mut().split(split.id, split.parent, split.depth); } /// Hands the inner context the start revm settled into `gas`, its caller's, and settles it on - /// the start ledger, which compares its figures with the fork's. - #[cfg(debug_assertions)] + /// the start ledger, which gives the start charge back to `gas` when the start did not keep + /// its records: a call that did not succeed, a creation that did not succeed or took no + /// address — but for an inspector's answer and an outcome an inspector rebuilt, which carry + /// none. It is given back as history, as it was charged, and after revm's own settlement of + /// the start, where the fork gave it back; for the transaction's start revm then consumes what + /// it credits to regular gas when the frame halted, as it consumes the rest of a halted + /// frame's. + #[inline] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); - self.additional_limit.ledger_mut().settle(&settle.into(), gas); + let refund = self.additional_limit.ledger_mut().settle(&settle.into()); + if refund != 0 { + gas.refill_history(refund); + } } /// Hands the inner context the lifecycle's end, and ends the start ledger with it: every start /// settled, or what is open discarded. - #[cfg(debug_assertions)] + #[inline] fn frame_lifecycle_end(&mut self, end: LifecycleEnd) { self.inner.frame_lifecycle_end(end); self.additional_limit.ledger_mut().end(end == LifecycleEnd::Settled); @@ -479,29 +488,25 @@ impl revm::context_interface::Host } impl MegaContext { - /// Parks on the start ledger what the start the running frame is making owes, as the - /// frame-start hook decided it: the shares of the frame's pools and the part of its reservoir, - /// `reservoir` once the hook charged it, the frame keeps, by the engine's rule - /// ([`frame_kept_percent`](Self::frame_kept_percent)); the start `charge` the hook declared; - /// and the allowance a value-transferring `CALL` or `CALLCODE` gives its frame. - #[cfg(debug_assertions)] - fn park_start(&mut self, start: &FrameStart, reservoir: u64, charge: u64) { - let value_call = matches!(start.kind, FrameStartKind::Call | FrameStartKind::CallCode) && - !start.value.is_zero(); - let allowance = if value_call { self.value_call_allowance() } else { 0 }; - self.park_owed(reservoir, charge, allowance); - } - - /// Parks on the start ledger what the start the running frame is making owes: the shares of - /// the frame's pools and the part of `reservoir`, what it holds once the start's charges are - /// made, the frame keeps, by the engine's rule - /// ([`frame_kept_percent`](Self::frame_kept_percent)); the start's `charge`; and the - /// child's `allowance`. The frame-start hook parks an instruction's start, and a + /// Forwards what the start the running frame is making takes from it, by the engine's rule + /// ([`frame_kept_percent`](Self::frame_kept_percent)): the frame's share of `gas`'s EIP-8037 + /// reservoir, as it stands once the start's charges are made, which is taken out of `gas` and + /// answered, the frame keeping the rest; and, parked on the start ledger for the split that + /// opens the start, the shares of the frame's pools, taken out of them, the start's `charge`, + /// and the child's `allowance`. The frame-start hook forwards an instruction's start, and a /// `keylessDeploy` call's builder its creation. - #[cfg(debug_assertions)] - pub(crate) fn park_owed(&mut self, reservoir: u64, charge: u64, allowance: u64) { + pub(crate) fn forward_start( + &mut self, + gas: &mut GasTracker, + charge: u64, + allowance: u64, + ) -> u64 { let kept = self.frame_kept_percent(); - self.additional_limit.ledger_mut().park(kept, reservoir, charge, allowance); + let reservoir = gas.reservoir(); + let share = crate::limit::reservoir_share(reservoir, kept); + gas.set_reservoir(reservoir - share); + self.additional_limit.ledger_mut().park(kept, charge, allowance); + share } /// Prices one EIP-8037 state gas unit `id` at `site`, scaling the schedule's entry by the SALT diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index f4c1da8b2..e41bb0b0a 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -2,27 +2,28 @@ //! //! Satin takes the Amsterdam schedule — the one that carries EIP-8037 state gas, EIP-8038's //! state-access prices, the EIP-2780 intrinsic decomposition, the EIP-7976 calldata floor and -//! EIP-7981 access-list data — and changes exactly four things: +//! EIP-7981 access-list data — and changes exactly three things: //! //! 1. the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte //! ([`STATE_GAS_REPRICED`]), which is what makes the state dimension `MegaETH`'s rather than //! Glamsterdam's; -//! 2. the history price of deposited code ([`HISTORY_GAS_PRICED`]), and the history allowance a -//! value-transferring call gives the frame it starts, the entries outside Amsterdam's table: -//! upstream leaves them at zero, and Satin gives deposited code the cost of one history byte per -//! byte, which is what makes a deployment pay for the bytes every node has to carry, and the -//! allowance the cost of [`HISTORY_ALLOWANCE_BYTES`]; -//! 3. the share of its caller's pools — data size, KV updates, state growth — and of its caller's -//! EIP-8037 reservoir a frame starts with: upstream forwards the whole of each, and Satin's -//! caller keeps [`FRAME_KEPT_PERCENT`] of what it has left (`GasId::pool_kept_percent`, -//! `GasId::reservoir_kept_percent`). The fork rounds the two differently, as the spec does: a -//! pool's share is `floor(remaining × 98 / 100)`, and the reservoir's `remaining − remaining × 2 -//! / 100`, so a caller keeps nothing of a reservoir below 50. The transaction's own frame and a -//! system call's outermost frame take the whole reservoir; -//! 4. the regular gas a call or creation forwards: at most `remaining − remaining × 2 / 100` of +//! 2. the history price of deposited code ([`HISTORY_GAS_PRICED`]), an entry outside Amsterdam's +//! table: upstream leaves it at zero, and Satin gives deposited code the cost of one history +//! byte per byte, which is what makes a deployment pay for the bytes every node has to carry; +//! 3. the regular gas a call or creation forwards: at most `remaining − remaining × 2 / 100` of //! what its caller has left, Rex6's rule, in place of EIP-150's 63/64 //! ([`FORWARD_REDUCTION_QUOTIENT`], the fork's `GasId::call_stipend_reduction`). //! +//! What else a frame start takes from its caller is the engine's, not the schedule's, and the +//! schedule keeps Amsterdam's entries for it, which take nothing: the share of its caller's pools — +//! data size, KV updates, state growth — and of its caller's EIP-8037 reservoir a frame starts +//! with, all but [`FRAME_KEPT_PERCENT`] of what the caller has left, and the history allowance a +//! value-transferring call gives the frame, `HISTORY_ALLOWANCE_BYTES` at the cost per history +//! byte, are decided where the start is made (`MegaContext::forward_start`) and kept on the +//! engine's start ledger. A pool's share is `floor(remaining × 98 / 100)`, and the reservoir's +//! `remaining − remaining × 2 / 100`, so a caller keeps nothing of a reservoir below 50; the +//! transaction's own frame and a system call's outermost frame take the whole reservoir. +//! //! Every regular-gas price is Amsterdam's, so state creation is split between the two dimensions //! as Amsterdam splits it: the regular part is the access and write work EIP-8038 prices, and the //! new state itself is state gas alone. A value `CALL` that creates its recipient pays the 11,300 @@ -50,14 +51,8 @@ use revm::{ }; use crate::{ - evm::{ - history::HISTORY_ALLOWANCE_BYTES, - prices::{active_satin_prices, SatinPrices}, - }, - limit::{ - DATA_SIZE_POOL, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, KV_UPDATE_POOL, - STATE_GROWTH_POOL, - }, + evm::prices::{active_satin_prices, SatinPrices}, + limit::{FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR}, }; /// A schedule entry and the number of bytes it prices: the entry is that many bytes at a byte @@ -82,18 +77,15 @@ pub const STATE_GAS_REPRICED: &[ScheduleEntry] = &[ /// /// Deposited code is the one history charge the schedule prices, because it is the one revm makes /// itself: `return_create` writes the code and charges the entry for its length. Every other -/// history charge is made by the engine, which prices its own byte counts (the `history` module). -/// The allowance a value-transferring call gives the frame it starts is in the schedule because -/// revm's call instruction gives it, where it gives the call stipend; only a log the frame emits -/// draws on it ([`history_allowance_gas`](crate::history_allowance_gas)). -pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[ - (GasId::code_deposit_history_gas, 1), - (GasId::call_history_allowance, HISTORY_ALLOWANCE_BYTES), -]; +/// history charge is made by the engine, which prices its own byte counts (the `history` module), +/// and so is the allowance a value-transferring call gives the frame it starts, which only a log +/// the frame emits draws on ([`history_allowance_gas`](crate::history_allowance_gas)). +pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[(GasId::code_deposit_history_gas, 1)]; /// The part of its pool, in per cent, a caller keeps when it starts a frame, which starts with the /// rest: its budget, [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what the -/// caller has left. revm's forward of a pool rounds the share down, as the budget's rule does. +/// caller has left, rounded down. The engine takes a start's shares by it, of the pools and of the +/// reservoir, where the start is made. pub(crate) const FRAME_KEPT_PERCENT: u64 = 100 - FRAME_DATA_SHARE_NUMERATOR * 100 / FRAME_DATA_SHARE_DENOMINATOR; const _: () = @@ -152,13 +144,7 @@ pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { params.override_gas( HISTORY_GAS_PRICED.iter().map(|&(id, bytes)| (id(), prices.cphb.fixed_size_gas(bytes))), ); - params.override_gas([ - (GasId::pool_kept_percent(DATA_SIZE_POOL), FRAME_KEPT_PERCENT), - (GasId::pool_kept_percent(KV_UPDATE_POOL), FRAME_KEPT_PERCENT), - (GasId::pool_kept_percent(STATE_GROWTH_POOL), FRAME_KEPT_PERCENT), - (GasId::reservoir_kept_percent(), FRAME_KEPT_PERCENT), - (GasId::call_stipend_reduction(), FORWARD_REDUCTION_QUOTIENT), - ]); + params.override_gas([(GasId::call_stipend_reduction(), FORWARD_REDUCTION_QUOTIENT)]); params } @@ -169,7 +155,11 @@ mod tests { constants::{ ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, SLOT_STATE_GAS, }, - evm::prices::{runs_at_measurement_prices, BytePrice}, + evm::{ + history::HISTORY_ALLOWANCE_BYTES, + prices::{runs_at_measurement_prices, BytePrice}, + }, + limit::{DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL}, }; fn osaka() -> GasParams { @@ -192,10 +182,6 @@ mod tests { let id = GasId::new(slot); let rebuilt = STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) || - id == GasId::pool_kept_percent(DATA_SIZE_POOL) || - id == GasId::pool_kept_percent(KV_UPDATE_POOL) || - id == GasId::pool_kept_percent(STATE_GROWTH_POOL) || - id == GasId::reservoir_kept_percent() || id == GasId::call_stipend_reduction(); if rebuilt { continue; @@ -288,21 +274,27 @@ mod tests { } } - /// A frame starts with 98 per cent of what its caller has left of its data-size, KV-update and - /// state-growth budgets, which revm forwards at every frame start as the schedule's share of - /// each pool, the caller keeping 2 per cent, rounded down as the budget's rule is; upstream - /// forwards the whole pool. + /// The schedule takes nothing at a frame start beyond the regular gas it forwards: it keeps + /// none of a caller's pools or reservoir from the frame and gives a value call's frame no + /// history allowance, as upstream's, so revm forwards every pool and the reservoir whole and + /// grants nothing. The engine takes the shares and grants the allowance itself, by + /// [`FRAME_KEPT_PERCENT`], 2, and `HISTORY_ALLOWANCE_BYTES`, 160. #[test] - fn test_a_frame_is_forwarded_98_percent_of_its_callers_pools() { + fn test_the_schedule_leaves_a_starts_shares_and_allowance_to_the_engine() { let satin = satin_gas_params(); for id in [DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL] { - assert_eq!(satin.get(GasId::pool_kept_percent(id)), 2); - assert_eq!(amsterdam().get(GasId::pool_kept_percent(id)), 0); - for pool in [0, 1, 49, 50, 51, 99, 100, 101, 9_690, u64::MAX] { - let floor = (u128::from(pool) * 98 / 100) as u64; - assert_eq!(satin.pool_forward_share(id, pool), floor, "{pool}"); + assert_eq!(satin.get(GasId::pool_kept_percent(id)), 0); + for pool in [0, 1, 49, 50, 99, 9_690, u64::MAX] { + assert_eq!(satin.pool_forward_share(id, pool), pool, "{pool}: the whole pool"); } } + assert_eq!(satin.get(GasId::reservoir_kept_percent()), 0); + for reservoir in [0, 1, 49, 50, 99, 1_000, u64::MAX] { + assert_eq!(satin.reservoir_forward_share(reservoir), reservoir, "{reservoir}"); + } + assert_eq!(satin.get(GasId::call_history_allowance()), 0); + assert_eq!(FRAME_KEPT_PERCENT, 2); + assert_eq!(HISTORY_ALLOWANCE_BYTES, 160); } /// A call or creation forwards at most `remaining − remaining × 2 / 100` of its caller's @@ -324,12 +316,9 @@ mod tests { /// A frame starts with the reservoir its caller has left less the caller's 2 per cent, the /// division truncating, so a caller keeps nothing of a reservoir below 50 and the child gets - /// 98 of 99; upstream forwards the whole reservoir. + /// 98 of 99; the neutral configuration, which keeps nothing, forwards the whole reservoir. #[test] fn test_a_frame_is_forwarded_its_callers_reservoir_less_two_percent() { - let satin = satin_gas_params(); - assert_eq!(satin.get(GasId::reservoir_kept_percent()), 2); - assert_eq!(amsterdam().get(GasId::reservoir_kept_percent()), 0); for (reservoir, share) in [ (0, 0), (1, 1), @@ -342,24 +331,12 @@ mod tests { (1_000_000, 980_000), (u64::MAX, u64::MAX - u64::MAX / 50), ] { - assert_eq!(satin.reservoir_forward_share(reservoir), share, "{reservoir}"); - assert_eq!(amsterdam().reservoir_forward_share(reservoir), reservoir, "{reservoir}"); + let kept = FRAME_KEPT_PERCENT; + assert_eq!(crate::limit::reservoir_share(reservoir, kept), share, "{reservoir}"); + assert_eq!(crate::limit::reservoir_share(reservoir, 0), reservoir, "{reservoir}"); } } - /// The history allowance a value-transferring call gives the frame it starts is - /// [`HISTORY_ALLOWANCE_BYTES`] at the cost per history byte, the same figure the engine - /// prices its history at; Osaka and Amsterdam give none. - #[test] - fn test_a_value_call_is_given_the_history_allowance() { - let id = GasId::call_history_allowance(); - assert_eq!(satin_gas_params().get(id), crate::history_allowance_gas()); - let constants = satin_gas_params_at(SatinPrices::CONSTANTS); - assert_eq!(constants.get(id), 160 * COST_PER_HISTORY_BYTE); - assert_eq!(osaka().get(id), 0); - assert_eq!(amsterdam().get(id), 0); - } - /// Deposited code costs one history byte per byte, which is the whole of Satin's history /// schedule. Osaka and Amsterdam price no history byte at all. #[test] @@ -410,7 +387,6 @@ mod tests { (GasId::code_deposit_state_gas(), 313), (GasId::tx_eip7702_state_gas_bytecode(), 7_188), (GasId::code_deposit_history_gas(), 400), - (GasId::call_history_allowance(), 160 * 400), ]; for slot in 0..=u8::MAX { let id = GasId::new(slot); diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 055243597..9553b4517 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -1,140 +1,76 @@ -//! The engine's ledger of what each frame start owes and holds, kept in a debug build beside the -//! figures the revm fork carries, and checked against them. +//! The engine's ledger of what each frame start owes and holds: the frame budgets, the start +//! charge and the history allowance. //! -//! The revm fork carries four figures of a frame's start on the frame's gas: the shares of its -//! caller's three pools — data size, KV updates, state growth — with their nets and crossings; the -//! part of its caller's EIP-8037 reservoir the caller keeps while it runs; the start charge its -//! failure gives back to the caller; and the history allowance a value call gives it. The ledger -//! keeps the same four for every start, computed by the engine's own rules, in an entry per open -//! start. +//! A frame start carries three figures beside its gas that are the engine's: the shares of its +//! caller's three pools — data size, KV updates, state growth — it may draw, with its net draws; +//! the start charge its failure gives back to its caller, the history of the records its start +//! made on it; and the history allowance a value call gives it. The ledger keeps them in an entry +//! per open start, by the engine's own rules, and they decide: a draw is held to the top entry's +//! budget ([`budget`](StartLedger::budget)), a settlement gives the start charge back +//! ([`settle`](StartLedger::settle)), and a log's history draws the top entry's allowance first +//! ([`draw_allowance`](StartLedger::draw_allowance)). The part of its EIP-8037 reservoir a caller +//! keeps is the engine's rule too ([`reservoir_share`]), taken out of the caller's gas where the +//! start is made; the reservoir itself stays on the gas, which revm settles. //! //! It is driven by the start lifecycle revm owns and by nothing else: an entry opens when revm //! opens the start (`Host::frame_split`), settles when revm settles it (`Host::frame_settle`), and //! the ledger is dropped when the lifecycle ends, settled or discarded //! (`Host::frame_lifecycle_end`). The transaction's start resets it, so nothing a context's ledger //! held carries into the next transaction. The ledger pairs nothing: revm's record says which start -//! settles, and the ledger asserts it is the one on top. +//! settles, and refuses a start or a settlement out of order before the ledger sees it; a debug +//! build asserts the settling start is the one on top. //! //! # The rules //! //! - **What a start owes is parked where it is made**, on the entry of the frame that makes it, and //! the split that opens the start takes it ([`park`](StartLedger::park)): an instruction's start //! at the frame-start hook, after the hook's charge; a `keylessDeploy` call's creation where its -//! builder takes the creation's shares; the transaction's start where its first frame's input is -//! built ([`park_transaction`](StartLedger::park_transaction)). A start dropped before revm -//! consumes it loses what was parked for it, and the frame's next start parks over it. The -//! stand-in revm settles for a transaction whose runtime gas phase ran out of gas has nothing -//! parked: it starts with unlimited pools, as the transaction's rebuilt gas holds them. +//! builder makes it; the transaction's start where its first frame's input is built +//! ([`park_transaction`](StartLedger::park_transaction)). A start dropped before revm consumes it +//! loses what was parked for it, and the frame's next start parks over it. The stand-in revm +//! settles for a transaction whose runtime gas phase ran out of gas has nothing parked: it starts +//! with unlimited pools and owes nothing. A start whose input an inspector built itself has +//! nothing parked either, and opens with no pool and nothing owed. //! - **A child's share of each pool** is all but `kept` per cent of what its caller has left, //! rounded down, taken out of the caller's entry where it is parked; the caller keeps `kept` per -//! cent of its reservoir, rounded down. `kept` is the engine's +//! cent of its reservoir, rounded down ([`reservoir_share`]). `kept` is the engine's //! ([`frame_kept_percent`](crate::MegaContext)): two on the spec's configuration, none on the //! neutral one, which forwards the whole of each as Ethereum does. When the child's frame starts, //! its shares are held to the frame cap and, for a caller whose net is negative, to the share of //! the caller's budget, and the excess goes back to the caller //! ([`cap_child`](StartLedger::cap_child)). -//! - **A draw goes to the top entry**, the running frame's start: a completed write, a frame -//! start's records on the started frame, a deposit's code on the creating frame, a creator's -//! nonce record on the creator once its creation returned ([`draw`](StartLedger::draw)); a log's -//! history draws the top entry's allowance first -//! ([`draw_allowance`](StartLedger::draw_allowance)). +//! - **A draw goes to the top entry**, the running frame's start, held first to its budget: a +//! completed write, a frame start's records on the started frame, a deposit's code on the +//! creating frame, a creator's nonce record on the creator once its creation returned +//! ([`draw`](StartLedger::draw)). With no start open, as for a frame a test drives by hand, there +//! is no frame budget. //! - **A precompile's draws are adopted when it answers**, fail-closed: a draw past the share -//! empties the pool, caps the net at the share and sets the crossing, whatever the answer's -//! status ([`adopt_provider_draws`](StartLedger::adopt_provider_draws)). -//! - **A settlement** merges the child's entry into its caller's ([`settle`](StartLedger::settle)), -//! as the fork settles a frame's gas: on success the child's remaining pools join what the caller -//! kept and its nets the caller's; on a revert or a halt its draws are undone, and its whole -//! share comes back. The start charge comes back on a failure, and for a creation also when it -//! took no address. An inspector's answer, and a result whose gas an inspector replaced, settle -//! as unlimited pools with no net; neither an inspector's answer nor an outcome an inspector -//! rebuilt gives the start charge back. -//! -//! # The comparison -//! -//! At every settlement the ledger compares what it computed with the fork's figures for the same -//! start: each of the caller's pools, nets and crossings once the child merged into it; the -//! reservoir the caller kept, with the reservoir revm says the caller held before it settled the -//! child; the start charge the fork gave back; and, for a frame revm built whose gas no inspector -//! replaced, the allowance the frame returns. At the lifecycle's successful end the ledger holds no -//! entry. -//! -//! A difference is a panic. Some inspector shapes differ by design, because they move a figure -//! the ledger keeps off the tracker, which a tracker copy or a field an inspector writes cannot -//! reach: a tracker restored from a snapshot, an interpreter replaced, an answer, an input or a -//! result built with pools, an allowance or a charge an inspector set, a tracker or an outcome -//! copied from another start. Once the engine reads its ledger, those figures are the ledger's, and -//! such an inspector's values are not taken. A test that runs one has the context record the -//! differences instead, and asserts each (`test_utils::tolerate_start_ledger_divergences`). After a -//! recorded difference in a caller's pools the ledger takes the fork's, so what it records is where -//! the two part, not what follows. +//! empties the pool and caps the net at the share, whatever the answer's status +//! ([`adopt_provider_draws`](StartLedger::adopt_provider_draws)). +//! - **A settlement** merges the child's entry into its caller's ([`settle`](StartLedger::settle)): +//! on success the child's remaining pools join what the caller kept and its nets the caller's; on +//! a revert or a halt its draws are undone, and its whole share comes back. The start charge +//! comes back on a failure, and for a creation also when it took no address. An inspector's +//! answer, and a result whose gas an inspector replaced, settle as unlimited pools with no net; +//! neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back. +//! The figures an inspector puts on the gas or the input it hands over are not read. #[cfg(not(feature = "std"))] use alloc as std; use std::vec::Vec; use revm::context_interface::{ - cfg::gas::{GasTracker, PoolAmounts, PoolId}, + cfg::gas::{PoolAmounts, PoolId}, host::{FrameSettle, SettleStatus}, }; use super::Counted; -/// A figure of a settled start the ledger compares with the fork's. -/// -/// Public to the test tools, which record and assert a difference; a debug build without them -/// reaches it only through the ledger's panic. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[cfg_attr(not(any(test, feature = "test-utils")), allow(unreachable_pub))] -pub enum LedgerFigure { - /// What the started frame may still draw on a pool, as its result returns it. - FrameRemaining(PoolId), - /// The started frame's net draw on a pool, as its result returns it. - FrameNet(PoolId), - /// Whether a draw on the started frame's pool was refused (`1`) or not (`0`), as its result - /// returns it. - FrameCrossing(PoolId), - /// What the start's caller may still draw on a pool, once the start settled into it. - CallerRemaining(PoolId), - /// The caller's net draw on a pool, once the start settled into it. - CallerNet(PoolId), - /// Whether a draw on the caller's pool was refused (`1`) or not (`0`). - CallerCrossing(PoolId), - /// The part of its reservoir the caller kept while the start ran. - KeptReservoir, - /// The history gas the start's settlement gave back to its caller. - StartChargeRefund, - /// What the frame returned of its history allowance. - Allowance, -} - -/// One of a pool's figures, named by the pool. -type PoolFigure = fn(PoolId) -> LedgerFigure; - -/// A figure of a settled start in which the ledger and the fork differ. -/// -/// Public to the test tools, as [`LedgerFigure`] is. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[cfg_attr(not(any(test, feature = "test-utils")), allow(unreachable_pub))] -pub struct LedgerDivergence { - /// The identity revm gave the start. - pub start: u32, - /// The started frame's depth. - pub depth: usize, - /// The figure. - pub figure: LedgerFigure, - /// The ledger's value. - pub ledger: i128, - /// The fork's value. - pub fork: i128, -} - /// What a start owes, decided where it is made and taken by the split that opens it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Parked { /// The child's share of each of its caller's pools. shares: PoolAmounts, - /// The part of its reservoir the caller keeps while the child runs. - kept_reservoir: u64, /// The history gas the start charged its caller for the records on the child, which the /// child's failure gives back. charge: u64, @@ -144,54 +80,48 @@ pub(crate) struct Parked { impl Parked { /// What the transaction's start owes: its pools, `pools`, the start `charge` of the record its - /// frame makes, and no kept reservoir and no allowance, its frame taking the transaction's - /// whole reservoir and making no value call. + /// frame makes, and no allowance, its frame making no value call. pub(crate) const fn transaction(pools: PoolAmounts, charge: u64) -> Self { - Self { shares: pools, kept_reservoir: 0, charge, allowance: 0 } + Self { shares: pools, charge, allowance: 0 } } } /// What a transaction's start owes when nothing was parked for it: the stand-in revm settles for a -/// transaction whose runtime gas phase ran out of gas, which carries every pool of the rebuilt -/// gas, unlimited, and owes nothing else. +/// transaction whose runtime gas phase ran out of gas, which carries every pool, unlimited, and +/// owes nothing else. const STAND_IN: Parked = Parked::transaction(PoolAmounts::UNLIMITED, 0); /// What a start owes when an inspector consumed an input it built itself, which no start parked /// anything for: nothing, and no pool. -const UNPARKED: Parked = - Parked { shares: PoolAmounts::ZERO, kept_reservoir: 0, charge: 0, allowance: 0 }; +const UNPARKED: Parked = Parked { shares: PoolAmounts::ZERO, charge: 0, allowance: 0 }; + +/// What a precompile's provider drew on one pool of its answer: its signed `net` draw, and whether +/// it drew past a share it was held to, which the net alone cannot tell once that share capped it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ProviderDraw { + /// The net draw. + pub(crate) net: i64, + /// Whether the draw went past a share it was held to. + pub(crate) past_a_share: bool, +} -/// A frame's three pools as the engine keeps them: what it may still draw, its signed net draw, -/// and whether a draw it could not pay was refused. +/// A frame's three pools as the engine keeps them: what it may still draw, and its signed net draw. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Pools { remaining: PoolAmounts, net: [i64; PoolId::COUNT], - crossings: [bool; PoolId::COUNT], } impl Pools { /// Pools that start at `shares`, undrawn. const fn of(shares: PoolAmounts) -> Self { - Self { remaining: shares, net: [0; PoolId::COUNT], crossings: [false; PoolId::COUNT] } - } - - /// The pools `gas` holds. - fn on(gas: &GasTracker) -> Self { - Self { - remaining: gas.pools_remaining(), - net: PoolId::ALL.map(|pool| gas.pool_spent(pool)), - crossings: PoolId::ALL.map(|pool| gas.pool_crossing(pool)), - } + Self { remaining: shares, net: [0; PoolId::COUNT] } } - /// Draws `amount` on `pool`; a draw the pool cannot pay takes nothing and sets its crossing. + /// Draws `amount` on `pool`; a draw the pool cannot pay takes nothing. fn record(&mut self, pool: PoolId, amount: u64) -> bool { let index = pool.index(); - let Some(left) = self.remaining.get(pool).checked_sub(amount) else { - self.crossings[index] = true; - return false; - }; + let Some(left) = self.remaining.get(pool).checked_sub(amount) else { return false }; self.remaining.set(pool, left); self.net[index] = self.net[index].saturating_add(signed(amount)); true @@ -216,7 +146,7 @@ impl Pools { /// Takes back what a child that `succeeded`, or failed, returns: its remaining pools join what /// this frame kept, and its nets this frame's when it succeeded. A failed child's draws are - /// undone first. A child's crossings stay the child's. + /// undone first. fn absorb(&mut self, mut child: Self, succeeded: bool) { if !succeeded { child.roll_back(); @@ -250,6 +180,13 @@ const fn kept_part(amount: u64, kept: u64) -> u64 { (amount as u128 * kept as u128 / 100) as u64 } +/// The share of its caller's EIP-8037 `reservoir` a frame starts with: all but the caller's +/// `kept` per cent of it, which is rounded down, so a caller that keeps two per cent keeps nothing +/// of a reservoir below 50 and forwards 98 of 99. +pub(crate) const fn reservoir_share(reservoir: u64, kept: u64) -> u64 { + reservoir - kept_part(reservoir, kept) +} + /// The share of a pool holding `remaining` a child starts with: `100 − kept` per cent of it, /// rounded down. const fn pool_share(remaining: u64, kept: u64) -> u64 { @@ -259,24 +196,6 @@ const fn pool_share(remaining: u64, kept: u64) -> u64 { (remaining as u128 * (100 - kept) as u128 / 100) as u64 } -/// What a precompile's provider drew on one pool of its answer: its signed `net` draw, and whether -/// it drew past a share it was held to, which the net alone cannot tell once that share capped it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct ProviderDraw { - /// The net draw. - pub(crate) net: i64, - /// Whether the draw went past a share it was held to. - pub(crate) past_a_share: bool, -} - -impl ProviderDraw { - /// A net draw of `net`, within any share it was held to. - #[cfg(test)] - pub(crate) const fn of(net: i64) -> Self { - Self { net, past_a_share: false } - } -} - /// One open start. #[derive(Clone, Copy, Debug)] struct Entry { @@ -289,14 +208,10 @@ struct Entry { shares: PoolAmounts, /// Its pools as its frame draws them. pools: Pools, - /// The part of its reservoir the start's caller kept. - kept_reservoir: u64, /// The start charge its failure gives back. charge: u64, /// What is left of its history allowance. allowance: u64, - /// Whether revm built a frame for it, which ran or ended before it ran; an answer has none. - built: bool, /// What the next start its frame makes owes. parked: Option, } @@ -308,10 +223,8 @@ impl Entry { depth, shares: owed.shares, pools: Pools::of(owed.shares), - kept_reservoir: owed.kept_reservoir, charge: owed.charge, allowance: owed.allowance, - built: false, parked: None, } } @@ -328,7 +241,6 @@ pub(crate) struct Settlement { inspector_answer: bool, gas_replaced: bool, outcome_rebuilt: bool, - held_reservoir: u64, } impl From<&FrameSettle> for Settlement { @@ -341,30 +253,50 @@ impl From<&FrameSettle> for Settlement { inspector_answer: settle.inspector_answer, gas_replaced: settle.gas_replaced, outcome_rebuilt: settle.outcome_rebuilt, - held_reservoir: settle.held_reservoir, } } } -/// The fork's figures of the result about to settle, read before revm consumes it. +/// A frame's pools as a settlement left them: what it may still draw on each, and its signed net +/// draw on each. +/// +/// Public to the test tools, which read the ledger's settlements. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Returning { - /// The frame's pools as its result's gas holds them. - pools: Pools, - /// The history the fork gives back to the caller for the start. - refund: u64, - /// What the result's gas holds of the frame's history allowance. - allowance: u64, +#[cfg(any(test, feature = "test-utils"))] +pub struct LedgerPools { + /// What the frame may still draw on each pool. + pub remaining: PoolAmounts, + /// The frame's net draw on each pool, by the pool's index. + pub net: [i64; PoolId::COUNT], } -impl Returning { - /// The figures of a result whose gas is `gas`: its pools and what it holds of its frame's - /// history allowance; and `refund`, the history of the start charge the fork gives back. - pub(crate) fn of(gas: &GasTracker, refund: u64) -> Self { - Self { pools: Pools::on(gas), refund, allowance: gas.history_allowance() } +#[cfg(any(test, feature = "test-utils"))] +impl From for LedgerPools { + fn from(pools: Pools) -> Self { + Self { remaining: pools.remaining, net: pools.net } } } +/// A start's settlement as the ledger made it. +/// +/// Public to the test tools, which read the ledger's settlements. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg(any(test, feature = "test-utils"))] +pub struct LedgerSettlement { + /// The identity revm gave the start. + pub start: u32, + /// The started frame's depth. + pub depth: usize, + /// The started frame's pools as they settled into its caller: an inspector's answer and a + /// result whose gas an inspector replaced settle as unlimited pools. + pub frame: LedgerPools, + /// The caller's pools once the start settled into them; for the transaction's start, the + /// transaction's, which held none of its frame's pools while the frame ran. + pub caller: LedgerPools, + /// The history gas the settlement gave back to the caller: the start charge, or nothing. + pub refund: u64, +} + /// The engine's ledger of the open starts of the running transaction. See the module /// documentation. #[derive(Clone, Debug, Default)] @@ -373,10 +305,9 @@ pub(crate) struct StartLedger { entries: Vec, /// What the transaction's start owes, parked where its first frame's input is built. transaction: Option, - /// The fork's figures of the result settling next. - returning: Option, - /// The differences found, when the ledger records them rather than panics. - divergences: Option>, + /// The settlements made, when a test has them recorded. + #[cfg(any(test, feature = "test-utils"))] + settlements: Option>, } impl StartLedger { @@ -390,23 +321,24 @@ impl StartLedger { /// Opens the start revm just opened, `id` at `depth` under `parent`, with what was parked for /// it. The transaction's start, with no parent, resets the ledger. + /// + /// revm opens a child only under the start of the frame on top of its stack, which is the + /// ledger's top entry, one depth less; a debug build asserts it. A hook called by hand out of + /// that order opens the start on whatever is on top. pub(crate) fn split(&mut self, id: u32, parent: Option, depth: usize) { let owed = match parent { None => { self.entries.clear(); - self.returning = None; self.transaction.take().unwrap_or(STAND_IN) } Some(parent) => { - let caller = self.entries.last_mut(); - let Some(caller) = - caller.filter(|caller| caller.id == parent && caller.depth + 1 == depth) - else { - panic!( - "start {id} at depth {depth} opened under {parent}, not the ledger's top" - ) - }; - caller.parked.take().unwrap_or(UNPARKED) + debug_assert!( + self.entries + .last() + .is_some_and(|caller| caller.id == parent && caller.depth + 1 == depth), + "start {id} at depth {depth} opened under {parent}, not the ledger's top" + ); + self.entries.last_mut().and_then(|caller| caller.parked.take()).unwrap_or(UNPARKED) } }; self.entries.push(Entry::open(id, depth, owed)); @@ -414,26 +346,21 @@ impl StartLedger { /// Ends the lifecycle: every start settled when it `settled`, or what is open discarded. pub(crate) fn end(&mut self, settled: bool) { - if settled { - assert!( - self.entries.is_empty(), - "the lifecycle settled with starts open in the ledger: {:?}", - self.entries - ); - } + debug_assert!( + !settled || self.entries.is_empty(), + "the lifecycle settled with starts open in the ledger: {:?}", + self.entries + ); self.entries.clear(); - self.returning = None; self.transaction = None; } /* What a start owes */ /// Parks on the running frame's entry what the start it is making owes: the share of each of - /// its pools, taken out of them, and the part of `reservoir` it keeps, all by `kept`; the - /// start's `charge`; and the child's `allowance`. `reservoir` is what the caller holds once the - /// start's charges are made. Overwrites what an earlier start of the frame parked and no split - /// took. - pub(crate) fn park(&mut self, kept: u64, reservoir: u64, charge: u64, allowance: u64) { + /// its pools, by `kept`, taken out of them; the start's `charge`; and the child's `allowance`. + /// Overwrites what an earlier start of the frame parked and no split took. + pub(crate) fn park(&mut self, kept: u64, charge: u64, allowance: u64) { let Some(caller) = self.entries.last_mut() else { return }; let mut shares = PoolAmounts::ZERO; for pool in PoolId::ALL { @@ -442,8 +369,7 @@ impl StartLedger { caller.pools.remaining.set(pool, remaining - share); shares.set(pool, share); } - let kept_reservoir = kept_part(reservoir, kept); - caller.parked = Some(Parked { shares, kept_reservoir, charge, allowance }); + caller.parked = Some(Parked { shares, charge, allowance }); } /// Holds the shares of the start on top, which its caller below it is suspended on, to `caps` @@ -470,17 +396,24 @@ impl StartLedger { } } - /// Notes that revm built a frame for the start on top. - pub(crate) fn built(&mut self) { - if let Some(entry) = self.entries.last_mut() { - entry.built = true; - } + /// The start charge of the start on top: the history its caller paid for the records the start + /// makes on its frame. Nothing with no start open. + pub(crate) fn charge(&self) -> u64 { + self.entries.last().map_or(0, |entry| entry.charge) } /* Draws */ + /// The budget of the running frame on `pool`: what it may still draw, and its signed net draw. + /// With no start open there is no frame budget: the pool is unlimited, undrawn. + pub(crate) fn budget(&self, pool: PoolId) -> (u64, i64) { + self.entries.last().map_or((u64::MAX, 0), |entry| { + (entry.pools.remaining.get(pool), entry.pools.net[pool.index()]) + }) + } + /// Draws `counted` on the top entry's pools, which the limits admitted: what it takes back goes - /// back to each pool first, then what it adds is drawn. + /// back to each pool first, then what it adds is drawn. A pool it leaves alone is not visited. pub(crate) fn draw(&mut self, counted: &Counted) { let Some(entry) = self.entries.last_mut() else { return }; for pool in PoolId::ALL { @@ -489,11 +422,13 @@ impl StartLedger { continue; } entry.pools.refill(pool, taken); - if !entry.pools.record(pool, added) { - // Admitted by the limits, so refused only past a saturated unlimited pool, which is - // no crossing. - entry.pools.crossings[pool.index()] = false; - } + let drew = entry.pools.record(pool, added); + // Admitted by the limits, so refused only past a saturated unlimited pool, which an + // exempt transaction's frames hold. + debug_assert!( + drew || entry.pools.remaining.get(pool) == u64::MAX, + "the checks admit the draw" + ); } } @@ -507,9 +442,8 @@ impl StartLedger { } /// Adopts `draws`, what a precompile's provider drew on each pool of its answer to the start on - /// top, fail-closed: a draw within the share is drawn, and one past it empties the pool, caps - /// the net at the share and sets the crossing. The answer's status is the provider's either - /// way. + /// top, fail-closed: a draw within the share is drawn, and one past it empties the pool and + /// caps the net at the share. The answer's status is the provider's either way. /// /// The adoption replaces the entry's pools with the share less the provider's draw, so it runs /// before anything else is drawn on the answer: the start's own records, which the frame start @@ -522,7 +456,6 @@ impl StartLedger { if past_a_share || (drawn > 0 && drawn as u64 > share) { entry.pools.remaining.set(pool, 0); entry.pools.net[index] = signed(share); - entry.pools.crossings[index] = true; } else { entry .pools @@ -543,34 +476,27 @@ impl StartLedger { /* Settlement */ - /// Notes the fork's figures of the result about to settle. - pub(crate) const fn returning(&mut self, figures: Returning) { - self.returning = Some(figures); - } - - /// Settles the start on top, which revm just settled into `gas`, its caller's — the - /// transaction's gas, for the transaction's start — and compares the caller's pools, what the - /// caller kept of its reservoir, the start charge given back and the allowance the frame - /// returned with the fork's. - pub(crate) fn settle(&mut self, settlement: &Settlement, gas: &GasTracker) { - let Some(child) = self.entries.pop() else { - panic!("start {} settled with no start open in the ledger", settlement.id) - }; - assert_eq!( - (child.id, child.depth), - (settlement.id, settlement.depth), - "the start on top of the ledger is not the one revm settled" + /// Settles the start on top, which revm just settled into its caller's gas — the transaction's + /// gas, for the transaction's start — into its caller's entry, and answers the history gas the + /// caller gets back for it: the start charge, when the start did not keep its records. + /// + /// revm settles only the start on top of its record, the ledger's top entry; a debug build + /// asserts it. A hook called by hand out of that order settles whatever is on top, and with + /// nothing open settles nothing. + pub(crate) fn settle(&mut self, settlement: &Settlement) -> u64 { + debug_assert!( + self.entries + .last() + .is_some_and(|child| (child.id, child.depth) == (settlement.id, settlement.depth)), + "the start on top of the ledger is not the one revm settled: {settlement:?}" ); - let Some(fork) = self.returning.take() else { - panic!("start {} settled without the fork's figures of its result", settlement.id) - }; + let Some(child) = self.entries.pop() else { return 0 }; let inspected = settlement.inspector_answer || settlement.gas_replaced; let pools = if inspected { Pools::of(PoolAmounts::UNLIMITED) } else { child.pools }; let succeeded = settlement.status == SettleStatus::Ok; let failed = !succeeded || settlement.created == Some(false); let refunds = failed && !settlement.inspector_answer && !settlement.outcome_rebuilt; let refund = if refunds { child.charge } else { 0 }; - let returned = child.built && !inspected; // The transaction's gas holds none of its pools while its frame runs, which took them // whole. @@ -580,96 +506,39 @@ impl StartLedger { None => &mut transaction, }; caller.absorb(pools, succeeded); - let ledger = *caller; - let on_gas = Pools::on(gas); - - let mut differences = Vec::new(); - let figures: [(Pools, Pools, [PoolFigure; 3]); 2] = [ - ( - pools, - fork.pools, - [LedgerFigure::FrameRemaining, LedgerFigure::FrameNet, LedgerFigure::FrameCrossing], - ), - ( - ledger, - on_gas, - [ - LedgerFigure::CallerRemaining, - LedgerFigure::CallerNet, - LedgerFigure::CallerCrossing, - ], - ), - ]; - for (ledger, fork, [remaining, net, crossing]) in figures { - for pool in PoolId::ALL { - let index = pool.index(); - differences.extend([ - ( - remaining(pool), - i128::from(ledger.remaining.get(pool)), - i128::from(fork.remaining.get(pool)), - ), - (net(pool), ledger.net[index].into(), fork.net[index].into()), - (crossing(pool), ledger.crossings[index].into(), fork.crossings[index].into()), - ]); - } - } - differences.extend([ - ( - LedgerFigure::KeptReservoir, - child.kept_reservoir.into(), - settlement.held_reservoir.into(), - ), - (LedgerFigure::StartChargeRefund, refund.into(), fork.refund.into()), - ]); - if returned { - differences.push(( - LedgerFigure::Allowance, - child.allowance.into(), - fork.allowance.into(), - )); - } - differences.retain(|(_, ledger, fork)| ledger != fork); - if differences.is_empty() { - return; - } - let pools_differ = differences.iter().any(|(figure, ..)| { - matches!( - figure, - LedgerFigure::CallerRemaining(_) | - LedgerFigure::CallerNet(_) | - LedgerFigure::CallerCrossing(_) - ) - }); - let Some(recorded) = &mut self.divergences else { - panic!( - "the start ledger parts from the fork at start {} (depth {}), settled {:?}: \ - (figure, ledger, fork) {differences:?}", - child.id, child.depth, settlement - ) - }; - recorded.extend(differences.into_iter().map(|(figure, ledger, fork)| LedgerDivergence { - start: child.id, - depth: child.depth, - figure, - ledger, - fork, - })); - if pools_differ { - if let Some(caller) = self.entries.last_mut() { - caller.pools = on_gas; - } + #[cfg(any(test, feature = "test-utils"))] + if let Some(settlements) = &mut self.settlements { + settlements.push(LedgerSettlement { + start: child.id, + depth: child.depth, + frame: pools.into(), + caller: (*caller).into(), + refund, + }); } + refund } - /// Each pool of the start on top: what it may still draw, its net and its crossing. + /* The settlements a test reads */ + + /// Records every settlement from now on. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) fn record_settlements(&mut self) { + self.settlements.get_or_insert_with(Vec::new); + } + + /// The settlements recorded since they were last taken, in the order they were made; `None` + /// unless they are recorded. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) fn take_settlements(&mut self) -> Option> { + self.settlements.as_mut().map(core::mem::take) + } + + /// Each pool of the start on top: what it may still draw and its net. #[cfg(test)] - pub(crate) fn top_pools(&self) -> [(u64, i64, bool); PoolId::COUNT] { + pub(crate) fn top_pools(&self) -> [(u64, i64); PoolId::COUNT] { let pools = self.entries.last().expect("a start is open").pools; - PoolId::ALL.map(|pool| { - let index = pool.index(); - (pools.remaining.get(pool), pools.net[index], pools.crossings[index]) - }) + PoolId::ALL.map(|pool| (pools.remaining.get(pool), pools.net[pool.index()])) } /// The shares the start on top started with and the pools of the start below it. @@ -678,39 +547,18 @@ impl StartLedger { let [.., caller, child] = self.entries.as_slice() else { panic!("two starts are open") }; (child.shares, caller.pools.remaining) } - - /* The differences an inspector's shape makes */ - - /// Records every difference from now on rather than panicking on it. - #[cfg(any(test, feature = "test-utils"))] - pub(crate) fn tolerate_divergences(&mut self) { - self.divergences.get_or_insert_with(Vec::new); - } - - /// The differences recorded since the last were taken; `None` unless they are recorded. - #[cfg(any(test, feature = "test-utils"))] - pub(crate) fn take_divergences(&mut self) -> Option> { - self.divergences.as_mut().map(core::mem::take) - } } #[cfg(test)] mod tests { use super::*; - use crate::{ - limit::{DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL}, - satin_gas_params, - }; - use revm::{ - context_interface::cfg::GasParams, handler::handle_reservoir_remaining_gas, - interpreter::InstructionResult, primitives::hardfork::SpecId, - }; + use crate::limit::{DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL}; /// The part of its pools and reservoir the spec's configuration has a caller keep. const KEPT: u64 = crate::evm::FRAME_KEPT_PERCENT; /// A settlement of start `id` at `depth` with `status`, which no inspector touched, of a call. - fn settled(id: u32, depth: usize, status: SettleStatus, held_reservoir: u64) -> Settlement { + fn settled(id: u32, depth: usize, status: SettleStatus) -> Settlement { Settlement { id, depth, @@ -719,28 +567,9 @@ mod tests { inspector_answer: false, gas_replaced: false, outcome_rebuilt: false, - held_reservoir, } } - /// The status a settlement reports of `result`, as revm's record reports it. - fn status_of(result: InstructionResult) -> SettleStatus { - if result.is_ok() { - SettleStatus::Ok - } else if result.is_revert() { - SettleStatus::Revert - } else { - SettleStatus::Halt - } - } - - /// A tracker with `pools`, regular gas and `reservoir`. - fn tracker(pools: PoolAmounts, reservoir: u64) -> GasTracker { - let mut gas = GasTracker::new(10_000_000, 10_000_000, reservoir); - gas.set_pools_remaining(pools); - gas - } - /// A ledger whose transaction's start, 1, has `pools`, open. fn opened(pools: PoolAmounts) -> StartLedger { let mut ledger = StartLedger::default(); @@ -759,29 +588,40 @@ mod tests { .with(KV_UPDATE_POOL, 250) .with(STATE_GROWTH_POOL, 49); - /// A child's share of each pool is what the fork forwards on the spec's schedule, the floor of - /// 98 per cent, and the caller keeps the rest; the caller keeps the part of its reservoir the - /// fork leaves it, the floor of 2 per cent, so nothing below 50. On the neutral configuration - /// the caller keeps nothing of either, as the fork forwards on a schedule that keeps nothing. + /// `amount × numerator / 100`, rounded down, computed apart from the ledger's arithmetic. + fn per_cent(amount: u64, numerator: u64) -> u64 { + u64::try_from(u128::from(amount) * u128::from(numerator) / 100).unwrap() + } + + /// A child's share of each pool is the floor of 98 per cent of what its caller has left, the + /// caller keeping the rest; a child's share of the reservoir is what the caller has less the + /// floor of its 2 per cent, so a caller keeps nothing of a reservoir below 50 and forwards 98 + /// of + /// 99. On the neutral configuration the caller keeps nothing of either. #[test] - fn test_a_start_takes_the_forks_shares_and_leaves_the_caller_its_part() { - let amsterdam = GasParams::new_spec(SpecId::AMSTERDAM); - for (kept, params) in [(KEPT, satin_gas_params()), (0, amsterdam)] { - for reservoir in [0, 1, 49, 50, 99, 100, 12_345, u64::MAX] { - for pools in [POOLS, PoolAmounts::UNLIMITED, PoolAmounts::ZERO] { - let case = format!("kept {kept}, reservoir {reservoir}, pools {pools:?}"); - let mut ledger = opened(pools); - ledger.park(kept, reservoir, 7, 9); - let mut caller = tracker(pools, reservoir); - let shares = caller.forward_to_child(¶ms); - assert_eq!(top(&ledger).remaining, caller.pools_remaining(), "{case}"); - let parked = ledger.entries[0].parked.expect("parked"); - assert_eq!(parked.shares, shares.pools, "{case}"); - assert_eq!(parked.kept_reservoir, caller.reservoir(), "{case}"); - assert_eq!((parked.charge, parked.allowance), (7, 9), "{case}"); + fn test_a_start_takes_its_shares_and_leaves_the_caller_its_part() { + for (kept, forwarded) in [(KEPT, 98), (0, 100)] { + for reservoir in [0, 1, 49, 50, 99, 100, 149, 12_345, u64::MAX] { + let share = reservoir_share(reservoir, kept); + assert_eq!(share, reservoir - per_cent(reservoir, 100 - forwarded), "{reservoir}"); + } + for pools in [POOLS, PoolAmounts::UNLIMITED, PoolAmounts::ZERO] { + let case = format!("kept {kept}, pools {pools:?}"); + let mut ledger = opened(pools); + ledger.park(kept, 7, 9); + let parked = ledger.entries[0].parked.expect("parked"); + for pool in PoolId::ALL { + let share = per_cent(pools.get(pool), forwarded); + assert_eq!(parked.shares.get(pool), share, "{case}: {pool:?}"); + let left = top(&ledger).remaining.get(pool); + assert_eq!(left, pools.get(pool) - share, "{case}: {pool:?}"); } + assert_eq!((parked.charge, parked.allowance), (7, 9), "{case}"); } } + assert_eq!(reservoir_share(99, KEPT), 98); + assert_eq!(reservoir_share(49, KEPT), 49); + assert_eq!(per_cent(99, 98), 97, "a pool's share of 99 is rounded down"); } /// What a start owes is the frame's own scratch: the split that opens it takes it, a start @@ -790,9 +630,9 @@ mod tests { #[test] fn test_a_dropped_start_loses_its_shares_and_the_next_start_parks_over_it() { let mut ledger = opened(POOLS); - ledger.park(KEPT, 0, 1, 0); + ledger.park(KEPT, 1, 0); let after_first = top(&ledger).remaining; - ledger.park(KEPT, 0, 2, 0); + ledger.park(KEPT, 2, 0); let parked = ledger.entries[0].parked.expect("parked"); assert_eq!(parked.charge, 2, "the second start's"); for pool in PoolId::ALL { @@ -804,40 +644,49 @@ mod tests { assert_eq!(ledger.entries[0].parked, None, "taken"); assert_eq!(ledger.entries[1].shares, parked.shares); assert_eq!(ledger.entries[1].charge, 2); + assert_eq!(ledger.charge(), 2, "the start on top's"); } - /// A child's draws settle into its caller as the fork settles them: a success hands its - /// remaining pools and its nets to the caller, a revert and a halt give its whole share back - /// and leave the caller's nets alone; a child's take-back of a caller's draw nets out on - /// success. The comparison finds nothing to part on. + /// A child's draws settle into its caller: a success hands its remaining pools and its nets to + /// the caller, a revert and a halt give its whole share back and leave the caller's nets alone; + /// a child's take-back of a caller's draw nets out on success. #[test] - fn test_a_settlement_merges_as_the_fork_does() { - let results = - [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas]; - for result in results { - let case = format!("{result:?}"); + fn test_a_settlement_merges_a_success_and_gives_a_failures_share_back() { + for status in [SettleStatus::Ok, SettleStatus::Revert, SettleStatus::Halt] { + let case = format!("{status:?}"); let mut ledger = opened(POOLS); - let mut caller = tracker(POOLS, 0); // The caller draws, then starts a child, which draws and takes back. let caller_draw = Counted::records(3, 0, false).with_growth(2, 0); ledger.draw(&caller_draw); - for pool in PoolId::ALL { - assert!(caller.record_pool(pool, caller_draw.added.get(pool))); - } - ledger.park(KEPT, 0, 0, 0); + ledger.park(KEPT, 0, 0); + let kept = top(&ledger); ledger.split(2, Some(1), 1); - let mut child = tracker(caller.forward_to_child(&satin_gas_params()).pools, 0); + let shares = ledger.entries[1].shares; let child_draw = Counted::records(5, 2, true).with_growth(1, 2); ledger.draw(&child_draw); + let child_net = PoolId::ALL.map(|pool| { + let (added, taken) = (child_draw.added.get(pool), child_draw.taken.get(pool)); + i64::try_from(added).unwrap() - i64::try_from(taken).unwrap() + }); + assert_eq!(top(&ledger).net, child_net, "{case}: the child's draws"); + assert_eq!(ledger.settle(&settled(2, 1, status)), 0, "{case}: no charge"); + let caller = top(&ledger); for pool in PoolId::ALL { - child.refill_pool(pool, child_draw.taken.get(pool)); - assert!(child.record_pool(pool, child_draw.added.get(pool))); + let index = pool.index(); + let (kept, share, net) = + (kept.remaining.get(pool), shares.get(pool), child_net[index]); + let caller_net = i64::try_from(caller_draw.added.get(pool)).unwrap(); + let (remaining, net) = if status == SettleStatus::Ok { + (kept + share.saturating_add_signed(-net), caller_net + net) + } else { + (kept + share, caller_net) + }; + assert_eq!( + (caller.remaining.get(pool), caller.net[index]), + (remaining, net), + "{case}: {pool:?}" + ); } - assert_eq!(top(&ledger), Pools::on(&child), "{case}: the child's draws"); - ledger.returning(Returning::of(&child, 0)); - handle_reservoir_remaining_gas(result, &mut caller, &mut child); - ledger.settle(&settled(2, 1, status_of(result), 0), &caller); - assert_eq!(top(&ledger), Pools::on(&caller), "{case}: the caller's"); } } @@ -860,214 +709,177 @@ mod tests { for (status, created, inspector_answer, outcome_rebuilt, refunded) in cases { let case = format!("{status:?}, {created:?}, {inspector_answer}, {outcome_rebuilt}"); let mut ledger = opened(PoolAmounts::UNLIMITED); - ledger.tolerate_divergences(); - ledger.park(KEPT, 0, 123, 0); + ledger.park(KEPT, 123, 0); ledger.split(2, Some(1), 1); - ledger.returning(Returning::of(&tracker(PoolAmounts::UNLIMITED, 0), 0)); - let settlement = Settlement { - created, - inspector_answer, - outcome_rebuilt, - ..settled(2, 1, status, 0) - }; - ledger.settle(&settlement, &tracker(PoolAmounts::UNLIMITED, 0)); - let refund = ledger - .take_divergences() - .unwrap_or_default() - .into_iter() - .find(|divergence| divergence.figure == LedgerFigure::StartChargeRefund) - .map(|divergence| divergence.ledger); - assert_eq!(refund, refunded.then_some(123), "{case}"); + let settlement = + Settlement { created, inspector_answer, outcome_rebuilt, ..settled(2, 1, status) }; + assert_eq!(ledger.settle(&settlement), if refunded { 123 } else { 0 }, "{case}"); } + // The transaction's start gives its own charge back the same way. + let mut ledger = StartLedger::default(); + ledger.park_transaction(Some(Parked::transaction(POOLS, 45))); + ledger.split(1, None, 0); + assert_eq!(ledger.settle(&settled(1, 0, SettleStatus::Halt)), 45); } /// An inspector's answer and a result whose tracker an inspector replaced settle as unlimited - /// pools with no net, as the fork settles one built with `Gas::new`; an outcome an inspector - /// rebuilt around the frame's own tracker settles on the frame's pools. + /// pools with no net, whatever the frame drew and whatever the status: the caller is left with + /// unlimited pools. An outcome an inspector rebuilt around the frame's own tracker settles on + /// the frame's pools. #[test] fn test_an_inspectors_answer_and_a_replaced_tracker_settle_as_unlimited_pools() { for (inspector_answer, gas_replaced, outcome_rebuilt) in [(true, false, false), (false, true, false), (false, false, true)] { - let case = format!("{inspector_answer}, {gas_replaced}, {outcome_rebuilt}"); - let mut ledger = opened(POOLS); - let mut caller = tracker(POOLS, 0); - ledger.park(KEPT, 0, 0, 0); - ledger.split(2, Some(1), 1); - let mut child = tracker(caller.forward_to_child(&satin_gas_params()).pools, 0); - ledger.draw(&Counted::records(1, 0, false)); - for pool in [DATA_SIZE_POOL, KV_UPDATE_POOL] { - assert!(child.record_pool(pool, ledger.entries[1].pools.net[pool.index()] as u64)); + for status in [SettleStatus::Ok, SettleStatus::Revert] { + let case = + format!("{inspector_answer}, {gas_replaced}, {outcome_rebuilt}, {status:?}"); + let mut ledger = opened(POOLS); + ledger.record_settlements(); + ledger.park(KEPT, 0, 0); + let kept = top(&ledger); + ledger.split(2, Some(1), 1); + let shares = ledger.entries[1].shares; + ledger.draw(&Counted::records(1, 0, false)); + let settlement = Settlement { + inspector_answer, + gas_replaced, + outcome_rebuilt, + ..settled(2, 1, status) + }; + ledger.settle(&settlement); + let settled = ledger.take_settlements().expect("recorded")[0]; + let caller = top(&ledger); + assert_eq!(settled.caller, caller.into(), "{case}: the record"); + if outcome_rebuilt { + let back = if status == SettleStatus::Ok { 40 } else { 0 }; + let data = + kept.remaining.get(DATA_SIZE_POOL) + shares.get(DATA_SIZE_POOL) - back; + assert_eq!(caller.remaining.get(DATA_SIZE_POOL), data, "{case}: the frame's"); + } else { + assert_eq!(settled.frame.remaining, PoolAmounts::UNLIMITED, "{case}"); + assert_eq!(settled.frame.net, [0; PoolId::COUNT], "{case}"); + assert_eq!(caller.remaining, PoolAmounts::UNLIMITED, "{case}: unlimited"); + assert_eq!(caller.net, [0; PoolId::COUNT], "{case}: no net"); + } } - let mut returned = if outcome_rebuilt { child } else { GasTracker::new(0, 0, 0) }; - ledger.returning(Returning::of(&returned, 0)); - handle_reservoir_remaining_gas(InstructionResult::Stop, &mut caller, &mut returned); - let settlement = Settlement { - inspector_answer, - gas_replaced, - outcome_rebuilt, - ..settled(2, 1, SettleStatus::Ok, 0) - }; - ledger.settle(&settlement, &caller); - assert_eq!(top(&ledger), Pools::on(&caller), "{case}"); } } - /// A precompile's draws are adopted fail-closed, as the fork adopts them: within the share they - /// are drawn, and past it the pool is emptied, the net capped at the share and the crossing - /// set — share 10, draw 11 — whatever the answer's status. A draw marked past a share is - /// adopted as one past the entry's, whatever its net: an unlimited share included, which no - /// net can pass. + /// A precompile's draws are adopted fail-closed: within the share they are drawn, and past it + /// the pool is emptied and the net capped at the share — share 10, draw 11 — whatever the + /// answer's status. A draw marked past a share is adopted as one past the entry's, whatever its + /// net: an unlimited share included, which no net can pass. #[test] fn test_a_precompiles_draws_past_its_share_are_adopted_fail_closed() { let none = ProviderDraw::default(); - for drawn in [0_i64, 4, 10, 11, -3] { - let pools = PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10); + let adopted = |share: u64, net: i64, past_a_share: bool| { let mut ledger = opened(PoolAmounts::UNLIMITED); - ledger.park(0, 0, 0, 0); - ledger.split(2, Some(1), 1); - ledger.entries[1].shares = pools; - ledger.adopt_provider_draws([ProviderDraw::of(drawn), none, none]); - let mut answer = GasTracker::new(0, 0, 0); - answer.set_pool_spent(DATA_SIZE_POOL, drawn); - answer.adopt_pool_shares(pools); - assert_eq!(top(&ledger), Pools::on(&answer), "drawn {drawn}"); - } - let past = |share: u64, net: i64, past_a_share: bool| { - let mut ledger = opened(PoolAmounts::UNLIMITED); - ledger.park(0, 0, 0, 0); + ledger.park(0, 0, 0); ledger.split(2, Some(1), 1); ledger.entries[1].shares = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, share); ledger.adopt_provider_draws([ProviderDraw { net, past_a_share }, none, none]); - let pools = top(&ledger); - ( - pools.remaining.get(DATA_SIZE_POOL), - pools.net[DATA_SIZE_POOL.index()], - pools.crossings[DATA_SIZE_POOL.index()], - ) + ledger.top_pools()[DATA_SIZE_POOL.index()] }; - assert_eq!(past(10, 11, false), (0, 10, true), "share 10, draw 11"); - assert_eq!(past(10, 10, true), (0, 10, true), "a draw a share of 10 capped at it"); + for (drawn, expected) in + [(0, (10, 0)), (4, (6, 4)), (10, (0, 10)), (11, (0, 10)), (-3, (13, -3))] + { + assert_eq!(adopted(10, drawn, false), expected, "share 10, drawn {drawn}"); + } + assert_eq!(adopted(10, 10, true), (0, 10), "a draw a share of 10 capped at it"); let unlimited = u64::MAX; - assert_eq!(past(unlimited, 7, false), (unlimited - 7, 7, false), "an unlimited share"); - assert_eq!( - past(unlimited, i64::MAX, true), - (0, i64::MAX, true), - "an unlimited share, a draw marked past a share" - ); + assert_eq!(adopted(unlimited, 7, false), (unlimited - 7, 7), "an unlimited share"); + assert_eq!(adopted(unlimited, i64::MAX, true), (0, i64::MAX), "marked past a share"); } - /// A log's history draws the allowance first and pays the rest, and what the frame returns of - /// it is compared for a frame revm built; an answer's allowance is never drawn or compared. + /// A log's history draws the allowance first and pays the rest; with no start open it pays all. #[test] - fn test_the_allowance_is_drawn_first_and_compared_for_a_built_frame() { - for built in [false, true] { - let mut ledger = opened(PoolAmounts::UNLIMITED); - ledger.tolerate_divergences(); - ledger.park(KEPT, 0, 0, 100); - ledger.split(2, Some(1), 1); - if built { - ledger.built(); - } - assert_eq!(ledger.draw_allowance(30), 0, "within it"); - assert_eq!(ledger.draw_allowance(80), 10, "past it"); - assert_eq!(ledger.draw_allowance(5), 5, "spent"); - let mut returned = tracker(PoolAmounts::UNLIMITED, 0); - returned.set_history_allowance(1); - ledger.returning(Returning::of(&returned, 0)); - ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &tracker(PoolAmounts::UNLIMITED, 0)); - let allowance = ledger - .take_divergences() - .unwrap_or_default() - .into_iter() - .find(|divergence| divergence.figure == LedgerFigure::Allowance); - let expected = built.then_some(LedgerDivergence { - start: 2, - depth: 1, - figure: LedgerFigure::Allowance, - ledger: 0, - fork: 1, - }); - assert_eq!(allowance, expected, "built {built}"); - } + fn test_the_allowance_is_drawn_first() { + let mut ledger = opened(PoolAmounts::UNLIMITED); + ledger.park(KEPT, 0, 100); + ledger.split(2, Some(1), 1); + assert_eq!(ledger.draw_allowance(30), 0, "within it"); + assert_eq!(ledger.draw_allowance(80), 10, "past it"); + assert_eq!(ledger.draw_allowance(5), 5, "spent"); + assert_eq!(StartLedger::default().draw_allowance(5), 5, "no start open"); } - /// The transaction's start resets the ledger, takes what its first frame's input parked or the - /// stand-in's unlimited pools, and settles into the transaction's gas, which holds none of its - /// pools while it runs. The lifecycle's end drops what is open. + /// The running frame's budget is its entry's pools; with no start open there is none, and a + /// draw draws nothing. + #[test] + fn test_the_budget_is_the_top_entrys() { + let mut ledger = opened(POOLS); + ledger.draw(&Counted::records(1, 0, false)); + assert_eq!(ledger.budget(DATA_SIZE_POOL), (10_000 - 40, 40)); + assert_eq!(ledger.budget(KV_UPDATE_POOL), (249, 1)); + assert_eq!(ledger.budget(STATE_GROWTH_POOL), (49, 0)); + let mut none = StartLedger::default(); + none.draw(&Counted::records(1, 0, false)); + assert_eq!(none.budget(DATA_SIZE_POOL), (u64::MAX, 0), "no frame budget"); + } + + /// The transaction's start resets the ledger and takes what its first frame's input parked or + /// the stand-in's unlimited pools; a settlement with nothing open settles nothing. The + /// lifecycle's end drops what is open. #[test] fn test_the_transactions_start_resets_the_ledger() { let mut ledger = opened(POOLS); - ledger.park(KEPT, 0, 0, 0); + ledger.park(KEPT, 0, 0); ledger.split(2, Some(1), 1); ledger.end(false); assert!(ledger.entries.is_empty(), "discarded"); ledger.split(1, None, 0); assert_eq!(top(&ledger).remaining, PoolAmounts::UNLIMITED, "the stand-in's"); - ledger.park(KEPT, 0, 0, 0); + ledger.park(KEPT, 0, 0); ledger.split(1, None, 0); assert_eq!(ledger.entries.len(), 1, "a transaction's start resets"); - let mut transaction = tracker(PoolAmounts::UNLIMITED, 0); - let mut frame = tracker(transaction.forward_all_to_child().pools, 0); - ledger.returning(Returning::of(&frame, 0)); - handle_reservoir_remaining_gas(InstructionResult::Stop, &mut transaction, &mut frame); - ledger.settle(&settled(1, 0, SettleStatus::Ok, 0), &transaction); + assert_eq!(ledger.settle(&settled(1, 0, SettleStatus::Ok)), 0); ledger.end(true); } - /// A settled lifecycle with a start open in the ledger is a broken pairing. + /// A settled lifecycle with a start open in the ledger is a broken pairing, which a debug build + /// asserts. #[test] + #[cfg(debug_assertions)] #[should_panic(expected = "the lifecycle settled with starts open in the ledger")] fn test_a_settled_end_with_a_start_open_panics() { opened(POOLS).end(true); } - /// A start that opens under another start than the ledger's top is a broken pairing. + /// A start that opens under another start than the ledger's top is a broken pairing, which a + /// debug build asserts. #[test] + #[cfg(debug_assertions)] #[should_panic(expected = "not the ledger's top")] fn test_a_start_under_another_than_the_top_panics() { let mut ledger = opened(POOLS); ledger.split(3, Some(2), 1); } - /// A difference panics, naming the start and every figure that parts. + /// A settlement of another start than the ledger's top is a broken pairing, which a debug build + /// asserts. #[test] - #[should_panic(expected = "the start ledger parts from the fork at start 2 (depth 1)")] - fn test_a_difference_panics() { + #[cfg(debug_assertions)] + #[should_panic(expected = "is not the one revm settled")] + fn test_a_settlement_of_another_start_than_the_top_panics() { let mut ledger = opened(POOLS); - ledger.park(KEPT, 1_000, 0, 0); - ledger.split(2, Some(1), 1); - ledger.returning(Returning::of(&tracker(ledger.entries[1].shares, 0), 0)); - ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &tracker(POOLS, 0)); + ledger.settle(&settled(2, 1, SettleStatus::Ok)); } - /// A ledger that tolerates differences records each, in the order of the figures, and takes the - /// fork's pools for the caller, so the next settlement compares from where the two parted. + /// A release build takes a broken pairing, which only a hook called by hand makes, without a + /// panic: a start opens on whatever is on top, a settlement settles it, one with nothing open + /// settles nothing, and a settled end with a start open drops it. #[test] - fn test_a_tolerated_difference_is_recorded_and_the_caller_takes_the_forks_pools() { + #[cfg(not(debug_assertions))] + fn test_a_broken_pairing_does_not_panic_a_release_build() { let mut ledger = opened(POOLS); - ledger.tolerate_divergences(); - ledger.park(KEPT, 1_000, 0, 0); - ledger.split(2, Some(1), 1); - let shares = ledger.entries[1].shares; - let returned = tracker(shares.with(KV_UPDATE_POOL, 7), 0); - ledger.returning(Returning::of(&returned, 5)); - let fork = tracker(POOLS.with(DATA_SIZE_POOL, 1), 0); - ledger.settle(&settled(2, 1, SettleStatus::Ok, 0), &fork); - let at = - |figure, ledger, fork| LedgerDivergence { start: 2, depth: 1, figure, ledger, fork }; - let shared = i128::from(shares.get(KV_UPDATE_POOL)); - assert_eq!( - ledger.take_divergences(), - Some(std::vec![ - at(LedgerFigure::FrameRemaining(KV_UPDATE_POOL), shared, 7), - at(LedgerFigure::CallerRemaining(DATA_SIZE_POOL), 10_000, 1), - at(LedgerFigure::KeptReservoir, 20, 0), - at(LedgerFigure::StartChargeRefund, 0, 5), - ]) - ); - assert_eq!(top(&ledger), Pools::on(&fork), "the fork's pools taken"); - assert_eq!(ledger.take_divergences(), Some(std::vec![]), "taken once"); + ledger.split(3, Some(2), 5); + assert_eq!(ledger.settle(&settled(9, 9, SettleStatus::Revert)), 0); + ledger.end(true); + assert!(ledger.entries.is_empty()); + assert_eq!(ledger.settle(&settled(1, 0, SettleStatus::Ok)), 0, "nothing open"); + ledger.split(4, Some(1), 1); + assert_eq!(ledger.entries.len(), 1, "a child with nothing under it opens unparked"); } } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 6f917d0b3..baaffb36e 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -2,7 +2,7 @@ use alloy_primitives::Bytes; use revm::{ - context_interface::cfg::gas::{GasTracker, PoolAmounts, PoolId}, + context_interface::cfg::gas::{PoolAmounts, PoolId}, handler::FrameResult, interpreter::InstructionResult, }; @@ -11,11 +11,9 @@ use revm::{ use alloc as std; use std::vec::Vec; -#[cfg(debug_assertions)] -use super::StartLedger; use super::{ - CreatorBefore, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, COUNTED, DATA_SIZE_POOL, - KV_UPDATE_POOL, STATE_GROWTH_POOL, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, + CreatorBefore, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, StartLedger, COUNTED, + DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; /// What the common execution layer tracks for the running transaction: what it keeps of the @@ -122,10 +120,9 @@ pub struct AdditionalLimit { /// The EIP-8037 reservoir the settled transaction or system call left unspent: none from where /// an execution builds its gas until it reports what it settled with. reservoir_remaining: Option, - /// In a debug build, the engine's own ledger of what each open start owes and holds, checked - /// against the fork's figures at every settlement. It is not begun with the transaction: the - /// start lifecycle drives it, from the transaction's start to the lifecycle's end. - #[cfg(debug_assertions)] + /// The engine's ledger of what each open start owes and holds: the frame budgets, the start + /// charges and the history allowances. It is not begun with the transaction: the start + /// lifecycle drives it, from the transaction's start to the lifecycle's end. ledger: StartLedger, } @@ -581,12 +578,12 @@ impl AdditionalLimit { LimitCheck::WithinLimit } - /// The verdict on `counted` kept on a frame whose pools `gas` holds: in each counted dimension - /// in order, the frame's budget, then the transaction's limit; the first crossing is the - /// verdict. `held` holds the transaction to its limits whatever `counted` adds; otherwise a - /// dimension `counted` leaves alone crosses nothing and is not looked at - /// ([`Counted::touches`]). - fn check(&self, gas: &GasTracker, counted: &Counted, held: bool) -> LimitCheck { + /// The verdict on `counted` kept on the running frame, whose budgets are the start ledger's top + /// entry: in each counted dimension in order, the frame's budget, then the transaction's limit; + /// the first crossing is the verdict. `held` holds the transaction to its limits whatever + /// `counted` adds; otherwise a dimension `counted` leaves alone crosses nothing and is not + /// looked at ([`Counted::touches`]). + fn check(&self, counted: &Counted, held: bool) -> LimitCheck { for kind in COUNTED { let Some(pool) = kind.pool() else { continue }; if !held && !counted.touches(pool) { @@ -597,9 +594,8 @@ impl AdditionalLimit { continue; } let rise = counted.rise(pool); - let remaining = gas.pool_remaining(pool); + let (remaining, spent) = self.ledger.budget(pool); if rise > remaining as i128 { - let spent = gas.pool_spent(pool); let check = self.budget_crossed(kind, remaining, spent, rise as u64); if check.exceeded_limit() { return check; @@ -613,45 +609,25 @@ impl AdditionalLimit { LimitCheck::WithinLimit } - /// Counts what the frame whose pools `gas` holds keeps of `counted`, held to the frame's - /// budgets and the transaction's limits in the order [`check`](Self::check) holds them: the - /// amounts `counted` takes back go back to each pool first, and the amounts it adds are drawn. - /// A crossing counts nothing and draws nothing, and is the stop the frame reverts with. A - /// count that adds nothing and takes nothing holds nothing. - pub(crate) fn draw(&mut self, gas: &mut GasTracker, counted: &Counted) -> LimitCheck { + /// Counts what the running frame keeps of `counted`, held to the frame's budgets and the + /// transaction's limits in the order [`check`](Self::check) holds them, and draws it on the + /// frame's budgets, the start ledger's top entry: the amounts `counted` takes back go back to + /// each pool first, and the amounts it adds are drawn. A crossing counts nothing and draws + /// nothing, and is the stop the frame reverts with. A count that adds nothing and takes nothing + /// holds nothing. + pub(crate) fn draw(&mut self, counted: &Counted) -> LimitCheck { if counted.is_none() { return LimitCheck::WithinLimit; } - let check = self.check(gas, counted, false); + let check = self.check(counted, false); if check.exceeded_limit() { return check; } - Self::apply(gas, counted); - self.count(counted); - #[cfg(debug_assertions)] self.ledger.draw(counted); + self.count(counted); LimitCheck::WithinLimit } - /// Draws `counted` on the pools `gas` holds, which the checks made sure can pay it; a pool it - /// leaves alone is not visited. - fn apply(gas: &mut GasTracker, counted: &Counted) { - for pool in PoolId::ALL { - if !counted.touches(pool) { - continue; - } - gas.refill_pool(pool, counted.taken.get(pool)); - let drew = gas.record_pool(pool, counted.added.get(pool)); - debug_assert!( - drew || gas.pool_remaining(pool) == u64::MAX, - "the checks admit the draw" - ); - if !drew { - gas.clear_pool_crossing(pool); - } - } - } - /// Adds `counted` to what the frames keep. /// /// What a frame takes back the transaction's frames counted: a record or a byte taken back was @@ -699,8 +675,8 @@ impl AdditionalLimit { } /// Holds the start revm just decided — a frame it built, or a call it answered with a success — - /// whose frame's pools `gas` holds, to the limits, and counts `counted`, the records, state - /// growth and transfer log it made, read off the journal, on those pools + /// whose budgets are the start ledger's top entry, to the limits, and counts `counted`, the + /// records, state growth and transfer log it made, read off the journal, on those budgets /// ([`draw`](Self::draw)): the verdict is the stop the frame returns before it runs, or the /// one its answer gives way to. An answer that failed kept nothing and is not held. `credit` is /// what the start's caller gets back once the frame returned with its start kept. @@ -710,20 +686,13 @@ impl AdditionalLimit { /// ([`hold_caller`](Self::hold_caller)), and the caller a deposit-like transaction created is /// counted unchecked ([`count_created_caller`](Self::count_created_caller)); a start is where /// a frame first meets it. - pub(crate) fn count_start( - &mut self, - gas: &mut GasTracker, - counted: &Counted, - credit: u64, - ) -> LimitCheck { - let check = self.check(gas, counted, true); + pub(crate) fn count_start(&mut self, counted: &Counted, credit: u64) -> LimitCheck { + let check = self.check(counted, true); if check.exceeded_limit() { return check; } - Self::apply(gas, counted); - self.count(counted); - #[cfg(debug_assertions)] self.ledger.draw(counted); + self.count(counted); if let Some(start) = self.decided.last_mut() { start.credit = credit; } @@ -840,9 +809,13 @@ impl AdditionalLimit { /* The start ledger */ - /// The engine's own ledger of what each open start owes and holds, which a debug build keeps - /// beside the fork's figures and checks against them. - #[cfg(debug_assertions)] + /// The engine's ledger of what each open start owes and holds. + pub(crate) const fn ledger(&self) -> &StartLedger { + &self.ledger + } + + /// The engine's ledger of what each open start owes and holds, for the start lifecycle and the + /// sites that park, cap and settle a start. pub(crate) const fn ledger_mut(&mut self) -> &mut StartLedger { &mut self.ledger } @@ -978,6 +951,16 @@ mod tests { ); } + /// A layer whose running frame, the transaction's own, starts with `pools` on the start ledger. + fn running(limits: EvmTxRuntimeLimits, class: TxClass, pools: PoolAmounts) -> AdditionalLimit { + let mut layer = AdditionalLimit::new(limits); + layer.begin_transaction(class, 0); + let ledger = layer.ledger_mut(); + ledger.park_transaction(Some(super::super::Parked::transaction(pools, 0))); + ledger.split(1, None, 0); + layer + } + /// A frame budget admits a count that uses exactly what the pool holds and stops one more: /// the boundary is the pool's remaining amount, in each counted pool, with the transaction's /// limit out of the way so only the frame's budget decides. @@ -988,17 +971,16 @@ mod tests { for (added, within) in [(remaining - 1, true), (remaining, true), (remaining + 1, false)] { - let mut layer = AdditionalLimit::new(EvmTxRuntimeLimits::no_limits()); - layer.begin_transaction(TxClass::Ordinary, 0); - let mut gas = GasTracker::new(1_000, 1_000, 0); - gas.set_pools_remaining(PoolAmounts::ZERO.with(pool, remaining)); + let pools = PoolAmounts::ZERO.with(pool, remaining); + let mut layer = running(EvmTxRuntimeLimits::no_limits(), TxClass::Ordinary, pools); let mut counted = Counted::NONE; counted.added.set(pool, added); - let verdict = layer.draw(&mut gas, &counted); + let verdict = layer.draw(&counted); let case = format!("{pool:?}, adds {added} to {remaining}"); + let left = layer.ledger().budget(pool).0; if within { assert_eq!(verdict, LimitCheck::WithinLimit, "{case}"); - assert_eq!(gas.pool_remaining(pool), remaining - added, "{case}"); + assert_eq!(left, remaining - added, "{case}"); assert_eq!( layer.kept.net[pool.index()], i64::try_from(added).unwrap(), @@ -1010,26 +992,35 @@ mod tests { matches!(verdict, LimitCheck::ExceedsLimit { frame_local: true, .. }), "{case}: {verdict:?}" ); - assert_eq!(gas.pool_remaining(pool), remaining, "{case}: nothing drawn"); + assert_eq!(left, remaining, "{case}: nothing drawn"); assert_eq!(layer.kept.net[pool.index()], 0, "{case}: nothing counted"); } } } } + /// The running frame's budgets, each pool's remaining and net. + fn budgets(layer: &AdditionalLimit) -> [(u64, i64); PoolId::COUNT] { + PoolId::ALL.map(|pool| layer.ledger().budget(pool)) + } + /// `draw` as it was before it learned to leave alone the pools a count does not touch: every - /// pool's budget and every dimension's limit checked off a snapshot of the pools, and every - /// pool drawn, refilled and counted. The reference [`draw`](AdditionalLimit::draw) is held to. + /// pool's budget and every dimension's limit checked off a snapshot of the budgets, and every + /// pool drawn, refilled and counted, on a copy of the budgets it answers. The reference + /// [`draw`](AdditionalLimit::draw) is held to. fn draw_by_every_pool( limit: &mut AdditionalLimit, - gas: &mut GasTracker, counted: &Counted, - ) -> LimitCheck { + ) -> (LimitCheck, [(u64, i64); PoolId::COUNT]) { + let mut pools = budgets(limit); if counted.is_none() { - return LimitCheck::WithinLimit; + return (LimitCheck::WithinLimit, pools); } - let remaining = gas.pools_remaining(); - let spent = PoolId::ALL.map(|pool| gas.pool_spent(pool)); + let remaining = PoolAmounts::ZERO + .with(DATA_SIZE_POOL, pools[DATA_SIZE_POOL.index()].0) + .with(KV_UPDATE_POOL, pools[KV_UPDATE_POOL.index()].0) + .with(STATE_GROWTH_POOL, pools[STATE_GROWTH_POOL.index()].0); + let spent = pools.map(|(_, net)| net); for kind in COUNTED { let Some(pool) = kind.pool() else { continue }; let rise = counted.rise(pool); @@ -1041,18 +1032,22 @@ mod tests { rise as u64, ); if check.exceeded_limit() { - return check; + return (check, pools); } } let check = limit.transaction_crossed(kind, counted, false); if check.exceeded_limit() { - return check; + return (check, pools); } } for pool in PoolId::ALL { - gas.refill_pool(pool, counted.taken.get(pool)); - if !gas.record_pool(pool, counted.added.get(pool)) { - gas.clear_pool_crossing(pool); + let (left, net) = &mut pools[pool.index()]; + let (added, taken) = (counted.added.get(pool), counted.taken.get(pool)); + *left = left.saturating_add(taken); + *net = net.saturating_sub_unsigned(taken); + if let Some(after) = left.checked_sub(added) { + *left = after; + *net = net.saturating_add_unsigned(added); } let net = &mut limit.kept.net[pool.index()]; *net = net @@ -1060,7 +1055,7 @@ mod tests { .saturating_sub_unsigned(counted.taken.get(pool)); } limit.kept.transfer_logs += u64::from(counted.transfer_log); - LimitCheck::WithinLimit + (LimitCheck::WithinLimit, pools) } /// A draw that visits only the pools its count touches decides, draws and counts exactly as @@ -1120,26 +1115,27 @@ mod tests { continue; } // Two drawn already, so a frame's net is not zero. - let mut gas = GasTracker::new(1_000, 1_000, 0); - gas.set_pools_remaining( + let mut layer = layer.clone(); + let ledger = layer.ledger_mut(); + let start = super::super::Parked::transaction( PoolAmounts::ZERO .with(DATA_SIZE_POOL, pa + 2) .with(KV_UPDATE_POOL, pb + 2) .with(STATE_GROWTH_POOL, pc + 2), + 0, ); + ledger.park_transaction(Some(start)); + ledger.split(1, None, 0); + let mut two = Counted::NONE; for pool in PoolId::ALL { - assert!(gas.record_pool(pool, 2)); + two.added.set(pool, 2); } + ledger.draw(&two); let (mut by_touched, mut by_every) = (layer.clone(), layer.clone()); - let (mut gas_touched, mut gas_every) = (gas, gas); - let verdict = - by_touched.draw(&mut gas_touched, &counted); - let reference = draw_by_every_pool( - &mut by_every, - &mut gas_every, - &counted, - ); + let verdict = by_touched.draw(&counted); + let (reference, pools) = + draw_by_every_pool(&mut by_every, &counted); let case = format!( "{class:?}, limit {tx_limit}, kept {kept}, \ {counted:?}, pools {pa}/{pb}/{pc}" @@ -1149,24 +1145,7 @@ mod tests { by_touched.kept, by_every.kept, "{case}" ); - assert_eq!( - gas_touched.pools_remaining(), - gas_every.pools_remaining(), - "{case}" - ); - for pool in PoolId::ALL { - assert_eq!( - ( - gas_touched.pool_spent(pool), - gas_touched.pool_crossing(pool) - ), - ( - gas_every.pool_spent(pool), - gas_every.pool_crossing(pool) - ), - "{case}" - ); - } + assert_eq!(budgets(&by_touched), pools, "{case}"); cases += 1; } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 95f1dc9cd..42ce58bea 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -179,16 +179,14 @@ //! recipient is the block beneficiary or a fee vault pays a record the body already bound. It is //! an over-charge, never an under-charge. -#[cfg(debug_assertions)] mod ledger; #[allow(clippy::module_inception)] mod limit; mod record; -#[cfg(all(debug_assertions, any(test, feature = "test-utils")))] -pub use ledger::{LedgerDivergence, LedgerFigure}; -#[cfg(debug_assertions)] -pub(crate) use ledger::{Parked, ProviderDraw, Returning, StartLedger}; +pub(crate) use ledger::{reservoir_share, Parked, ProviderDraw, StartLedger}; +#[cfg(any(test, feature = "test-utils"))] +pub use ledger::{LedgerPools, LedgerSettlement}; pub use limit::AdditionalLimit; pub(crate) use limit::{Counted, TxClass}; #[cfg(test)] diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ff5e16ff2..ef44e6c84 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -11,10 +11,7 @@ use alloy_sol_types::SolCall; use revm::{ context::{Cfg, ContextError, ContextTr, JournalTr}, context_interface::{ - cfg::{ - gas::{PoolAmounts, StartCharge}, - GasId, StateGasCharge, StateGasSite, - }, + cfg::{GasId, StateGasCharge, StateGasSite}, Host, }, handler::{EthFrame, FrameResult}, @@ -188,24 +185,20 @@ pub(crate) fn start( return Ok(InterpreterAction::new_return(result, output, *gas)); } }; - // The creation's shares of the call's reservoir and pools are taken out of the call, as a - // `CREATE` opcode's are: the creation's return adds what it left back to what the call kept. - #[cfg(debug_assertions)] - ctx.park_owed(gas.reservoir(), deployment.on_frame_record_charge, 0); - let shares = gas.tracker_mut().forward_to_child(ctx.gas_params()); + // The creation's shares of the call's reservoir and budgets are taken out of the call, and its + // start charge parked, as a `CREATE` opcode's are: the creation's return adds what it left of + // the reservoir back to what the call kept, and its settlement what it left of its budgets. + let reservoir = ctx.forward_start(gas.tracker_mut(), deployment.on_frame_record_charge, 0); let mut create = CreateInputs::new( deployment.signer, CreateScheme::Custom { address: deployment.deploy_address }, deployment.value, deployment.init_code, deployment.gas_limit, - shares.reservoir, + reservoir, ); create.set_charged_create_state_gas(deployment.charged_create_state_gas); create.set_charged_state_gas_address(deployment.deploy_address); - create - .set_charged_start(StartCharge::new(deployment.on_frame_record_charge, PoolAmounts::ZERO)); - create.set_pool_shares(shares.pools); ctx.keyless_creation = Some(Started { deploy_address: deployment.deploy_address, signer: deployment.signer, diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 983274197..5541f4409 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -170,7 +170,7 @@ pub(crate) fn settle( if started.signer_nonce > 0 && nonce == started.signer_nonce + 1 { take_back_bump(ctx, gas, &started)?; } - let stop = bumped.and_then(|signer| hold_creator(ctx, gas.tracker_mut(), &signer)); + let stop = bumped.and_then(|signer| hold_creator(ctx, &signer)); Ok((Returned { started, creation }, stop)) } diff --git a/crates/mega-evm/src/test_utils/ledger.rs b/crates/mega-evm/src/test_utils/ledger.rs index f3bd7301a..39c4f185c 100644 --- a/crates/mega-evm/src/test_utils/ledger.rs +++ b/crates/mega-evm/src/test_utils/ledger.rs @@ -1,11 +1,12 @@ -//! The differences a debug build's start ledger finds between its figures and the fork's, for a -//! test that runs an inspector shape whose figures are accepted to change. +//! The start ledger's settlements, for a test that reads the frame budgets and start charges the +//! engine settled. //! -//! The start ledger panics on any difference. An inspector that restores a snapshot of a running -//! tracker, replaces an interpreter, answers or rewrites with pools, an allowance or a start charge -//! it set, copies a tracker or an outcome from another start, or builds an input itself, moves the -//! fork's figures where the ledger, which keeps them off the tracker, does not follow: a test that -//! runs one tolerates the differences, then asserts each of them. +//! The engine keeps a frame's budgets, its start charge and its history allowance on its own start +//! ledger, not on the frame's gas: a test reads them as the ledger settled each start, once the +//! transaction ran. An inspector's answer and a result whose gas an inspector replaced settle as +//! unlimited budgets whatever pools the inspector's gas carries, and a tracker an inspector +//! restores from a snapshot leaves the ledger's draws where they were, which is what a test of +//! such an inspector asserts. #[cfg(not(feature = "std"))] use alloc as std; @@ -14,20 +15,20 @@ use std::vec::Vec; use crate::{ExternalEnvTypes, MegaContext}; use revm::Database; -pub use crate::limit::{LedgerDivergence, LedgerFigure}; +pub use crate::limit::{LedgerPools, LedgerSettlement}; -/// Has `ctx`'s start ledger record every difference from now on rather than panic on it, and take -/// the fork's pools where a caller's differ. -pub fn tolerate_start_ledger_divergences( +/// Has `ctx`'s start ledger record every settlement from now on, across transactions, until they +/// are taken. +pub fn record_start_ledger_settlements( ctx: &mut MegaContext, ) { - ctx.additional_limit.ledger_mut().tolerate_divergences(); + ctx.additional_limit.ledger_mut().record_settlements(); } -/// The differences `ctx`'s start ledger recorded since they were last taken, in the order it found -/// them; none when it was not told to tolerate them. -pub fn take_start_ledger_divergences( +/// The settlements `ctx`'s start ledger recorded since they were last taken, in the order it made +/// them, innermost first within a transaction; none when it was not told to record them. +pub fn take_start_ledger_settlements( ctx: &mut MegaContext, -) -> Vec { - ctx.additional_limit.ledger_mut().take_divergences().unwrap_or_default() +) -> Vec { + ctx.additional_limit.ledger_mut().take_settlements().unwrap_or_default() } diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index 432c88bc6..d911b743a 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -4,7 +4,6 @@ mod bytes; mod database; mod evm; mod inspectors; -#[cfg(debug_assertions)] mod ledger; mod logs; mod neutral; @@ -18,7 +17,6 @@ pub use bytes::*; pub use database::*; pub use evm::*; pub use inspectors::*; -#[cfg(debug_assertions)] pub use ledger::*; pub use logs::*; pub use neutral::*; diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 487e7da7f..cde71b57c 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -3,19 +3,18 @@ use alloy_evm::Evm; use alloy_op_evm::OpTx; use alloy_primitives::{Address, Bytes, TxKind, B256, U256}; -#[cfg(debug_assertions)] -use mega_evm::test_utils::{LedgerDivergence, LedgerFigure}; use mega_evm::{ active_satin_prices, - test_utils::{note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder}, + test_utils::{ + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, LedgerSettlement, + }, EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionOutcome, }; -#[cfg(debug_assertions)] -use revm::interpreter::{PoolAmounts, PoolId}; use revm::{ bytecode::opcode::{PUSH0, RETURN}, context::{result::ResultAndState, BlockEnv, TxEnv}, + interpreter::{PoolAmounts, PoolId}, Database, }; @@ -301,57 +300,23 @@ pub(crate) fn body_history(calldata_len: u64) -> u64 { history(mega_evm::TX_BODY_SIZE + calldata_len) } -/// The pools the transaction's own frame starts with under `limits` when `tx` counts nothing -/// before it but its body: what each limit leaves once the body is counted, the data size under the -/// frame cap. -#[cfg(debug_assertions)] -pub(crate) fn first_frame_pools(limits: &EvmTxRuntimeLimits, tx: &MegaTransaction) -> PoolAmounts { - let data_size = limits.tx_data_size_limit.saturating_sub(mega_evm::transaction_body_bytes(tx)); - PoolAmounts::ZERO - .with(PoolId::new(0), data_size.min(limits.frame_data_size_limit)) - .with(PoolId::new(1), limits.tx_kv_update_limit) - .with(PoolId::new(2), limits.tx_state_growth_limit) -} - -/// The share of each of `caller`'s pools a frame it starts begins with: 98/100 of each, rounded -/// down. -#[cfg(debug_assertions)] -pub(crate) fn frame_shares(caller: PoolAmounts) -> PoolAmounts { - let share = |amount: u64| { - let share = u128::from(amount) * u128::from(mega_evm::FRAME_DATA_SHARE_NUMERATOR) / - u128::from(mega_evm::FRAME_DATA_SHARE_DENOMINATOR); - u64::try_from(share).expect("a share is less than the pool") - }; - PoolId::ALL.into_iter().fold(caller, |shares, pool| shares.with(pool, share(caller.get(pool)))) -} - -/// What a debug build's start ledger records where an inspector answered start `start`, at -/// `depth`, on gas that carries the shares its input was forwarded, `shares`, as the engine's -/// `untouched_call_gas` and `untouched_create_gas` build it: an answer with pools the inspector -/// set, whose pools stop being taken once the engine reads its ledger, the pool fields leaving the -/// frame's input and gas. The ledger settles an inspector's answer at -/// unlimited pools, so it parts from the fork on the answer's own pools wherever a share is -/// limited, and on its caller's once it settled, wherever the caller, which the fork gives back -/// the shares and so leaves with what it held before the start, `caller`, is limited. -#[cfg(debug_assertions)] -pub(crate) fn answered_on_its_shares( +/// Asserts that the start ledger settled start `start`, at `depth`, an inspector's answer, at +/// unlimited budgets, whatever pools the inspector's gas carried — the engine's own +/// `untouched_call_gas` and `untouched_create_gas` included, which carry none of the start's +/// budgets — and left the answer's caller with unlimited budgets: the frame's pools as it settled +/// and its caller's once it settled into them, all three unlimited, with no net drawn on the +/// answer. +pub(crate) fn assert_answered_at_unlimited_budgets( + settlements: &[LedgerSettlement], start: u32, depth: usize, - caller: PoolAmounts, - shares: PoolAmounts, -) -> Vec { - let parts = |amounts: PoolAmounts, figure: fn(PoolId) -> LedgerFigure| { - PoolId::ALL.into_iter().filter(move |pool| amounts.get(*pool) != u64::MAX).map( - move |pool| LedgerDivergence { - start, - depth, - figure: figure(pool), - ledger: u64::MAX.into(), - fork: amounts.get(pool).into(), - }, - ) - }; - parts(shares, LedgerFigure::FrameRemaining) - .chain(parts(caller, LedgerFigure::CallerRemaining)) - .collect() +) { + let settled = settlements + .iter() + .find(|settled| settled.start == start) + .unwrap_or_else(|| panic!("start {start} settled: {settlements:?}")); + assert_eq!(settled.depth, depth, "start {start}"); + assert_eq!(settled.frame.remaining, PoolAmounts::UNLIMITED, "start {start}: the answer's"); + assert_eq!(settled.frame.net, [0; PoolId::COUNT], "start {start}: the answer's"); + assert_eq!(settled.caller.remaining, PoolAmounts::UNLIMITED, "start {start}: its caller's"); } diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 0598b1c60..39d808df8 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -44,11 +44,11 @@ use revm::{ Inspector, }; -#[cfg(debug_assertions)] -use crate::common::{answered_on_its_shares, first_frame_pools, frame_shares}; -use crate::common::{call, call_with_data, context, create, execute, runs_at_measurement_prices}; -#[cfg(debug_assertions)] -use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; +use crate::common::{ + assert_answered_at_unlimited_budgets, call, call_with_data, context, create, execute, + runs_at_measurement_prices, +}; +use mega_evm::test_utils::{record_start_ledger_settlements, take_start_ledger_settlements}; const CALLER: Address = address!("0000000000000000000000000000000000a00000"); const CALLEE: Address = address!("0000000000000000000000000000000000a00001"); @@ -258,18 +258,11 @@ fn test_a_creation_answered_without_running_appends_no_code() { let db = callee_running(creating(BytecodeBuilder::default(), &deploying())); let tx = call(CALLER, CALLEE, U256::ZERO, gas_limit); let mut evm = MegaEvm::new(context(db)).with_inspector(AnswersCreations); - #[cfg(debug_assertions)] - tolerate_start_ledger_divergences(evm.ctx_mut()); + record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm.execute_transaction(tx.clone()).expect("the transaction is valid"); - // The answer carries the creation's shares, pools the inspector set, which a debug build's - // start ledger does not take: it settles an inspector's answer at unlimited pools, and - // parts from the fork. - #[cfg(debug_assertions)] - { - let caller = first_frame_pools(&EvmTxRuntimeLimits::default(), &tx); - let expected = answered_on_its_shares(2, 1, caller, frame_shares(caller)); - assert_eq!(take_start_ledger_divergences(evm.ctx_mut()), expected); - } + // The answer is built on the engine's untouched gas, and the start ledger settles an + // inspector's answer at unlimited budgets, which its caller is left with. + assert_answered_at_unlimited_budgets(&take_start_ledger_settlements(evm.ctx_mut()), 2, 1); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.usage.write_records, 0, "no bump, no record"); diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index fc70f3a66..54d720be6 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -42,13 +42,7 @@ use crate::{ common::{body_history, call, context, reservoir_share}, salt::entry, }; -#[cfg(debug_assertions)] -use mega_evm::test_utils::{ - take_start_ledger_divergences, tolerate_start_ledger_divergences, LedgerDivergence, - LedgerFigure, -}; -#[cfg(debug_assertions)] -use revm::interpreter::PoolId; +use mega_evm::test_utils::{record_start_ledger_settlements, take_start_ledger_settlements}; sol! { /// The cheatcodes these tests drive, as Foundry's `Vm` interface declares them. @@ -314,31 +308,20 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { let (worked, answered) = { let tx = call(CALLER, TEST, U256::ZERO, GAS_LIMIT); let mut evm = MegaEvm::new(context(db(paused(true)))).with_inspector(Cheatcodes::default()); - #[cfg(debug_assertions)] - tolerate_start_ledger_divergences(evm.ctx_mut()); + record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm.execute_transaction(tx).expect("valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - // The paused region's slot is drawn on the frame's pools, and the snapshot `step` puts - // back before the next instruction takes the draw back off the frame's gas: a tracker - // restored from a snapshot, which cannot restore a figure kept off it. A debug build's - // start ledger keeps the pools off the tracker and keeps the record's draw, and parts from - // the fork in `TEST`'s nets where the call to `resumeGasMetering`, start 3, settles; the - // pools themselves both read unlimited, the cheatcode's answer on `Gas::new` having - // carried unlimited pools back to `TEST` at the pause. - #[cfg(debug_assertions)] - { - let net = |pool, drawn: u64| LedgerDivergence { - start: 3, - depth: 1, - figure: LedgerFigure::CallerNet(PoolId::new(pool)), - ledger: drawn.into(), - fork: 0, - }; - assert_eq!( - take_start_ledger_divergences(evm.ctx_mut()), - [net(0, WRITE_RECORD_SIZE), net(1, 1), net(2, 1)] - ); - } + // The paused region's slot is drawn on `TEST`'s budgets, and the snapshot `step` puts + // back before the next instruction restores the frame's gas: a tracker restored from a + // snapshot, which cannot restore a figure kept off it. The start ledger keeps the budgets + // off the tracker and keeps the record's draw, which `TEST`'s nets hold where the call to + // `resumeGasMetering`, start 3, settles into them: one record of data size, one KV update + // and one new slot. The budgets themselves read unlimited, the cheatcode's answer at the + // pause having left `TEST` with unlimited budgets. + let settlements = take_start_ledger_settlements(evm.ctx_mut()); + let resumed = settlements.iter().find(|settled| settled.start == 3).expect("settled"); + assert_eq!((resumed.depth, resumed.caller.net), (1, [WRITE_RECORD_SIZE as i64, 1, 1])); + assert_eq!(resumed.caller.remaining, revm::interpreter::PoolAmounts::UNLIMITED); (outcome, evm.inspector().answered) }; assert_eq!(answered, 2); diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index ac1bc2519..c731c53f4 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -29,11 +29,10 @@ use revm::{ Database, Inspector, }; -#[cfg(debug_assertions)] -use crate::common::{answered_on_its_shares, first_frame_pools, frame_shares}; -use crate::common::{body_history, call, context, reservoir_share}; -#[cfg(debug_assertions)] -use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; +use crate::common::{ + assert_answered_at_unlimited_budgets, body_history, call, context, reservoir_share, +}; +use mega_evm::test_utils::{record_start_ledger_settlements, take_start_ledger_settlements}; const CALLER: Address = address!("0000000000000000000000000000000000e00000"); const A: Address = address!("0000000000000000000000000000000000e00001"); @@ -397,24 +396,13 @@ fn test_an_answer_settles_on_the_gas_it_is_built_on() { let tx = call(CALLER, A, U256::ZERO, gas_limit); let mut evm = MegaEvm::new(context(a_calls_b()).with_tx_runtime_limits(limits)) .with_inspector(inspector); - #[cfg(debug_assertions)] - tolerate_start_ledger_divergences(evm.ctx_mut()); - let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); - // An answer on `Gas::new` carries unlimited pools, as the start ledger settles an - // inspector's answer; one on the call's shares carries pools the inspector set, which - // the ledger does not take, and it parts from the fork where `A`'s pool is limited. - #[cfg(debug_assertions)] - { - let expected = match gas { - AnswerGas::Fresh => Vec::new(), - AnswerGas::Untouched | AnswerGas::Charged => { - let caller = first_frame_pools(&limits, &tx); - answered_on_its_shares(2, 1, caller, frame_shares(caller)) - } - }; - let divergences = take_start_ledger_divergences(evm.ctx_mut()); - assert_eq!(divergences, expected, "{result:?}, {gas:?}"); - } + record_start_ledger_settlements(evm.ctx_mut()); + let outcome = evm.execute_transaction(tx).expect("a valid transaction"); + // The start ledger settles an inspector's answer at unlimited budgets whatever pools + // its gas carries — none on `Gas::new`, the call's shares set on it — and leaves `A` + // with unlimited budgets. + let settlements = take_start_ledger_settlements(evm.ctx_mut()); + assert_answered_at_unlimited_budgets(&settlements, 2, 1); outcome }; let untouched = answer(AnswerGas::Untouched); diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index 753d2f967..66c366443 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -38,14 +38,14 @@ use revm::{ Inspector, }; -#[cfg(debug_assertions)] -use crate::common::{answered_on_its_shares, first_frame_pools, frame_shares}; -use crate::salt::{ - create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, value_call, - SaltEnvs, CALLER, CONTRACT, EMPTY, +use crate::{ + common::assert_answered_at_unlimited_budgets, + salt::{ + create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, + value_call, SaltEnvs, CALLER, CONTRACT, EMPTY, + }, }; -#[cfg(debug_assertions)] -use mega_evm::test_utils::{take_start_ledger_divergences, tolerate_start_ledger_divergences}; +use mega_evm::test_utils::{record_start_ledger_settlements, take_start_ledger_settlements}; /// A contract `CONTRACT` calls. const CALLEE: Address = address!("0000000000000000000000000000000000c00010"); @@ -132,11 +132,9 @@ where } /// [`inspected`] under `inspector`, which answers start `start`, at `depth`, on the gas its input -/// carries, the shares of its caller's pools included: an answer with pools the inspector set, -/// which a debug build's start ledger does not take. The ledger, which settles an inspector's -/// answer at unlimited pools, records where it parts from the fork, and each part is asserted -/// ([`answered_on_its_shares`]): the caller is the transaction's own frame, or the transaction, -/// which holds its first frame's pools when the start is made. +/// carries: the start ledger settles an inspector's answer at unlimited budgets, whatever pools +/// its gas carries, and leaves its caller — the transaction's own frame, or the transaction — +/// with unlimited budgets ([`assert_answered_at_unlimited_budgets`]). fn answered( db: MemoryDatabase, envs: SaltEnvs, @@ -148,21 +146,13 @@ where I: Inspector, EthInterpreter>, { let mut evm = MegaEvm::new(salt_context(db, envs)).with_inspector(inspector); - #[cfg(debug_assertions)] - tolerate_start_ledger_divergences(evm.ctx_mut()); - let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); - #[cfg(debug_assertions)] - { - let caller = first_frame_pools(&EvmTxRuntimeLimits::default(), &tx); - let shares = if depth == 0 { caller } else { frame_shares(caller) }; - assert_eq!( - take_start_ledger_divergences(evm.ctx_mut()), - answered_on_its_shares(start, depth, caller, shares), - "start {start} at depth {depth}" - ); - } - #[cfg(not(debug_assertions))] - let _ = (start, depth); + record_start_ledger_settlements(evm.ctx_mut()); + let outcome = evm.execute_transaction(tx).expect("a valid transaction"); + assert_answered_at_unlimited_budgets( + &take_start_ledger_settlements(evm.ctx_mut()), + start, + depth, + ); outcome } diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index 7405a9559..7a63fbaad 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -4,7 +4,7 @@ Generated by `cargo test -p mega-evm --test satin`; the test compares this file ## Schedule entries -Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte, deposited code and a value call's history allowance priced at `MegaETH`'s cost per history byte, and a frame forwarded 98 per cent of what its caller has left of its regular gas, of its reservoir and of its data-size, KV-update and state-growth budgets; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those applies. +Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte, deposited code priced at `MegaETH`'s cost per history byte, and a frame forwarded 98 per cent of what its caller has left of its regular gas; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those applies. A frame's share of its caller's reservoir and of its data-size, KV-update and state-growth budgets, 98 per cent of what the caller has left, and the history allowance a value call gives its frame are the engine's, taken where the frame starts, and are in no entry: Satin keeps Amsterdam's, which take nothing. | Gas id | Osaka | Amsterdam | Satin | |---|---:|---:|---:| @@ -57,11 +57,11 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | max_refund_quotient | 5 | 5 | 5 | | tx_account_write_cost | 0 | 9000 | 9000 | | tx_create_access_cost | 0 | 12000 | 12000 | -| pool2_kept_percent | 0 | 0 | 2 | -| pool1_kept_percent | 0 | 0 | 2 | -| pool0_kept_percent | 0 | 0 | 2 | -| reservoir_kept_percent | 0 | 0 | 2 | -| call_history_allowance | 0 | 0 | 14080 | +| pool2_kept_percent | 0 | 0 | 0 | +| pool1_kept_percent | 0 | 0 | 0 | +| pool0_kept_percent | 0 | 0 | 0 | +| reservoir_kept_percent | 0 | 0 | 0 | +| call_history_allowance | 0 | 0 | 0 | | code_deposit_history_gas | 0 | 0 | 88 | ## Measured transactions diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index f5dd920d2..1644c9132 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -141,11 +141,14 @@ fn render() -> String { out.push_str( "Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam \ devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state \ - entries rebuilt at `MegaETH`'s cost per state byte, deposited code and a value call's \ - history allowance priced at `MegaETH`'s cost per history byte, and a frame forwarded \ - 98 per cent of what its caller has left of its regular gas, of its reservoir and of its \ - data-size, KV-update and state-growth budgets; the `Satin` column differs from \ - `Amsterdam` in exactly the entries where one of those applies.\n\n", + entries rebuilt at `MegaETH`'s cost per state byte, deposited code priced at \ + `MegaETH`'s cost per history byte, and a frame forwarded 98 per cent of what its caller \ + has left of its regular gas; the `Satin` column differs from `Amsterdam` in exactly the \ + entries where one of those applies. A frame's share of its caller's reservoir and of \ + its data-size, KV-update and state-growth budgets, 98 per cent of what the caller has \ + left, and the history allowance a value call gives its frame are the engine's, taken \ + where the frame starts, and are in no entry: Satin keeps Amsterdam's, which take \ + nothing.\n\n", ); out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); for slot in 0..=u8::MAX { @@ -309,21 +312,13 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { // Every regular entry is Amsterdam's. The state entries are rebuilt rather than copied, and // land on Amsterdam's numbers because the provisional cost per state byte is the one - // Glamsterdam uses. The history entries are the ones Satin adds — upstream prices no history - // byte at all — and so are the parts of the data-size, KV-update and state-growth pools and of - // the reservoir a caller keeps from the frame it starts, which upstream forwards whole, and the - // quotient of the regular gas a call forwards, Rex6's 98/100 in place of EIP-150's 63/64. + // Glamsterdam uses. The history entry is the one Satin adds — upstream prices no history byte + // at all — and so is the quotient of the regular gas a call forwards, Rex6's 98/100 in place + // of EIP-150's 63/64. The parts of the pools and of the reservoir a caller keeps from the + // frame it starts, and a value call's history allowance, are the engine's and in no entry. assert_eq!( differing, - [ - "call_stipend_reduction", - "pool2_kept_percent", - "pool1_kept_percent", - "pool0_kept_percent", - "reservoir_kept_percent", - "call_history_allowance", - "code_deposit_history_gas" - ], + ["call_stipend_reduction", "code_deposit_history_gas"], "the entries Satin prices differently from Amsterdam" ); } diff --git a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap index 644a3fff0..6be7655ad 100644 --- a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap +++ b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap @@ -4,148 +4,148 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0xbbb1a321fa8fabf8d27760616c768bf9f2a0d5649438373c76fc4348d88cfb8a", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0xc3ab1c1af149f2cbe5733aeac1c9cdb42eadc2b47e270a5b721b14eed20c410a", - "rule: arguments that do not decode @ 50000000 | keccak256=0xb0db489839a78c2e662f000d2220ddeef36e06c5a473eceaaccf3e0866dc53d8", - "rule: malformed transaction @ 50000000 | keccak256=0xba96cfe68c780d656f805049a752b68a4049a7c1ef502eccefb3f6c6ca81e8f8", - "rule: a trailing byte @ 50000000 | keccak256=0x5c624cfbbeb559e89cd58716f98111cb2d4f07902c8e71d9df478997c0a84619", - "rule: not a creation @ 50000000 | keccak256=0x0386ff909ab7ea665c8b7c11d8181445da53b91efdc2c2941b6533036e92dc3b", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0xc9a0492b8f7f17629e2ebd8bebf7acff541dbf9458a9e262e147cfdaad714b52", - "rule: signed at nonce 1 @ 50000000 | keccak256=0x84315464c623f5cbc5ee897e2bc8bfd119ad900e123143ac721555e0c2e3a3e1", - "rule: override below the signed gas limit @ 50000000 | keccak256=0xc00f787f6cae8873132a89f2038212b36ee02270d3410df38338adcfad75f6ee", - "rule: invalid signature @ 50000000 | keccak256=0x0123d8ec66253bfee2c311b216a5d9f19cb3c15457dd4b99aba8678431cb3303", - "rule: signer nonce 2 @ 50000000 | keccak256=0x74f3e6b4e5ffc6831d4f2322f91a596707fd1887699f43e9f811f2645a0ba3da", - "rule: signer with code @ 50000000 | keccak256=0xc43364d930583df0460bc9dd42d3cc23386abba568218a3b5db7a8d530bf78bd", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x7e885926e896aac59f698ae640a0a2e6777938661d0f2a7cf7e12d3b1e3ecf00", - "rule: occupied address @ 50000000 | keccak256=0x34719a7157d75c75a400db9d1dde3c03682120e583f3392ec8b1ee36be0613ec", - "rule: value the signer cannot fund @ 50000000 | keccak256=0x199eb3f0514dc7eb89d00b814e9be6ec96147ceb2614753a0e25b762024434be", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xa1fcdd4a0bbf7c9c08985315582f9c4c31a37525c5e6f08e2bb045066c2d16b3", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x0bf902ac6bebbd9e81996c57e45f893937320dcfb1fa92223d246e9cacae047f", - "deploys from nonce 1 @ 50000000 | keccak256=0xa520227afa0779933441e9c8d0a81b82d5d4796763a0deaec2db7543baf413d4", - "the address already has a balance @ 50000000 | keccak256=0x854e5d67d0b3ae6d8eb7cd5e516475df2baf36301993404093da7e2c78e2aea4", - "moves value @ 50000000 | keccak256=0xe68adf4ea6323e5e85daf9baa8f674dd6780d7c5e09aeea5f6aa950f25135522", - "moves value from nonce 1 @ 50000000 | keccak256=0xbd4dd91295040091c9daa24f413d6c9dac7987ab302fb756f51523feed7c0f69", - "the CREATE2 factory @ 50000000 | keccak256=0xa4eb75201156746b64933d762f2578d85eec1b973fd8f44a27f1a9b82b1fac56", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x814369e9694895a04efcdf10e46d291f77debf3360a7da90f162fbd8ff8b3f81", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x04c1ef35d5661cd9e663bfef971e77257290c620ff0b02ec2a7240ecda007306", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xbb72f34db268a2e3887ed09e962acd0594acbdaaa38c886d46fa16b4a9f5a24c", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x26959ab40d300c7c80e74399f2cd52a8104f2c8d2df3f2187868e28318a425c9", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xc4b37379e510c216a96aaf24979d06e3be3a2fc3a03d6538bf9253fb8e452639", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x064dd785d29f0bc752281e4bbce7c180d4d7914bde6eee54f59deac6d4839b91", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x5708cede78495e8a958a94377f3e5fbdb437a9a36b5e5b2572cfc3c2a619f1c1", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x74c1faf2ea41ef8023efd520ef2a149617e919657d26a3a67f866bf2e99a40d4", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x2ed3583f5a9b25f68e6a68771ed8715b836135a3ce6e7351c0031adbd43ddd46", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x1ddb229bdc98071111d5a644e98a5e3402c89e440056044b50e42d5bb1c98546", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x6abf2671730921222c7e0486fc58421a29c3b286f2075c6312bbca64a352a656", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x54c19083cb9b9253786f583e80007a9c467a2e1783e3e4dd4aabfb7f456b0829", - "a constructor out of gas @ 50000000 | keccak256=0xed4e182648a6a0eeb5f61018a3eaca23a60974f3a6167f31218ac538280726bf", - "the signer sends it @ 50000000 | keccak256=0x0ced203a45283f8624433c0835beec78f12792ddf7e92d2f12fea1cddea5560a", - "the signer sends it, and it reverts @ 50000000 | keccak256=0xe5713953532d5bc302ea6160476e728624ca3af937bd6e89fc8553f89f9ff2dd", - "a delegated signer @ 50000000 | keccak256=0x38d2ce3b0bb3da4d31d02be4e87013cf7daf22ffc487562e464dc7d41256dcd7", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xf4d03fbc577835fcd11e7288e0cc4d2ed642d48738d44ff0c8280e768598c35d", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x35e254125b51703420e8deb970c97aa8074627918996d8e97bc5671b524e674f", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0xbe19e2acd0ee697fc43ab05cd0cc9ecada8e8d700b158fda10ec6f6bc5c1e53c", - "limit: compute, nonce 0 @ 50000000 | keccak256=0x2944b7d9bf52ea422166c67d00937280a9ee1c88958fdb4b119298455cc6e82f", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x797de99052c6684ca98831510e1746166d2a9dfc6939e65a04d79705c6fac121", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x5451cb823c7026bf7cd782549d118c84c8fadc0b2b0791aad17ea04640b873c2", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x4e3a6609240565a3b8f9ec0278c29e08a15dac083bc70c93cec71dc5b2d4a284", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xb4a3e25c6b0253329363c075ad24f7810fa574d9c6b4abf47cfedcd463aa7df8", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x45b1d087eaecc7df26d766ec791eef23560c46269e58faeaf131758e7af705a7", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x5845d201af918e1750abfcd4332f0dccae77c77944db18976357cbd43029fffd", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x4ca715d952d52d966160cd70482e6dec9d55396b808afecf01b76f7bb9e6815c", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x769a1fa287ccaebe0944d36d9405909abf987c3260d54922249afb4684096b41", + "rule: value @ 50000000 | keccak256=0xc49d7ab2b636fd532a8aafde807c175cb4120d23544db47cb3e14ccca013e372", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0xdd70d1ca3a7b307ba7cb3a1ff5a006efbb474650d5b9377e5f63c733be100c4e", + "rule: arguments that do not decode @ 50000000 | keccak256=0x02847dffb84d05c98e40aa21ea3e4530c38300e8737521d13b72d8ba5679c7e4", + "rule: malformed transaction @ 50000000 | keccak256=0xc22224482c4dc8794da51ab41d3d1c4185f77804e9bffbb459860c5bcab42665", + "rule: a trailing byte @ 50000000 | keccak256=0xc411c146221a1d9107f1265694e170eb98e3313e8172f36006c7333fd6836a6b", + "rule: not a creation @ 50000000 | keccak256=0x088f9214c5ea94835b1df766a196eec1da040ddf774f942398b44ff8eb2df691", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0x9d68849d07fd9fe28469de36f0ca8ffd80a619276ae64f25cb1c2dcc5f093998", + "rule: signed at nonce 1 @ 50000000 | keccak256=0xe4edd71acc4e477d3f8b7367df3f376c4e5c7de91bae721a8b946072430c75a5", + "rule: override below the signed gas limit @ 50000000 | keccak256=0xd15bcab016904099529eeccfe263a030703f0a020417b0e238c1db361e603f61", + "rule: invalid signature @ 50000000 | keccak256=0x6e98838f0aa46f1bce758c7ebd3cbfd7069fff53ff7b2e62ab47fdb60bc05229", + "rule: signer nonce 2 @ 50000000 | keccak256=0x29f3f4b9a77eb6a29d1170bd3ee2387a5987dab90a68a0efc94fdb254aeba92b", + "rule: signer with code @ 50000000 | keccak256=0x7a7d8546eef20936d1a1bc0a404d1d3d4409cf47548acd5540441a9dcd7ff6eb", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xeb06de9554f82be298a3083a1e12f05d5bb69228d305560d0437c6a75e08ef1d", + "rule: occupied address @ 50000000 | keccak256=0x5bf6ba308b278d3c01b55b96a2189f44727408e379e050d2b8cc5934fe9ba71b", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x14aaf68fb49bdf7d64de2e0b34ccaeead8c3c88fe9b132584304aab08f83419e", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xb88fd56f50517f4ba0dd1e220c6db27895313f782852910626faadb9c9ff8d1d", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xeb6f85f8f46b7b53bc5fcd498907143054d857e3314aa84c3fcc06c1a8fe72e0", + "deploys from nonce 1 @ 50000000 | keccak256=0xb81df7edb18ab9ed4de3087bf334bee52a4458b1d4ec90856227734b251549d8", + "the address already has a balance @ 50000000 | keccak256=0x947dd735cf4309adf7ff5ac4c14323eabb3899ef7a0f51a2c915b41ab0f2cea9", + "moves value @ 50000000 | keccak256=0x8d6f548db0b0354aea50814115e3cf6762348f7d1cdc9a39e3adc98cbf0d659e", + "moves value from nonce 1 @ 50000000 | keccak256=0xca714d3e1fe5c46e891d78449792a269cf3f1995a24da7a49c41f6e3eaba4a30", + "the CREATE2 factory @ 50000000 | keccak256=0xb56be4ebc822d43123ec1b408b7546120f6668983cc955db51618aa3600337f5", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x719bb8ed6d3ad4d31483fb21e874b927f6ada36f1cd6e23187c9da32755daee7", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x2bd8ed509016021153ca19eb646ec10d0d1a22892aa993185a0330ad3746bada", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0x85abff2dd878dcacc394c08927fd3def573074ab48165fefbce0f189e158a6c0", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x339b35d83b0e9a6832ec9e34452921d8b037980f451e5cbacb0aba7dda2def48", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xd0b6942feb0b4289e5c654456447a051841c3ae9485b7a0818657f1167a73d58", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0xfd916915bb325f1ad28dfece8b6e5f74d785b9ee9edf01c7e97922777e47ac57", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xe8ed512e9196f432a85373f432f975ea2e05f9f8e3f8fd3da1e10146dee08918", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x4c4ffd0686e071bd8d5eb1425a877aa6fe46691bed177000568962d7773339db", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0xaaee0b100cb4aee1545b5135dce04207925446324745c0ae9a907e302632c51b", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x987a1f4fca0ba1352b9369d2826f113ce8b7e8b1a9ca77a91161034f3a04cd01", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xc3a2f4c58895cb351eba03b7c5e292062f48f9d1b38eebc4428a80086830767f", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0xdf72e4147d9d14fb2f441ea4dede58bd32fbdb2b43905eef7c6e8d511ef0de6a", + "a constructor out of gas @ 50000000 | keccak256=0xc81b4855bbea65bc2dfab1be8c191e273e96193ac3259b340aecdf0e7417d9d0", + "the signer sends it @ 50000000 | keccak256=0x6091a84a69080e4459c02b0a8aa81c982064cc9ad2459de627bacf349ba2d781", + "the signer sends it, and it reverts @ 50000000 | keccak256=0x2aa3d7fb39b7e9773f00e84a52dfa4013d1613f8a5f60a5c95c89f649df561ce", + "a delegated signer @ 50000000 | keccak256=0x7c8c540b4df92a35101d29016d14abec166703cbd839e972a81bd919fe5781cd", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x5c991e23288b57b9b3b50d2d4a2c7007c09eef5801eca99de67cb580ebe335c4", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xf4105216d3a71300ea11775154aa73b51df8def725eb5b2ee4ed059ac2d87826", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x9f290c5e1b39f09e2e41aceee4c660636e97279b4ac20ef119a0bc09c29e85b1", + "limit: compute, nonce 0 @ 50000000 | keccak256=0x1c3537636cf791f7a30535f2fc89b719e0a7d91b98d2ea2ee6df2668dd05f1b8", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xbd9123386b0baef9fc54162d49ca085866e13dc8c5d804eb53109e83cf16adc9", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x8343e8e5893153f698e49d918be880b04b9dfc6714e2474b16a18185991816b5", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x3fe719ae2087a91c92f64f52963195563213b034dfe2dc17c12119de42bf8571", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x9ff5771100c956032e1fdf9abb1d223e899d755c8279129366adb89e747f9ffb", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x3483f1dab7f09e977d83c84cc88d1ae5fd9a3c5536fec4aa56deacc027175a57", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xf0f75c887dd7a54f531d8fc37c10e5e5f1fbc6fdb8a1e6056fae3ea739fb67c6", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x23f53fca9b56d35087b510cbbf615ace5fa2bd0d0b64a163f115c559f67a1c5c", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xc846628fdba2bf1b45a887a32335b357ba7c648ab70d697cce3aee16bf615068", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0xb9b6a4f4f4da4ff07d70af782977146943836dd091c23bbe9c4ed7a9e4bb9f27", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x23ee0068e75b5a67d97e1a45bc5f5b66e34c2dc8798fa9e752a11080bee93dc1", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0xdd925caae45fadd96556e1d7f018b1d83045ad2734d2f4f525a5f911a00975e0", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x40a829bd5cb26d43f18f3b177e051c1387857cd7265a7440e5a4fae346a31cc8", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x56f60b8f8bc96d3815e7a120f09fe74d1cbc3c85cb4d80a5886b98f4a6158122", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x2abbe75645d93afdbcc7687b6c0afc479613f57afbe28463f223273e683bbee5", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xf279c5307fac715d603ebbe9b8c74aa223c5594b798abb3de195e0cb23ae6bd5", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x92e09638ad6a4e0af87f695337f3aafd6fa9196da822f38cdfbbebc7e0a0c39c", - "not dispatched: version() @ 50000000 | keccak256=0x7c5ee96f08957b0fd43ec3609c12cef5bd0074792d595a9f1ea971ca31fd7875", - "not dispatched: no selector @ 50000000 | keccak256=0xc0be8244d5572b8b9fb9ad4d4c4e0db85d8ffca5002f37279b9c52ddc3fa5b02", - "not dispatched: from a contract @ 50000000 | keccak256=0xa0f75061e50b6327aaadf92e71f9af22665b274ea379aa98bf396b8e08071d20", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x268116d81aba3d36b1bfd0f3473a60adf58644ac1dfc8886a2fb0224bd4aa82b", - "no contract code @ 50000000 | keccak256=0x253953af0211838296cd30ba77a533ea7798a45b1c5accd1a2b739e290605d47", - "a system call @ 50000000 | keccak256=0x4ff198380163db3fd96b41cac5955f3c4723a559398265bfb2b32405dd00edc2", - "rule: value @ 400000000 | keccak256=0xa18ebeca543b35b95bcd4fd93a0679cdd9486f1d1c8d0feef804ffc1b9ad4d0f", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0xf986d1cac4109cbb2466259d2110ea80ce1f4de09f3fa2038a51d0f81b4384ae", - "rule: arguments that do not decode @ 400000000 | keccak256=0xeba2668832f3afd0ee12d3a70f506e50ff8c491017c079245bde2181c8c8ba98", - "rule: malformed transaction @ 400000000 | keccak256=0x287361e49cc3a3985b31a7c25a558074861a227e9bbe7643190c426e20720289", - "rule: a trailing byte @ 400000000 | keccak256=0x77cf0ce7ea670c10f24127fc9549928877d70bff052f8b82cdb36829865a65cb", - "rule: not a creation @ 400000000 | keccak256=0x41e892cdfdf1964cfe253027160234eafc5cd532e42ac66d851015a220436675", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0xb8772e8dabb39783785b7999e3c138ead3904b9f5efffe173c44a809b34ccc40", - "rule: signed at nonce 1 @ 400000000 | keccak256=0x302873560dce8cb91d53397f6189cc657823d918512e98c299fdb45b3a9327d3", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x2fd5a2d895fd1dbbf20d73eee0c2e29eebaec2e6476f5d9bc4b614e4f9b3137c", - "rule: invalid signature @ 400000000 | keccak256=0x491f9c8eb64f398c3399171c286cd7db7d01c23e0f256dba72dc36d7b91cfc4f", - "rule: signer nonce 2 @ 400000000 | keccak256=0x91cd17bd5232587c10bc61fec1446a8058a5399723976f4b0af1745ddffd22b1", - "rule: signer with code @ 400000000 | keccak256=0x1a75998f8e5a2654da4b90af611fdc21e4a0b21b3bb7ccec1c3c41066b180eb9", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x282c1e56d00c8e98ddf030dee7c443ed146bd37bd1950b38fc37a9925eea5a7f", - "rule: occupied address @ 400000000 | keccak256=0x173768aec05d99a3b4f2f8a514bc8189f1f0d699d6ccda32e8ea14238c3228b6", - "rule: value the signer cannot fund @ 400000000 | keccak256=0x496e2dc7b600882979349caf494d574a55f4ca03435079b95e932d84006116b3", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x3e2c83f410dee0ba6ba3907641250811618c539150ff18370b00c084bbd718a3", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x5008280aa7bf2ecdbcf76ed8d79a74798b58628b93a03683b15979440fd953fc", - "deploys from nonce 1 @ 400000000 | keccak256=0x62aa872f3858800f4ea40b9d1a956f89c3cf8bd3ad7fc22f872c823e8a3c0cfb", - "the address already has a balance @ 400000000 | keccak256=0x3b5b6e733d25fae001d95c053553c30a3e557099851432da7f24b5d9dcc98fa2", - "moves value @ 400000000 | keccak256=0xccd0aaf8e8333f0651d6846a9caff6d2a7561e9545d7db98afe7fb41b162fc85", - "moves value from nonce 1 @ 400000000 | keccak256=0x97de89df5cb3776fab2e0dbc5c8ac479326d7b0413780c9650a9583d376b6b71", - "the CREATE2 factory @ 400000000 | keccak256=0xf2a19245595181d80dc2652cedcd2b6bc2e56a2aa6e0374b8f03490012b0d723", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x4d0e173f5592e65112162b83dd01c4bed23f58304b289aeb7f0a6f0ab86e795d", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x1ec883ee368ed36093aba984eac350045b962d2e6ee6b4b635e0a901f79426c0", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x1e3d2de4feb46b93cb142d18a19732fa0f82c41ad5d7e313b76eabcbc5eca33d", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x94e3351af11a471277dd64ad107ca6afe43192ed20a0bdfb4a226dbb673cf37a", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xf070389fce7571465c57ab2c64a99bf68a33c60afd6cb1f80229e1b07495193d", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x690f7ae1f153f7b29374fee5e68181039f1372b68fa9df80931a17dc28e6cef3", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x3817844eb1ece2cbc97c7b6b7ecbdb1e543ce3bbc098431dbd45db3682c70f82", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xecc6b6a5fd7719e95d1a5775558038aef9d7855b41980a9dd9d203040ab45aa4", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x48df122101a9b81d974c3237bebc381d79551cae986badab597bb412d7dcb6b8", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0xe457f48c9514540b08c08824e66ef7ea82cf99fdb4c640aece47340eb0d26a31", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x1deb9dc2b89d6ee0d0b3f112b9b7d57f64e9b982cc40c271dacc9794dbae5355", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x74086a0c3fa9ed53cc49bc1df8c405d0d2624ba5b99ffaebe58dc52d2066edf1", - "a constructor out of gas @ 400000000 | keccak256=0x6f036558fefbd5f702390c01155793948729106ff9273141de789c93eb9fc6e9", - "the signer sends it @ 400000000 | keccak256=0xfe626210c579451c32e2f626c26834b42d17cddaf18882e101beb02014bdf06c", - "the signer sends it, and it reverts @ 400000000 | keccak256=0x491266db1558879e50eebae46bb33d9d5ea0f16a34ee3b13c7ac2e263036ee93", - "a delegated signer @ 400000000 | keccak256=0x8f487f733dbfbaa181fb520e69d984a19deec1caca1d050c0f3b166a049b6a27", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xa107860c667709332d37c4ec41fdfd0cceeaab19ef93b2e55c679184bc76ac7b", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x2b21304f22f83d0bbb83974ab351c33b78ad2fcd8d052fa838bbe3bad39ecba9", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xa10400d847c8bb7dff794681de273610f0abcbb592d60e221e015880dce5904d", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x164eb97b6134fc61fe58d2803253adfad06b514a1443bf12e5b7c23e56b996d8", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xfda55f9a2100228c51c54da623f5a69891fa02f564887f61646a2a44ab0e45a7", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xaa6722d542bda19e9050f94e4b82676d3630f6f09be8eecbf67e43da6ef90cc3", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x5ad715ed7e110f818526030bb5f13738d4b7dc330118c23e9a331ae3526c7a05", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x6494bb9f4cd13f0f60b1b2d162386905a3fe97299b7f42d844fec3e4863ecefa", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x50426648fa3561c26af727374ede6f44be7f33fef83fd732679ae9b48fc7bfd3", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x5fcc23bc18404f8b3325b694cb671119236f914248b22f9508c7f3fdfcaf3d93", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xb549fca44063b07fbb35746c9a92776bf53c9b2eb63557034f99cba42aadd658", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xa84f7ecc5a86208551f0527940f6288e998f795e6621a6c9f67305eb49bf0eb8", + "limit: the default limits @ 50000000 | keccak256=0xeb76b302232049dc90fc7c6246ec751c99e807d173ffc92c1666f10a63ca6967", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0xb5f05b3f02de07063b2021ea8e1e40b23674b96d397add127ca7034bdf93460f", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x78aa6bdc2d19d6a899a638e128c00b1477217a56a8edccfcfaaf38cd4ddfb537", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xa8c303aacf72c79a5aa7303cc75637d69fdd658574dfcafb300566c5bc088695", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0xbc257c0ea2c50d6a0b757f045123f4a5e95c46e9f2f994425ef59fcf19d8dca5", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0xeec0d8719b0e7f5bb57e20897c96b42ab2f58615e598e56e5226b76e21ad2f52", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x067fccfd9852612f2ba625c45dfd0768d674690eb8f00f1a5e067b99b5bbdf31", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x223b55bcdda152f6c01a32b8ab40e59de61bff5cae9c33f1b09ccf242cc61836", + "not dispatched: version() @ 50000000 | keccak256=0xc33a3a154b6162feee1c3feff7124221b9f44451e5ac583fd042f6a6435f3734", + "not dispatched: no selector @ 50000000 | keccak256=0x3fb4950f994b33c1e69c1a35fecf5c31f17a4aa43ba784b72139f6b30618a139", + "not dispatched: from a contract @ 50000000 | keccak256=0x6e09a48c63b9291e9562f3275e22b02fc6b7eb886664d75c0e7f1cc59cc24650", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0xf7e7dc2d3f65aa42d043a25b31825ec05736a447e597cff1c7a25be0529ffd99", + "no contract code @ 50000000 | keccak256=0xe0ed629008123f447ef2ebf1519e199500e2e80ad661415f6dc1ccabbf8f818a", + "a system call @ 50000000 | keccak256=0xffdd1ae43372ff52bdbf864c1b5a623f86644901454aee23a239e57205bca821", + "rule: value @ 400000000 | keccak256=0x4d07710426aff7e9b40809a278e9b6f1fee2f8d98eb7865256bdeb88a5273bf7", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0x9b3e0e3be9faf8cbf74d4a815cc0672512110714cd6332c173f684061ad68bfc", + "rule: arguments that do not decode @ 400000000 | keccak256=0xa95007810eda03a41b376b35f04aa9e3f326c587e39510535d399f0e26acf021", + "rule: malformed transaction @ 400000000 | keccak256=0x6c1d478fb1840b6ee3c84f20b01537ef5e1ec6df3803fad664752d2ac8360a48", + "rule: a trailing byte @ 400000000 | keccak256=0xb6e29d55c7e5c46542ba5d98c21dc1aff26c4279353a6bc758a41c7dbae637b7", + "rule: not a creation @ 400000000 | keccak256=0x5dcd141edc7741305fa3e91ad98891636ff460a296c750977391a4ee255563a0", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0xa88f727a1a7eb8d1ecdc9b51abe9e8fa2f7dcf9f7cb4e2b28bbcc951dc650ec1", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x2477f74ad56b183160a9319e2c982144ce8cd6a6acdda7a77b1038e5789519a6", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x5f8974a99a53657a6f493cfc86e60f0ce7aba5b998dd256b52ae5cb865cf27bc", + "rule: invalid signature @ 400000000 | keccak256=0xbbcc676b1e59eee0f0330059f20fdc5df56d6c6593ae661273be4bd0ad52de72", + "rule: signer nonce 2 @ 400000000 | keccak256=0xb813d5b1903e4a8ee729a5e733b56d854e5435e7c1a821da1cbc76a48b27db11", + "rule: signer with code @ 400000000 | keccak256=0x9809ee122cce398ebc43cf5a77527caa40999a4b93ddd715ab8ed9f5670c6291", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x63f5534341bc6896fd1ff853b911bb52d516650307860a4f5682b445d299feea", + "rule: occupied address @ 400000000 | keccak256=0x2a3d25f5a60a72a39d573aca80740d4b519ef702343f88e323086c1ada90d205", + "rule: value the signer cannot fund @ 400000000 | keccak256=0xc68f3e19e35532d7bc7e997cff5d57e6345d5ec374d68a366059eb22585d05c8", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x87067be71dd4d42e8c97d0799004a5d606674bb4b64e3f7a184786001c65835c", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x323efe7003fa4a7ca7bc4a59f7bdffaa4b88ffdf7e5a09dc0d8dd9968265de31", + "deploys from nonce 1 @ 400000000 | keccak256=0x7c5eb36ea36aa8653744de5c89413ade2a7b966f8b3cb0e817548898cb4e8bc7", + "the address already has a balance @ 400000000 | keccak256=0x0820ff4222aafcc0ed512a719fd2c5f2855e4499914f35c56bddc884737b6f96", + "moves value @ 400000000 | keccak256=0x563f55401ee2b1bb38a295eed971814624a2625a4a286cb640bfba57ed73bd06", + "moves value from nonce 1 @ 400000000 | keccak256=0xc9ba03a5c1c7201d2e472d33ef3dcd3b9cc18176685b585e42bc085432859c32", + "the CREATE2 factory @ 400000000 | keccak256=0x95db537f470d1db81bbcf46fd31fb22c79f458469bf4fa4eeb8fc031d8afab22", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x189f60aaf33de771c4b9bbb49d4e5e212b51c65d23e1cf43861669f5b49e1fa3", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x29771ac8486f3c5cc050dba5bdcc0c012884c27d441df1247651ac284bdf0b69", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x6d1d2438dbc55a163416ae888dc23b6b7d635793855adee2619083a8549398ca", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xb7d5a6c033f0018be8bdf38e37f5e062f816fc9c7d97c7c7f690897ffc4158b0", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x9d63d0227f6d37f5fda76be17e16ef02c2e928bde5c0e295ce1386b7331df030", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x7ac15ad59dde01f3554883788d2c7ba6babe8b211958ee0745db5bb7528138be", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0xfb68d486cc5d8c2f889f8aeac3883919ef6f8b78a8da33419e4c47ee362988a3", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x043dd4b84dbea3a3d310605643d4145f91d530feb5d52489623b10ffc80b8033", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x29404ee1f940082709ca013592fa131f67eb29c1c7b2703a2cb1259f100254f1", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0xe390fc3b57ecf5531103928ac6da0015ae0f0a3fa551098a218757e4debfad29", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x346ca9e1ae46d69480cd0b388f6ddb69f6fb2592a41baa52d1479d12d58110af", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0xa2e16f9a2cb9018e6ba5d9526f2bc013d1bb94b119614249b4b98dd79a22efd3", + "a constructor out of gas @ 400000000 | keccak256=0xfeda9604e09c6288226f5b2c85b606ad10ce83ec98e14073b1bc1765c0927a2b", + "the signer sends it @ 400000000 | keccak256=0x3be7311d374e28a3a54cd9350016b4efa9bf376db4073cc742aeccf137461855", + "the signer sends it, and it reverts @ 400000000 | keccak256=0xf1405cc47dcd6dbabd5603fc9b2aefc96573e6d237daaded9b90cfddd67e2092", + "a delegated signer @ 400000000 | keccak256=0x20c9f1c4bef08f79ee64bf5e3692a416122ffd331d51fa7462004588b8979918", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x374277d33aae64acec716fb716339177a9108c514bf764b7321e15fb6a4c1409", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x20bf7e2873056beedd7ca19b20e56dd913e4cf07e1721996a3388cd5bc493daf", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x2eee569fa02148b5ac520d5940d1b65e99552d02338a05f74c48e843699503d2", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x08c4a1e36db53c33bfd259554b5782d4c4478b67fa0c4c5f57b6c2f6c6332b1b", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x339759bcc0c2ab8a8f876e0d45bf8fbcdb0a45e78ade4f12a527dae7d1ab6b5b", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x4fe739ef1dd5ed7987d62b4e7eb886ce9a23e8e81ca5a92079d1d9e5d429b54e", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x6a2cacdbcb3d9ec6550f50035854b54bdcc748774deb11fb6650e06658b5d9d6", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x69e249a049d570fdfa87f44706e51f5d5c8df3f9615a3f50e04ca36058e5d5aa", + "limit: compute, nonce 1 @ 400000000 | keccak256=0xd99dfa9a3692a42f7a975082fba152a429a03c1d30ba621ab163c8d9979443fc", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x5f7a019e0bb3a3c0b2114c66247500a6957c658866b1ad5095d2eb3f16fc1336", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xb71dce0aa5217c9e5caedb3075d74c78e2fe124203f9da7ba19b30cebc51bcb1", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x767c6338db5d1aebcbd7d97b0b5bc8a197c4a29c41685b7135c85d16d6192f7e", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0xf2871d0172174549bbfc91d7cf684dfeddc058a330911913403976c47f656c8a", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x055cf0c41d75363ebbb2ce416ddd379b3f8f6f931acd8c2852bfbe27da79dfdb", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x1c13190dfd8c7ba6f1d4e4b257ba9c4236acd01636e6a5655053b7aa7884925d", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x343cce5a7e77fff5350bcc29ab8a34044f599cb1bf018cc46624dcf3026c45cd", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x1f08a9c99ca1d6c759b171eccb25d3e6820cb40c38bda50976c993b5b2686f5b", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x366811708e9a1b60152807d8c5dd3984ed1b88a0016c86ab2f0aa4d763b09ae2", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x43602609a20ae5de69612764d022fd449af3d17c1b8cb39698c9cdcb16dd34c4", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x539be37bb5236f91463bf14405e2d8fbecc38ca8d6913c376af276b39258cce0", - "not dispatched: version() @ 400000000 | keccak256=0xf21dab241d0565c2393c9e0c37035f6be5de3b03a33921186dc6044f506775bc", - "not dispatched: no selector @ 400000000 | keccak256=0xec805be7015aa71877a9df3bea1213c555c71c0b8607af8d6044f45fee86f790", - "not dispatched: from a contract @ 400000000 | keccak256=0x77bca1e5ada4917e8ff0dd9e9d481e75f3df2de516327c1ffc50926730d6bf5e", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x2a9952071b259bebd707febdf9f9569b4a6401dfef933777e104c432daf84942", - "no contract code @ 400000000 | keccak256=0xfce752eedcc5e1032c0c2d2da6c959bdc5bc642bed36645a002b1f00af0266f7", - "a system call @ 400000000 | keccak256=0x2753d26c7e11d1b72c62b08fdc4f837edc93238506589ed4137a1ae5aac6c656", - "out of gas: the overhead @ 161535 | keccak256=0x46d0e2acc5da4810497ed4749f8176deeeac29fc6325babd64a609f4e02d369f", - "out of gas: the signer's account @ 162536 | keccak256=0x22574237323abc6ea7696732db91b88baf87ae39d55aa4fe95e599e215091c66", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x003485722c66eff085661021f5f19626c15898fc5bf93a8beddc1cd2c59d9456", - "out of gas: the creation's charges @ 163024 | keccak256=0xa576d982542405802977013b3806c9bd522dcbaae1ee07fb81b6122b57e032c7", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x5de05094feaf6cf89a99eb14871f718dcde64a0b52deb7feb6fa6e9de8db0bd0", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0x37fe0d37c5b7662773341c622b439cfd9cb8159e103834bf92a11032cd307dd3", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x445fccc13f9822d385a925895a79bf1a230fad9dd1e4001d222c4009cbf88046", - "rule: init code over the limit @ 150000000 | keccak256=0x7ec570ba276f8b3c81c80cb731e98c1482d7a42cc327ed79e606851b608a30d1", - "rule: init code over the limit @ 2000000000 | keccak256=0xa1e17bd2b8390974bab623c8d659da58eae6ac84ef35102103a07b429f5d705b" + "limit: the default limits @ 400000000 | keccak256=0xbccf72c35c794ed4a468f7c50b639c61c15045a55de3b75563a9ae4803ac21cd", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0xe478387eb2857945c73febad81abd3a8ef5539a672cce804801b5d2a785a5cda", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xbd0eb9c45f3e22c7f452b8fc16e058214a319cc3e8a5f82852252671de8300a5", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x52bc553677f1510d3ddd64c533eea801d21c94ad4ac513680509aa5e89f1c0e4", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xfbdfc6e4bd66c2d5e26b0acaa20a934d90f8b7c492038837b9dff1ddd7d94b44", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x6391a8de0634663ecb2b3d77e7bf7c665c892bcb3fc48b14d71da691d25f4d51", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0xc67dedb0a0040ca724f77cfaa51eb451a25e444cce28da474f1fa2a5d9204d20", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x37b81702269dbafd8ab389fd7123378cef7dd7ea1923cca320f51d91c5bcd86b", + "not dispatched: version() @ 400000000 | keccak256=0x929430c2e162ee777eb160f952e2549abd657be498b82747fe7a7fbb6c93396b", + "not dispatched: no selector @ 400000000 | keccak256=0xae609007e6eea2f71723749724023318c9c592bf4766e1c5b8d2f3a4da21c0e9", + "not dispatched: from a contract @ 400000000 | keccak256=0xbf337c59e8ac9e59051396559b9046750fb7717cd2042234e84a936c9d5e8d21", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x3e9c7e73294f2847bbc0ea2c208c6f34207c0ac74f66b979a5963394a174743e", + "no contract code @ 400000000 | keccak256=0x0e672d81fabef2d7ec5ff4e00068af0eaaa17cc54639da162494110562a3f668", + "a system call @ 400000000 | keccak256=0x227c05675e38bf85232621aa01168f5b4ca3c532274fa5b2fddc3dd2a52a640b", + "out of gas: the overhead @ 161535 | keccak256=0x7d9405d494d1c43dad43a9569deb75e2ad74a235efb2146a7f6bd47aef411198", + "out of gas: the signer's account @ 162536 | keccak256=0xa4d8c7e70321a73bf60c7b99eac76e515f66226cef7d3542e7df1ea36b525eca", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0xcb8d53bb967c26325dd785067c121f01fb481dc5f51a72200badfda86229760e", + "out of gas: the creation's charges @ 163024 | keccak256=0xed048cedb2a4a666be8883453c76dd137360c95a83ecea4a8058d24815f9e2bf", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x1887556707b93eb287304ef081ab8fd6b5c92e4b274b2de9e9044eb1f9be9146", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0x5a3bdad32567cbad138ccd255d8506cb053d98cc9d8b7e0cd14a0a9c851d467a", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x20ac0e5458c94b7754449e2506e92df19f11fa088ffdae2d069de0f9d33f8a26", + "rule: init code over the limit @ 150000000 | keccak256=0xab6a40e0c6c384f8c45bb3209a50cf90b6be674af3a3a008759a63d04e647487", + "rule: init code over the limit @ 2000000000 | keccak256=0xbd687283e7812531af3c16c5d89bf30cad7e0d8812243887be14c6efb92971f5" ], "summary": { - "bytes": 2577938, + "bytes": 2582112, "cases": 139, "lines": 11452, "runs": 556 From cc48b304db0335b8e457313f9eddffdfabb0eb70 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 10:16:42 +0800 Subject: [PATCH 52/83] docs(evm): the neutral configuration forwards a frame the whole reservoir and budgets, whatever schedule it is given --- crates/mega-evm/src/evm/context.rs | 6 ++++++ crates/mega-evm/tests/satin/history_exemption.rs | 6 ++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 9fde449d5..beaed5c9f 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -152,6 +152,12 @@ impl MegaContext { /// exemption: every transaction runs `cfg`'s schedule. /// - A system call's gas is not split: its whole gas limit is regular gas, as revm's own runner /// has it. + /// - A frame start forwards the whole of its caller's EIP-8037 reservoir and of each of its + /// data-size, KV-update and state-growth budgets, as Ethereum forwards the reservoir, + /// whatever schedule `cfg` carries: the share a caller keeps is the engine's, not the + /// schedule's, and the neutral configuration keeps none (`MegaContext::frame_kept_percent`). + /// A value call's frame gets no history allowance, which no transaction draws here anyway, + /// none paying history. /// - SALT pricing needs nothing here: without a SALT environment every bucket is minimal, and /// the multiplier is one. /// - Gas detention is not part of the configuration: its caps are runtime limits, which the diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 121418735..e1a94976d 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -395,8 +395,10 @@ fn test_a_context_switched_back_from_the_neutral_configuration_prices_no_history ctx.with_neutral_cfg(neutral_cfg(EthSpecId::OSAKA).expect("Osaka has a configuration")) .with_cfg(CfgEnv::new_with_spec(MegaSpecId::SATIN)) } else { - // The neutral configuration on the spec's own fields: on this call, it differs from - // the spec's in the history it prices alone. + // The neutral configuration on the spec's own fields: on this call, which starts no + // frame below its own, it differs from the spec's in the history it prices alone. A + // frame it started would also take the whole of its caller's reservoir and budgets, + // which the neutral configuration forwards whole whatever schedule it is given. ctx.with_neutral_cfg(spec_cfg(CfgEnv::new_with_spec(MegaSpecId::SATIN))) }; let mut call = MegaTransaction::new_system_tx_with_caller(CALLER, STORER, Bytes::new()); From 9c973575bd714c99093561c76a6d624c52a5efd1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 10:34:07 +0800 Subject: [PATCH 53/83] test(satin): what the start ledger settles for rewrites, answers and a halted transaction's own value transfer --- crates/mega-evm/tests/satin/start_ledger.rs | 83 +++++++++++++++------ crates/mega-evm/tests/satin/stops.rs | 47 ++++++++++++ 2 files changed, 109 insertions(+), 21 deletions(-) diff --git a/crates/mega-evm/tests/satin/start_ledger.rs b/crates/mega-evm/tests/satin/start_ledger.rs index 2d5eefa47..d5b8ed73f 100644 --- a/crates/mega-evm/tests/satin/start_ledger.rs +++ b/crates/mega-evm/tests/satin/start_ledger.rs @@ -1,20 +1,21 @@ //! The start ledger over the engine's paths no other test drives through a transaction's start //! lifecycle. //! -//! A debug build keeps the engine's own ledger of what each frame start owes and holds beside the -//! fork's figures, and compares the two at every settlement, panicking on a difference. Every test -//! of the crate runs under it, so a path the suite drives is a path the comparison holds on. These -//! tests drive the ones it does not: the depth guard's answer inside a running transaction, a -//! fatal error with starts open and the reuse of the EVM after it, an EVM run inside an inspector's -//! callback, an inspector's answer to the transaction's own frame, and the end-callback rewrites -//! whose figures the ledger settles exactly. Each reads the starts revm settled off its debug -//! mirror of the lifecycle, so the path is shown taken, and passes only if the ledger agreed with -//! the fork at each of them. +//! The engine keeps what each frame start owes and holds — its budgets, its start charge, its +//! history allowance — on its own start ledger, driven by revm's start lifecycle. These tests drive +//! the lifecycle's paths the rest of the suite does not: the depth guard's answer inside a running +//! transaction, a fatal error with starts open and the reuse of the EVM after it, an EVM run inside +//! an inspector's callback, an inspector's answer to the transaction's own frame, the end-callback +//! rewrites the ledger settles by the new status and revm's flags, and a creation that takes no +//! address. Each reads the starts revm settled off its debug mirror of the lifecycle, so the path +//! is shown taken, and what the ledger settled for them (`take_start_ledger_settlements`). use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ test_utils::{ - neutral_cfg, neutralize_evm, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, + neutral_cfg, neutralize_evm, record_start_ledger_settlements, + take_start_ledger_settlements, BytecodeBuilder, ErrorInjectingDatabase, LedgerSettlement, + MemoryDatabase, }, EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, WRITE_RECORD_SIZE, }; @@ -28,7 +29,7 @@ use revm::{ handler::FrameResult, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, - FrameInput, Gas, InstructionResult, InterpreterResult, + FrameInput, Gas, InstructionResult, InterpreterResult, PoolAmounts, }, primitives::CALL_STACK_LIMIT, Database, Inspector, @@ -65,6 +66,14 @@ fn shape(settled: &[FrameSettle]) -> Vec<(u32, usize, SettleStatus)> { settled.iter().map(|settle| (settle.id, settle.depth, settle.status)).collect() } +/// What the start ledger settled for `start`. +fn ledger_settled(settlements: &[LedgerSettlement], start: u32) -> LedgerSettlement { + *settlements + .iter() + .find(|settled| settled.start == start) + .unwrap_or_else(|| panic!("start {start} settled on the ledger: {settlements:?}")) +} + /// `OUTER` sends one wei to `CHILD`, which writes a fresh slot and then returns or reverts as /// `reverts` says; `OUTER` stops either way. The child's start makes two write records, which its /// caller is charged for at the `CALL` and which its failure gives back. @@ -130,12 +139,14 @@ fn test_a_fatal_error_with_starts_open_discards_the_ledger_and_the_evm_runs_on() let mut db = ErrorInjectingDatabase::new(db); db.fail_on_storage = Some((FAILS, key)); let mut evm = MegaEvm::new(context(db)); + record_start_ledger_settlements(evm.ctx_mut()); let failing = call(CALLER, CALLS_FAILS, U256::ZERO, GAS_LIMIT); let error = evm.execute_transaction(failing).expect_err("the storage read fails"); assert!(format!("{error:?}").contains("injected storage()"), "{error:?}"); let (settled, end) = settlements(evm.ctx_mut()); assert_eq!((settled.len(), end), (0, LifecycleEnd::Discarded), "both starts discarded"); + assert_eq!(take_start_ledger_settlements(evm.ctx_mut()), [], "the ledger settled nothing"); let outcome = evm .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) @@ -144,6 +155,12 @@ fn test_a_fatal_error_with_starts_open_discards_the_ledger_and_the_evm_runs_on() let (settled, end) = settlements(evm.ctx_mut()); assert_eq!(end, LifecycleEnd::Settled); assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + // The ledger started over at the transaction's start: its own two starts, the value call's + // charge kept by the call's success. + let ledger = take_start_ledger_settlements(evm.ctx_mut()); + let starts: Vec<_> = ledger.iter().map(|settled| (settled.start, settled.depth)).collect(); + assert_eq!(starts, [(2, 1), (1, 0)]); + assert!(ledger.iter().all(|settled| settled.refund == 0), "{ledger:?}"); } /// Runs a transaction on an EVM of its own, over a copy of the state, in its `call` callback for @@ -157,6 +174,7 @@ impl Inspector, EthInterpreter> for Simulates { fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { if inputs.target_address == CHILD { let mut nested = MegaEvm::new(context(self.db.clone())); + record_start_ledger_settlements(nested.ctx_mut()); let outcome = nested .execute_transaction(call(CALLER, OUTER, U256::from(1), GAS_LIMIT)) .expect("the simulation is valid"); @@ -164,6 +182,9 @@ impl Inspector, EthInterpreter> for Simulates { let (settled, end) = settlements(nested.ctx_mut()); assert_eq!(end, LifecycleEnd::Settled); assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + let ledger = take_start_ledger_settlements(nested.ctx_mut()); + let starts: Vec<_> = ledger.iter().map(|settled| settled.start).collect(); + assert_eq!(starts, [2, 1], "the simulation's own starts, on its own ledger"); self.simulated += 1; } None @@ -179,6 +200,7 @@ fn test_an_evm_run_inside_a_callback_keeps_a_ledger_of_its_own() { let db = value_call_to_a_writer(false); let inspector = Simulates { db: db.clone(), simulated: 0 }; let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); + record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) .expect("the transaction is valid"); @@ -187,6 +209,9 @@ fn test_an_evm_run_inside_a_callback_keeps_a_ledger_of_its_own() { let (settled, end) = settlements(evm.ctx_mut()); assert_eq!(end, LifecycleEnd::Settled); assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + let ledger = take_start_ledger_settlements(evm.ctx_mut()); + let starts: Vec<_> = ledger.iter().map(|settled| settled.start).collect(); + assert_eq!(starts, [2, 1], "the outer transaction's own starts, none of the simulation's"); } /// Answers the transaction's own frame on `Gas::new`, as Foundry answers a cheatcode: in @@ -239,9 +264,9 @@ impl Inspector, EthInterpreter> for AnswersTheTran } /// An inspector's answer to the transaction's own frame, on `Gas::new`, settles as the start -/// ledger settles an inspector's answer — unlimited pools, no start charge back — and the fork -/// settles it the same: a value transfer and a creation, answered with a success, a revert and a -/// halt, in `frame_start` and in `call` or `create`. +/// ledger settles an inspector's answer — unlimited budgets, which the transaction is left with, +/// and no start charge back: a value transfer and a creation, answered with a success, a revert +/// and a halt, in `frame_start` and in `call` or `create`. #[test] fn test_an_inspectors_answer_to_the_transactions_frame_settles_as_unlimited_pools() { let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); @@ -258,12 +283,17 @@ fn test_an_inspectors_answer_to_the_transactions_frame_settles_as_unlimited_pool ); let inspector = AnswersTheTransaction { result, at_frame_start }; let mut evm = MegaEvm::new(context(db())).with_inspector(inspector); + record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm.execute_transaction(transaction).expect("valid"); assert_eq!(outcome.result.is_success(), result.is_ok(), "{case}"); let (settled, end) = settlements(evm.ctx_mut()); assert_eq!(end, LifecycleEnd::Settled, "{case}"); assert_eq!(settled.len(), 1, "{case}"); assert!(settled[0].inspector_answer, "{case}: flagged"); + let ledger = ledger_settled(&take_start_ledger_settlements(evm.ctx_mut()), 1); + assert_eq!(ledger.refund, 0, "{case}: no start charge back"); + assert_eq!(ledger.frame.remaining, PoolAmounts::UNLIMITED, "{case}"); + assert_eq!(ledger.caller.remaining, PoolAmounts::UNLIMITED, "{case}"); } } } @@ -309,20 +339,22 @@ impl Inspector, EthInterpreter> for Rewrites { } } -/// The end-callback rewrites the start ledger settles exactly settle as the fork settles them: -/// a status rewritten either way settles by the new status; a tracker replaced with `Gas::new` -/// settles as unlimited pools, and its start charge comes back by the status; an outcome rebuilt -/// around the same result settles on the frame's pools and gives no start charge back, the -/// constructor having dropped it; one rebuilt keeping the outcome is no rewrite at all. Each on a -/// value call to a child that writes a fresh slot and then succeeds or reverts. +/// The end-callback rewrites settle on the start ledger by the new status and revm's flags: a +/// status rewritten either way settles by the new status, the start charge — the two write records +/// of the value call's start — back on a failure; a tracker replaced with `Gas::new` settles as +/// unlimited budgets, and its start charge comes back by the status; an outcome rebuilt around the +/// same result settles on the frame's budgets and gives no start charge back, as the constructor's +/// outcome carries none; one rebuilt keeping the outcome is no rewrite at all. Each on a value call +/// to a child that writes a fresh slot and then succeeds or reverts. #[test] -fn test_end_callback_rewrites_settle_as_the_fork_settles_them() { +fn test_end_callback_rewrites_settle_by_the_new_status_and_the_flags() { for rewrite in [Rewrite::Status, Rewrite::Tracker, Rewrite::Outcome, Rewrite::KeepingTheOutcome] { for reverts in [false, true] { let case = format!("{rewrite:?}, the child reverts {reverts}"); let mut evm = MegaEvm::new(context(value_call_to_a_writer(reverts))) .with_inspector(Rewrites(rewrite)); + record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) .expect("the transaction is valid"); @@ -339,6 +371,12 @@ fn test_end_callback_rewrites_settle_as_the_fork_settles_them() { Rewrite::Outcome => (false, false, true), }; assert_eq!(flags, expected, "{case}: the flags"); + let ledger = ledger_settled(&take_start_ledger_settlements(evm.ctx_mut()), 2); + let charge = history(2 * WRITE_RECORD_SIZE); + let refunded = !ok && !matches!(rewrite, Rewrite::Outcome); + assert_eq!(ledger.refund, if refunded { charge } else { 0 }, "{case}: the refund"); + let unlimited = ledger.frame.remaining == PoolAmounts::UNLIMITED; + assert_eq!(unlimited, matches!(rewrite, Rewrite::Tracker), "{case}: the budgets"); } } } @@ -418,6 +456,7 @@ fn test_a_creation_that_takes_no_address_settles_as_one() { for rewrite in [AddressRewrite::Cleared, AddressRewrite::AnsweredWithout] { let mut evm = MegaEvm::new(context(creates_an_empty_contract())) .with_inspector(CreationRewrites(rewrite)); + record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) .expect("the transaction is valid"); @@ -436,5 +475,7 @@ fn test_a_creation_that_takes_no_address_settles_as_one() { AddressRewrite::AnsweredWithout => 0, }; assert_eq!(outcome.gas.history, kept.gas.history - given_back, "{rewrite:?}"); + let ledger = ledger_settled(&take_start_ledger_settlements(evm.ctx_mut()), 2); + assert_eq!(ledger.refund, given_back, "{rewrite:?}: the ledger's refund"); } } diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 8ece1bcd5..e80ec51be 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1016,6 +1016,53 @@ fn test_the_transactions_own_frame_that_halts_burns_its_regular_gas() { } } +/// The transaction's own value transfer to a contract that halts keeps neither the value nor its +/// recipient's write record, so the history charged before execution for that record is the +/// transaction's start charge, given back when its start settles — as history, and nothing more: +/// below the execution cap the charge spilled onto regular gas, and the halt burns the regular gas +/// it gives back, so the sender gets back none of it; above the cap the charge came out of the +/// reservoir, which the settlement hands back with the rest. Either way the transaction bills the +/// history and the reservoir of the same call without value, which makes no record. +#[test] +fn test_the_transactions_own_value_transfer_that_halts_gives_its_record_back_as_history_alone() { + use revm::context::result::HaltReason; + + for gas_limit in TIERS { + let run = |value: u64| { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(A, spin()); + let outcome = MegaEvm::new(context(db).with_tx_runtime_limits(armed())) + .execute_transaction(call(CALLER, A, U256::from(value), gas_limit)) + .expect("the transaction is valid"); + assert!( + matches!( + &outcome.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), + .. + } + ), + "value {value}, gas limit {gas_limit}: {:?}", + outcome.result + ); + assert_eq!(outcome.usage.write_records, 0, "value {value}: nothing kept"); + assert_eq!( + outcome.gas.gas_used + outcome.gas.reservoir_remaining, + gas_limit, + "value {value}, gas limit {gas_limit}: the regular gas burned, the reservoir back" + ); + outcome.gas + }; + let (transfer, plain) = (run(1), run(0)); + assert_eq!(transfer.history, plain.history, "gas limit {gas_limit}: the record's history"); + assert_eq!( + transfer.reservoir_remaining, plain.reservoir_remaining, + "gas limit {gas_limit}: what the record's charge took from the reservoir comes back" + ); + } +} + /* ---------- the legacy engine's rows ---------- */ // The legacy engine halted a transaction a limit stopped, and gave back what detention withheld From 535b32d956b14226c1a1399f86e74598dfbd2cb9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 10:38:15 +0800 Subject: [PATCH 54/83] test(satin): a halting child gives its start's records back as a reverting one does --- .../mega-evm/tests/satin/history_reservoir.rs | 44 ++++++++++++++++++- crates/mega-evm/tests/satin/main.rs | 2 +- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index 7b8af71f5..99c2090a9 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -28,7 +28,9 @@ use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, LimitUsage, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use revm::bytecode::opcode::{CALL, CREATE, GAS, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP}; +use revm::bytecode::opcode::{ + CALL, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP, +}; use crate::{ common::{ @@ -199,6 +201,46 @@ fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { ); } +/// A child that halts keeps none of the records its caller paid for either, as one that reverts: +/// the charge goes back once, to the reservoir it came from, while the halt burns the gas the child +/// was forwarded, a fixed forward here, so the two tiers burn the same. The net history is the body +/// alone. +#[test] +fn test_a_halting_child_gives_its_records_back_as_a_reverting_one_does() { + if runs_at_measurement_prices() { + return; + } + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(CONTRACT) + .push_number(100_000u64) + .append(CALL) + .append(POP) + .append(STOP) + .build(); + let outcome = + assert_the_reservoir_pays_what_regular_gas_pays("a value call whose child halts", || { + funded() + .account_code(CALLEE, code.clone()) + .account_code(CONTRACT, Bytes::from_static(&[INVALID])) + }); + + assert!(outcome.result.is_success(), "the caller survives its child's halt"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, + "the halted transfer kept nothing but the body" + ); + assert_eq!(outcome.gas.history, BODY, "the body alone"); + assert_eq!( + outcome.gas.reservoir_remaining, + RESERVOIR - BODY, + "the transfer's records cost the reservoir nothing in the end", + ); +} + /// A value call a system contract's interceptor refuses never starts a frame: its start counts /// nothing and the whole charge comes back. It is the path where the caller is paid back twice if /// the frame inherited the caller's reservoir from before the charge, because the refund of the diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 5173fa9d0..400dbadad 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -49,7 +49,7 @@ mod schedule; #[path = "../shared/snapshot.rs"] mod snapshot; mod spec_numbers; -// The start ledger runs in a debug build alone. +// These read the start lifecycle off revm's debug mirror, which a debug build alone keeps. #[cfg(debug_assertions)] mod start_ledger; mod state; From 297da90cf83b99868920efcf5f43b7af25535ed9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 10:38:15 +0800 Subject: [PATCH 55/83] docs: the engine decides a frame start's budgets, start charge, allowance and reservoir share, and the fork forwards whole --- .claude/skills/satin-review/SKILL.md | 30 ++++++++------ AGENTS.md | 61 +++++++++++++++------------- crates/mega-evm/src/evm/mod.rs | 12 +++--- crates/mega-evm/src/limit/limit.rs | 24 +++++------ crates/mega-evm/src/limit/mod.rs | 32 +++++++-------- 5 files changed, 84 insertions(+), 75 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index d085132d4..d92db7145 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -69,14 +69,17 @@ Each change is stated here in plain words with its reason; the specification has revm's frame run returns an action set on a frame before it runs, without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`: a `keylessDeploy` call's creation and answer, and the stop of a caller a child left over a limit, come back through revm's own run. The run-result hook (`EvmTr::frame_run_result`) is called once a frame's run returns, before the inspector's `call_end`, `create_end` and `frame_end` and before `frame_return_result`; gas detention turns a crossing into the stop there, so inspectors and tracers see the stop the caller gets. Why: both are points in the middle of revm's own loop that mega-evm cannot reach from outside, which is what the fork is for, and with them the engine has no frame run of its own. -- **A debug build keeps its own ledger of every frame start and checks it against the fork's figures.** - The fork carries four figures of a start on the frame's gas: the three pools with their nets and crossings, the part of the reservoir the caller keeps, the start charge and the history allowance. - The engine keeps the same four in an entry per start (`src/limit/ledger.rs`), computed by its own rules and driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and compares them with the fork's at every settlement, panicking on a difference; every result still reads the fork's figures, and a release build carries none of it. - A test of an inspector that answers or rewrites with pools or a start charge it set, or restores a snapshot of a running tracker, records the differences and asserts each, since those figures are accepted to change once the engine reads its own ledger. - Why: the figures are to leave the fork for the engine, and the ledger that will replace them is proved against them, on every engine path, before anything reads it. +- **The engine decides the four figures of a frame start, and the fork forwards whole.** + The fork carries four figures of a start on the frame's gas: the three pools with their nets, the part of the reservoir the caller keeps, the start charge and the history allowance. + The engine now decides all four itself, in every build: the budgets, the start charge and the allowance on its start ledger (`src/limit/ledger.rs`), an entry per start driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and the reservoir's share where the start is made (`MegaContext::forward_start`, named to revm on `FrameStart::reservoir`). + The fork's figures are inert: the Satin schedule keeps Amsterdam's zero in `pool_kept_percent`, `reservoir_kept_percent` and `call_history_allowance`, so revm forwards every pool and the reservoir whole and grants no allowance; the engine declares no start charge on a start or on the first frame's input, puts no pool on a tracker and draws none; its synthetic answers carry neither pools nor a charge. + A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). + The ledger is no longer checked against the fork's figures, which stopped meaning the same once the fork forwards whole; a randomized differential against the build that still read the fork's figures found every result, ledger and inspector observation equal, but for the inspector shapes accepted to change: an answer built on gas whose pools the inspector set or with the input's start charge copied, which settles at unlimited budgets with no charge back, and a tracker an inspector restores from a snapshot, which leaves the ledger's draws where they were. + A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`). + Why: the figures leave the fork for the engine, and the fork's copy of them goes next. - **Writes and frame starts are metered in the fork's instruction hooks.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. - The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, and the frame's own part is declared on the start (`FrameStart::charge`) for the fork to refund when the frame fails. + The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, the frame's own part is parked on the start ledger as the start's charge, which its settlement gives back when the frame fails, and the frame's share of the caller's reservoir is taken and named on the start (`FrameStart::reservoir`). Why: a write the opcode's own failure takes back is never counted, and the engine no longer rebuilds revm's state from outside with instruction wrappers. ### What is counted @@ -137,7 +140,7 @@ Each change is stated here in plain words with its reason; the specification has The three pools give a child `remaining × 98 / 100`, rounded down, so the two formulas differ at some values. Why: the regular forward is Rex6's, and the reservoir share keeps a caller's own work within reach of what it calls, since state and history gas draw the reservoir first; EIP-8037 passes the reservoir whole, which would let a callee spend all of it. - **The history allowance replaces the storage-gas stipend.** - A value `CALL` or `CALLCODE` below the transaction's own frame gives the frame it starts 160 bytes of history (`HISTORY_ALLOWANCE_BYTES`, 14,080 gas at the cost per history byte, the schedule's `call_history_allowance`), on which only a log's history charge draws. + A value `CALL` or `CALLCODE` below the transaction's own frame gives the frame it starts 160 bytes of history (`HISTORY_ALLOWANCE_BYTES`, 14,080 gas at the cost per history byte, kept on the start's entry of the start ledger), on which only a log's history charge draws. It never enters the frame's gas and is on no ledger. Why: a `receive()` reached through Solidity's `transfer()` can still emit one event, and an allowance that is not gas leaves nothing to burn on return. - **One fixed gas budget for the pre-block calls.** @@ -226,7 +229,7 @@ A test name or a line count is not a reason to trust the code: read the code aga - **Stop**: what a limit does. The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, and its caller resumes and may catch it. - **Answered frame**: a frame that gets a result without running (a precompile, a call to an account with no code, an interceptor, the engine, an inspector's hook). -- **Start charge**: the history gas a frame start charges its caller for the records the started frame makes, declared on the start and refunded by the fork when the frame fails. +- **Start charge**: the history gas a frame start charges its caller for the records the started frame makes, kept on the start's entry of the start ledger and given back to the caller when the frame fails. - **Failed-charge record**: the regular gas a frame had before a charge that failed, which the fork keeps, so the engine knows exactly what a halting frame burned. - **Byte-price grid**: the CI job that runs the suite at other costs per state and history byte, because the prices are provisional. @@ -237,7 +240,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. ### Limits: data size, KV updates, state growth, the stop -- **Where:** `src/limit/` (the byte table, `LimitKind`, `LimitCheck`, `MegaLimitExceeded` and `EvmTxRuntimeLimits` in `mod.rs`; the write records and the state growth a write and a frame start make in `record.rs`; `AdditionalLimit` in `limit.rs`; the debug build's start ledger in `ledger.rs`), `src/block/limit.rs` (`ProtocolLimits::for_spec`, `BlockLimits`, `BlockLimiter`), `src/constants.rs`. +- **Where:** `src/limit/` (the byte table, `LimitKind`, `LimitCheck`, `MegaLimitExceeded` and `EvmTxRuntimeLimits` in `mod.rs`; the write records and the state growth a write and a frame start make in `record.rs`; `AdditionalLimit` in `limit.rs`; the start ledger in `ledger.rs`), `src/block/limit.rs` (`ProtocolLimits::for_spec`, `BlockLimits`, `BlockLimiter`), `src/constants.rs`. - **Read first:** the module doc of `src/limit/mod.rs` and the doc of `AdditionalLimit` in `src/limit/limit.rs`. - **Check:** - A count is drawn where it is made, on the pool of the frame that makes it (`AdditionalLimit::draw`), and a failed frame's draws go back with its gas. @@ -265,7 +268,8 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **Check:** - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them. - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. - - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. + - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, parks the frame's own part as the start's charge on the start ledger with the frame's budget shares and allowance, and takes the frame's reservoir share out of the caller (`forward_start`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. + - Every budget a limit check reads, and every draw, is the start ledger's top entry, the running frame's start (`StartLedger::budget`, `draw`); with no start open there is no frame budget. The start charge comes back in `frame_settle`, by the settlement's status, `created` and revm's inspector flags. - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::count` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), but for a call that moves no value and runs no precompile, which writes nothing on them (`start_writes_nothing`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed counts nothing and is held to no records limit, and a precompile gas detention answers from its price counts nothing and is held to the price alone; a start revm refuses on its caller's account counts nothing and is charged nothing. - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); a success revm gave without building a frame gives way to the stop on its untouched forward, its value move and log taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`); an answer that failed is revm's result, held to nothing. - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). @@ -337,12 +341,12 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **Where:** `src/evm/schedule.rs`, `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` (SALT pricing), `state_gas_price` in `src/evm/host.rs`, the Amsterdam opcode activation in `src/evm/instructions.rs`. - **Check:** - Every regular entry is Amsterdam's; state creation is paid once, in state gas. - - The forwards are schedule entries: `call_stipend_reduction` = 50 (the regular-gas cap), `reservoir_kept_percent` = 2, and `pool_kept_percent` = 2 for each of the three pools; the neutral configuration keeps EIP-150's 63/64 and forwards the whole reservoir. + - The regular-gas forward is a schedule entry, `call_stipend_reduction` = 50; the shares of the reservoir and the three budgets are the engine's (`FRAME_KEPT_PERCENT` = 2), and the schedule's `reservoir_kept_percent` and `pool_kept_percent` are Amsterdam's zero; the neutral configuration keeps EIP-150's 63/64 and forwards the whole reservoir and budgets, whatever schedule it is given. - State gas = schedule entry × bucket multiplier `m`; regular gas never scales. A failed capacity lookup is a node fault: the transaction gets no outcome and is not settled, and the node reports an internal error with the cause. - History gas uses the limit layer's byte table, so a record's history bytes are its data size; the three sites where the totals part are in the `src/limit/mod.rs` module doc, "The byte table". - A deposit, a protocol-produced transaction and a system call pay no history gas. - - The history allowance (`HISTORY_ALLOWANCE_BYTES`, 160 bytes; `history_allowance_gas()` in `src/evm/history.rs`, the schedule's `call_history_allowance`) draws only on a log's charge. + - The history allowance (`HISTORY_ALLOWANCE_BYTES`, 160 bytes; `history_allowance_gas()` in `src/evm/history.rs`, kept on the start ledger, the schedule's `call_history_allowance` being zero) draws only on a log's charge. - The EIP-7623 floor is still computed and validated. - The constants are provisional; a build with `satin-price-override` must never reach a node. - **Spec:** §2, §4, §5, §6, §7, §8, §9. @@ -359,7 +363,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing (a frame that fails, or a start revm refuses before it bumps a nonce or moves a value), and its records are those revm then made. - A pre-block system call runs on the plain system-call path, with no callback. - `test_utils::ReadOnlyObserver` checks, in debug builds, that an inspector a test declares an observer writes nothing back: a tripwire for tests, not a proof. - - A debug build's start ledger settles an inspector's answer and a replaced tracker at unlimited pools, and gives no start charge back for an answer or a rebuilt outcome; a test whose inspector builds an answer or a result with pools or a charge of its own, or restores a snapshot of a running tracker, records the ledger's differences from the fork and asserts each, and every other test fails on any difference. + - The start ledger settles an inspector's answer and a replaced tracker at unlimited budgets, and gives no start charge back for an answer or a rebuilt outcome; the pools, charge and allowance fields an inspector writes on an input, an answer or a result are not read, and a restored tracker snapshot leaves the ledger's draws standing; the tests of such inspectors read what the ledger settled. - **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer), the entries on inspectors. ### Node surface, validation and the stateless witness diff --git a/AGENTS.md b/AGENTS.md index 1994e9e1d..6733d113e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,14 +106,15 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `cargo tree -i revm` must show exactly one revm, from the fork: the engine's graph (the default member) never reaches another. The workspace also locks revm 27.1.0, linked only by `mega-evme`: its `legacy` feature, and its `mega-state-test` 1.7.1 dev-dependency, which is unconditional, so a test build without `legacy` links it too (`cargo tree --workspace -i revm@27.1.0`). - The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. -- The engine implements the fork's start lifecycle hooks (`Host::frame_split`, `frame_settle`, `frame_lifecycle_end`) in a debug build alone: each reaches the inner context, whose mirror checks the lifecycle's order, and drives the engine's start ledger (`limit/ledger.rs`), which pairs nothing itself; a release build takes the hooks' defaults, which do nothing. +- The engine implements the fork's start lifecycle hooks (`Host::frame_split`, `frame_settle`, `frame_lifecycle_end`): each reaches the inner context, whose mirror checks the lifecycle's order in a debug build, and drives the engine's start ledger (`limit/ledger.rs`), which pairs nothing itself and decides a start's budgets, its start charge and its history allowance. - Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), whose crossing record holds the regular gas the frame had before the charge that crossed (`WithheldCrossing::remaining`), on the fork's failed-charge record, the regular gas a frame had before every deduction that failed and before a halt on a cold access it could not pay (`failed_charge_remaining`, `set_failed_charge_remaining`), which tells what a halting frame burned, and on the fork's precompile price (`Precompile::required_gas`), none of which upstream revm has. - Writes and frame starts are metered inside revm's instructions, through the fork's two instruction hooks on `Host`, which upstream revm does not have: `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge they make has been made, and the four calls and two creations call `frame_starting` once the forward is taken and before the frame's input is built. `CompletedWrite` and `FrameStartKind` are exhaustive on purpose, so the engine's matches over them carry no wildcard arm and a new kind is a compile error here. - The actions the engine makes for a frame outside an instruction — a `keylessDeploy` call's creation and its answer, and the stop of a frame a child returned into over a limit — come back through revm's own frame run, plain or inspected: the fork's run returns an action set on a frame's interpreter before it runs without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`, so the engine's `frame_run` only forwards to revm's. A frame's own end is decided in the fork's run-result hook (`EvmTr::frame_run_result`), which revm's plain and inspected loops call once a frame's run returns and before the inspector's `call_end`, `create_end` and `frame_end` and `frame_return_result`: gas detention's classification is made there, so an inspector sees the stop the caller gets. - The fork pins at a published commit of its byte-pool branch, and op-revm at a published commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), both by revision until the fork's review is done. - The byte-pool branch carries three resource pools on every frame's gas tracker, which the engine gives their meaning (`PoolId`, `GasTracker::record_pool`, `refill_pool`, `pool_remaining`, `pool_spent`), each forwarded at every start as the schedule's share (`GasId::pool_kept_percent`, the part the caller keeps) and settled as the reservoir is, and the reservoir itself forwarded by its own share (`GasId::reservoir_kept_percent`, `GasTracker::forward_to_child`), the child's return adding what it left to what the caller kept; a start charge the frame-start hook declares on the start (`FrameStart::charge`, `StartCharge`) and the fork refunds when the frame fails; the history allowance a value call gives its child (`GasId::call_history_allowance`, `GasTracker::draw_history_allowance`); a creation's address on its start (`FrameStart::target`) and a `SELFDESTRUCT`'s moved balance on its completed write (`CompletedWrite::SelfDestruct::balance`). + The byte-pool branch carries three resource pools on every frame's gas tracker, each forwarded at every start as the schedule's share (`GasId::pool_kept_percent`) and settled as the reservoir is, the reservoir's own share (`GasId::reservoir_kept_percent`), a start charge the frame-start hook may declare on the start (`FrameStart::charge`) and the history allowance a value call gives its child (`GasId::call_history_allowance`); the engine uses none of these four figures, which the fork removes next: its schedule keeps Amsterdam's zero in the three entries, so the fork forwards every pool and the reservoir whole and grants no allowance, it declares no start charge, and it keeps the budgets, the start charges and the allowances on its own start ledger. + What the engine uses of the branch is the child's reservoir the frame-start hook names (`FrameStart::reservoir`): the engine takes the child's share of the caller's reservoir itself, and revm's settlement adds what the child left to what the caller kept; a creation's address on its start (`FrameStart::target`) and a `SELFDESTRUCT`'s moved balance on its completed write (`CompletedWrite::SelfDestruct::balance`). The fork does not split a system call's gas or report the reservoir on `ResultGas`: Satin does both itself (`MegaHandler::tx_gas`, `AdditionalLimit::reservoir_remaining`), and its op-revm baselines run op-revm through a reference handler that does the same (`tests/shared/op_reference.rs`). Its switch back to revm 40.0.3's journal semantics (`CfgEnv::legacy_journal_semantics`) is the legacy engine's: Satin's spec and neutral configurations fix it off. - The op-revm fork prices its size-limited precompiles through that hook, which upstream op-revm does not, so gas detention decides a call to the BN254 pairing or a BLS12-381 MSM or pairing from its price rather than running it on the allowance. @@ -141,17 +142,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | | `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | | `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); in a debug build, the start ledger beside it: what each open frame start owes and holds of the four figures the fork carries — the three pools with their nets and crossings, the reservoir its caller keeps, its start charge and its history allowance — computed by the engine's own rules, driven by the start lifecycle hooks alone, and compared with the fork's figures at every settlement (`ledger.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | | `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | | `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | | `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | | `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | -| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); in a debug build, the start ledger's differences from the fork that a test of an inspector shape accepted to change records and asserts (`tolerate_start_ledger_divergences`, `take_start_ledger_divergences`, `LedgerDivergence`, `LedgerFigure`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | +| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the start ledger's settlements, which a test records and reads (`record_start_ledger_settlements`, `take_start_ledger_settlements`, `LedgerSettlement`, `LedgerPools`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | ### How Satin executes today - `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments. - Its journal is revm's own (`Journal`): what the transaction keeps of the data-size limit is drawn from the byte pool on each frame's gas tracker and counted on the common execution layer (see the contracts below), not beside the journal. + Its journal is revm's own (`Journal`): what the transaction keeps of the data-size limit is drawn from each frame's budget on the engine's start ledger and counted on the common execution layer (see the contracts below), not beside the journal. It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. - The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 on and not disabled, the chain-id check on (`tx_chain_id_check`, which the legacy engine pinned off), the contract size limit at 512 KiB, the initcode size limit at 1 MiB, and the fork's journal semantics (`legacy_journal_semantics` off). That function is exported as `spec_cfg`: a node builds its `EvmEnv` through it, so what reads the env before an EVM exists (reth's gas estimation reads the execution cap) reads the configuration the EVM runs with. @@ -160,7 +161,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It reports the intrinsic gas by ledger (`IntrinsicGas`): regular, state (zero under EIP-2780, which charges the state a transaction adds when it runs), the body's history, and the floor. op-revm includes a deposit that fails validation as a failed deposit rather than refusing it, so for a deposit or a promoted system-address transaction the error says it would fail. Gas above the 200M execution cap goes to the EIP-8037 reservoir. -- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with four changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte; the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`), and a value call's history allowance at `HISTORY_ALLOWANCE_BYTES` of it; a child starts with 98/100 of its caller's reservoir and of each of its three pools (`GasId::reservoir_kept_percent`, `GasId::pool_kept_percent`); and a call or creation forwards at most `remaining − remaining × 2 / 100` of the caller's regular gas, Rex6's rule in place of EIP-150's 63/64 (`GasId::call_stipend_reduction`). +- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with three changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte; the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`); and a call or creation forwards at most `remaining − remaining × 2 / 100` of the caller's regular gas, Rex6's rule in place of EIP-150's 63/64 (`GasId::call_stipend_reduction`). + The rest of what a start takes is the engine's, not the schedule's, which keeps Amsterdam's zero there: a child starts with 98/100 of its caller's reservoir and of each of its three budgets (`FRAME_KEPT_PERCENT`, the part the caller keeps), and a value call's child with a history allowance of `HISTORY_ALLOWANCE_BYTES` at the cost per history byte, decided where the start is made (`MegaContext::forward_start`). Every regular-gas entry is Amsterdam's, EIP-8038's state-access prices included, so creating state costs the access and the write in regular gas and the new state itself in state gas alone, as upstream. The static opcode prices, which revm keeps in the instruction table, are Amsterdam's too (`satin_gas_table`): they part from the Osaka base's only in EIP-8038's 200-gas base of `EXTCODESIZE` and `EXTCODECOPY`. It is built once per process, with a second copy that prices that entry at zero for a transaction exempt from history gas (`satin_gas_params_history_exempt`); the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. @@ -180,9 +182,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat At the minimum bucket every number is the schedule's own, which is why the op-revm baseline and the pricing table did not move when SALT pricing landed. - History gas prices the bytes a transaction appends to the chain, at `MegaETH`'s cost per history byte and never scaled by SALT — history bytes live in no bucket (`evm/history.rs`). The byte table is the `limit` module's, the same counts the data-size limit meters, so a record's history bytes are its own data size and the two cannot drift apart: a transaction body of 310 bytes (110 for the envelope and one 40-byte record for each of the five writes every transaction makes — the sender's account and the four accounts its fees are credited to), one byte per calldata byte, 20 per access-list address and 32 per key, 101 per EIP-7702 authorization, a log's 32 for its address and 32 per topic plus its data, one 40-byte record per kept account or storage write, and one byte per byte of deployed code. - The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body where revm builds the transaction's gas (`MegaHandler::tx_gas`), as intrinsic gas — the reservoir pays it first, it is not held to the execution cap, and revm's runtime out-of-gas fallback, which rebuilds the gas through the same phase, keeps it charged — and the two record charges in pre-execution, where the records are made; the first frame carries its record's charge on its input (`charged_start`), which the shared first-frame settlement gives back when it fails. + The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body where revm builds the transaction's gas (`MegaHandler::tx_gas`), as intrinsic gas — the reservoir pays it first, it is not held to the execution cap, and revm's runtime out-of-gas fallback, which rebuilds the gas through the same phase, keeps it charged — and the two record charges in pre-execution, where the records are made; the first frame's record charge is the transaction's start charge on the start ledger, parked where its input is built (`first_frame_input`), which the transaction's start settlement gives back when the frame fails, revm consuming what it credits to regular gas after a halt. A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas. - Every other charge is made where the record is: the completed-write hook charges a storage write's record, a log's and a `SELFDESTRUCT`'s records at the end of its opcode, and the frame-start hook charges the caller of a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` for the records the frame it starts makes, out of what the caller kept rather than out of what it forwards, and declares the frame's own on the start (`FrameStart::charge`), which the fork refunds when the frame fails. + Every other charge is made where the record is: the completed-write hook charges a storage write's record, a log's and a `SELFDESTRUCT`'s records at the end of its opcode, and the frame-start hook charges the caller of a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` for the records the frame it starts makes, out of what the caller kept rather than out of what it forwards, and parks the frame's own as the start's charge on the start ledger, which gives it back to the caller when the frame fails (`Host::frame_settle`). What a frame does not keep comes back, at the same price, to whoever paid it. The pairing is per record: per transaction the two totals part at three sites, each by decision — an Oracle hint's payload is data size that is never history, an EIP-7708 transfer log is data size that is never history either, and the body's five records are an upper bound, so a transfer to the block beneficiary or a fee vault pays a record the body already bound. A deposit, a transaction the protocol itself produced and a system call pay no history at all (`MegaContext::prices_history`), and an exempt transaction runs a schedule that prices a deposited byte at zero, so the one history charge revm makes itself is off it too. @@ -209,7 +211,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A start past the call-stack limit, of any scheme or a creation, is answered by the depth guard with revm's own `CallTooDeep` before it is counted. A start's log is the one revm journaled for it; `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log. - The data-size limit holds a transaction to `EvmTxRuntimeLimits::tx_data_size_limit` and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left, under an optional frame cap. - A frame's budget is a pool on its gas tracker (`limit::DATA_SIZE_POOL`; the KV-update and state-growth budgets are the other two pools): the transaction's tracker starts with what the body and the counts made before the frame leave (`AdditionalLimit::first_frame_pools`), revm hands the first frame the whole of it and every child the schedule's share of its caller's (`GasId::pool_kept_percent` = 2, so a child gets 98%), capped where the caller suspends (`cap_the_shares`: the frame cap, and a frame's remaining clamped to its budget, so a negative net never enlarges a child's share), and settles a returning child's pool as it settles the reservoir; the transaction's limit is held beside the pools on what the transaction keeps (`AdditionalLimit::usage`). + A frame's budget is a pool on its start's entry of the engine's start ledger (`limit::DATA_SIZE_POOL`; the KV-update and state-growth budgets are the other two pools): the transaction's start opens with what the body and the counts made before the frame leave (`AdditionalLimit::first_frame_pools`), every child with its share of its caller's, taken where its start is made (`MegaContext::forward_start`: the caller keeps `FRAME_KEPT_PERCENT` = 2, so a child gets 98%, rounded down), capped where the caller suspends (`StartLedger::cap_child`: the frame cap, and a frame's remaining clamped to its budget, so a negative net never enlarges a child's share), and the ledger settles a returning child's pool as revm settles the reservoir; the transaction's limit is held beside the pools on what the transaction keeps (`AdditionalLimit::usage`). In each counted dimension the frame budget is tested before the transaction limit: a crossing of both names the budget, and the transaction limit is named only when the budget is not crossed — after Oracle hints used what the transaction had left, or when a deposit-like transaction's created caller stands on a state-growth limit of nothing; the budgets of the frames on the stack add up to what the transaction has left, so otherwise a frame that crosses the transaction limit crosses its own budget too. The bytes are the byte table's, counted where they are made: the body before any frame, the authorities' records before the first frame, a frame start's records when it starts, held to the limits once revm decided it (none for a start revm refuses on its caller's account), a storage write, a log or a `SELFDESTRUCT`'s records (the account it clears and its beneficiary) once the opcode completed, an EIP-7708 transfer log with the frame-start records or the `SELFDESTRUCT` that moves the value, deployed code once `return_create` has made every charge for it and before it commits the creation (`MegaContext::admit_code_deposit`; code starting with `0xEF` or over the code-size limit, and a creation that cannot pay a part of its deposit, the history included, fail the creation alone and are not counted), an Oracle hint before it is forwarded (one that would cross the transaction's limit is neither counted nor forwarded, and its call is answered with the stop, so the transaction keeps none of its bytes). A frame that crosses its budget or the transaction's limit reverts alone, and its caller resumes (the contracts below). @@ -347,6 +349,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The legacy engine's limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. Its gas leakage pitfalls have no counterpart: detention, the one mechanism that caps a frame's gas, withholds it inside the frame's own tracker, where every reader but a regular charge still counts it, so nothing it withholds is ever moved or released (see Gas detention). Its storage-gas stipend does have a counterpart, the history allowance above, and it is a different thing: it never enters a frame's gas limit, so there is nothing to burn on return. + The per-start figures the engine keeps on its start ledger — the allowance, the start charge, the budgets, and the reservoir share a start takes — are checked against the three paths the legacy engine named, each by a test: an interceptor's answer settles on its start by status, the refused value call's records given back once (`history_reservoir::test_an_intercepted_value_call_gives_its_records_back_once`, `history_allowance::test_an_intercepted_call_neither_takes_nor_adds_an_allowance`, `synthetic_frame_gas::test_an_intercepted_refusal_keeps_the_reservoir`); a stop or a halt of the transaction's own frame gives its start charge back as history alone, revm burning the regular gas the refund credits after a halt (`stops::test_the_transactions_own_value_transfer_that_halts_gives_its_record_back_as_history_alone`, `history_allowance::test_a_transaction_level_stop_does_not_hand_the_allowance_back`); and a frame's return gives the start charge back on a revert and a halt alike and none of the allowance (`history_reservoir::test_a_reverting_child_gives_its_records_back_to_the_reservoir`, `test_a_halting_child_gives_its_records_back_as_a_reverting_one_does`, `history_allowance::test_an_unspent_allowance_does_not_return_to_the_caller`, `history_allowance::test_a_drained_allowance_is_not_refunded_by_a_revert`). ### Gas detention @@ -437,10 +440,10 @@ Every later mechanism plugs into these; a change to one comes back to this layer A `SELFDESTRUCT` that moved value also counts the transfer log revm journaled for the move, in the same check as its records, and is charged nothing for it. After an `SSTORE` it holds the frame to the compute limit again (`Detention::hold`, the one formula over the frame's `GasTracker`): a restore refills the state gas, revm before the hook, and the history gas, the hook, that spilled onto regular gas. - **The frame-start hook.** - revm's `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it (`MegaContext::frame_starting`) after every charge they make and after the forward is taken from the caller, before they build the frame's input: it charges the caller the history of the records the start makes, out of what the caller kept, and declares the part the frame's own records cost on the start (`FrameStart::charge`), which revm carries on the frame's input and outcome and refunds to the caller when the frame fails; the history of a creator's nonce record is charged there and not declared, the record outliving the creation. + revm's `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it (`MegaContext::frame_starting`) after every charge they make and after the forward is taken from the caller, before they build the frame's input: it charges the caller the history of the records the start makes, out of what the caller kept, and parks the part the frame's own records cost as the start's charge on the start ledger, which revm's split of the start takes and the start's settlement gives back to the caller when the frame fails; the history of a creator's nonce record is charged there and not part of the start's charge, the record outliving the creation. The hook only prices, and counts nothing: a start's records are counted once revm decided it, and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision and nothing is given back. - After the hook revm takes the frame's share of the caller's reservoir and of each pool out of the caller (`GasTracker::forward_to_child`) and puts it on the frame's input, so a built frame and an answered start both inherit a share of the reservoir the charge left: `remaining − remaining × 2 / 100` (the schedule's `GasId::reservoir_kept_percent` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs, and the child's return adds what it left back to what the caller kept, unwinding the caller's outstanding spill first (`absorb_returned_reservoir`). - A keyless deployment's creation takes the same share of what the call has left after the call's start charges (`keyless::start`, through `forward_to_child`). + The hook then takes the frame's share of the caller's reservoir out of the caller and names it on the start (`MegaContext::forward_start`, `FrameStart::reservoir`), which revm puts on the frame's input, so a built frame and an answered start both inherit a share of the reservoir the charge left: `remaining − remaining × 2 / 100` (`FRAME_KEPT_PERCENT` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs, and the child's return adds what it left back to what the caller kept, unwinding the caller's outstanding spill first (revm's `absorb_returned_reservoir`); it parks the frame's shares of the caller's budgets, taken out of the caller's entry, beside the charge, and, for a value-transferring `CALL` or `CALLCODE`, the frame's history allowance. + A keyless deployment's creation takes the same shares of what the call has left after the call's start charges (`keyless::start`, through `forward_start`). The transaction's own frame and a system call's outermost frame take the whole reservoir (the fork's `forward_all_to_child`), and the neutral configuration, on the fixture fork's schedule, gives every child the whole. A caller that cannot pay, or a price that does not fit, gets the forward back and the halt's record re-written, and the opcode fails out of gas without starting a frame. The records the hook prices are one rule over caller, target and value (`Accounts::start_records`), asked at the opcode, a creation's at the address it takes (`FrameStart::target`); the records counted on the started frame's pool are those revm's start made, read off the journal once revm decided it, and a price that differs from them is settled by the start's credit. @@ -456,16 +459,21 @@ Every later mechanism plugs into these; a change to one comes back to this layer Records live on the pool of the frame that made them: a success hands them to the caller, a failure takes them back and puts back what the frame took back; a creator's nonce record is the creating frame's, counted on its pool once the creation returned with the nonce bumped, the creation's share having been taken at the opcode before it, so it survives the creation's failure and is held to the creator's budget, not the creation's. It is held to the creator's budget and then to the transaction's limit as it is counted, before the creator runs on, which reverts alone if it crossed (`hold_creator`). The KV count a node reports is the write-record count, which the KV-update limit holds. -- **The byte pool decides.** - A frame's data-size budget is the byte pool on its gas tracker, which the revm fork forwards and settles as it does the reservoir: what the transaction's own execution keeps is drawn there where it is made — a frame start's records and transfer log on the started frame, a completed write and a deposit's code from the Host's hooks — and a frame that fails gives its draws back with its state and history gas. +- **The frame's budget decides.** + A frame's data-size budget is its start's byte pool on the engine's start ledger, forwarded where the start is made and settled when revm settles the start: what the transaction's own execution keeps is drawn there where it is made — a frame start's records and transfer log on the started frame, a completed write and a deposit's code from the Host's hooks — and a frame that fails gives its draws back, as its state and history gas roll back. The transaction's limit is held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints and the authorities' records, which are no frame's, and the frames' draws, counted with them and restored to what they were at a start when that start's frame keeps nothing (`AdditionalLimit::close_start`, one entry per start revm decided, keyed by its depth). The entry also carries what a pool cannot: the write-record count and the transfer logs the transaction reports apart from its bytes, the take-back credit a kept start gives its caller, and a creation's creator as it stood before revm decided it. Nothing a tool or a precompile writes is drawn or counted: only the hooks draw, and only where the transaction's own execution writes; a tool's checkpoint the tool reverts takes the writes back but not the draws. The one exception is a node's own precompile that writes in a success answer, which revm runs inside the start: a start is read off the journal once revm decided it, so what the precompile changes of the start's own accounts — the nonce, balance or code an account's record follows, and one account of state growth for each that was empty and it leaves not empty — and a transfer log it journals are read with the start's, a start counting one transfer log, its value's or the precompile's; its storage writes and its writes to any other account are not (`tests/satin/tool_writes.rs`); the Satin set writes nothing. - Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. -- **A start's charge rides on revm's carriers.** - The frame-start hook declares what a start's own records cost on the start (`FrameStart::charge`), revm carries it on the frame's input and outcome and refunds it when the frame fails, for a frame it built and an answer it gave alike; the transaction's own frame carries its record's charge on its input from `first_frame_input`, refunded by the shared first-frame settlement. An answer the engine builds itself carries its input's share and charge (`synthetic_frame_result`); an inspector's answer carries what the inspector built it with. - The history allowance a value call gives its child is the fork's tracker field, set from the schedule's `call_history_allowance`; only a log draws on it. + Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the start's charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. +- **A start's figures are the engine's, on its start ledger.** + The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding what the start owes and holds: its budgets with their nets, its start charge and its history allowance; it is driven by the start lifecycle hooks alone, and pairs nothing: revm's record says which start settles. + What a start owes is parked where it is decided — `frame_starting`, the keyless builder, the first frame's input (`first_frame_input`) — and taken by revm's split; every draw `AdditionalLimit` makes is on the top entry; the frame cap is applied where the caller suspends (`cap_child`); and a settlement merges by status and revm's inspector flags, giving the start charge back to the caller's gas on a failure, and on a creation that took no address, through `Host::frame_settle`, where revm settles the start: after its own settlement of the frame, and, for the transaction's start, before revm's halt rule consumes what the refund credited to regular gas. + An inspector's answer and a result whose tracker an inspector replaced settle as unlimited budgets; neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back; the figures an inspector puts on an input, an answer or a result — pools, a start charge, an allowance, through the fork's fields — are not read, and a tracker it restores from a snapshot leaves the ledger's draws where they were. + The history allowance a value call gives its child is the entry's; only a log draws on it, first, in the completed-write hook. + A precompile's draws on its answer, which no provider of the engine makes, are adopted fail-closed against the share (`StartLedger::adopt_provider_draws`). + The fork's figures are inert: the schedule forwards every pool and the reservoir whole and grants no allowance, and the engine declares no start charge, puts no pool on a tracker and draws none. + A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`, `take_start_ledger_settlements`). - **The stop.** A limit stops the frame that crosses it with a revert, never a halt, whether the limit is the transaction's or the frame's own budget: the frame reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` (`AdditionalLimit::crossed`, for the data size and gas detention's compute stop alike, answering the exemption), what it counted goes with its frame, and its caller resumes as after any revert. There is no latch: a caller that resumes is within every limit — but where a failure below it put back a record a frame above made while a hint the failed frame sent stays, which stops the caller as it resumes (below) — is held to what the transaction has left, and is stopped in turn by a write or a charge of its own that crosses one, so the transaction never keeps more than its data-size limit and never computes past detention's limit; a caller that catches the stop and ends lets the transaction succeed. @@ -489,13 +497,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **A per-frame gas cap stays inside the frame's tracker.** Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame's run returns (`frame_run_result`). A later mechanism that caps a frame's gas uses the same part; it limits the frame at its start and again after every credit — a child's return, `SSTORE`'s refill — and never releases a creating frame's withheld part before `return_create`, whose charges are the frame's own regular charges. -- **A debug build checks every start's figures against a ledger of the engine's own.** - The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding the four figures the fork carries on the frame's gas — its pools, the reservoir its caller keeps, its start charge and its history allowance — computed by the engine's own rules: what a start owes is parked where it is decided (`frame_starting`, the keyless builder, the first frame's input) and taken by the split, every draw `AdditionalLimit` applies is mirrored on the top entry, the frame cap is applied as `cap_the_shares` applies it, and a settlement merges by status and the inspector flags. - At every settlement it compares the frame's pools as its result returns them, its caller's once settled, the kept reservoir with `held_reservoir` and the start-charge refund with the fork's figures, and the allowance the frame returns for a frame revm built whose result no inspector answered or replaced the tracker of (an answer's allowance is never drawn), and panics on a difference; the lifecycle's successful end finds it empty. - The engine still reads the fork's figures for every result. - The inspector shapes accepted to change when the engine reads its ledger instead — an answer or a result built with pools or a charge the inspector set, a restored snapshot, a replaced interpreter, a copied tracker or outcome, an input the inspector built — differ by design: a test that runs one records the differences and asserts each (`test_utils::tolerate_start_ledger_divergences`). -- **Synthetic frame results carry the caller's pools.** - A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir and byte share (`untouched_call_gas`, `untouched_create_gas`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags and start charge, so revm's own frame return settles it exactly like a result of its own. +- **Synthetic frame results carry the inherited reservoir.** + A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `untouched_create_gas`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so revm's own frame return settles it exactly like a result of its own; it settles on its start's entry of the start ledger by status, budgets and start charge alike, so it carries neither. - **Inspectors in block execution.** Block execution admits any inspector: which inspectors may run on block production is a node's decision, not the engine's. A block builds from an EVM the node made with `MegaEvmFactory::create_evm_with_inspector` (or `MegaEvm::with_inspector`) and `MegaBlockExecutorFactory::create_executor` (or `MegaBlockExecutor::new`). @@ -504,15 +507,15 @@ Every later mechanism plugs into these; a change to one comes back to this layer No rewrite is refused, and none is corrected: the engine takes a rewritten result as given (below). The test utilities' inspectors are not declared. - **A rewritten result is taken as given, as revm takes it.** - revm commits or reverts a frame's journal checkpoint before the inspector sees the frame's result, and the caller settles the result the inspector hands back, its classification, output and gas, reservoir and byte pool included; the engine adds nothing to that settlement. + revm commits or reverts a frame's journal checkpoint before the inspector sees the frame's result, and the caller settles the result the inspector hands back, its classification, output and gas, reservoir included; the start ledger settles the start by the status the inspector left and revm's flags, and the engine adds nothing else to that settlement. A failed frame revived into a success — Foundry's `expectRevert` on a call that wrote and reverted — keeps its journal reverted and settles as a success: its state gas, history, refund and the records it counted merge into its caller, and the upfront charge its caller's opcode made stays. A success rewritten into a failure keeps its journal, the inspector's own writes in that callback included, and settles as a failure: its charges roll back, its counts are restored with its start's entry and its start charge is refunded. - A frame an inspector answers in place of running never started: what its caller's opcode was charged for it — the upfront state gas and the history of its start's records — stays charged unless the answer carries the upfront-charge flags and the start charge back; a creation's creator record is not counted, revm having bumped no nonce, and its history stays charged; and the answer settles on the gas it is built on. + A frame an inspector answers in place of running never started: what its caller's opcode was charged for it — the upfront state gas and the history of its start's records — stays charged unless the answer carries the upfront-charge flags back, the start charge staying charged whatever the answer carries; a creation's creator record is not counted, revm having bumped no nonce, and its history stays charged; and the answer settles on the gas it is built on, at unlimited budgets. So a tool's state and its ledgers can part under a rewrite, as they do under revm; keeping them consistent is the tool's business, and block execution runs no rewriting inspector the node did not choose. - The write records and transfer logs the transaction reports follow the result its caller settles, as the byte pool does (`AdditionalLimit::close_start`). + The write records and transfer logs the transaction reports follow the result its caller settles, as the start's budgets do (`AdditionalLimit::close_start`). - **An inspector's writes to gas.** Gas an inspector writes in the `step_end` of a frame's last instruction reaches nobody: the instruction copied the frame's gas into its result; the result's gas, rewritten in `call_end`, is what the caller merges, reservoir included. - An answer settles on the `Gas` it is built on: `Gas::new(limit)`, which Foundry answers every cheatcode on, carries no reservoir and unlimited pools, so above the execution cap — Foundry's default gas limit of 2^30 is above it — the caller is left only the 2 per cent of its reservoir it kept when it handed the call its share, as the fork's add-settlement has it. + An answer settles on the `Gas` it is built on: `Gas::new(limit)`, which Foundry answers every cheatcode on, carries no reservoir, so above the execution cap — Foundry's default gas limit of 2^30 is above it — the caller is left only the 2 per cent of its reservoir it kept when it handed the call its share, as the fork's add-settlement has it; its budgets are unlimited, the ledger's rule for an inspector's answer. A charge the frame cannot pay is refused and takes nothing, and the frame runs on, with the record of the refused charge left on its gas, as revm leaves it: a withheld-part crossing stops nothing in a frame that ends without an out-of-gas, and a later halt that records nothing of its own is read off the failed-charge record. An inspector that overwrites the interpreter's gas (Foundry's `pauseGasMetering` restores a snapshot before every instruction) overwrites detention's split with it, and the frame runs on the snapshot's split until detention next holds it: at a read, a start or resume, or after an `SSTORE`. - **The interceptor dispatch.** diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index f033533c5..8cf9a3e32 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -14,15 +14,17 @@ //! //! - **A rewrite is taken as given.** revm commits or reverts a frame's journal checkpoint before //! the inspector sees its result, and the caller settles the result the inspector hands back — -//! its classification, output and gas, reservoir and byte pool included — and an answer the -//! inspector gives in place of a frame never reaches the engine's frame start: the depth guard, -//! the interceptors and gas detention see none of it, and it settles on the gas it is built on. +//! its classification, output and gas, reservoir included, the start ledger settling the start by +//! the status the inspector left and revm's flags — and an answer the inspector gives in place of +//! a frame never reaches the engine's frame start: the depth guard, the interceptors and gas +//! detention see none of it, and it settles on the gas it is built on, at unlimited budgets and +//! with no start charge back. //! - **A callback's writes to gas are the inspector's.** A charge a frame cannot pay is refused, //! and leaves its record on the frame's gas as an opcode's does: a crossing of the withheld part //! stops nothing in a frame that ends without an out-of-gas, and a later halt that records //! nothing of its own is read off the record. An inspector that overwrites the interpreter's gas -//! overwrites gas detention's split and the byte pool with it, until detention next holds the -//! frame. +//! overwrites gas detention's split with it, until detention next holds the frame; the frame's +//! budgets are on the start ledger, which a gas it restores does not reach. //! - **What an inspector sees.** A frame's end as the engine settled it: a frame that crossed gas //! detention's compute limit ends with the stop, which the engine makes of its out-of-gas once //! its run returns and before the inspector's `call_end`, `create_end` and `frame_end` see it, as diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index baaffb36e..56e7c1d4e 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -27,18 +27,18 @@ use super::{ /// # The three counted dimensions /// /// Data size, KV updates (write records) and state growth are each limited per transaction and -/// per frame ([`COUNTED`]). A frame's budget in a dimension is a pool on its gas tracker -/// ([`LimitKind::pool`]), which the revm fork forwards and settles as it does the reservoir: the -/// transaction's own frame gets what the transaction has left once its body and the counts made -/// before it are counted ([`first_frame_pools`](Self::first_frame_pools)), every child the -/// schedule's share of what its caller has left (98/100: the caller keeps -/// `GasId::pool_kept_percent`) under the frame cap, a failing frame's draws go back to its pool and -/// a successful one hands its signed net to its caller. A count is drawn where it is made, on the -/// pool of the frame that makes it ([`draw`](Self::draw)): a completed write's record or log, a -/// frame start's records and transfer log on the started frame, deployed code on the creating -/// frame. A creator's nonce record is the creating frame's own, drawn on its pools once the -/// creation returned into it with the nonce bumped ([`close_start`](Self::close_start) hands back -/// what tells): the creation's budgets were taken before it. +/// per frame ([`COUNTED`]). A frame's budget in a dimension is a pool on its start's entry of the +/// start ledger ([`LimitKind::pool`]), which settles when revm settles the start: the transaction's +/// own frame gets what the transaction has left once its body and the counts made before it are +/// counted ([`first_frame_pools`](Self::first_frame_pools)), every child its share of what its +/// caller has left (98/100, the caller keeping `FRAME_KEPT_PERCENT`) under the frame cap, a failing +/// frame's draws go back to its pool and a successful one hands its signed net to its caller. A +/// count is drawn where it is made, on the pool of the frame that makes it ([`draw`](Self::draw)): +/// a completed write's record or log, a frame start's records and transfer log on the started +/// frame, deployed code on the creating frame. A creator's nonce record is the creating frame's +/// own, drawn on its pools once the creation returned into it with the nonce bumped +/// ([`close_start`](Self::close_start) hands back what tells): the creation's budgets were taken +/// before it. /// /// The transaction's limits are held beside the pools, on what the transaction keeps /// ([`usage`](Self::usage)): its body, its Oracle hints, the records of its applied authorities, diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 42ce58bea..f9134f4ad 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -13,13 +13,13 @@ //! ([`LimitCheck::ExceedsLimit`]). //! //! What the data-size limit meters — data-size bytes, among them the write records — is drawn from -//! the byte pool on each frame's gas tracker, which the revm fork forwards to a child as its share -//! and settles as it does the reservoir: a frame that fails gives its draws back, and a frame that -//! succeeds hands its caller what it kept. A write an opcode makes is drawn once the opcode -//! completed, in the Host's completed-write hook, which revm calls after every charge the opcode -//! makes; a frame start's records once revm decided the start, on the pool its frame starts with. -//! [`AdditionalLimit`] holds the transaction's limit beside the pools, on what the transaction -//! keeps, with the stops and the settled figures. +//! each frame's byte pool on the engine's start ledger, which a child's start takes its share of +//! and which settles when revm settles the start: a frame that fails gives its draws back, and a +//! frame that succeeds hands its caller what it kept. A write an opcode makes is drawn once the +//! opcode completed, in the Host's completed-write hook, which revm calls after every charge the +//! opcode makes; a frame start's records once revm decided the start, on the pool its frame starts +//! with. [`AdditionalLimit`] holds the transaction's limit beside the pools, on what the +//! transaction keeps, with the stops and the settled figures. //! //! # The data-size limit //! @@ -204,20 +204,20 @@ use alloy_primitives::Bytes; use alloy_sol_types::SolError; use revm::{context::result::ExecutionResult, interpreter::PoolId}; -/// The pool of a frame's gas tracker that is the frame's data-size budget: the bytes the frame -/// may still keep. +/// The pool of a frame's start on the start ledger that is the frame's data-size budget: the bytes +/// the frame may still keep. pub(crate) const DATA_SIZE_POOL: PoolId = PoolId::new(0); -/// The pool of a frame's gas tracker that is the frame's KV-update budget: the write records the -/// frame may still keep. +/// The pool of a frame's start on the start ledger that is the frame's KV-update budget: the write +/// records the frame may still keep. pub(crate) const KV_UPDATE_POOL: PoolId = PoolId::new(1); -/// The pool of a frame's gas tracker that is the frame's state-growth budget: the new accounts -/// and new storage slots the frame may still keep, net. +/// The pool of a frame's start on the start ledger that is the frame's state-growth budget: the +/// new accounts and new storage slots the frame may still keep, net. pub(crate) const STATE_GROWTH_POOL: PoolId = PoolId::new(2); /// The dimensions the common execution layer counts and limits, each drawn from the pool of a -/// frame's gas tracker it names ([`LimitKind::pool`]), in the order an operation that crosses more +/// frame's start it names ([`LimitKind::pool`]), in the order an operation that crosses more /// than one of them stops on: data size, KV updates, state growth. pub(crate) const COUNTED: [LimitKind; 3] = [LimitKind::DataSize, LimitKind::KvUpdate, LimitKind::StateGrowth]; @@ -532,8 +532,8 @@ impl LimitKind { } } - /// The pool of a frame's gas tracker the dimension is drawn from; `None` for compute, which - /// gas detention holds through the frame's gas instead. + /// The pool of a frame's start the dimension is drawn from; `None` for compute, which gas + /// detention holds through the frame's gas instead. pub(crate) const fn pool(&self) -> Option { match self { Self::DataSize => Some(DATA_SIZE_POOL), From ef989d285af8a0dfde5ddadd0bbc57248c5125b6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 11:05:37 +0800 Subject: [PATCH 56/83] fix(limit): a draw on a start an inspector made itself takes nothing rather than trip a debug assertion --- crates/mega-evm/src/limit/ledger.rs | 30 ++++++-- crates/mega-evm/tests/satin/start_ledger.rs | 76 +++++++++++++++++++-- 2 files changed, 95 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 9553b4517..d4c08a96f 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -414,6 +414,10 @@ impl StartLedger { /// Draws `counted` on the top entry's pools, which the limits admitted: what it takes back goes /// back to each pool first, then what it adds is drawn. A pool it leaves alone is not visited. + /// + /// The limits admit a draw past the pool only for an exempt transaction, which no budget holds: + /// past a saturated unlimited pool, or on a start an inspector built itself, which opens with + /// none. Such a draw takes nothing. pub(crate) fn draw(&mut self, counted: &Counted) { let Some(entry) = self.entries.last_mut() else { return }; for pool in PoolId::ALL { @@ -422,13 +426,7 @@ impl StartLedger { continue; } entry.pools.refill(pool, taken); - let drew = entry.pools.record(pool, added); - // Admitted by the limits, so refused only past a saturated unlimited pool, which an - // exempt transaction's frames hold. - debug_assert!( - drew || entry.pools.remaining.get(pool) == u64::MAX, - "the checks admit the draw" - ); + entry.pools.record(pool, added); } } @@ -804,6 +802,24 @@ mod tests { assert_eq!(StartLedger::default().draw_allowance(5), 5, "no start open"); } + /// A start an inspector built itself, which nothing parked for, opens with no budget; a draw + /// the limits admitted on it anyway — an exempt transaction's, which no budget holds — takes + /// nothing and is no broken invariant. + #[test] + fn test_a_draw_on_a_start_nothing_was_parked_for_takes_nothing() { + let mut ledger = opened(PoolAmounts::UNLIMITED); + ledger.split(2, Some(1), 1); + assert_eq!(ledger.budget(DATA_SIZE_POOL), (0, 0), "no budget"); + ledger.draw(&Counted::records(1, 0, false).with_growth(1, 0)); + assert_eq!(ledger.top_pools(), [(0, 0); PoolId::COUNT], "nothing taken"); + assert_eq!(ledger.settle(&settled(2, 1, SettleStatus::Ok)), 0); + assert_eq!( + top(&ledger).remaining, + PoolAmounts::UNLIMITED, + "the caller's pools as they were" + ); + } + /// The running frame's budget is its entry's pools; with no start open there is none, and a /// draw draws nothing. #[test] diff --git a/crates/mega-evm/tests/satin/start_ledger.rs b/crates/mega-evm/tests/satin/start_ledger.rs index d5b8ed73f..1b58e66b1 100644 --- a/crates/mega-evm/tests/satin/start_ledger.rs +++ b/crates/mega-evm/tests/satin/start_ledger.rs @@ -21,18 +21,21 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, REVERT, STOP}, - context::{BlockEnv, ContextTr}, + context::{BlockEnv, ContextTr, JournalTr}, context_interface::{ host::{FrameSettle, LifecycleEnd, SettleStatus}, LifecycleEvent, LocalContextTr, }, handler::FrameResult, interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, - FrameInput, Gas, InstructionResult, InterpreterResult, PoolAmounts, + interpreter::EthInterpreter, + interpreter_types::{InputsTr, LoopControl}, + CallInput, CallInputs, CallOutcome, CallScheme, CallValue, CreateInputs, CreateOutcome, + FrameInput, Gas, InstructionResult, Interpreter, InterpreterAction, InterpreterResult, + PoolAmounts, }, primitives::CALL_STACK_LIMIT, - Database, Inspector, + Database, InspectSystemCallEvm, Inspector, }; use crate::common::{block, call, context, create, history}; @@ -479,3 +482,68 @@ fn test_a_creation_that_takes_no_address_settles_as_one() { assert_eq!(ledger.refund, given_back, "{rewrite:?}: the ledger's refund"); } } + +/// Starts a call of its own from the first instruction `OUTER` runs, without an opcode: a start +/// nothing parked anything for. +struct StartsItsOwnCall { + started: bool, +} + +impl Inspector, EthInterpreter> for StartsItsOwnCall { + fn step(&mut self, interp: &mut Interpreter, ctx: &mut MegaContext) { + if self.started || interp.input.target_address() != OUTER { + return; + } + self.started = true; + // The account a call's opcode would have loaded, with its code, before it starts the frame. + let callee = JournalTr::load_account_with_code(ctx.journal_mut(), CHILD) + .expect("the database serves the callee"); + let info = &callee.data.info; + let known_bytecode = (info.code_hash, info.code.clone().expect("loaded with its code")); + let inputs = CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 0..0, + gas_limit: 1_000_000, + bytecode_address: CHILD, + known_bytecode, + target_address: CHILD, + caller: OUTER, + value: CallValue::Transfer(U256::ZERO), + scheme: CallScheme::Call, + is_static: false, + reservoir: 0, + charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: PoolAmounts::UNLIMITED, + history_allowance: 0, + }; + interp.bytecode.set_action(InterpreterAction::NewFrame(FrameInput::Call(Box::new(inputs)))); + } +} + +/// A start an inspector makes itself, without an opcode, has nothing parked and opens with no +/// budget on the start ledger. A system call is held to no budget, so a write in that frame is +/// admitted, and the ledger takes nothing for it: the call succeeds and keeps the write. +#[test] +fn test_a_write_in_a_start_an_inspector_made_itself_runs_in_a_system_call() { + let outer = BytecodeBuilder::default().append_many([PUSH0, POP]).stop().build(); + let child = BytecodeBuilder::default().sstore(U256::from(7), U256::from(1)).stop().build(); + let db = MemoryDatabase::default().account_code(OUTER, outer).account_code(CHILD, child); + let mut evm = MegaEvm::new(context(db)).with_inspector(StartsItsOwnCall { started: false }); + record_start_ledger_settlements(evm.ctx_mut()); + let result = InspectSystemCallEvm::inspect_one_system_call_with_caller( + &mut evm, + CALLER, + OUTER, + Bytes::new(), + ) + .expect("the system call runs"); + assert!(result.is_success(), "{result:?}"); + assert!(evm.inspector().started); + let ledger = take_start_ledger_settlements(evm.ctx_mut()); + let child = ledger_settled(&ledger, 2); + assert_eq!(child.frame.remaining, PoolAmounts::ZERO, "no budget"); + assert_eq!(child.frame.net, [0; 3], "the write took nothing"); + let slot = evm.ctx().journal_ref().state[&CHILD].storage[&U256::from(7)].present_value; + assert_eq!(slot, U256::from(1), "the write is kept"); +} From 4b1cb409d375294842dc9c018fb882907c98fc2a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 11:10:00 +0800 Subject: [PATCH 57/83] test(satin): the start ledger's lifecycle tests run in release too, and share one settlement lookup --- crates/mega-evm/src/limit/limit.rs | 10 +- crates/mega-evm/tests/satin/common.rs | 13 +- .../tests/satin/inspector_cheatcodes.rs | 2 +- crates/mega-evm/tests/satin/main.rs | 2 - crates/mega-evm/tests/satin/start_ledger.rs | 132 ++++++++++-------- 5 files changed, 86 insertions(+), 73 deletions(-) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 56e7c1d4e..3b6c8d15a 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -710,9 +710,9 @@ impl AdditionalLimit { /// is counted after the creation's own counts are closed, and outlives the creation's failure. /// /// A result revm did not decide the start of — the depth guard's, an interceptor's, an - /// inspector's — has no start to close, and no creator: revm bumped no nonce for it. The depth - /// guard's and an interceptor's carry the start charge their input declared, which revm gives - /// back; an inspector's carries what the inspector built it with. + /// inspector's — has no start to close, and no creator: revm bumped no nonce for it. The start + /// charge of each comes back where revm settles its start, from the start ledger: by its status + /// for the depth guard's and an interceptor's, never for an inspector's. pub(crate) fn close_start(&mut self, depth: usize, kept: bool) -> (u64, Option) { let Some(&start) = self.decided.last().filter(|start| start.depth == depth) else { return (0, None); @@ -956,7 +956,7 @@ mod tests { let mut layer = AdditionalLimit::new(limits); layer.begin_transaction(class, 0); let ledger = layer.ledger_mut(); - ledger.park_transaction(Some(super::super::Parked::transaction(pools, 0))); + ledger.park_transaction(Some(crate::limit::Parked::transaction(pools, 0))); ledger.split(1, None, 0); layer } @@ -1117,7 +1117,7 @@ mod tests { // Two drawn already, so a frame's net is not zero. let mut layer = layer.clone(); let ledger = layer.ledger_mut(); - let start = super::super::Parked::transaction( + let start = crate::limit::Parked::transaction( PoolAmounts::ZERO .with(DATA_SIZE_POOL, pa + 2) .with(KV_UPDATE_POOL, pb + 2) diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index cde71b57c..f0c0349b3 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -311,12 +311,17 @@ pub(crate) fn assert_answered_at_unlimited_budgets( start: u32, depth: usize, ) { - let settled = settlements - .iter() - .find(|settled| settled.start == start) - .unwrap_or_else(|| panic!("start {start} settled: {settlements:?}")); + let settled = ledger_settled(settlements, start); assert_eq!(settled.depth, depth, "start {start}"); assert_eq!(settled.frame.remaining, PoolAmounts::UNLIMITED, "start {start}: the answer's"); assert_eq!(settled.frame.net, [0; PoolId::COUNT], "start {start}: the answer's"); assert_eq!(settled.caller.remaining, PoolAmounts::UNLIMITED, "start {start}: its caller's"); } + +/// What the start ledger settled for `start`, among `settlements`. +pub(crate) fn ledger_settled(settlements: &[LedgerSettlement], start: u32) -> LedgerSettlement { + *settlements + .iter() + .find(|settled| settled.start == start) + .unwrap_or_else(|| panic!("start {start} settled on the ledger: {settlements:?}")) +} diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 54d720be6..5679e8d3f 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -319,7 +319,7 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { // and one new slot. The budgets themselves read unlimited, the cheatcode's answer at the // pause having left `TEST` with unlimited budgets. let settlements = take_start_ledger_settlements(evm.ctx_mut()); - let resumed = settlements.iter().find(|settled| settled.start == 3).expect("settled"); + let resumed = crate::common::ledger_settled(&settlements, 3); assert_eq!((resumed.depth, resumed.caller.net), (1, [WRITE_RECORD_SIZE as i64, 1, 1])); assert_eq!(resumed.caller.remaining, revm::interpreter::PoolAmounts::UNLIMITED); (outcome, evm.inspector().answered) diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 400dbadad..8fa4b99e2 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -49,8 +49,6 @@ mod schedule; #[path = "../shared/snapshot.rs"] mod snapshot; mod spec_numbers; -// These read the start lifecycle off revm's debug mirror, which a debug build alone keeps. -#[cfg(debug_assertions)] mod start_ledger; mod state; mod state_growth; diff --git a/crates/mega-evm/tests/satin/start_ledger.rs b/crates/mega-evm/tests/satin/start_ledger.rs index 1b58e66b1..98ec373c0 100644 --- a/crates/mega-evm/tests/satin/start_ledger.rs +++ b/crates/mega-evm/tests/satin/start_ledger.rs @@ -6,16 +6,17 @@ //! the lifecycle's paths the rest of the suite does not: the depth guard's answer inside a running //! transaction, a fatal error with starts open and the reuse of the EVM after it, an EVM run inside //! an inspector's callback, an inspector's answer to the transaction's own frame, the end-callback -//! rewrites the ledger settles by the new status and revm's flags, and a creation that takes no -//! address. Each reads the starts revm settled off its debug mirror of the lifecycle, so the path -//! is shown taken, and what the ledger settled for them (`take_start_ledger_settlements`). +//! rewrites the ledger settles by the new status and revm's flags, a creation that takes no +//! address, and a start an inspector makes itself. Each asserts what the ledger settled for its +//! starts (`take_start_ledger_settlements`), and, in a debug build, reads the starts revm settled +//! off its debug mirror of the lifecycle, so the path is shown taken with the status and the flags +//! revm settled it with. use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ test_utils::{ neutral_cfg, neutralize_evm, record_start_ledger_settlements, - take_start_ledger_settlements, BytecodeBuilder, ErrorInjectingDatabase, LedgerSettlement, - MemoryDatabase, + take_start_ledger_settlements, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, }, EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, WRITE_RECORD_SIZE, }; @@ -38,7 +39,7 @@ use revm::{ Database, InspectSystemCallEvm, Inspector, }; -use crate::common::{block, call, context, create, history}; +use crate::common::{block, call, context, create, history, ledger_settled}; const CALLER: Address = address!("0000000000000000000000000000000000d00000"); const OUTER: Address = address!("0000000000000000000000000000000000d00001"); @@ -48,10 +49,13 @@ const CALLS_FAILS: Address = address!("0000000000000000000000000000000000d00005" const GAS_LIMIT: u64 = 10_000_000; /// The settlements of the last transaction's start lifecycle, as revm's debug mirror recorded -/// them, and how it ended: each settlement is one the start ledger compared with the fork's -/// figures. -fn settlements(ctx: &mut MegaContext) -> (Vec, LifecycleEnd) { - let mirror = ctx.local_mut().lifecycle_mirror().expect("a debug build's mirror"); +/// them — the status, `created` and revm's inspector flags each start settled with — and how it +/// ended; `None` in a release build, which keeps no mirror. Each settlement is one the start ledger +/// settled. +fn settlements( + ctx: &mut MegaContext, +) -> Option<(Vec, LifecycleEnd)> { + let mirror = ctx.local_mut().lifecycle_mirror()?; let mut settled = Vec::new(); let mut end = None; for event in mirror.events() { @@ -61,7 +65,7 @@ fn settlements(ctx: &mut MegaContext) -> (Vec, Li LifecycleEvent::Split(_) => {} } } - (settled, end.expect("the lifecycle ended")) + Some((settled, end.expect("the lifecycle ended"))) } /// `(start, depth, status)` of each settlement, innermost first. @@ -69,14 +73,6 @@ fn shape(settled: &[FrameSettle]) -> Vec<(u32, usize, SettleStatus)> { settled.iter().map(|settle| (settle.id, settle.depth, settle.status)).collect() } -/// What the start ledger settled for `start`. -fn ledger_settled(settlements: &[LedgerSettlement], start: u32) -> LedgerSettlement { - *settlements - .iter() - .find(|settled| settled.start == start) - .unwrap_or_else(|| panic!("start {start} settled on the ledger: {settlements:?}")) -} - /// `OUTER` sends one wei to `CHILD`, which writes a fresh slot and then returns or reverts as /// `reverts` says; `OUTER` stops either way. The child's start makes two write records, which its /// caller is charged for at the `CALL` and which its failure gives back. @@ -113,19 +109,26 @@ fn test_the_depth_guards_answer_settles_on_its_start() { .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); let mut evm = MegaEvm::new(ctx); neutralize_evm(&mut evm, EthSpecId::OSAKA).expect("Osaka neutralizes"); + record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm .execute_transaction(call(CALLER, RECURSES, U256::ZERO, 1_000_000_000_000)) .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - let (settled, end) = settlements(evm.ctx_mut()); - assert_eq!(end, LifecycleEnd::Settled); let past = CALL_STACK_LIMIT as usize + 1; - assert_eq!(settled.len(), past + 1, "a start for every frame and the guard's answer"); - // revm counts `CallTooDeep` among its revert results. - let guards = [(past as u32 + 1, past, SettleStatus::Revert)]; - assert_eq!(shape(&settled[..1]), guards, "the guard's answer"); - assert!(settled[1..].iter().all(|settle| settle.status == SettleStatus::Ok), "the frames'"); + let ledger = take_start_ledger_settlements(evm.ctx_mut()); + assert_eq!(ledger.len(), past + 1, "a start for every frame and the guard's answer"); + let guard = ledger[0]; + assert_eq!((guard.start, guard.depth, guard.refund), (past as u32 + 1, past, 0)); + if let Some((settled, end)) = settlements(evm.ctx_mut()) { + assert_eq!(end, LifecycleEnd::Settled); + assert_eq!(settled.len(), past + 1, "a start for every frame and the guard's answer"); + // revm counts `CallTooDeep` among its revert results. + let guards = [(past as u32 + 1, past, SettleStatus::Revert)]; + assert_eq!(shape(&settled[..1]), guards, "the guard's answer"); + let frames = &settled[1..]; + assert!(frames.iter().all(|settle| settle.status == SettleStatus::Ok), "the frames'"); + } } /// A database error in a frame two starts deep fails the transaction with both starts open: the @@ -147,17 +150,19 @@ fn test_a_fatal_error_with_starts_open_discards_the_ledger_and_the_evm_runs_on() let failing = call(CALLER, CALLS_FAILS, U256::ZERO, GAS_LIMIT); let error = evm.execute_transaction(failing).expect_err("the storage read fails"); assert!(format!("{error:?}").contains("injected storage()"), "{error:?}"); - let (settled, end) = settlements(evm.ctx_mut()); - assert_eq!((settled.len(), end), (0, LifecycleEnd::Discarded), "both starts discarded"); + if let Some((settled, end)) = settlements(evm.ctx_mut()) { + assert_eq!((settled.len(), end), (0, LifecycleEnd::Discarded), "both starts discarded"); + } assert_eq!(take_start_ledger_settlements(evm.ctx_mut()), [], "the ledger settled nothing"); let outcome = evm .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - let (settled, end) = settlements(evm.ctx_mut()); - assert_eq!(end, LifecycleEnd::Settled); - assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + if let Some((settled, end)) = settlements(evm.ctx_mut()) { + assert_eq!(end, LifecycleEnd::Settled); + assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + } // The ledger started over at the transaction's start: its own two starts, the value call's // charge kept by the call's success. let ledger = take_start_ledger_settlements(evm.ctx_mut()); @@ -182,9 +187,10 @@ impl Inspector, EthInterpreter> for Simulates { .execute_transaction(call(CALLER, OUTER, U256::from(1), GAS_LIMIT)) .expect("the simulation is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - let (settled, end) = settlements(nested.ctx_mut()); - assert_eq!(end, LifecycleEnd::Settled); - assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + if let Some((settled, end)) = settlements(nested.ctx_mut()) { + assert_eq!(end, LifecycleEnd::Settled); + assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + } let ledger = take_start_ledger_settlements(nested.ctx_mut()); let starts: Vec<_> = ledger.iter().map(|settled| settled.start).collect(); assert_eq!(starts, [2, 1], "the simulation's own starts, on its own ledger"); @@ -209,9 +215,10 @@ fn test_an_evm_run_inside_a_callback_keeps_a_ledger_of_its_own() { .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(evm.inspector().simulated, 1); - let (settled, end) = settlements(evm.ctx_mut()); - assert_eq!(end, LifecycleEnd::Settled); - assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + if let Some((settled, end)) = settlements(evm.ctx_mut()) { + assert_eq!(end, LifecycleEnd::Settled); + assert_eq!(shape(&settled), [(2, 1, SettleStatus::Ok), (1, 0, SettleStatus::Ok)]); + } let ledger = take_start_ledger_settlements(evm.ctx_mut()); let starts: Vec<_> = ledger.iter().map(|settled| settled.start).collect(); assert_eq!(starts, [2, 1], "the outer transaction's own starts, none of the simulation's"); @@ -289,10 +296,11 @@ fn test_an_inspectors_answer_to_the_transactions_frame_settles_as_unlimited_pool record_start_ledger_settlements(evm.ctx_mut()); let outcome = evm.execute_transaction(transaction).expect("valid"); assert_eq!(outcome.result.is_success(), result.is_ok(), "{case}"); - let (settled, end) = settlements(evm.ctx_mut()); - assert_eq!(end, LifecycleEnd::Settled, "{case}"); - assert_eq!(settled.len(), 1, "{case}"); - assert!(settled[0].inspector_answer, "{case}: flagged"); + if let Some((settled, end)) = settlements(evm.ctx_mut()) { + assert_eq!(end, LifecycleEnd::Settled, "{case}"); + assert_eq!(settled.len(), 1, "{case}"); + assert!(settled[0].inspector_answer, "{case}: flagged"); + } let ledger = ledger_settled(&take_start_ledger_settlements(evm.ctx_mut()), 1); assert_eq!(ledger.refund, 0, "{case}: no start charge back"); assert_eq!(ledger.frame.remaining, PoolAmounts::UNLIMITED, "{case}"); @@ -362,18 +370,19 @@ fn test_end_callback_rewrites_settle_by_the_new_status_and_the_flags() { .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); - let (settled, end) = settlements(evm.ctx_mut()); - assert_eq!(end, LifecycleEnd::Settled, "{case}"); - let child = settled[0]; let ok = matches!(rewrite, Rewrite::Status) == reverts; - assert_eq!(child.status == SettleStatus::Ok, ok, "{case}: the settled status"); - let flags = (child.inspector_answer, child.gas_replaced, child.outcome_rebuilt); - let expected = match rewrite { - Rewrite::Status | Rewrite::KeepingTheOutcome => (false, false, false), - Rewrite::Tracker => (false, true, false), - Rewrite::Outcome => (false, false, true), - }; - assert_eq!(flags, expected, "{case}: the flags"); + if let Some((settled, end)) = settlements(evm.ctx_mut()) { + assert_eq!(end, LifecycleEnd::Settled, "{case}"); + let child = settled[0]; + assert_eq!(child.status == SettleStatus::Ok, ok, "{case}: the settled status"); + let flags = (child.inspector_answer, child.gas_replaced, child.outcome_rebuilt); + let expected = match rewrite { + Rewrite::Status | Rewrite::KeepingTheOutcome => (false, false, false), + Rewrite::Tracker => (false, true, false), + Rewrite::Outcome => (false, false, true), + }; + assert_eq!(flags, expected, "{case}: the flags"); + } let ledger = ledger_settled(&take_start_ledger_settlements(evm.ctx_mut()), 2); let charge = history(2 * WRITE_RECORD_SIZE); let refunded = !ok && !matches!(rewrite, Rewrite::Outcome); @@ -464,15 +473,16 @@ fn test_a_creation_that_takes_no_address_settles_as_one() { .execute_transaction(call(CALLER, OUTER, U256::ZERO, GAS_LIMIT)) .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{rewrite:?}: {:?}", outcome.result); - let (settled, end) = settlements(evm.ctx_mut()); - assert_eq!(end, LifecycleEnd::Settled, "{rewrite:?}"); - let creation = settled[0]; - assert_eq!((creation.id, creation.depth), (2, 1), "{rewrite:?}: the creation's start"); - assert_eq!( - (creation.status, creation.created, creation.inspector_answer), - (SettleStatus::Ok, Some(false), rewrite == AddressRewrite::AnsweredWithout), - "{rewrite:?}: a success that took no address" - ); + if let Some((settled, end)) = settlements(evm.ctx_mut()) { + assert_eq!(end, LifecycleEnd::Settled, "{rewrite:?}"); + let creation = settled[0]; + assert_eq!((creation.id, creation.depth), (2, 1), "{rewrite:?}: the creation's start"); + assert_eq!( + (creation.status, creation.created, creation.inspector_answer), + (SettleStatus::Ok, Some(false), rewrite == AddressRewrite::AnsweredWithout), + "{rewrite:?}: a success that took no address" + ); + } let given_back = match rewrite { AddressRewrite::Cleared => history(WRITE_RECORD_SIZE), AddressRewrite::AnsweredWithout => 0, From 803b2c7d1783dd3499b3a96348c477d8347241ad Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 11:10:01 +0800 Subject: [PATCH 58/83] docs: a frame's budgets and start charge are the start ledger's wherever the docs still put them on the gas tracker --- .claude/skills/satin-review/SKILL.md | 16 +++++++++------- AGENTS.md | 27 ++++++++++++++------------- REVIEW.md | 2 +- crates/mega-evm/src/evm/host.rs | 8 ++++---- crates/mega-evm/src/limit/ledger.rs | 10 +++++----- 5 files changed, 33 insertions(+), 30 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index d92db7145..2ace61262 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -74,9 +74,10 @@ Each change is stated here in plain words with its reason; the specification has The engine now decides all four itself, in every build: the budgets, the start charge and the allowance on its start ledger (`src/limit/ledger.rs`), an entry per start driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and the reservoir's share where the start is made (`MegaContext::forward_start`, named to revm on `FrameStart::reservoir`). The fork's figures are inert: the Satin schedule keeps Amsterdam's zero in `pool_kept_percent`, `reservoir_kept_percent` and `call_history_allowance`, so revm forwards every pool and the reservoir whole and grants no allowance; the engine declares no start charge on a start or on the first frame's input, puts no pool on a tracker and draws none; its synthetic answers carry neither pools nor a charge. A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). - The ledger is no longer checked against the fork's figures, which stopped meaning the same once the fork forwards whole; a randomized differential against the build that still read the fork's figures found every result, ledger and inspector observation equal, but for the inspector shapes accepted to change: an answer built on gas whose pools the inspector set or with the input's start charge copied, which settles at unlimited budgets with no charge back, and a tracker an inspector restores from a snapshot, which leaves the ledger's draws where they were. + The ledger is not checked against the fork's figures, which do not mean the same once the fork forwards whole. + The inspector shapes whose results change: an answer built on gas whose pools the inspector set, or with the input's start charge copied, settles at unlimited budgets with no charge back; a tracker an inspector restores from a snapshot, or a replaced interpreter, leaves the ledger's draws and allowance where they were. A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`). - Why: the figures leave the fork for the engine, and the fork's copy of them goes next. + Why: the figures are the engine's decisions, and the fork carries them only until they leave it. - **Writes and frame starts are metered in the fork's instruction hooks.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, the frame's own part is parked on the start ledger as the start's charge, which its settlement gives back when the frame fails, and the frame's share of the caller's reservoir is taken and named on the start (`FrameStart::reservoir`). @@ -223,7 +224,7 @@ A test name or a line count is not a reason to trust the code: read the code aga - **System-originated** (spec §19, `originates_from_the_protocol` in `src/system/tx.rs`), decided from the transaction's own fields: an MST before or after promotion; any transaction whose caller is the pre-block caller; any deposit carrying the source hash the promotion stamps, `keccak256("MEGA_SYSTEM_TRANSACTION")`, whoever sends it. Such work is exempt from history gas, every per-transaction limit and frame budget, and detention, and priced at the minimum bucket; its usage is still counted. -- **Pool**: a frame's budget in data size, KV updates or state growth, held on its `GasTracker`; the fork forwards a child its share at the start and settles the child's pools on its return, as it does the reservoir. +- **Pool**: a frame's budget in data size, KV updates or state growth, held on its start's entry of the engine's start ledger (`src/limit/ledger.rs`); the frame-start hook parks a child's share, revm's split of the start opens the child's entry with it, and revm's settlement of the start merges the child's pools into its caller's, as revm settles the reservoir. - **Write record**: one per account or storage slot the transaction keeps changed, by the net change; 40 bytes of data size and of history; the KV count. - **State growth**: the net count of new accounts and new slots the transaction keeps. - **Stop**: what a limit does. @@ -243,14 +244,14 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **Where:** `src/limit/` (the byte table, `LimitKind`, `LimitCheck`, `MegaLimitExceeded` and `EvmTxRuntimeLimits` in `mod.rs`; the write records and the state growth a write and a frame start make in `record.rs`; `AdditionalLimit` in `limit.rs`; the start ledger in `ledger.rs`), `src/block/limit.rs` (`ProtocolLimits::for_spec`, `BlockLimits`, `BlockLimiter`), `src/constants.rs`. - **Read first:** the module doc of `src/limit/mod.rs` and the doc of `AdditionalLimit` in `src/limit/limit.rs`. - **Check:** - - A count is drawn where it is made, on the pool of the frame that makes it (`AdditionalLimit::draw`), and a failed frame's draws go back with its gas. + - A count is drawn where it is made, on the pool of the frame that makes it (`AdditionalLimit::draw`), and a failed frame's draws go back when its start settles. - The transaction's limits are held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints, the authorities' records and the accounts they created, a deposit's created caller, and what the frames keep, restored when a start's frame keeps nothing (`AdditionalLimit::close_start`). - A completed write and a decided start are held in one function (`AdditionalLimit::check`, through `draw` and `count_start`): in the order data size, KV updates, state growth (`limit::COUNTED`), the frame budget, then the transaction limit; a hint, the authorization list and a caller's hold at a child's return check the same limits directly. - The stop names the budget when the budget is crossed, and the transaction limit only when it is not, which a framed write reaches only in data size, after Oracle hints used what the transaction had left; a start names it too when a deposit-like transaction's created caller stands on a state-growth limit of nothing, which only a tool's limit sets. - Every stop comes from `AdditionalLimit::crossed`, which also applies the exemption of system-originated work and system calls. - A write record follows the net change: an account's while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original; the sender's account and the fee credits the settlement makes are the body's, not records. - A creator's nonce record is counted on the creator when the creation returns with the nonce bumped, held to the creator's budget, and survives the creation's failure; the creation's budget is the share taken at the opcode, before it. - - State growth rises by one at each EIP-8037 account-leaf or fresh-slot charge site and for the caller a failed deposit creates, and a slot written from an original zero back to zero falls by one; a frame's net is signed, a negative net never enlarges a child's budget (`cap_the_shares` in `src/evm/execution.rs`), and a transaction reports `max(net, 0)`. + - State growth rises by one at each EIP-8037 account-leaf or fresh-slot charge site and for the caller a failed deposit creates, and a slot written from an original zero back to zero falls by one; a frame's net is signed, a negative net never enlarges a child's budget (`StartLedger::cap_child` in `src/limit/ledger.rs`), and a transaction reports `max(net, 0)`. - The first effective `SELFDESTRUCT` of an account created in the transaction applies the destruction table: each part absent at the transaction's start (a slot by its original in the transaction, a leaf by no account standing there) and present before the destruction is refilled at the price it was charged, to the destroying frame, the leaf and each such slot lower state growth by one and lose their write records, and the code's data size and history gas are taken back; from the mark the account adds no further state growth, state gas or write record, and a failure of the destroying frame, or of a frame that contains it, discards it all. - A caller resumed after its child's crossing is held to what the transaction has left, and stops in turn if a count or a charge of its own crosses again; a caller a failure below it left over the transaction's data-size limit, a hint having filled room a take-back freed, returns the transaction's stop before its next instruction (`AdditionalLimit::hold_caller`). - `LimitKind` keeps Rex6's encoding: data size 0, KV updates 1, compute gas 2, state growth 3. @@ -269,7 +270,8 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them. - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, parks the frame's own part as the start's charge on the start ledger with the frame's budget shares and allowance, and takes the frame's reservoir share out of the caller (`forward_start`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. - - Every budget a limit check reads, and every draw, is the start ledger's top entry, the running frame's start (`StartLedger::budget`, `draw`); with no start open there is no frame budget. The start charge comes back in `frame_settle`, by the settlement's status, `created` and revm's inspector flags. + - Every budget a limit check reads, and every draw, is the start ledger's top entry, the running frame's start (`StartLedger::budget`, `draw`); with no start open there is no frame budget. + - The start charge comes back in `frame_settle`, by the settlement's status, `created` and revm's inspector flags. - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::count` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), but for a call that moves no value and runs no precompile, which writes nothing on them (`start_writes_nothing`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed counts nothing and is held to no records limit, and a precompile gas detention answers from its price counts nothing and is held to the price alone; a start revm refuses on its caller's account counts nothing and is charged nothing. - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); a success revm gave without building a frame gives way to the stop on its untouched forward, its value move and log taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`); an answer that failed is revm's result, held to nothing. - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). @@ -416,7 +418,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. Read this before rating a finding that says a failure reverts where it should halt, or halts where it should revert. A refusal the protocol imposes reverts; an execution fault halts. -Every limit stop — the transaction's data-size, KV-update and state-growth limits, a frame's budget in those three, gas detention's compute limit — reverts the frame that crosses it with `MegaLimitExceeded(uint8 kind, uint64 limit)` on the frame's own gas, so the unspent gas goes back to the caller, its reservoir and pools included, and the caller resumes and may catch the stop. +Every limit stop — the transaction's data-size, KV-update and state-growth limits, a frame's budget in those three, gas detention's compute limit — reverts the frame that crosses it with `MegaLimitExceeded(uint8 kind, uint64 limit)` on the frame's own gas, so the unspent gas goes back to the caller, its reservoir included, the frame's budgets go back to the caller's when its start settles, and the caller resumes and may catch the stop. An execution fault — a real out-of-gas, a precompile given less than its price, an invalid opcode, a charge the frame cannot pay — halts and consumes the frame's gas, as in revm. One ABI serves every kind of stop, and there is no third ending: the halt reasons are op-revm's (`MegaHaltReason`), and the engine makes no halt of its own. An operation that crosses several counted dimensions at one site stops on the first of data size (kind 0), KV updates (kind 1) and state growth (kind 3); compute (kind 2) is decided at the regular charge, before the write is counted. diff --git a/AGENTS.md b/AGENTS.md index 6733d113e..e9b19eccc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,7 +113,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The actions the engine makes for a frame outside an instruction — a `keylessDeploy` call's creation and its answer, and the stop of a frame a child returned into over a limit — come back through revm's own frame run, plain or inspected: the fork's run returns an action set on a frame's interpreter before it runs without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`, so the engine's `frame_run` only forwards to revm's. A frame's own end is decided in the fork's run-result hook (`EvmTr::frame_run_result`), which revm's plain and inspected loops call once a frame's run returns and before the inspector's `call_end`, `create_end` and `frame_end` and `frame_return_result`: gas detention's classification is made there, so an inspector sees the stop the caller gets. - The fork pins at a published commit of its byte-pool branch, and op-revm at a published commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), both by revision until the fork's review is done. - The byte-pool branch carries three resource pools on every frame's gas tracker, each forwarded at every start as the schedule's share (`GasId::pool_kept_percent`) and settled as the reservoir is, the reservoir's own share (`GasId::reservoir_kept_percent`), a start charge the frame-start hook may declare on the start (`FrameStart::charge`) and the history allowance a value call gives its child (`GasId::call_history_allowance`); the engine uses none of these four figures, which the fork removes next: its schedule keeps Amsterdam's zero in the three entries, so the fork forwards every pool and the reservoir whole and grants no allowance, it declares no start charge, and it keeps the budgets, the start charges and the allowances on its own start ledger. + The byte-pool branch carries three resource pools on every frame's gas tracker, each forwarded at every start as the schedule's share (`GasId::pool_kept_percent`) and settled as the reservoir is, the reservoir's own share (`GasId::reservoir_kept_percent`), a start charge the frame-start hook may declare on the start (`FrameStart::charge`) and the history allowance a value call gives its child (`GasId::call_history_allowance`). + The engine uses none of these four figures: the Satin schedule keeps Amsterdam's zero in the three entries, so the fork forwards every pool and the reservoir whole and grants no allowance; the engine declares no start charge; and the engine keeps the budgets, the start charges and the allowances on its own start ledger. What the engine uses of the branch is the child's reservoir the frame-start hook names (`FrameStart::reservoir`): the engine takes the child's share of the caller's reservoir itself, and revm's settlement adds what the child left to what the caller kept; a creation's address on its start (`FrameStart::target`) and a `SELFDESTRUCT`'s moved balance on its completed write (`CompletedWrite::SelfDestruct::balance`). The fork does not split a system call's gas or report the reservoir on `ResultGas`: Satin does both itself (`MegaHandler::tx_gas`, `AdditionalLimit::reservoir_remaining`), and its op-revm baselines run op-revm through a reference handler that does the same (`tests/shared/op_reference.rs`). Its switch back to revm 40.0.3's journal semantics (`CfgEnv::legacy_journal_semantics`) is the legacy engine's: Satin's spec and neutral configurations fix it off. @@ -137,17 +138,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds | -| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | -| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | -| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | -| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | -| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the start ledger's settlements, which a test records and reads (`record_start_ledger_settlements`, `take_start_ledger_settlements`, `LedgerSettlement`, `LedgerPools`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | +| Module | Holds | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_start`) — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | +| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | +| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | +| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the start ledger's settlements, which a test records and reads (`record_start_ledger_settlements`, `take_start_ledger_settlements`, `LedgerSettlement`, `LedgerPools`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | ### How Satin executes today @@ -218,7 +219,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Every `MegaContext`, a bare one included, runs under its spec's limits, and a block executor installs the same (see the protocol limits below): Satin holds each transaction to `TX_DATA_LIMIT` and the block to `BLOCK_DATA_LIMIT`, 12.5 MiB each. The block's data size is a packing budget (see the block executor below). `tests/satin/data_size.rs` derives where the stop gives way to out-of-gas: a top-level fresh `SSTORE` is counted at 152,306 gas, and keeping its record costs its 3,520 history on top. -- A limit stop names one of four runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), KV updates (1) and state growth (3), each drawn from a pool of the frames' gas trackers under a transaction limit, and compute gas (2), gas detention's stop. +- A limit stop names one of four runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), KV updates (1) and state growth (3), each drawn from a pool of the frames' starts on the start ledger under a transaction limit, and compute gas (2), gas detention's stop. An operation that crosses more than one counted dimension stops on the first of data size, KV updates, state growth (`limit::COUNTED`); compute is decided at the regular charge, before the write is counted. - The KV-update limit holds the write records a transaction keeps — its KV count, one record per kept account or storage write: an account's while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original, each taken back by a write that returns the account or the slot and with a failed frame — to `EvmTxRuntimeLimits::tx_kv_update_limit` (`TX_KV_UPDATE_LIMIT`, 500,000) and every frame to 98% of what its parent has left, on the KV-update pool (`limit::KV_UPDATE_POOL`); a crossing reverts the frame with `MegaLimitExceeded(1, limit)` (`tests/satin/kv_updates.rs`), and the count is reported, in the outcome's usage and the block's. The sender's account is the body's, not a record, and so are the fee credits the settlement makes, so a transaction that writes nothing counts none; a write execution makes to a fee account that is not the sender is a record like a write to any other account. diff --git a/REVIEW.md b/REVIEW.md index 30b51e477..f0bc1333b 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -37,7 +37,7 @@ Defer to the baseline for everything not listed here; the rules below take prece Flag a stop that surfaces as a halt, a limit that is checked after the state change it guards, a stopped frame whose writes, logs or counted bytes survive into its caller, and an answer the engine turns into the stop whose journal is not taken back. The outcome's `limit_exceeded`, not the output bytes, tells a stop from a contract that reverts with the same bytes. - **Pools and ledgers stay aligned with frames.** - A frame's byte pool is on its gas tracker and settles with it; `frame_init` opens one entry per start revm decided (`AdditionalLimit::open_start`), which the result returning at that depth closes (`close_start`), and a start revm did not decide opens none; a synthetic frame result carries the caller's pools (`synthetic_frame_result`), never `Gas::new(limit)`. + A frame's budgets are on its start's entry of the engine's start ledger, which revm's start lifecycle opens and settles (`limit/ledger.rs`); `frame_init` opens one entry per start revm decided (`AdditionalLimit::open_start`), which the result returning at that depth closes (`close_start`), and a start revm did not decide opens none; a synthetic frame result carries the inherited reservoir (`synthetic_frame_result`), never `Gas::new(limit)`, and settles on its start's budgets and start charge by status. A mechanism that adds a state charge goes through `Host::state_gas_price` at the site the state lands on and does not price the charge itself; a charge is given back at the price it was made at, unless an inspector rewrote the call's target, which revm reads the refund's account off. The three ledgers (regular, state, history) add up to the raw spend, and the block counts `max(regular, floor)` with history taken out first. - **Gas detention caps a frame inside the frame's own tracker.** diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 5ecb256f0..b6fb7c41b 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -465,10 +465,10 @@ impl revm::context_interface::Host /// the start ledger, which gives the start charge back to `gas` when the start did not keep /// its records: a call that did not succeed, a creation that did not succeed or took no /// address — but for an inspector's answer and an outcome an inspector rebuilt, which carry - /// none. It is given back as history, as it was charged, and after revm's own settlement of - /// the start, where the fork gave it back; for the transaction's start revm then consumes what - /// it credits to regular gas when the frame halted, as it consumes the rest of a halted - /// frame's. + /// none. It is given back as history, as it was charged, once revm's own settlement of the + /// frame is made, its upfront state-gas refund included; for the transaction's start revm then + /// consumes what it credits to regular gas when the frame halted, as it consumes the rest of a + /// halted frame's. #[inline] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index d4c08a96f..b9104e21f 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -181,8 +181,8 @@ const fn kept_part(amount: u64, kept: u64) -> u64 { } /// The share of its caller's EIP-8037 `reservoir` a frame starts with: all but the caller's -/// `kept` per cent of it, which is rounded down, so a caller that keeps two per cent keeps nothing -/// of a reservoir below 50 and forwards 98 of 99. +/// `kept` per cent of it, which is rounded down. A caller that keeps two per cent keeps nothing of +/// a reservoir below 50, and of a reservoir of 99 it forwards 98. pub(crate) const fn reservoir_share(reservoir: u64, kept: u64) -> u64 { reservoir - kept_part(reservoir, kept) } @@ -593,9 +593,9 @@ mod tests { /// A child's share of each pool is the floor of 98 per cent of what its caller has left, the /// caller keeping the rest; a child's share of the reservoir is what the caller has less the - /// floor of its 2 per cent, so a caller keeps nothing of a reservoir below 50 and forwards 98 - /// of - /// 99. On the neutral configuration the caller keeps nothing of either. + /// floor of its 2 per cent, so a caller keeps nothing of a reservoir below 50, and of a + /// reservoir of 99 it forwards 98. On the neutral configuration the caller keeps nothing of + /// either. #[test] fn test_a_start_takes_its_shares_and_leaves_the_caller_its_part() { for (kept, forwarded) in [(KEPT, 98), (0, 100)] { From d8064bdb3b2cf60da18ecde9b74a33fadd46aae1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 11:13:04 +0800 Subject: [PATCH 59/83] docs: the budgets and an allowance are on a frame's start, in the review guide and a test's doc --- .claude/skills/satin-review/SKILL.md | 8 ++++---- crates/mega-evm/tests/satin/history_allowance.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 2ace61262..d056ae610 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -85,10 +85,10 @@ Each change is stated here in plain words with its reason; the specification has ### What is counted -- **Data size, KV updates and state growth are pools on revm's gas tracker.** - Each is a pool on every frame's `GasTracker`, which the fork forwards to a child at a start and settles on the child's return as it settles the EIP-8037 reservoir; the transaction's limits are held beside the pools, on what the transaction keeps. - The engine's per-frame record lanes, its journal wrapper and its ledger are gone, and the context's journal is revm's own. - Why: a frame's budget then fails and succeeds with the frame's own gas, by revm's settlement, instead of a second account kept beside the journal. +- **Data size, KV updates and state growth are pools on each frame start, settled with revm's start lifecycle.** + Each is a pool on the frame's entry of the engine's start ledger, which a child's start takes its share of where it is made and which merges into the caller's when revm settles the start, as revm settles the EIP-8037 reservoir; the transaction's limits are held beside the pools, on what the transaction keeps. + The engine's per-frame record lanes and its journal wrapper are gone, and the context's journal is revm's own. + Why: a frame's budget then fails and succeeds with the frame's start, paired by revm, instead of a second account kept beside the journal. - **Write records follow the net change.** An account's record exists while its nonce, balance or code differs from what the transaction loaded, and a slot's while its value differs from its original. The per-frame deduplication is gone, a `SELFDESTRUCT` records the account it clears as well as its beneficiary, and a creation is charged exactly the records it makes. diff --git a/crates/mega-evm/tests/satin/history_allowance.rs b/crates/mega-evm/tests/satin/history_allowance.rs index 270d00cbb..90df41035 100644 --- a/crates/mega-evm/tests/satin/history_allowance.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -638,7 +638,7 @@ fn test_an_unspent_allowance_does_not_return_to_the_caller() { /// A chain of value transfers grants each frame its own allowance, and one frame's spending is /// not another's: three frames each emit their event and the transaction pays for none of them. /// -/// An allowance is on the gas tracker of the frame it was granted to, and a child is granted its +/// An allowance is on the start of the frame it was granted to, and a child is granted its /// own rather than handed its caller's, so a chain cannot draw on an allowance granted further up. #[test] fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { From 70a371eab8723bf5dd07dfd55b3379bfd95dfb42 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 12:07:15 +0800 Subject: [PATCH 60/83] fix(evm): a halted transaction's start-charge refund burns the regular gas its settlement left --- crates/mega-evm/src/evm/host.rs | 17 ++- .../tests/satin/inspector_settlement.rs | 126 +++++++++++++++++- 2 files changed, 136 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index b6fb7c41b..92478eb31 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -90,7 +90,7 @@ use revm::{ context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, host::{ CompletedWrite, FrameSettle, FrameSplit, FrameStart, FrameStartKind, LifecycleEnd, - LoadError, WriteVerdict, + LoadError, SettleStatus, WriteVerdict, }, journaled_state::AccountInfoLoad, }, @@ -466,15 +466,24 @@ impl revm::context_interface::Host /// its records: a call that did not succeed, a creation that did not succeed or took no /// address — but for an inspector's answer and an outcome an inspector rebuilt, which carry /// none. It is given back as history, as it was charged, once revm's own settlement of the - /// frame is made, its upfront state-gas refund included; for the transaction's start revm then - /// consumes what it credits to regular gas when the frame halted, as it consumes the rest of a - /// halted frame's. + /// frame is made, its upfront state-gas refund included. + /// + /// The transaction's start ends the transaction: when its frame halted, giving the charge back + /// burns every regular gas the transaction's gas holds, what the refill credited and what + /// revm's settlement left alike, as revm's settlement burns a halted transaction's after each + /// of its own refunds. revm's settlement leaves regular gas there only where an inspector + /// handed the frame back more reservoir than it inherited, which unwinds part of the spill the + /// charge made: an input's or a result's reservoir raised, or a tracker built in the result's + /// place. A child's caller runs on, and keeps its regular gas. #[inline] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); let refund = self.additional_limit.ledger_mut().settle(&settle.into()); if refund != 0 { gas.refill_history(refund); + if settle.depth == 0 && settle.status == SettleStatus::Halt { + gas.spend_all(); + } } } diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index 66c366443..f77878772 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -21,11 +21,11 @@ use mega_evm::{ op_revm::OpHaltReason, test_utils::{BytecodeBuilder, MemoryDatabase}, transaction_body_bytes, untouched_call_gas, untouched_create_gas, EvmTxRuntimeLimits, - LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, + LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, WRITE_RECORD_SIZE, }; use revm::{ bytecode::{ - opcode::{CALL, POP, PUSH0, RETURN, REVERT, STOP}, + opcode::{CALL, INVALID, POP, PUSH0, RETURN, REVERT, STOP}, Bytecode, }, context::{result::ExecutionResult, ContextTr, JournalTr}, @@ -33,7 +33,7 @@ use revm::{ handler::SYSTEM_ADDRESS, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue, CreateInputs, - CreateOutcome, InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, + CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, }, Inspector, }; @@ -1141,3 +1141,123 @@ fn test_a_refused_creation_holds_an_empty_pool_to_nothing() { assert_eq!(refused.limit_exceeded, None, "no stop"); assert_keeps_only_its_body_and_the_opcodes_charge("empty pool", &tx, &refused); } + +/* ---------- a halt an inspector returns more reservoir from ---------- */ + +/// How an inspector hands back more reservoir than a frame inherited, in the shapes revm settles +/// as given. +#[derive(Clone, Copy, Debug)] +enum MoreReservoir { + /// `call` adds one to the input's reservoir, which the frame starts with and, halting, gives + /// back. + OnTheInput, + /// `call_end` adds one to the result's reservoir, in place. + OnTheResult, + /// `call_end` puts a tracker built with a constructor in the result's place: spent, with one + /// more reservoir than the result's. + OnABuiltTracker, +} + +const MORE_RESERVOIR: [MoreReservoir; 3] = + [MoreReservoir::OnTheInput, MoreReservoir::OnTheResult, MoreReservoir::OnABuiltTracker]; + +/// Hands a call to `target` one more reservoir than it inherited, as `how` says. +#[derive(Clone, Copy, Debug)] +struct AddsReservoir { + target: Address, + how: MoreReservoir, +} + +impl Inspector for AddsReservoir { + fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { + if inputs.target_address == self.target && matches!(self.how, MoreReservoir::OnTheInput) { + inputs.reservoir += 1; + } + None + } + + fn call_end(&mut self, _: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address != self.target { + return; + } + let gas = &mut outcome.result.gas; + match self.how { + MoreReservoir::OnTheInput => {} + MoreReservoir::OnTheResult => gas.set_reservoir(gas.reservoir() + 1), + MoreReservoir::OnABuiltTracker => { + *gas = Gas::new_spent_with_reservoir(gas.limit(), gas.reservoir() + 1); + } + } + } +} + +/// The transaction's own frame halts, and an inspector hands back one more reservoir than it +/// inherited: on the input, on the result, or on a tracker it built. Below the execution cap the +/// history charged before execution for the frame's write record spilled onto regular gas, and the +/// extra reservoir unwinds part of that spill into regular gas before the record's charge is given +/// back. The halt burns every regular gas the settlement leaves, so the sender gets back the extra +/// reservoir and nothing more: the transaction bills one gas less than its run without the +/// inspector, and its gas used and the reservoir it leaves add up to its gas limit. So it does +/// whether the transaction moves value, which makes the record, or not; below the cap, above it +/// with a reservoir the record's charge drains, and above it with one that pays the charge. +#[test] +fn test_the_transactions_own_halt_burns_its_regular_gas_when_an_inspector_adds_to_its_reservoir() { + let tx = |value: u64, gas_limit: u64| to(CONTRACT, value, Bytes::new(), gas_limit); + let body = history_gas(transaction_body_bytes(&tx(0, 0))).unwrap(); + let record = history_gas(WRITE_RECORD_SIZE).unwrap(); + let drains = TX_GAS_LIMIT_CAP + body + record / 2; + let invalid = || db(Bytes::from_static(&[INVALID])); + for gas_limit in [GAS_LIMITS[0], drains, GAS_LIMITS[1]] { + for value in [1, 0] { + let tx = tx(value, gas_limit); + let ran = plain(invalid(), minimal_envs(), tx.clone()); + assert!(ran.result.is_halt(), "{:?}", ran.result); + for how in MORE_RESERVOIR { + let case = format!("{how:?}, value {value}, gas limit {gas_limit}"); + let adds = AddsReservoir { target: CONTRACT, how }; + let halted = inspected(invalid(), minimal_envs(), tx.clone(), adds); + assert!(halted.result.is_halt(), "{case}: {:?}", halted.result); + assert_eq!(halted.gas.history, ran.gas.history, "{case}: the body's history"); + assert_eq!( + halted.gas.reservoir_remaining, + ran.gas.reservoir_remaining + 1, + "{case}: the extra reservoir comes back" + ); + assert_eq!( + halted.gas.gas_used + halted.gas.reservoir_remaining, + gas_limit, + "{case}: the halt burns the regular gas" + ); + } + } + } +} + +/// A child that halts after its value call, with one more reservoir than it inherited handed back +/// by an inspector, gives its caller the extra reservoir on top of the record's charge, and the +/// caller keeps every regular gas it had: a halt burns the regular gas of the frame that halts, and +/// of the transaction when that frame is the transaction's own, and no caller's. The transaction +/// succeeds, billing one gas less than its run without the inspector. +#[test] +fn test_a_halting_child_handed_more_reservoir_leaves_its_caller_its_regular_gas() { + let caller = BytecodeBuilder::default().call(CALLEE, U256::from(1)).append(POP).stop().build(); + let db = || db(caller.clone()).account_code(CALLEE, Bytes::from_static(&[INVALID])); + for gas_limit in GAS_LIMITS { + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let ran = plain(db(), minimal_envs(), tx.clone()); + assert!(ran.result.is_success(), "{:?}", ran.result); + for how in MORE_RESERVOIR { + let case = format!("{how:?}, gas limit {gas_limit}"); + let adds = AddsReservoir { target: CALLEE, how }; + let returned = inspected(db(), minimal_envs(), tx.clone(), adds); + assert!(returned.result.is_success(), "{case}: {:?}", returned.result); + assert_eq!(returned.gas.history, ran.gas.history, "{case}: the records given back"); + assert_eq!( + returned.gas.reservoir_remaining, + ran.gas.reservoir_remaining + 1, + "{case}: the extra reservoir comes back" + ); + assert_eq!(returned.gas.gas_used, ran.gas.gas_used - 1, "{case}: nothing burned"); + } + } +} From e1ba9073041b4906376d66c517c09c327ecad355 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 12:10:11 +0800 Subject: [PATCH 61/83] test(satin): a value call's frame whose interpreter an inspector replaces keeps its history allowance --- .../mega-evm/tests/satin/history_allowance.rs | 76 ++++++++++++++++++- 1 file changed, 72 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/satin/history_allowance.rs b/crates/mega-evm/tests/satin/history_allowance.rs index 90df41035..6d81cdfc9 100644 --- a/crates/mega-evm/tests/satin/history_allowance.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -27,13 +27,21 @@ use mega_evm::{ test_utils::{ is_transfer_log, note_price_guard, transfer_log, BytecodeBuilder, MemoryDatabase, }, - EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, + EvmTxRuntimeLimits, LimitKind, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, HISTORY_ALLOWANCE_BYTES, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use revm::bytecode::opcode::{ - ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, - POP, PUSH0, PUSH1, PUSH2, SSTORE, STATICCALL, STOP, SUB, SWAP1, +use revm::{ + bytecode::opcode::{ + ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, + LOG3, POP, PUSH0, PUSH1, PUSH2, SSTORE, STATICCALL, STOP, SUB, SWAP1, + }, + interpreter::{ + interpreter::{EthInterpreter, ExtBytecode}, + interpreter_types::InputsTr, + Interpreter, + }, + Inspector, }; use crate::common::{ @@ -849,3 +857,63 @@ fn test_a_transfer_forwarding_no_gas_still_buys_its_event() { assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); assert_eq!(outcome.gas.history, body() + 2 * record()); } + +/* ---------- an inspector that replaces the interpreter ---------- */ + +/// Replaces the interpreter of every frame running `target`'s code, as revm initialises it, with +/// one built afresh on the same memory, code and input, and a fresh gas of the same limit. +struct ReplacesTheInterpreter { + target: Address, + replaced: usize, +} + +impl Inspector, EthInterpreter> for ReplacesTheInterpreter { + fn initialize_interp( + &mut self, + interp: &mut Interpreter, + _: &mut MegaContext, + ) { + if interp.input.target_address() != self.target { + return; + } + self.replaced += 1; + *interp = Interpreter::new( + interp.memory.clone(), + ExtBytecode::new(interp.bytecode.clone()), + interp.input.clone(), + interp.runtime_flag.is_static, + interp.runtime_flag.spec_id, + interp.gas.limit(), + ); + } +} + +/// An inspector that replaces a value call's interpreter leaves the frame its history allowance: +/// the allowance is on the frame's start, which the replacement does not touch, as a tracker an +/// inspector restores from a snapshot leaves it. The event the receiver emits is paid for by the +/// allowance, and the transaction pays the history of its body and the transfer's two records +/// alone, as without the inspector. +/// +/// This is a change for such an inspector: when the allowance was on the frame's gas, the fresh +/// gas of the replaced interpreter held none, so the event paid its own bytes. At the spec's byte +/// prices the transaction's history gas was 48,400, and is 34,320. +#[test] +fn test_a_replaced_interpreter_keeps_its_frames_allowance() { + let sender = + BytecodeBuilder::default().call(RECEIVER, U256::from(1)).append(POP).stop().build(); + let receiver = event().append(STOP).build(); + let mut evm = MegaEvm::new(context(db(sender, receiver))) + .with_inspector(ReplacesTheInterpreter { target: RECEIVER, replaced: 0 }); + let outcome = evm + .execute_transaction(call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid"); + + assert_eq!(evm.inspector().replaced, 1, "the receiver's interpreter was replaced"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(events(&outcome).len(), 1, "the receiver emitted its event"); + assert_eq!( + outcome.gas.history, + history(TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE), + "the body and the transfer's two records; the event's bytes the allowance paid for", + ); +} From 1961a6df948672e376396032d176bd82cdfd46ad Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 12:10:11 +0800 Subject: [PATCH 62/83] docs: a replaced interpreter keeps the frame's allowance, deployed code draws the creation's budget, and the engine has no separate inspected lifecycle --- .claude/skills/satin-review/SKILL.md | 7 ++++--- AGENTS.md | 5 +++-- crates/mega-evm/src/evm/mod.rs | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index d056ae610..a064dc8c6 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -60,9 +60,10 @@ Each change is stated here in plain words with its reason; the specification has ### Where the engine meets revm -- **Inspectors run on revm's own inspected lifecycle, and the engine has no inspector-specific code.** +- **Inspectors run on revm's own inspected lifecycle, and the engine has no separate inspected lifecycle.** The engine's inspected copies of the frame lifecycle, its step guard and `src/evm/inspector.rs` are gone: every per-frame mechanism sits in the frame start, run result and return (`frame_init`, `frame_run_result`, `frame_return_result`) that revm's plain and inspected loops share. A result an inspector rewrites is settled by the caller as revm settles it, with no correction of the engine's, and an answer it gives in place of a frame never reaches the engine's frame start, so the depth guard, the interceptors and gas detention see none of it. + What the engine decides for an inspector is the start ledger's settlement of an inspector's answer, a replaced tracker and a rebuilt outcome, read off revm's flags. Block execution admits any inspector. Why: a second copy of the lifecycle had to be kept in step with revm's and made an inspected run differ from a plain one, and which inspectors run on block production is the node's choice. - **The fork's loop hooks.** @@ -75,7 +76,7 @@ Each change is stated here in plain words with its reason; the specification has The fork's figures are inert: the Satin schedule keeps Amsterdam's zero in `pool_kept_percent`, `reservoir_kept_percent` and `call_history_allowance`, so revm forwards every pool and the reservoir whole and grants no allowance; the engine declares no start charge on a start or on the first frame's input, puts no pool on a tracker and draws none; its synthetic answers carry neither pools nor a charge. A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). The ledger is not checked against the fork's figures, which do not mean the same once the fork forwards whole. - The inspector shapes whose results change: an answer built on gas whose pools the inspector set, or with the input's start charge copied, settles at unlimited budgets with no charge back; a tracker an inspector restores from a snapshot, or a replaced interpreter, leaves the ledger's draws and allowance where they were. + The inspector shapes whose results change, each accepted: an answer built on gas whose pools the inspector set, or with the input's start charge copied, settles at unlimited budgets with no charge back; a tracker an inspector restores from a snapshot leaves the ledger's draws and the allowance where they were; and an inspector that replaces a value call's interpreter leaves the frame its allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas. A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`). Why: the figures are the engine's decisions, and the fork carries them only until they leave it. - **Writes and frame starts are metered in the fork's instruction hooks.** @@ -365,7 +366,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing (a frame that fails, or a start revm refuses before it bumps a nonce or moves a value), and its records are those revm then made. - A pre-block system call runs on the plain system-call path, with no callback. - `test_utils::ReadOnlyObserver` checks, in debug builds, that an inspector a test declares an observer writes nothing back: a tripwire for tests, not a proof. - - The start ledger settles an inspector's answer and a replaced tracker at unlimited budgets, and gives no start charge back for an answer or a rebuilt outcome; the pools, charge and allowance fields an inspector writes on an input, an answer or a result are not read, and a restored tracker snapshot leaves the ledger's draws standing; the tests of such inspectors read what the ledger settled. + - The start ledger settles an inspector's answer and a replaced tracker at unlimited budgets, and gives no start charge back for an answer or a rebuilt outcome; the pools, charge and allowance fields an inspector writes on an input, an answer or a result are not read, a restored tracker snapshot leaves the ledger's draws standing, and a replaced interpreter leaves the frame its allowance; the tests of such inspectors read what the ledger settled. - **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer), the entries on inspectors. ### Node surface, validation and the stateless witness diff --git a/AGENTS.md b/AGENTS.md index e9b19eccc..f9c1edbc2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,7 +119,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The fork does not split a system call's gas or report the reservoir on `ResultGas`: Satin does both itself (`MegaHandler::tx_gas`, `AdditionalLimit::reservoir_remaining`), and its op-revm baselines run op-revm through a reference handler that does the same (`tests/shared/op_reference.rs`). Its switch back to revm 40.0.3's journal semantics (`CfgEnv::legacy_journal_semantics`) is the legacy engine's: Satin's spec and neutral configurations fix it off. - The op-revm fork prices its size-limited precompiles through that hook, which upstream op-revm does not, so gas detention decides a call to the BN254 pairing or a BLS12-381 MSM or pairing from its price rather than running it on the allowance. -- The limits hold deployed code at the fork's code-deposit admission (`ContextTr::admit_code_deposit`), which `return_create` asks after every deposit charge and before it commits the creation, lending it the creating frame's tracker, whose pool the code's bytes are drawn from. +- The limits hold deployed code at the fork's code-deposit admission (`ContextTr::admit_code_deposit`), which `return_create` asks after every deposit charge and before it commits the creation; the code's bytes are drawn from the creation's budget on its start's entry of the engine's start ledger, and the creating frame's tracker the fork lends the admission is not read. ## Architecture @@ -470,7 +470,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **A start's figures are the engine's, on its start ledger.** The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding what the start owes and holds: its budgets with their nets, its start charge and its history allowance; it is driven by the start lifecycle hooks alone, and pairs nothing: revm's record says which start settles. What a start owes is parked where it is decided — `frame_starting`, the keyless builder, the first frame's input (`first_frame_input`) — and taken by revm's split; every draw `AdditionalLimit` makes is on the top entry; the frame cap is applied where the caller suspends (`cap_child`); and a settlement merges by status and revm's inspector flags, giving the start charge back to the caller's gas on a failure, and on a creation that took no address, through `Host::frame_settle`, where revm settles the start: after its own settlement of the frame, and, for the transaction's start, before revm's halt rule consumes what the refund credited to regular gas. - An inspector's answer and a result whose tracker an inspector replaced settle as unlimited budgets; neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back; the figures an inspector puts on an input, an answer or a result — pools, a start charge, an allowance, through the fork's fields — are not read, and a tracker it restores from a snapshot leaves the ledger's draws where they were. + An inspector's answer and a result whose tracker an inspector replaced settle as unlimited budgets; neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back; the figures an inspector puts on an input, an answer or a result — pools, a start charge, an allowance, through the fork's fields — are not read, and a tracker it restores from a snapshot, or an interpreter it replaces, leaves the ledger's draws and the frame's allowance where they were. + A value call's frame whose interpreter an inspector replaces so keeps its history allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas: a change accepted for such an inspector, as for one that restores a snapshot. The history allowance a value call gives its child is the entry's; only a log draws on it, first, in the completed-write hook. A precompile's draws on its answer, which no provider of the engine makes, are adopted fail-closed against the share (`StartLedger::adopt_provider_draws`). The fork's figures are inert: the schedule forwards every pool and the reservoir whole and grants no allowance, and the engine declares no start charge, puts no pool on a tracker and draws none. diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 8cf9a3e32..981831435 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -24,7 +24,8 @@ //! stops nothing in a frame that ends without an out-of-gas, and a later halt that records //! nothing of its own is read off the record. An inspector that overwrites the interpreter's gas //! overwrites gas detention's split with it, until detention next holds the frame; the frame's -//! budgets are on the start ledger, which a gas it restores does not reach. +//! budgets and its history allowance are on its start on the start ledger, which a gas it +//! restores, or an interpreter it replaces, does not reach. //! - **What an inspector sees.** A frame's end as the engine settled it: a frame that crossed gas //! detention's compute limit ends with the stop, which the engine makes of its out-of-gas once //! its run returns and before the inspector's `call_end`, `create_end` and `frame_end` see it, as From d8de200e27c981efa57724182695250012848926 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 13:10:03 +0800 Subject: [PATCH 63/83] test(satin): a halted transaction with no start charge keeps what its settlement left, and the halt tests skip a free history byte --- .../tests/satin/inspector_settlement.rs | 79 ++++++++++++++----- 1 file changed, 61 insertions(+), 18 deletions(-) diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index f77878772..a9585831f 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -39,10 +39,12 @@ use revm::{ }; use crate::{ - common::assert_answered_at_unlimited_budgets, + common::{ + assert_answered_at_unlimited_budgets, authorizing_call, history_is_free, state_is_free, + }, salt::{ create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, - value_call, SaltEnvs, CALLER, CONTRACT, EMPTY, + value_call, SaltEnvs, AUTHORITY, CALLER, CONTRACT, DELEGATE, EMPTY, }, }; use mega_evm::test_utils::{record_start_ledger_settlements, take_start_ledger_settlements}; @@ -1158,8 +1160,24 @@ enum MoreReservoir { OnABuiltTracker, } -const MORE_RESERVOIR: [MoreReservoir; 3] = - [MoreReservoir::OnTheInput, MoreReservoir::OnTheResult, MoreReservoir::OnABuiltTracker]; +impl MoreReservoir { + const ALL: [Self; 3] = [Self::OnTheInput, Self::OnTheResult, Self::OnABuiltTracker]; +} + +/// Requires `handed` — `ran` with an inspector handing back one more reservoir than a frame +/// inherited — to bill the same history and to leave one more reservoir. +fn assert_hands_back_one_more_reservoir( + case: &str, + handed: &MegaTransactionOutcome, + ran: &MegaTransactionOutcome, +) { + assert_eq!(handed.gas.history, ran.gas.history, "{case}: the history"); + assert_eq!( + handed.gas.reservoir_remaining, + ran.gas.reservoir_remaining + 1, + "{case}: the extra reservoir comes back" + ); +} /// Hands a call to `target` one more reservoir than it inherited, as `how` says. #[derive(Clone, Copy, Debug)] @@ -1202,6 +1220,9 @@ impl Inspector for AddsReservoir { /// with a reservoir the record's charge drains, and above it with one that pays the charge. #[test] fn test_the_transactions_own_halt_burns_its_regular_gas_when_an_inspector_adds_to_its_reservoir() { + if history_is_free() { + return; + } let tx = |value: u64, gas_limit: u64| to(CONTRACT, value, Bytes::new(), gas_limit); let body = history_gas(transaction_body_bytes(&tx(0, 0))).unwrap(); let record = history_gas(WRITE_RECORD_SIZE).unwrap(); @@ -1212,17 +1233,12 @@ fn test_the_transactions_own_halt_burns_its_regular_gas_when_an_inspector_adds_t let tx = tx(value, gas_limit); let ran = plain(invalid(), minimal_envs(), tx.clone()); assert!(ran.result.is_halt(), "{:?}", ran.result); - for how in MORE_RESERVOIR { + for how in MoreReservoir::ALL { let case = format!("{how:?}, value {value}, gas limit {gas_limit}"); let adds = AddsReservoir { target: CONTRACT, how }; let halted = inspected(invalid(), minimal_envs(), tx.clone(), adds); assert!(halted.result.is_halt(), "{case}: {:?}", halted.result); - assert_eq!(halted.gas.history, ran.gas.history, "{case}: the body's history"); - assert_eq!( - halted.gas.reservoir_remaining, - ran.gas.reservoir_remaining + 1, - "{case}: the extra reservoir comes back" - ); + assert_hands_back_one_more_reservoir(&case, &halted, &ran); assert_eq!( halted.gas.gas_used + halted.gas.reservoir_remaining, gas_limit, @@ -1240,24 +1256,51 @@ fn test_the_transactions_own_halt_burns_its_regular_gas_when_an_inspector_adds_t /// succeeds, billing one gas less than its run without the inspector. #[test] fn test_a_halting_child_handed_more_reservoir_leaves_its_caller_its_regular_gas() { + if history_is_free() { + return; + } let caller = BytecodeBuilder::default().call(CALLEE, U256::from(1)).append(POP).stop().build(); let db = || db(caller.clone()).account_code(CALLEE, Bytes::from_static(&[INVALID])); for gas_limit in GAS_LIMITS { let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); let ran = plain(db(), minimal_envs(), tx.clone()); assert!(ran.result.is_success(), "{:?}", ran.result); - for how in MORE_RESERVOIR { + for how in MoreReservoir::ALL { let case = format!("{how:?}, gas limit {gas_limit}"); let adds = AddsReservoir { target: CALLEE, how }; let returned = inspected(db(), minimal_envs(), tx.clone(), adds); assert!(returned.result.is_success(), "{case}: {:?}", returned.result); - assert_eq!(returned.gas.history, ran.gas.history, "{case}: the records given back"); - assert_eq!( - returned.gas.reservoir_remaining, - ran.gas.reservoir_remaining + 1, - "{case}: the extra reservoir comes back" - ); + assert_hands_back_one_more_reservoir(&case, &returned, &ran); assert_eq!(returned.gas.gas_used, ran.gas.gas_used - 1, "{case}: nothing burned"); } } } + +/// The transaction's own frame halts with no start charge to give back — it moves no value, so it +/// makes no write record — after an authorization the transaction applied before it, whose account +/// and record were charged below the execution cap and spilled onto regular gas. An inspector +/// hands the frame back one more reservoir than it inherited, which unwinds one gas of that spill +/// into regular gas, so no reservoir is left. With nothing to give back nothing is burned, as +/// revm's settlement burned nothing then: the sender keeps that one gas, and the transaction bills +/// one gas less than its run without the inspector, with the same history and reservoir. +#[test] +fn test_the_transactions_own_halt_with_no_start_charge_keeps_what_its_settlement_left() { + if history_is_free() || state_is_free() { + return; + } + let gas_limit = GAS_LIMITS[0]; + let tx = authorizing_call(CALLER, CONTRACT, U256::ZERO, gas_limit, DELEGATE, &[(AUTHORITY, 0)]); + let invalid = || db(Bytes::from_static(&[INVALID])); + let ran = plain(invalid(), minimal_envs(), tx.clone()); + assert!(ran.result.is_halt(), "{:?}", ran.result); + assert_eq!(ran.gas.gas_used + ran.gas.reservoir_remaining, gas_limit, "the halt burns"); + for how in MoreReservoir::ALL { + let case = format!("{how:?}"); + let adds = AddsReservoir { target: CONTRACT, how }; + let halted = inspected(invalid(), minimal_envs(), tx.clone(), adds); + assert!(halted.result.is_halt(), "{case}: {:?}", halted.result); + assert_eq!(halted.gas.history, ran.gas.history, "{case}: the history"); + assert_eq!(halted.gas.reservoir_remaining, ran.gas.reservoir_remaining, "{case}: unwound"); + assert_eq!(halted.gas.gas_used, ran.gas.gas_used - 1, "{case}: one regular gas kept"); + } +} From 30c8778221ceb96cfd9c3cfdc62e618a142f2372 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 13:10:03 +0800 Subject: [PATCH 64/83] docs: a halted transaction's start settlement burns its regular gas, wherever the docs still left it to revm's rule --- .claude/skills/satin-review/SKILL.md | 2 +- AGENTS.md | 8 ++++---- crates/mega-evm/src/evm/host.rs | 9 +++++---- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index a064dc8c6..4d7a35ac1 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -74,7 +74,7 @@ Each change is stated here in plain words with its reason; the specification has The fork carries four figures of a start on the frame's gas: the three pools with their nets, the part of the reservoir the caller keeps, the start charge and the history allowance. The engine now decides all four itself, in every build: the budgets, the start charge and the allowance on its start ledger (`src/limit/ledger.rs`), an entry per start driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and the reservoir's share where the start is made (`MegaContext::forward_start`, named to revm on `FrameStart::reservoir`). The fork's figures are inert: the Satin schedule keeps Amsterdam's zero in `pool_kept_percent`, `reservoir_kept_percent` and `call_history_allowance`, so revm forwards every pool and the reservoir whole and grants no allowance; the engine declares no start charge on a start or on the first frame's input, puts no pool on a tracker and draws none; its synthetic answers carry neither pools nor a charge. - A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). + A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history, and after a halt of the transaction's own frame burns the transaction's regular gas, as revm's settlement did after its own refund, so regular gas an inspector's extra reservoir unwound is not kept; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). The ledger is not checked against the fork's figures, which do not mean the same once the fork forwards whole. The inspector shapes whose results change, each accepted: an answer built on gas whose pools the inspector set, or with the input's start charge copied, settles at unlimited budgets with no charge back; a tracker an inspector restores from a snapshot leaves the ledger's draws and the allowance where they were; and an inspector that replaces a value call's interpreter leaves the frame its allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas. A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`). diff --git a/AGENTS.md b/AGENTS.md index f9c1edbc2..f179b1bd8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -183,7 +183,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat At the minimum bucket every number is the schedule's own, which is why the op-revm baseline and the pricing table did not move when SALT pricing landed. - History gas prices the bytes a transaction appends to the chain, at `MegaETH`'s cost per history byte and never scaled by SALT — history bytes live in no bucket (`evm/history.rs`). The byte table is the `limit` module's, the same counts the data-size limit meters, so a record's history bytes are its own data size and the two cannot drift apart: a transaction body of 310 bytes (110 for the envelope and one 40-byte record for each of the five writes every transaction makes — the sender's account and the four accounts its fees are credited to), one byte per calldata byte, 20 per access-list address and 32 per key, 101 per EIP-7702 authorization, a log's 32 for its address and 32 per topic plus its data, one 40-byte record per kept account or storage write, and one byte per byte of deployed code. - The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body where revm builds the transaction's gas (`MegaHandler::tx_gas`), as intrinsic gas — the reservoir pays it first, it is not held to the execution cap, and revm's runtime out-of-gas fallback, which rebuilds the gas through the same phase, keeps it charged — and the two record charges in pre-execution, where the records are made; the first frame's record charge is the transaction's start charge on the start ledger, parked where its input is built (`first_frame_input`), which the transaction's start settlement gives back when the frame fails, revm consuming what it credits to regular gas after a halt. + The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body where revm builds the transaction's gas (`MegaHandler::tx_gas`), as intrinsic gas — the reservoir pays it first, it is not held to the execution cap, and revm's runtime out-of-gas fallback, which rebuilds the gas through the same phase, keeps it charged — and the two record charges in pre-execution, where the records are made; the first frame's record charge is the transaction's start charge on the start ledger, parked where its input is built (`first_frame_input`), which the transaction's start settlement gives back when the frame fails, and after a halt burns every regular gas the transaction's gas then holds, the refund's credit included, as revm's settlement burned it after each refund of its own. A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas. Every other charge is made where the record is: the completed-write hook charges a storage write's record, a log's and a `SELFDESTRUCT`'s records at the end of its opcode, and the frame-start hook charges the caller of a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` for the records the frame it starts makes, out of what the caller kept rather than out of what it forwards, and parks the frame's own as the start's charge on the start ledger, which gives it back to the caller when the frame fails (`Host::frame_settle`). What a frame does not keep comes back, at the same price, to whoever paid it. @@ -350,7 +350,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The legacy engine's limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. Its gas leakage pitfalls have no counterpart: detention, the one mechanism that caps a frame's gas, withholds it inside the frame's own tracker, where every reader but a regular charge still counts it, so nothing it withholds is ever moved or released (see Gas detention). Its storage-gas stipend does have a counterpart, the history allowance above, and it is a different thing: it never enters a frame's gas limit, so there is nothing to burn on return. - The per-start figures the engine keeps on its start ledger — the allowance, the start charge, the budgets, and the reservoir share a start takes — are checked against the three paths the legacy engine named, each by a test: an interceptor's answer settles on its start by status, the refused value call's records given back once (`history_reservoir::test_an_intercepted_value_call_gives_its_records_back_once`, `history_allowance::test_an_intercepted_call_neither_takes_nor_adds_an_allowance`, `synthetic_frame_gas::test_an_intercepted_refusal_keeps_the_reservoir`); a stop or a halt of the transaction's own frame gives its start charge back as history alone, revm burning the regular gas the refund credits after a halt (`stops::test_the_transactions_own_value_transfer_that_halts_gives_its_record_back_as_history_alone`, `history_allowance::test_a_transaction_level_stop_does_not_hand_the_allowance_back`); and a frame's return gives the start charge back on a revert and a halt alike and none of the allowance (`history_reservoir::test_a_reverting_child_gives_its_records_back_to_the_reservoir`, `test_a_halting_child_gives_its_records_back_as_a_reverting_one_does`, `history_allowance::test_an_unspent_allowance_does_not_return_to_the_caller`, `history_allowance::test_a_drained_allowance_is_not_refunded_by_a_revert`). + The per-start figures the engine keeps on its start ledger — the allowance, the start charge, the budgets, and the reservoir share a start takes — are checked against the three paths the legacy engine named, each by a test: an interceptor's answer settles on its start by status, the refused value call's records given back once (`history_reservoir::test_an_intercepted_value_call_gives_its_records_back_once`, `history_allowance::test_an_intercepted_call_neither_takes_nor_adds_an_allowance`, `synthetic_frame_gas::test_an_intercepted_refusal_keeps_the_reservoir`); a stop or a halt of the transaction's own frame gives its start charge back as history alone, the settlement burning after a halt the regular gas the refund credits and any an inspector's extra reservoir unwound (`stops::test_the_transactions_own_value_transfer_that_halts_gives_its_record_back_as_history_alone`, `inspector_settlement::test_the_transactions_own_halt_burns_its_regular_gas_when_an_inspector_adds_to_its_reservoir`, `history_allowance::test_a_transaction_level_stop_does_not_hand_the_allowance_back`); and a frame's return gives the start charge back on a revert and a halt alike and none of the allowance (`history_reservoir::test_a_reverting_child_gives_its_records_back_to_the_reservoir`, `test_a_halting_child_gives_its_records_back_as_a_reverting_one_does`, `history_allowance::test_an_unspent_allowance_does_not_return_to_the_caller`, `history_allowance::test_a_drained_allowance_is_not_refunded_by_a_revert`). ### Gas detention @@ -469,9 +469,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the start's charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. - **A start's figures are the engine's, on its start ledger.** The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding what the start owes and holds: its budgets with their nets, its start charge and its history allowance; it is driven by the start lifecycle hooks alone, and pairs nothing: revm's record says which start settles. - What a start owes is parked where it is decided — `frame_starting`, the keyless builder, the first frame's input (`first_frame_input`) — and taken by revm's split; every draw `AdditionalLimit` makes is on the top entry; the frame cap is applied where the caller suspends (`cap_child`); and a settlement merges by status and revm's inspector flags, giving the start charge back to the caller's gas on a failure, and on a creation that took no address, through `Host::frame_settle`, where revm settles the start: after its own settlement of the frame, and, for the transaction's start, before revm's halt rule consumes what the refund credited to regular gas. + What a start owes is parked where it is decided — `frame_starting`, the keyless builder, the first frame's input (`first_frame_input`) — and taken by revm's split; every draw `AdditionalLimit` makes is on the top entry; the frame cap is applied where the caller suspends (`cap_child`); and a settlement merges by status and revm's inspector flags, giving the start charge back to the caller's gas on a failure, and on a creation that took no address, through `Host::frame_settle`, where revm settles the start, after its own settlement of the frame; for a transaction's start whose frame halted, the hook then burns every regular gas the transaction's gas holds, as revm's settlement burned it after each refund of its own, which leaves revm's consumption of a hook's credit after a halt nothing to consume. An inspector's answer and a result whose tracker an inspector replaced settle as unlimited budgets; neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back; the figures an inspector puts on an input, an answer or a result — pools, a start charge, an allowance, through the fork's fields — are not read, and a tracker it restores from a snapshot, or an interpreter it replaces, leaves the ledger's draws and the frame's allowance where they were. - A value call's frame whose interpreter an inspector replaces so keeps its history allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas: a change accepted for such an inspector, as for one that restores a snapshot. + A value call's frame keeps its history allowance when an inspector replaces its interpreter, as when it restores a snapshot: an accepted change for such an inspector, since the replaced interpreter's fresh gas held no allowance while the allowance was on the frame's gas. The history allowance a value call gives its child is the entry's; only a log draws on it, first, in the completed-write hook. A precompile's draws on its answer, which no provider of the engine makes, are adopted fail-closed against the share (`StartLedger::adopt_provider_draws`). The fork's figures are inert: the schedule forwards every pool and the reservoir whole and grants no allowance, and the engine declares no start charge, puts no pool on a tracker and draws none. diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 92478eb31..1ee93cad2 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -471,10 +471,11 @@ impl revm::context_interface::Host /// The transaction's start ends the transaction: when its frame halted, giving the charge back /// burns every regular gas the transaction's gas holds, what the refill credited and what /// revm's settlement left alike, as revm's settlement burns a halted transaction's after each - /// of its own refunds. revm's settlement leaves regular gas there only where an inspector - /// handed the frame back more reservoir than it inherited, which unwinds part of the spill the - /// charge made: an input's or a result's reservoir raised, or a tracker built in the result's - /// place. A child's caller runs on, and keeps its regular gas. + /// of its own refunds; with no charge to give back nothing is burned, as revm's settlement + /// burned nothing then. revm's settlement leaves regular gas there only where an inspector + /// makes the frame hand back more reservoir than it inherited — on its input, or in its + /// result's figures — which unwinds part of the spill the charges made before the frame. A + /// child's caller runs on, and keeps its regular gas. #[inline] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); From ff10952ee261e5f1bdfb50e6c1190af9ef73a7ab Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 13:19:22 +0800 Subject: [PATCH 65/83] test(satin): name the extra-reservoir shapes by where the inspector puts the reservoir --- .../tests/satin/inspector_settlement.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index a9585831f..bb4c43dcb 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -1146,22 +1146,22 @@ fn test_a_refused_creation_holds_an_empty_pool_to_nothing() { /* ---------- a halt an inspector returns more reservoir from ---------- */ -/// How an inspector hands back more reservoir than a frame inherited, in the shapes revm settles -/// as given. +/// Where an inspector puts the extra reservoir it hands back from a frame, in the shapes revm +/// settles as given. #[derive(Clone, Copy, Debug)] enum MoreReservoir { /// `call` adds one to the input's reservoir, which the frame starts with and, halting, gives /// back. - OnTheInput, + Input, /// `call_end` adds one to the result's reservoir, in place. - OnTheResult, + ResultInPlace, /// `call_end` puts a tracker built with a constructor in the result's place: spent, with one /// more reservoir than the result's. - OnABuiltTracker, + BuiltTracker, } impl MoreReservoir { - const ALL: [Self; 3] = [Self::OnTheInput, Self::OnTheResult, Self::OnABuiltTracker]; + const ALL: [Self; 3] = [Self::Input, Self::ResultInPlace, Self::BuiltTracker]; } /// Requires `handed` — `ran` with an inspector handing back one more reservoir than a frame @@ -1188,7 +1188,7 @@ struct AddsReservoir { impl Inspector for AddsReservoir { fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { - if inputs.target_address == self.target && matches!(self.how, MoreReservoir::OnTheInput) { + if inputs.target_address == self.target && matches!(self.how, MoreReservoir::Input) { inputs.reservoir += 1; } None @@ -1200,9 +1200,9 @@ impl Inspector for AddsReservoir { } let gas = &mut outcome.result.gas; match self.how { - MoreReservoir::OnTheInput => {} - MoreReservoir::OnTheResult => gas.set_reservoir(gas.reservoir() + 1), - MoreReservoir::OnABuiltTracker => { + MoreReservoir::Input => {} + MoreReservoir::ResultInPlace => gas.set_reservoir(gas.reservoir() + 1), + MoreReservoir::BuiltTracker => { *gas = Gas::new_spent_with_reservoir(gas.limit(), gas.reservoir() + 1); } } From 44b5add9e285f83f04b76b5f035f23e28784cb9f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 14:55:53 +0800 Subject: [PATCH 66/83] fix(satin): the fatal cleanup drops a recorded error and the failed call's journal transaction --- crates/mega-evm/src/evm/execution.rs | 21 +- crates/mega-evm/tests/satin/main.rs | 1 + .../mega-evm/tests/satin/reuse_after_error.rs | 234 ++++++++++++++++++ 3 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 crates/mega-evm/tests/satin/reuse_after_error.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 7bf6ca1c6..9079167d9 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -31,7 +31,7 @@ use revm::{ GasId, StateGasCharge, StateGasSite, }, journaled_state::{entry::JournalEntry, JournalCheckpoint}, - Host, + Host, LocalContextTr, }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, @@ -474,13 +474,32 @@ where /// account creates it: one account of state growth, which the transaction reports and its /// block counts, though it pays no state gas for it and no limit stops a deposit that already /// failed. + /// + /// It is the fatal cleanup of every entry point, so nothing the failed execution left is read + /// by the next one on the same EVM, whatever cleanup op-revm made: + /// + /// - the error a Host load recorded and the handler never took — post-execution failed first, + /// on a read of its own — is dropped before op-revm runs, which its own failure cannot skip; + /// the error returned is the one the execution failed with; + /// - an execution that fails with an error leaves no writes: its journal transaction is + /// discarded, which op-revm does only for the failed deposit it commits; the transactions + /// before it in the journal stay, for a caller of a `_one` entry point to finalize; + /// - the cached L1 cost, the local context and the frame stack are cleared after op-revm, whose + /// own clearing an error out of its failed-deposit recovery skips. fn catch_error( &self, evm: &mut Self::Evm, error: Self::Error, ) -> Result, Self::Error> { + *evm.ctx().error() = Ok(()); evm.ctx_mut().additional_limit.set_reservoir_remaining(0); let result = self.op.catch_error(evm, error); + if result.is_err() { + evm.ctx().journal_mut().discard_tx(); + } + evm.ctx().chain_mut().clear_tx_l1_cost(); + evm.ctx().local_mut().clear(); + evm.frame_stack().clear(); let failed_deposit = matches!( result, Ok(revm::context::result::ExecutionResult::Halt { diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 8fa4b99e2..d6ed1a06b 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -40,6 +40,7 @@ mod precompile_gas; mod pricing_table; mod reservoir_drain; mod reservoir_share; +mod reuse_after_error; mod salt; mod salt_delegation; mod salt_deposit; diff --git a/crates/mega-evm/tests/satin/reuse_after_error.rs b/crates/mega-evm/tests/satin/reuse_after_error.rs new file mode 100644 index 000000000..575dc4c7d --- /dev/null +++ b/crates/mega-evm/tests/satin/reuse_after_error.rs @@ -0,0 +1,234 @@ +//! An EVM reused after a call failed with an error runs its next call as a fresh EVM runs it. +//! +//! A call that fails with an error — a read the database could not serve — is no result a block +//! includes, and what it left in the EVM is the handler's fatal cleanup's to drop +//! (`MegaHandler::catch_error`): the error a Host load recorded and nothing took, the failed +//! call's journal transaction, op-revm's per-transaction caches and the frame stack. A `_one` +//! entry point leaves the journal to its caller, so the calls before the failed one stay in it and +//! none of the failed call's writes do; a failed deposit is a result, whose nonce bump and mint +//! stay. Nothing here needs an inspector. +//! +//! This file pins the state a failed call leaves behind; `db_error.rs` pins the error itself. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, TxKind, B256, U256}; +use mega_evm::{ + op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, + test_utils::{op_transaction, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, + EvmTxRuntimeLimits, MegaEvm, MegaHaltReason, MegaTransaction, MegaTransactionOutcome, + TX_BODY_SIZE, +}; +use revm::{ + bytecode::opcode::{BALANCE, POP, SLOAD}, + context::{result::ExecutionResult, BlockEnv, ContextTr, TxEnv}, + context_interface::LocalContextTr, + handler::EvmTr, + ExecuteEvm, +}; + +use crate::common::{block, call, context}; + +const SENDER: Address = address!("0000000000000000000000000000000000e10000"); +/// Another sender, of the transaction a `_one` journal holds before the failing one. +const EARLIER_SENDER: Address = address!("0000000000000000000000000000000000e10001"); +/// `SSTORE(0, 7)`, then a call to `CHILD`. +const WRITER: Address = address!("0000000000000000000000000000000000e10002"); +/// Reads slot 1, which the database fails. +const CHILD: Address = address!("0000000000000000000000000000000000e10003"); +/// `SSTORE(0, 1)`: the call that runs before the failing one. +const KEPT: Address = address!("0000000000000000000000000000000000e10004"); +/// Reads the balance of the account the test names. +const READS: Address = address!("0000000000000000000000000000000000e10005"); +const BENEFICIARY: Address = address!("0000000000000000000000000000000000e1bef0"); +const GAS_LIMIT: u64 = 100_000_000; + +/// A block whose beneficiary is [`BENEFICIARY`]. +fn block_with_beneficiary() -> BlockEnv { + BlockEnv { beneficiary: BENEFICIARY, ..block() } +} + +/// The pre-state every test starts from: the senders funded, and the contracts. +fn database() -> MemoryDatabase { + let writer = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(7)) + .call(CHILD, U256::ZERO) + .append(POP) + .stop() + .build(); + let child = BytecodeBuilder::default().push_number(1_u64).append(SLOAD).append(POP).stop(); + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10u64.pow(18))) + .account_balance(EARLIER_SENDER, U256::from(10u64.pow(18))) + .account_code(WRITER, writer) + .account_code(CHILD, child.build()) + .account_code(KEPT, BytecodeBuilder::default().sstore(U256::ZERO, U256::ONE).stop().build()) +} + +/// A Satin EVM over `db`, in a block whose beneficiary is [`BENEFICIARY`]. +fn evm( + db: ErrorInjectingDatabase, +) -> MegaEvm { + MegaEvm::new(context(db).with_block(block_with_beneficiary())) +} + +/// Asserts `reused` is the outcome `fresh` is, in every part: the result, the state, the gas by +/// ledger, the usage, the stop and the oracle reads. +fn assert_same_outcome(reused: &MegaTransactionOutcome, fresh: &MegaTransactionOutcome, row: &str) { + assert_eq!(reused.result, fresh.result, "{row}: the result"); + assert_eq!(reused.state, fresh.state, "{row}: the state"); + assert_eq!(reused.gas, fresh.gas, "{row}: the gas by ledger"); + assert_eq!(reused.usage, fresh.usage, "{row}: the usage"); + assert_eq!(reused.limit_exceeded, fresh.limit_exceeded, "{row}: the stop"); + assert_eq!(reused.oracle_reads, fresh.oracle_reads, "{row}: the oracle reads"); +} + +/// The transaction's own frame reads an account and the database fails the read: the Host records +/// the error and the frame ends, and post-execution then reads the same account — the beneficiary +/// it rewards, or a fee recipient it credits — and fails first, so the handler never takes the +/// recorded error. The fatal cleanup drops it with the failed transaction: the EVM's error slot is +/// empty, and a different transaction run next on the same EVM, the database serving again, has +/// the outcome a fresh EVM gives it. +#[test] +fn test_an_error_post_execution_preempts_does_not_fail_the_next_transaction() { + for account in [BENEFICIARY, L1_FEE_RECIPIENT, BASE_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { + let row = format!("a read of {account}"); + let reads = + BytecodeBuilder::default().push_address(account).append(BALANCE).append(POP).stop(); + let reads = reads.build(); + let db = || database().account_code(READS, reads.clone()); + let mut armed = ErrorInjectingDatabase::new(db()); + armed.fail_on_account = Some(account); + let mut evm = evm(armed); + + let error = evm + .execute_transaction(call(SENDER, READS, U256::ZERO, GAS_LIMIT)) + .expect_err("the read fails"); + assert!(format!("{error:?}").contains(&format!("{account}")), "{row}: {error:?}"); + assert!(evm.ctx_mut().error().is_ok(), "{row}: the recorded error is dropped"); + + evm.ctx_mut().db_mut().fail_on_account = None; + let next = call(SENDER, KEPT, U256::ZERO, GAS_LIMIT); + let reused = evm.execute_transaction(next.clone()).expect("the next transaction is valid"); + let fresh = self::evm(ErrorInjectingDatabase::new(db())) + .execute_transaction(next) + .expect("the next transaction is valid"); + assert!(fresh.result.is_success(), "{row}: {:?}", fresh.result); + assert_same_outcome(&reused, &fresh, &row); + } +} + +/// A transaction run through `transact_one` whose child's read fails after its own frame wrote a +/// slot leaves none of its writes in the journal — its nonce bump, its fee, the slot — and the +/// transaction the journal held before it stays: `transact_one` leaves the journal to its caller +/// on an error as on a success, and the failure takes back only its own transaction. +#[test] +fn test_a_failed_transact_one_keeps_the_transaction_before_it_and_none_of_its_own_writes() { + let mut db = ErrorInjectingDatabase::new(database()); + db.fail_on_storage = Some((CHILD, U256::ONE)); + let mut evm = evm(db); + let earlier = evm + .transact_one(call(EARLIER_SENDER, KEPT, U256::ZERO, GAS_LIMIT)) + .expect("the earlier transaction is valid"); + assert!(earlier.is_success(), "{earlier:?}"); + let error = + evm.transact_one(call(SENDER, WRITER, U256::ZERO, GAS_LIMIT)).expect_err("the read fails"); + assert!(format!("{error:?}").contains("injected storage()"), "{error:?}"); + + let state = evm.finalize(); + assert_eq!(state[&EARLIER_SENDER].info.nonce, 1, "the earlier transaction's nonce bump"); + assert_eq!(state[&KEPT].storage[&U256::ZERO].present_value, U256::ONE, "its slot"); + let sender = &state[&SENDER]; + assert_eq!( + (sender.info.nonce, sender.info.balance), + (0, U256::from(10u64.pow(18))), + "the failed transaction's nonce bump and fee" + ); + assert!(!sender.is_touched(), "the failed transaction's sender is touched by nothing kept"); + let written = state.get(&WRITER).and_then(|writer| writer.storage.get(&U256::ZERO)); + assert!( + written.is_none_or(|slot| slot.present_value == slot.original_value), + "the failed transaction's slot: {written:?}" + ); +} + +/// A deposit run through `transact_one` whose validation refuses it is a failed deposit, a result: +/// its nonce bump and mint stay in the journal, as op-revm commits them, and the journal hands them +/// out when the caller finalizes it. +#[test] +fn test_a_failed_deposit_through_transact_one_keeps_its_nonce_bump_and_mint() { + const MINT: u128 = 7; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); + let mut evm = evm(ErrorInjectingDatabase::new(database())).with_tx_runtime_limits(limits); + let result = + evm.transact_one(over_the_limit_deposit(SENDER, MINT)).expect("the deposit is included"); + assert!( + matches!(result, ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. }), + "{result:?}" + ); + let state = evm.finalize(); + let sender = &state[&SENDER].info; + assert_eq!(sender.nonce, 1, "the failed deposit's nonce bump"); + assert_eq!(sender.balance, U256::from(10u64.pow(18)) + U256::from(MINT), "its mint"); +} + +/// A deposit from `sender` minting `mint`, whose body is over a data-size limit of one byte below +/// [`TX_BODY_SIZE`]: validation refuses it before it reads its sender's account. +fn over_the_limit_deposit(sender: Address, mint: u128) -> MegaTransaction { + let mut tx = op_transaction(TxEnv { + caller: sender, + kind: TxKind::Call(KEPT), + gas_limit: 100_000, + ..Default::default() + }); + tx.deposit.source_hash = B256::repeat_byte(0x22); + tx.deposit.mint = Some(mint); + OpTx(tx) +} + +/// op-revm turns a deposit's refusal into a failed deposit by reading its sender's account, and a +/// read the database fails there is an error out of that recovery, which skips op-revm's own +/// cleanup of the per-transaction caches. The engine's cleanup runs on every path out of the +/// handler's error handling, so the error leaves the caches empty, the frame stack cleared, the +/// error slot empty and the journal with no transaction open, and the EVM runs the next transaction +/// as a fresh one does. +/// +/// No path fills the caches and then fails that read — a deposit computes no L1 cost and runs no +/// frame before its sender is read — so the test fills them itself: the cleanup makes no +/// assumption about what the failed call left. +#[test] +fn test_an_error_in_the_failed_deposit_recovery_leaves_the_evm_clean() { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); + let mut db = ErrorInjectingDatabase::new(database()); + db.fail_on_account = Some(SENDER); + let mut evm = evm(db).with_tx_runtime_limits(limits); + evm.ctx_mut().chain_mut().tx_l1_cost = Some(U256::from(1_000)); + evm.ctx_mut().local_mut().shared_memory_buffer().borrow_mut().resize(64, 0xff); + evm.ctx_mut().local_mut().set_precompile_error_context("left behind".into()); + + let error = evm + .transact_one(over_the_limit_deposit(SENDER, 7)) + .expect_err("the recovery's read of the sender fails"); + assert!(format!("{error:?}").contains("injected basic()"), "{error:?}"); + assert_eq!(evm.ctx_mut().chain_mut().tx_l1_cost, None, "the cached L1 cost"); + assert!( + evm.ctx_mut().local_mut().shared_memory_buffer().borrow().is_empty(), + "the shared memory" + ); + assert_eq!(evm.ctx_mut().local_mut().take_precompile_error_context(), None); + assert_eq!(EvmTr::frame_stack(&mut evm).index(), None, "the frame stack"); + assert!(evm.ctx_mut().error().is_ok(), "the error slot"); + let journal = evm.ctx_mut().journal_mut(); + assert_eq!((journal.depth, journal.journal.len()), (0, 0), "no transaction is open"); + + // What the refused deposit loaded is the caller's to drop, as after any `transact_one`; the + // next transaction runs under the spec's limits. + evm.ctx_mut().db_mut().fail_on_account = None; + let _ = evm.finalize(); + evm.set_tx_runtime_limits(EvmTxRuntimeLimits::default()); + let next = call(SENDER, KEPT, U256::ZERO, GAS_LIMIT); + let reused = evm.execute_transaction(next.clone()).expect("the next transaction is valid"); + let fresh = self::evm(ErrorInjectingDatabase::new(database())) + .execute_transaction(next) + .expect("the next transaction is valid"); + assert_same_outcome(&reused, &fresh, "after the recovery's error"); +} From ed4181e70fc4fe181b8398d035642d4964fbeade Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 15:06:34 +0800 Subject: [PATCH 67/83] fix(satin): every entry point that finalizes on a success finalizes on an error --- crates/mega-evm/src/evm/mod.rs | 54 +- .../mega-evm/tests/satin/reuse_after_error.rs | 497 +++++++++++++++++- 2 files changed, 528 insertions(+), 23 deletions(-) diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 981831435..ae0d8a055 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -121,6 +121,29 @@ pub(crate) type MegaInnerEvm = revm::context::Evm< /// execution traits ([`ExecuteEvm`], [`InspectEvm`], [`SystemCallEvm`] and their commit /// variants) and alloy-evm's [`Evm`](alloy_evm::Evm), which is what a node's block executor /// drives. +/// +/// # Reuse after an error +/// +/// A call that fails with an error — a read the database could not serve, a transaction +/// validation refuses — leaves nothing of itself in the EVM, whichever entry point ran it: the +/// handler's fatal cleanup ([`MegaHandler`]'s `catch_error`) drops the error a load recorded and +/// nothing took, takes back the call's journal transaction — its nonce bump and fee, and the writes +/// of its frames, those that completed before the error included — and clears the per-transaction +/// caches and the frame stack. What the next call reads of the context is prepared afresh when it +/// starts. So an EVM is reused after an error as after a success, and the next call runs as on a +/// fresh EVM over the same database. +/// +/// Every entry point that takes the state off the journal on a success does so on an error too: +/// [`execute_transaction`](Self::execute_transaction), `transact`, `transact_many`, `replay`, the +/// `inspect` methods, the `_commit` variants, the system calls that return state, alloy-evm's +/// methods and the pre-block calls. The `_one` entry points leave the journal to the caller on both +/// outcomes, so the calls before a failed one stay in it for the caller to finalize, and none of +/// the failed call's writes do. A failed deposit is a result, not an error: its nonce bump and mint +/// stay. +/// +/// A caller of the handler's `run_without_catch_error` that drops an error makes the same cleanup +/// first, through `catch_error`. A panic unwinds past the cleanup: an EVM a panic unwound out of is +/// not reused. #[allow(missing_debug_implementations)] pub struct MegaEvm { inner: MegaInnerEvm, @@ -352,11 +375,15 @@ impl ExecuteEvm for MegaEvm Result, Self::Error> { - let result = MegaHandler::<_, Self::Error, _>::new().run(self)?; - Ok(ExecResultAndState::new(result, self.finalize())) + let output_or_error = MegaHandler::<_, Self::Error, _>::new().run(self); + let state = self.finalize(); + Ok(ExecResultAndState::new(output_or_error?, state)) } } @@ -407,6 +434,21 @@ impl SystemCallEvm for MegaEvm Result, Self::Error> { + let output_or_error = + self.system_call_one_with_caller(caller, system_contract_address, data); + let state = self.finalize(); + Ok(ExecResultAndState::new(output_or_error?, state)) + } } impl MegaEvm { @@ -417,7 +459,8 @@ impl MegaEvm { /// budget, [`PRE_BLOCK_CALL_GAS_LIMIT`], instead of revm's [`SYSTEM_CALL_GAS_LIMIT`]: at most /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] of it is regular gas, as of every system call, and the /// rest is the call's state-gas reservoir. What the call left of its reservoir is - /// [`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining). + /// [`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining). The + /// journal is finalized whether or not the call succeeded, as `transact_system_call`'s. /// /// [`PRE_BLOCK_CALL_GAS_LIMIT`]: crate::constants::PRE_BLOCK_CALL_GAS_LIMIT /// [`SYSTEM_CALL_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_GAS_LIMIT @@ -430,8 +473,9 @@ impl MegaEvm { ) -> Result, EVMError> { let mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); tx.0.base.gas_limit = crate::constants::PRE_BLOCK_CALL_GAS_LIMIT; - let result = self.run_system_call(tx).map_err(map_op_err)?; - Ok(ResultAndState::new(result, ExecuteEvm::finalize(self))) + let output_or_error = self.run_system_call(tx); + let state = ExecuteEvm::finalize(self); + Ok(ResultAndState::new(output_or_error.map_err(map_op_err)?, state)) } /// Runs `tx` as a system call: the protocol's own work, prepared as such (see diff --git a/crates/mega-evm/tests/satin/reuse_after_error.rs b/crates/mega-evm/tests/satin/reuse_after_error.rs index 575dc4c7d..37dff3234 100644 --- a/crates/mega-evm/tests/satin/reuse_after_error.rs +++ b/crates/mega-evm/tests/satin/reuse_after_error.rs @@ -3,27 +3,39 @@ //! A call that fails with an error — a read the database could not serve — is no result a block //! includes, and what it left in the EVM is the handler's fatal cleanup's to drop //! (`MegaHandler::catch_error`): the error a Host load recorded and nothing took, the failed -//! call's journal transaction, op-revm's per-transaction caches and the frame stack. A `_one` -//! entry point leaves the journal to its caller, so the calls before the failed one stay in it and -//! none of the failed call's writes do; a failed deposit is a result, whose nonce bump and mint -//! stay. Nothing here needs an inspector. +//! call's journal transaction, op-revm's per-transaction caches and the frame stack. Every entry +//! point that takes the state off the journal on a success does so on an error too; a `_one` entry +//! point leaves the journal to its caller, so the calls before the failed one stay in it and none +//! of the failed call's writes do; a failed deposit is a result, whose nonce bump and mint stay. +//! The entry-point table runs a failing call through every public entry point. Nothing here needs +//! an inspector: the inspected entry points run on a no-op one. //! //! This file pins the state a failed call leaves behind; `db_error.rs` pins the error itself. +use std::collections::BTreeMap; + +use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, TxKind, B256, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use mega_evm::{ + mainnet_hardforks, op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, + system::{transact_apply_pending_changes, SEQUENCER_REGISTRY_ADDRESS}, test_utils::{op_transaction, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, - EvmTxRuntimeLimits, MegaEvm, MegaHaltReason, MegaTransaction, MegaTransactionOutcome, - TX_BODY_SIZE, + transact_beacon_root_contract_call, transact_blockhashes_contract_call, EvmTxRuntimeLimits, + MegaEvm, MegaHaltReason, MegaTransaction, MegaTransactionOutcome, TX_BODY_SIZE, }; use revm::{ bytecode::opcode::{BALANCE, POP, SLOAD}, - context::{result::ExecutionResult, BlockEnv, ContextTr, TxEnv}, + context::{ + result::{ExecResultAndState, ExecutionResult}, + BlockEnv, ContextSetters, ContextTr, TxEnv, + }, context_interface::LocalContextTr, - handler::EvmTr, - ExecuteEvm, + handler::{EvmTr, SystemCallEvm}, + inspector::NoOpInspector, + state::EvmState, + ExecuteCommitEvm, ExecuteEvm, InspectCommitEvm, InspectEvm, InspectSystemCallEvm, }; use crate::common::{block, call, context}; @@ -39,6 +51,10 @@ const CHILD: Address = address!("0000000000000000000000000000000000e10003"); const KEPT: Address = address!("0000000000000000000000000000000000e10004"); /// Reads the balance of the account the test names. const READS: Address = address!("0000000000000000000000000000000000e10005"); +/// `SSTORE(0, 7)`, then a read of the beneficiary's balance. +const READS_BENEFICIARY: Address = address!("0000000000000000000000000000000000e10006"); +/// `SSTORE(0, 7)`. +const WRITES: Address = address!("0000000000000000000000000000000000e10007"); const BENEFICIARY: Address = address!("0000000000000000000000000000000000e1bef0"); const GAS_LIMIT: u64 = 100_000_000; @@ -47,27 +63,29 @@ fn block_with_beneficiary() -> BlockEnv { BlockEnv { beneficiary: BENEFICIARY, ..block() } } -/// The pre-state every test starts from: the senders funded, and the contracts. -fn database() -> MemoryDatabase { - let writer = BytecodeBuilder::default() +/// [`WRITER`]'s code. +fn writer() -> Bytes { + BytecodeBuilder::default() .sstore(U256::ZERO, U256::from(7)) .call(CHILD, U256::ZERO) .append(POP) .stop() - .build(); + .build() +} + +/// The pre-state every test starts from: the senders funded, and the contracts. +fn database() -> MemoryDatabase { let child = BytecodeBuilder::default().push_number(1_u64).append(SLOAD).append(POP).stop(); MemoryDatabase::default() .account_balance(SENDER, U256::from(10u64.pow(18))) .account_balance(EARLIER_SENDER, U256::from(10u64.pow(18))) - .account_code(WRITER, writer) + .account_code(WRITER, writer()) .account_code(CHILD, child.build()) .account_code(KEPT, BytecodeBuilder::default().sstore(U256::ZERO, U256::ONE).stop().build()) } /// A Satin EVM over `db`, in a block whose beneficiary is [`BENEFICIARY`]. -fn evm( - db: ErrorInjectingDatabase, -) -> MegaEvm { +fn evm(db: ErrorInjectingDatabase) -> Evm { MegaEvm::new(context(db).with_block(block_with_beneficiary())) } @@ -232,3 +250,446 @@ fn test_an_error_in_the_failed_deposit_recovery_leaves_the_evm_clean() { .expect("the next transaction is valid"); assert_same_outcome(&reused, &fresh, "after the recovery's error"); } + +/// The EVM every row of the entry-point table runs on. +type Evm = MegaEvm; + +/// [`database`], with the contracts the entry-point table's calls run: [`WRITER`]'s code is also +/// at the three addresses the pre-block calls target. +fn table_database() -> MemoryDatabase { + let writes = || BytecodeBuilder::default().sstore(U256::ZERO, U256::from(7)); + let reads_beneficiary = writes().push_address(BENEFICIARY).append(BALANCE).append(POP); + database() + .account_code(WRITES, writes().stop().build()) + .account_code(READS_BENEFICIARY, reads_beneficiary.stop().build()) + .account_code(HISTORY_STORAGE_ADDRESS, writer()) + .account_code(BEACON_ROOTS_ADDRESS, writer()) + .account_code(SEQUENCER_REGISTRY_ADDRESS, writer()) +} + +/// An EVM over `db` for the entry-point table, with inspection enabled when `inspect`. +fn table_evm(db: ErrorInjectingDatabase, inspect: bool) -> Evm { + let evm = evm(db); + if inspect { + evm.with_inspector(NoOpInspector) + } else { + evm + } +} + +/// Where the failing call's error comes from. +#[derive(Clone, Copy, Debug)] +enum Site { + /// A child's read of slot 1, after the call's own frame wrote slot 0: the child ends with the + /// error, its caller's return takes it, and the call fails with its own frame's write open in + /// the journal. + Nested, + /// The call's own frame writes slot 0 and reads the beneficiary, which the database fails: the + /// Host records the error and the frame ends, and post-execution's read of the beneficiary + /// fails first, so the recorded error is never taken. A system call has no post-execution. + Preempted, + /// The call's own frame writes slot 0 and succeeds, and post-execution's read of a fee + /// recipient fails. A system call has no post-execution. + PostExecution, +} + +impl Site { + const ALL: [Self; 3] = [Self::Nested, Self::Preempted, Self::PostExecution]; + + /// The contract a transaction or a system call of the table calls. + const fn contract(self) -> Address { + match self { + Self::Nested => WRITER, + Self::Preempted => READS_BENEFICIARY, + Self::PostExecution => WRITES, + } + } + + /// Makes `db` fail the read the site's call fails on, or serve it again. + fn arm(self, db: &mut ErrorInjectingDatabase, armed: bool) { + match self { + Self::Nested => db.fail_on_storage = armed.then_some((CHILD, U256::ONE)), + Self::Preempted => db.fail_on_account = armed.then_some(BENEFICIARY), + Self::PostExecution => db.fail_on_account = armed.then_some(BASE_FEE_RECIPIENT), + } + } +} + +/// Every public way to run a transaction or a system call on a `MegaEvm`: the inherent method, +/// the required and provided methods of every execution trait it implements, revm's and +/// alloy-evm's, and the pre-block calls. The deprecated aliases are still callable and route +/// through the provided methods. +#[derive(Clone, Copy, Debug)] +enum EntryPoint { + ExecuteTransaction, + Transact, + TransactMany, + TransactManyFinalize, + Replay, + TransactCommit, + TransactManyCommit, + ReplayCommit, + InspectTx, + Inspect, + InspectTxCommit, + InspectCommit, + AlloyTransact, + AlloyTransactRaw, + AlloyTransactCommit, + TransactOne, + InspectOneTx, + InspectOne, + SystemCall, + SystemCallWithCaller, + DeprecatedTransactSystemCallFinalize, + DeprecatedTransactSystemCallWithCallerFinalize, + AlloyTransactSystemCall, + InspectSystemCall, + InspectSystemCallWithCaller, + InspectSystemCallWithInspector, + InspectSystemCallWithInspectorAndCaller, + BlockHashesPreBlockCall, + BeaconRootPreBlockCall, + ApplyPendingChangesPreBlockCall, + SystemCallOne, + SystemCallOneWithCaller, + DeprecatedTransactSystemCall, + DeprecatedTransactSystemCallWithCaller, + InspectOneSystemCall, + InspectOneSystemCallWithCaller, + InspectOneSystemCallWithInspector, + InspectOneSystemCallWithInspectorAndCaller, +} + +impl EntryPoint { + const ALL: [Self; 38] = [ + Self::ExecuteTransaction, + Self::Transact, + Self::TransactMany, + Self::TransactManyFinalize, + Self::Replay, + Self::TransactCommit, + Self::TransactManyCommit, + Self::ReplayCommit, + Self::InspectTx, + Self::Inspect, + Self::InspectTxCommit, + Self::InspectCommit, + Self::AlloyTransact, + Self::AlloyTransactRaw, + Self::AlloyTransactCommit, + Self::TransactOne, + Self::InspectOneTx, + Self::InspectOne, + Self::SystemCall, + Self::SystemCallWithCaller, + Self::DeprecatedTransactSystemCallFinalize, + Self::DeprecatedTransactSystemCallWithCallerFinalize, + Self::AlloyTransactSystemCall, + Self::InspectSystemCall, + Self::InspectSystemCallWithCaller, + Self::InspectSystemCallWithInspector, + Self::InspectSystemCallWithInspectorAndCaller, + Self::BlockHashesPreBlockCall, + Self::BeaconRootPreBlockCall, + Self::ApplyPendingChangesPreBlockCall, + Self::SystemCallOne, + Self::SystemCallOneWithCaller, + Self::DeprecatedTransactSystemCall, + Self::DeprecatedTransactSystemCallWithCaller, + Self::InspectOneSystemCall, + Self::InspectOneSystemCallWithCaller, + Self::InspectOneSystemCallWithInspector, + Self::InspectOneSystemCallWithInspectorAndCaller, + ]; + + /// Whether the entry point takes the state off the journal, on a success and on an error. The + /// `_one` ones leave it to the caller on both, so several calls can share one journal. + const fn finalizes(self) -> bool { + !matches!( + self, + Self::TransactOne | + Self::InspectOneTx | + Self::InspectOne | + Self::SystemCallOne | + Self::SystemCallOneWithCaller | + Self::DeprecatedTransactSystemCall | + Self::DeprecatedTransactSystemCallWithCaller | + Self::InspectOneSystemCall | + Self::InspectOneSystemCallWithCaller | + Self::InspectOneSystemCallWithInspector | + Self::InspectOneSystemCallWithInspectorAndCaller + ) + } + + /// Whether the entry point runs a system call rather than a transaction. + const fn is_system_call(self) -> bool { + matches!( + self, + Self::SystemCall | + Self::SystemCallWithCaller | + Self::DeprecatedTransactSystemCallFinalize | + Self::DeprecatedTransactSystemCallWithCallerFinalize | + Self::AlloyTransactSystemCall | + Self::InspectSystemCall | + Self::InspectSystemCallWithCaller | + Self::InspectSystemCallWithInspector | + Self::InspectSystemCallWithInspectorAndCaller | + Self::BlockHashesPreBlockCall | + Self::BeaconRootPreBlockCall | + Self::ApplyPendingChangesPreBlockCall | + Self::SystemCallOne | + Self::SystemCallOneWithCaller | + Self::DeprecatedTransactSystemCall | + Self::DeprecatedTransactSystemCallWithCaller | + Self::InspectOneSystemCall | + Self::InspectOneSystemCallWithCaller | + Self::InspectOneSystemCallWithInspector | + Self::InspectOneSystemCallWithInspectorAndCaller + ) + } + + /// The contract the call runs: a pre-block call's own, and otherwise the site's. + const fn target(self, site: Site) -> Address { + match self { + Self::BlockHashesPreBlockCall => HISTORY_STORAGE_ADDRESS, + Self::BeaconRootPreBlockCall => BEACON_ROOTS_ADDRESS, + Self::ApplyPendingChangesPreBlockCall => SEQUENCER_REGISTRY_ADDRESS, + _ => site.contract(), + } + } + + /// Runs the site's call through the entry point — a transaction from [`SENDER`], or a system + /// call, from [`SENDER`] where the entry point takes a caller — and answers its result or its + /// error. The state an entry point hands back is committed to the database; what a `_one` + /// entry point leaves in the journal stays there. + #[allow(deprecated)] + fn run(self, evm: &mut Evm, site: Site) -> Result, String> { + let (result, state) = self.run_handing_back(evm, site)?; + if let Some(state) = state { + ExecuteCommitEvm::commit(evm, state); + } + Ok(result) + } + + /// [`run`](Self::run), with the state the entry point handed back, if it handed any. + #[allow(deprecated)] + fn run_handing_back( + self, + evm: &mut Evm, + site: Site, + ) -> Result<(ExecutionResult, Option), String> { + let to = self.target(site); + let tx = || call(SENDER, to, U256::ZERO, GAS_LIMIT); + let data = Bytes::new; + let hardforks = mainnet_hardforks; + fn handed( + ran: Result, EvmState>, E>, + ) -> Result<(ExecutionResult, Option), String> { + ran.map(|ran| (ran.result, Some(ran.state))).map_err(|error| format!("{error:?}")) + } + fn kept( + ran: Result, E>, + ) -> Result<(ExecutionResult, Option), String> { + ran.map(|result| (result, None)).map_err(|error| format!("{error:?}")) + } + let first = |results: Vec>| { + results.into_iter().next().expect("one result") + }; + match self { + Self::ExecuteTransaction => { + handed(evm.execute_transaction(tx()).map(|outcome| outcome.result_and_state)) + } + Self::Transact => handed(ExecuteEvm::transact(evm, tx())), + Self::TransactMany => { + // The journal holds a success until the caller finalizes it. + let results = kept(evm.transact_many(core::iter::once(tx())).map(first))?; + Ok((results.0, Some(evm.finalize()))) + } + Self::TransactManyFinalize => handed( + evm.transact_many_finalize(core::iter::once(tx())) + .map(|ran| ExecResultAndState::new(first(ran.result), ran.state)), + ), + Self::Replay => { + evm.ctx_mut().set_tx(tx()); + handed(ExecuteEvm::replay(evm)) + } + Self::TransactCommit => kept(ExecuteCommitEvm::transact_commit(evm, tx())), + Self::TransactManyCommit => { + kept(evm.transact_many_commit(core::iter::once(tx())).map(first)) + } + Self::ReplayCommit => { + evm.ctx_mut().set_tx(tx()); + kept(evm.replay_commit()) + } + Self::InspectTx => handed(evm.inspect_tx(tx())), + Self::Inspect => handed(InspectEvm::inspect(evm, tx(), NoOpInspector)), + Self::InspectTxCommit => kept(evm.inspect_tx_commit(tx())), + Self::InspectCommit => kept(evm.inspect_commit(tx(), NoOpInspector)), + Self::AlloyTransact => handed(alloy_evm::Evm::transact(evm, tx())), + Self::AlloyTransactRaw => handed(alloy_evm::Evm::transact_raw(evm, tx())), + Self::AlloyTransactCommit => kept(alloy_evm::Evm::transact_commit(evm, tx())), + Self::TransactOne => kept(evm.transact_one(tx())), + Self::InspectOneTx => kept(evm.inspect_one_tx(tx())), + Self::InspectOne => kept(evm.inspect_one(tx(), NoOpInspector)), + Self::SystemCall => handed(evm.system_call(to, data())), + Self::SystemCallWithCaller => { + handed(SystemCallEvm::system_call_with_caller(evm, SENDER, to, data())) + } + Self::DeprecatedTransactSystemCallFinalize => { + handed(evm.transact_system_call_finalize(to, data())) + } + Self::DeprecatedTransactSystemCallWithCallerFinalize => { + handed(evm.transact_system_call_with_caller_finalize(SENDER, to, data())) + } + Self::AlloyTransactSystemCall => { + handed(alloy_evm::Evm::transact_system_call(evm, SENDER, to, data())) + } + Self::InspectSystemCall => handed(evm.inspect_system_call(to, data())), + Self::InspectSystemCallWithCaller => { + handed(evm.inspect_system_call_with_caller(SENDER, to, data())) + } + Self::InspectSystemCallWithInspector => { + handed(evm.inspect_system_call_with_inspector(to, data(), NoOpInspector)) + } + Self::InspectSystemCallWithInspectorAndCaller => { + handed(evm.inspect_system_call_with_inspector_and_caller( + SENDER, + to, + data(), + NoOpInspector, + )) + } + Self::BlockHashesPreBlockCall => handed( + transact_blockhashes_contract_call(hardforks(), B256::repeat_byte(1), evm) + .map(|ran| ran.expect("Prague is active")), + ), + Self::BeaconRootPreBlockCall => handed( + transact_beacon_root_contract_call(hardforks(), Some(B256::repeat_byte(2)), evm) + .map(|ran| ran.expect("Cancun is active")), + ), + Self::ApplyPendingChangesPreBlockCall => handed(transact_apply_pending_changes(evm)), + Self::SystemCallOne => kept(evm.system_call_one(to, data())), + Self::SystemCallOneWithCaller => { + kept(evm.system_call_one_with_caller(SENDER, to, data())) + } + Self::DeprecatedTransactSystemCall => { + kept(SystemCallEvm::transact_system_call(evm, to, data())) + } + Self::DeprecatedTransactSystemCallWithCaller => { + kept(evm.transact_system_call_with_caller(SENDER, to, data())) + } + Self::InspectOneSystemCall => kept(evm.inspect_one_system_call(to, data())), + Self::InspectOneSystemCallWithCaller => { + kept(evm.inspect_one_system_call_with_caller(SENDER, to, data())) + } + Self::InspectOneSystemCallWithInspector => { + kept(evm.inspect_one_system_call_with_inspector(to, data(), NoOpInspector)) + } + Self::InspectOneSystemCallWithInspectorAndCaller => { + kept(evm.inspect_one_system_call_with_inspector_and_caller( + SENDER, + to, + data(), + NoOpInspector, + )) + } + } + } +} + +/// What the database holds, account by account: nonce, balance, code hash and storage. +fn committed(evm: &Evm) -> BTreeMap)> { + let accounts = &evm.ctx().db().cache.accounts; + accounts + .iter() + .map(|(address, account)| { + let storage = account.storage.iter().map(|(key, value)| (*key, *value)).collect(); + let info = &account.info; + (*address, (info.nonce, info.balance, info.code_hash, storage)) + }) + .collect() +} + +/// A call that fails with an error leaves the EVM as a fresh one is, whichever public entry point +/// ran it and wherever the error came from: the error slot is empty, and an entry point that +/// finalizes the journal on a success hands it back empty on an error too, while a `_one` entry +/// point leaves a journal that holds the call before the failed one and none of the failed call's +/// writes. The same call run again on the same EVM, the database serving again, has the result a +/// fresh EVM gives it and leaves the database as the fresh one leaves it. Each entry point runs on +/// an EVM with inspection enabled and on one without, which only alloy-evm's `transact` methods and +/// `execute_transaction` read; a system call has no post-execution, so the two post-execution sites +/// are the transactions'. +#[test] +fn test_every_entry_point_leaves_nothing_of_a_failed_call() { + let (mut rows, mut skipped) = (0, 0); + for inspect in [false, true] { + for site in Site::ALL { + for entry in EntryPoint::ALL { + if entry.is_system_call() && !matches!(site, Site::Nested) { + skipped += 1; + continue; + } + rows += 1; + assert_a_failed_call_leaves_nothing(entry, site, inspect); + } + } + } + let system_calls = EntryPoint::ALL.iter().filter(|entry| entry.is_system_call()).count(); + assert_eq!(skipped, 2 * 2 * system_calls); + assert_eq!(rows + skipped, 2 * Site::ALL.len() * EntryPoint::ALL.len()); +} + +fn assert_a_failed_call_leaves_nothing(entry: EntryPoint, site: Site, inspect: bool) { + let row = format!("{entry:?} / {site:?} / inspect={inspect}"); + // A system call before the failing one, for a `_one` entry point's journal to hold: it reads + // neither the beneficiary nor a fee recipient, which the failing call's database fails. + let earlier = |evm: &mut Evm| { + if !entry.finalizes() { + let earlier = evm + .system_call_one_with_caller(SENDER, KEPT, Bytes::new()) + .expect("the earlier call runs"); + assert!(earlier.is_success(), "{row}: {earlier:?}"); + } + }; + + let mut evm = table_evm(ErrorInjectingDatabase::new(table_database()), inspect); + earlier(&mut evm); + site.arm(evm.ctx_mut().db_mut(), true); + let failed = entry.run(&mut evm, site); + assert!(matches!(&failed, Err(error) if error.contains("injected")), "{row}: {failed:?}"); + site.arm(evm.ctx_mut().db_mut(), false); + assert!(evm.ctx_mut().error().is_ok(), "{row}: the error slot"); + if entry.finalizes() { + assert!(evm.finalize().is_empty(), "{row}: the journal is handed back empty"); + } else { + let target = entry.target(site); + let journal = evm.ctx_mut().journal_mut(); + assert_eq!((journal.depth, journal.journal.len()), (0, 0), "{row}: no transaction open"); + assert_eq!( + journal.state[&KEPT].storage[&U256::ZERO].present_value, + U256::ONE, + "{row}: the earlier call's write" + ); + let sender = journal.state.get(&SENDER).map(|sender| sender.info.nonce); + assert!(sender.is_none_or(|nonce| nonce == 0), "{row}: the failed call's nonce bump"); + let written = journal.state.get(&target).and_then(|target| target.storage.get(&U256::ZERO)); + assert!( + written.is_none_or(|slot| slot.present_value == slot.original_value), + "{row}: the failed call's write: {written:?}" + ); + } + let retried = entry.run(&mut evm, site); + let mut fresh = table_evm(ErrorInjectingDatabase::new(table_database()), inspect); + earlier(&mut fresh); + let expected = entry.run(&mut fresh, site); + assert!(matches!(&expected, Ok(result) if result.is_success()), "{row}: {expected:?}"); + assert_eq!(retried, expected, "{row}: the call run again"); + if !entry.finalizes() { + for evm in [&mut evm, &mut fresh] { + let state = evm.finalize(); + ExecuteCommitEvm::commit(evm, state); + } + } + assert_eq!(committed(&evm), committed(&fresh), "{row}: what the database holds"); +} From 17644f7b2bb3eb3ce31247ed59a3b4a4070114ad Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 15:29:47 +0800 Subject: [PATCH 68/83] docs: an error leaves nothing of the failed call for the next one on the same EVM --- .claude/skills/satin-review/SKILL.md | 7 +++++++ AGENTS.md | 11 +++++++++++ docs/spec/upgrades/satin.md | 1 + 3 files changed, 19 insertions(+) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 4d7a35ac1..ffa46c7e0 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -83,6 +83,12 @@ Each change is stated here in plain words with its reason; the specification has `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, the frame's own part is parked on the start ledger as the start's charge, which its settlement gives back when the frame fails, and the frame's share of the caller's reservoir is taken and named on the start (`FrameStart::reservoir`). Why: a write the opcode's own failure takes back is never counted, and the engine no longer rebuilds revm's state from outside with instruction wrappers. +- **An error leaves nothing of the failed call.** + Made after #407 merged: the handler's fatal cleanup (`MegaHandler::catch_error`), which every entry point reaches, empties the error slot before op-revm's cleanup runs, discards the failed call's journal transaction on every error, and clears the cached L1 cost, the local context and the frame stack after op-revm; `replay`, `SystemCallEvm::system_call_with_caller` (with the deprecated aliases and alloy-evm's `transact_system_call` that route through it) and the pre-block calls finalize the journal on an error as they do on a success. + Before, an error a Host load recorded in the transaction's own frame, which post-execution preempted by failing first on a read of its own, stayed in the slot and failed the next transaction on the same EVM; and a `_one` entry point, `replay`, a system call returning state and a pre-block call left the failed call's writes, nonce bump, warm set and transaction id in the journal for the next call. + A failed deposit is a result: its nonce bump and mint stay; the calls a `_one` journal holds before the failed one stay too. + An embedder reuses an EVM after an error as after a success; a caller of `run_without_catch_error` that drops an error calls `catch_error` first, and an EVM a panic unwound out of is not reused. + Why: op-revm discards the journal only for a failed deposit, revm takes the recorded error only once post-execution succeeded, and op-revm's own clearing is skipped when its failed-deposit recovery errors; the boundary every entry point reaches is the engine's, so the repair is made there and the forks are unchanged. ### What is counted @@ -280,6 +286,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - The forwards: regular gas `remaining − remaining × 2 / 100`, plus a value call's stipend after the cap; the reservoir by the same subtraction, the transaction's own frame and a system call's outermost frame taking the whole; each pool `remaining × 98 / 100`, rounded down. - `spec_cfg` fixes the configuration whatever the caller passes (Satin schedule, EIP-8037, EIP-2780, execution cap 200,000,000, EIP-7708, chain-id check on, the contract size limit at 512 KiB and the initcode size limit at 1 MiB, the fork's legacy journal semantics off). - Per-transaction state resets with the transaction; a system call has its own entry point, and the handler splits its gas (`MegaHandler::tx_gas`). + - An execution that fails with an error leaves nothing the next one on the same EVM reads: `MegaHandler::catch_error` empties the error slot before op-revm runs, discards the journal transaction on an error (a failed deposit's commit stays), and clears the L1 cost, the local context and the frame stack after op-revm; every entry point that takes the state off the journal on a success does so on an error, and a `_one` entry point keeps the calls before the failed one (`tests/satin/reuse_after_error.rs`, every public entry point, plain and inspected). - A fact about the transaction's start is read with what the journal records of the transaction (its original info, its entries, its transaction id), never off an account flag revm sets once per journal alone, so on a journal that runs several transactions unfinalized the engine's counts follow what revm charges there. - **Spec:** §3, §4, §5, §9, §10, §11, §14, §21. - **Detail:** [`AGENTS.md`, "How Satin executes today"](../../../AGENTS.md#how-satin-executes-today). diff --git a/AGENTS.md b/AGENTS.md index f179b1bd8..d45602a5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -496,6 +496,14 @@ Every later mechanism plugs into these; a change to one comes back to this layer The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes: it names the crossing that produced the result of the transaction's own frame — a transaction-level limit or that frame's own budget in data size, KV updates or state growth — noted where the stop became a frame's result (`AdditionalLimit::note_frame_stop`) and kept only while that frame's result is still the stop's revert; a stop a caller caught, and re-raised or not, is none. `LimitStop::from_result` (and `MegaTransactionOutcome::limit_stop`) reads a stop off the two together, for an RPC's error; `decode_mega_limit_exceeded` reads the bytes alone, which make no stop by themselves. `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as the successes the inspector made of them. +- **An error leaves nothing of the failed call.** + A call that fails with an error — a read the database could not serve, a transaction validation refuses — is no result, and the next call on the same EVM runs as on a fresh EVM over the same database. + Every entry point reaches the handler's fatal cleanup (`MegaHandler::catch_error`), which drops the error a Host load recorded and nothing took — post-execution can fail on a read of its own before the handler takes it — before op-revm's cleanup runs, discards the failed call's journal transaction, which op-revm discards only for the failed deposit it commits, and clears the cached L1 cost, the local context and the frame stack after op-revm, whose own clearing an error out of its failed-deposit recovery skips; op-revm discards the start lifecycle first, and the start ledger with it. + Every entry point that takes the state off the journal on a success does so on an error too: `execute_transaction`, `transact`, `transact_many`, `replay`, the `inspect` methods, the `_commit` variants, the system calls that return state, alloy-evm's methods and the pre-block calls. + A `_one` entry point leaves the journal to its caller on both outcomes, so the calls before the failed one stay in it and none of its writes do, and a failed deposit is a result whose nonce bump and mint stay. + The rest of the context's per-transaction state is reset where the next execution is prepared, before anything reads it (`MegaContext::prepare`, through `on_new_tx` and `on_new_system_call`); the block-hash and bucket records are the block's, and keep a failed call's reads. + An embedder reuses an EVM after an error as after a success; a caller of the handler's `run_without_catch_error` that drops an error calls `catch_error` first, and an EVM a panic unwound out of is not reused. + `tests/satin/reuse_after_error.rs` runs a failing call through every public entry point, plain and inspected, at a nested read, a recorded error post-execution preempts, and a post-execution read. - **A per-frame gas cap stays inside the frame's tracker.** Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame's run returns (`frame_run_result`). A later mechanism that caps a frame's gas uses the same part; it limits the frame at its start and again after every credit — a child's return, `SSTORE`'s refill — and never releases a creating frame's withheld part before `return_create`, whose charges are the frame's own regular charges. @@ -692,6 +700,9 @@ When the agent is requested to implement a new feature or bug fix, it should con - **Always test logic changes.** Any logic change or modification to mega-evm should be equipped with tests if there is no specific reason of not adding tests. The agent should always consider accompanying tests or suggest to add additional tests. +- **Reset per-transaction state before the next execution reads it.** + An execution that fails with an error leaves through no settlement, so a new per-transaction field of `MegaContext` is reset in `MegaContext::prepare`, unless every execution overwrites it before reading it, and a new cache in revm's context or on the EVM that a run fills is cleared in `MegaHandler::catch_error` as well as on success. + A new public entry point that takes the state off the journal does so on an error too, and joins the entry-point table in `tests/satin/reuse_after_error.rs`; so does a provided method a revm or alloy-evm upgrade adds. - **Keep the op-revm baseline honest.** A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. - **Hold a test at any byte price.** diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index c6ac01d60..ed482c12f 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1502,6 +1502,7 @@ A node, a stateless validator and a replay tool must agree on everything below, An address read from another state treats the old system address's transactions as the protocol's and the new one's as a user's, or the reverse. A deposit is never refused for failing validation: one that fails validation is included as a failed deposit, which bumps its sender's nonce and uses its whole gas limit. A bucket or database read the node fails to make is not a validation failure, for a deposit either: the transaction gets no outcome; a failed bucket read, a database error the database declares fatal, or any database error on a read block execution makes around the transaction is an internal error of the node, while any other database error the transaction's execution meets makes the block invalid; a builder, which has no outcome to include for that transaction, may then leave a non-deposit transaction out, but cannot build a block that must hold the deposit while the read fails. + The reference implementation keeps nothing of a transaction that got no outcome: the transactions executed after it, and the same transaction executed again once the read succeeds, execute as they would on a fresh execution environment over the same state. - **Activation blocks.** Block execution does not work out whether a block admits only deposits: it is told, and refuses a non-deposit transaction only when told so. The chain's rule is therefore enforced by the nodes that derive and build the chain, not by the executor alone: MegaETH's op-node MUST enforce deposit-only activation blocks for Satin and for every later MegaETH fork, and a block builder MUST compute the flag from the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates. From ff18af6337a7b320ca9c52c2126bc5547451b8bb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 16:49:43 +0800 Subject: [PATCH 69/83] test(satin): classify the entry-point table exhaustively, and state what a failed _one call leaves in the journal --- .claude/skills/satin-review/SKILL.md | 2 +- AGENTS.md | 6 +- crates/mega-evm/src/evm/mod.rs | 20 +- .../mega-evm/tests/satin/reuse_after_error.rs | 271 ++++++++++-------- 4 files changed, 162 insertions(+), 137 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index ffa46c7e0..cb49ca864 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -83,7 +83,7 @@ Each change is stated here in plain words with its reason; the specification has `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, the frame's own part is parked on the start ledger as the start's charge, which its settlement gives back when the frame fails, and the frame's share of the caller's reservoir is taken and named on the start (`FrameStart::reservoir`). Why: a write the opcode's own failure takes back is never counted, and the engine no longer rebuilds revm's state from outside with instruction wrappers. -- **An error leaves nothing of the failed call.** +- **An error leaves nothing the next call depends on.** Made after #407 merged: the handler's fatal cleanup (`MegaHandler::catch_error`), which every entry point reaches, empties the error slot before op-revm's cleanup runs, discards the failed call's journal transaction on every error, and clears the cached L1 cost, the local context and the frame stack after op-revm; `replay`, `SystemCallEvm::system_call_with_caller` (with the deprecated aliases and alloy-evm's `transact_system_call` that route through it) and the pre-block calls finalize the journal on an error as they do on a success. Before, an error a Host load recorded in the transaction's own frame, which post-execution preempted by failing first on a read of its own, stayed in the slot and failed the next transaction on the same EVM; and a `_one` entry point, `replay`, a system call returning state and a pre-block call left the failed call's writes, nonce bump, warm set and transaction id in the journal for the next call. A failed deposit is a result: its nonce bump and mint stay; the calls a `_one` journal holds before the failed one stay too. diff --git a/AGENTS.md b/AGENTS.md index d45602a5d..23533c5c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -496,11 +496,11 @@ Every later mechanism plugs into these; a change to one comes back to this layer The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes: it names the crossing that produced the result of the transaction's own frame — a transaction-level limit or that frame's own budget in data size, KV updates or state growth — noted where the stop became a frame's result (`AdditionalLimit::note_frame_stop`) and kept only while that frame's result is still the stop's revert; a stop a caller caught, and re-raised or not, is none. `LimitStop::from_result` (and `MegaTransactionOutcome::limit_stop`) reads a stop off the two together, for an RPC's error; `decode_mega_limit_exceeded` reads the bytes alone, which make no stop by themselves. `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as the successes the inspector made of them. -- **An error leaves nothing of the failed call.** +- **An error leaves nothing the next call depends on.** A call that fails with an error — a read the database could not serve, a transaction validation refuses — is no result, and the next call on the same EVM runs as on a fresh EVM over the same database. Every entry point reaches the handler's fatal cleanup (`MegaHandler::catch_error`), which drops the error a Host load recorded and nothing took — post-execution can fail on a read of its own before the handler takes it — before op-revm's cleanup runs, discards the failed call's journal transaction, which op-revm discards only for the failed deposit it commits, and clears the cached L1 cost, the local context and the frame stack after op-revm, whose own clearing an error out of its failed-deposit recovery skips; op-revm discards the start lifecycle first, and the start ledger with it. - Every entry point that takes the state off the journal on a success does so on an error too: `execute_transaction`, `transact`, `transact_many`, `replay`, the `inspect` methods, the `_commit` variants, the system calls that return state, alloy-evm's methods and the pre-block calls. - A `_one` entry point leaves the journal to its caller on both outcomes, so the calls before the failed one stay in it and none of its writes do, and a failed deposit is a result whose nonce bump and mint stay. + Every entry point that takes the state off the journal on a success does so on an error too: `execute_transaction`, `transact`, `replay`, the `inspect` methods, the `_commit` variants, the system calls that return state, alloy-evm's methods and the pre-block calls; `transact_many`, which leaves a success's state in the journal, finalizes it on an error. + A `_one` entry point leaves the journal to its caller on both outcomes, so the calls before the failed one stay in it and none of its writes do — what it loaded stays as untouched entries, which a later transaction takes up afresh — and a failed deposit is a result whose nonce bump and mint stay. The rest of the context's per-transaction state is reset where the next execution is prepared, before anything reads it (`MegaContext::prepare`, through `on_new_tx` and `on_new_system_call`); the block-hash and bucket records are the block's, and keep a failed call's reads. An embedder reuses an EVM after an error as after a success; a caller of the handler's `run_without_catch_error` that drops an error calls `catch_error` first, and an EVM a panic unwound out of is not reused. `tests/satin/reuse_after_error.rs` runs a failing call through every public entry point, plain and inspected, at a nested read, a recorded error post-execution preempts, and a post-execution read. diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index ae0d8a055..3e6b0e773 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -125,7 +125,7 @@ pub(crate) type MegaInnerEvm = revm::context::Evm< /// # Reuse after an error /// /// A call that fails with an error — a read the database could not serve, a transaction -/// validation refuses — leaves nothing of itself in the EVM, whichever entry point ran it: the +/// validation refuses — leaves nothing the next call depends on, whichever entry point ran it: the /// handler's fatal cleanup ([`MegaHandler`]'s `catch_error`) drops the error a load recorded and /// nothing took, takes back the call's journal transaction — its nonce bump and fee, and the writes /// of its frames, those that completed before the error included — and clears the per-transaction @@ -134,12 +134,14 @@ pub(crate) type MegaInnerEvm = revm::context::Evm< /// fresh EVM over the same database. /// /// Every entry point that takes the state off the journal on a success does so on an error too: -/// [`execute_transaction`](Self::execute_transaction), `transact`, `transact_many`, `replay`, the -/// `inspect` methods, the `_commit` variants, the system calls that return state, alloy-evm's -/// methods and the pre-block calls. The `_one` entry points leave the journal to the caller on both -/// outcomes, so the calls before a failed one stay in it for the caller to finalize, and none of -/// the failed call's writes do. A failed deposit is a result, not an error: its nonce bump and mint -/// stay. +/// [`execute_transaction`](Self::execute_transaction), `transact`, `replay`, the `inspect` methods, +/// the `_commit` variants, the system calls that return state, alloy-evm's methods and the +/// pre-block calls; `transact_many`, which leaves a success's state in the journal, finalizes it +/// on an error. The `_one` entry points leave the journal to the caller on both outcomes, so the +/// calls before a failed one stay in it for the caller to finalize and none of the failed call's +/// writes do; what the failed call loaded stays as untouched entries, which a later transaction +/// takes up afresh, as it does what an earlier one loaded. A failed deposit is a result, not an +/// error: its nonce bump and mint stay. /// /// A caller of the handler's `run_without_catch_error` that drops an error makes the same cleanup /// first, through `catch_error`. A panic unwinds past the cleanup: an EVM a panic unwound out of is @@ -436,8 +438,8 @@ impl SystemCallEvm for MegaEvm BlockEnv { @@ -77,15 +79,15 @@ fn writer() -> Bytes { fn database() -> MemoryDatabase { let child = BytecodeBuilder::default().push_number(1_u64).append(SLOAD).append(POP).stop(); MemoryDatabase::default() - .account_balance(SENDER, U256::from(10u64.pow(18))) - .account_balance(EARLIER_SENDER, U256::from(10u64.pow(18))) + .account_balance(SENDER, U256::from(FUNDS)) + .account_balance(EARLIER_SENDER, U256::from(FUNDS)) .account_code(WRITER, writer()) .account_code(CHILD, child.build()) .account_code(KEPT, BytecodeBuilder::default().sstore(U256::ZERO, U256::ONE).stop().build()) } /// A Satin EVM over `db`, in a block whose beneficiary is [`BENEFICIARY`]. -fn evm(db: ErrorInjectingDatabase) -> Evm { +fn evm_over(db: ErrorInjectingDatabase) -> Evm { MegaEvm::new(context(db).with_block(block_with_beneficiary())) } @@ -116,7 +118,7 @@ fn test_an_error_post_execution_preempts_does_not_fail_the_next_transaction() { let db = || database().account_code(READS, reads.clone()); let mut armed = ErrorInjectingDatabase::new(db()); armed.fail_on_account = Some(account); - let mut evm = evm(armed); + let mut evm = evm_over(armed); let error = evm .execute_transaction(call(SENDER, READS, U256::ZERO, GAS_LIMIT)) @@ -127,7 +129,7 @@ fn test_an_error_post_execution_preempts_does_not_fail_the_next_transaction() { evm.ctx_mut().db_mut().fail_on_account = None; let next = call(SENDER, KEPT, U256::ZERO, GAS_LIMIT); let reused = evm.execute_transaction(next.clone()).expect("the next transaction is valid"); - let fresh = self::evm(ErrorInjectingDatabase::new(db())) + let fresh = evm_over(ErrorInjectingDatabase::new(db())) .execute_transaction(next) .expect("the next transaction is valid"); assert!(fresh.result.is_success(), "{row}: {:?}", fresh.result); @@ -143,7 +145,7 @@ fn test_an_error_post_execution_preempts_does_not_fail_the_next_transaction() { fn test_a_failed_transact_one_keeps_the_transaction_before_it_and_none_of_its_own_writes() { let mut db = ErrorInjectingDatabase::new(database()); db.fail_on_storage = Some((CHILD, U256::ONE)); - let mut evm = evm(db); + let mut evm = evm_over(db); let earlier = evm .transact_one(call(EARLIER_SENDER, KEPT, U256::ZERO, GAS_LIMIT)) .expect("the earlier transaction is valid"); @@ -158,7 +160,7 @@ fn test_a_failed_transact_one_keeps_the_transaction_before_it_and_none_of_its_ow let sender = &state[&SENDER]; assert_eq!( (sender.info.nonce, sender.info.balance), - (0, U256::from(10u64.pow(18))), + (0, U256::from(FUNDS)), "the failed transaction's nonce bump and fee" ); assert!(!sender.is_touched(), "the failed transaction's sender is touched by nothing kept"); @@ -176,7 +178,7 @@ fn test_a_failed_transact_one_keeps_the_transaction_before_it_and_none_of_its_ow fn test_a_failed_deposit_through_transact_one_keeps_its_nonce_bump_and_mint() { const MINT: u128 = 7; let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); - let mut evm = evm(ErrorInjectingDatabase::new(database())).with_tx_runtime_limits(limits); + let mut evm = evm_over(ErrorInjectingDatabase::new(database())).with_tx_runtime_limits(limits); let result = evm.transact_one(over_the_limit_deposit(SENDER, MINT)).expect("the deposit is included"); assert!( @@ -186,7 +188,7 @@ fn test_a_failed_deposit_through_transact_one_keeps_its_nonce_bump_and_mint() { let state = evm.finalize(); let sender = &state[&SENDER].info; assert_eq!(sender.nonce, 1, "the failed deposit's nonce bump"); - assert_eq!(sender.balance, U256::from(10u64.pow(18)) + U256::from(MINT), "its mint"); + assert_eq!(sender.balance, U256::from(FUNDS + MINT), "its mint"); } /// A deposit from `sender` minting `mint`, whose body is over a data-size limit of one byte below @@ -218,7 +220,7 @@ fn test_an_error_in_the_failed_deposit_recovery_leaves_the_evm_clean() { let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); let mut db = ErrorInjectingDatabase::new(database()); db.fail_on_account = Some(SENDER); - let mut evm = evm(db).with_tx_runtime_limits(limits); + let mut evm = evm_over(db).with_tx_runtime_limits(limits); evm.ctx_mut().chain_mut().tx_l1_cost = Some(U256::from(1_000)); evm.ctx_mut().local_mut().shared_memory_buffer().borrow_mut().resize(64, 0xff); evm.ctx_mut().local_mut().set_precompile_error_context("left behind".into()); @@ -245,7 +247,7 @@ fn test_an_error_in_the_failed_deposit_recovery_leaves_the_evm_clean() { evm.set_tx_runtime_limits(EvmTxRuntimeLimits::default()); let next = call(SENDER, KEPT, U256::ZERO, GAS_LIMIT); let reused = evm.execute_transaction(next.clone()).expect("the next transaction is valid"); - let fresh = self::evm(ErrorInjectingDatabase::new(database())) + let fresh = evm_over(ErrorInjectingDatabase::new(database())) .execute_transaction(next) .expect("the next transaction is valid"); assert_same_outcome(&reused, &fresh, "after the recovery's error"); @@ -269,7 +271,7 @@ fn table_database() -> MemoryDatabase { /// An EVM over `db` for the entry-point table, with inspection enabled when `inspect`. fn table_evm(db: ErrorInjectingDatabase, inspect: bool) -> Evm { - let evm = evm(db); + let evm = evm_over(db); if inspect { evm.with_inspector(NoOpInspector) } else { @@ -305,20 +307,28 @@ impl Site { } } - /// Makes `db` fail the read the site's call fails on, or serve it again. - fn arm(self, db: &mut ErrorInjectingDatabase, armed: bool) { + /// Makes `db` fail the read the site's call fails on. + const fn arm(self, db: &mut ErrorInjectingDatabase) { match self { - Self::Nested => db.fail_on_storage = armed.then_some((CHILD, U256::ONE)), - Self::Preempted => db.fail_on_account = armed.then_some(BENEFICIARY), - Self::PostExecution => db.fail_on_account = armed.then_some(BASE_FEE_RECIPIENT), + Self::Nested => db.fail_on_storage = Some((CHILD, U256::ONE)), + Self::Preempted => db.fail_on_account = Some(BENEFICIARY), + Self::PostExecution => db.fail_on_account = Some(BASE_FEE_RECIPIENT), } } + + /// Makes `db` serve every read again. + const fn disarm(db: &mut ErrorInjectingDatabase) { + db.fail_on_storage = None; + db.fail_on_account = None; + } } /// Every public way to run a transaction or a system call on a `MegaEvm`: the inherent method, /// the required and provided methods of every execution trait it implements, revm's and -/// alloy-evm's, and the pre-block calls. The deprecated aliases are still callable and route -/// through the provided methods. +/// alloy-evm's `Evm`, and the pre-block calls. The deprecated aliases are still callable and route +/// through the provided methods. alloy-evm's `EvmExt` replays compose `transact` and +/// `transact_commit`, which are rows. [`EntryPoint::kind`] classifies every variant without a +/// wildcard, so a new variant does not compile until it is classified; it runs once `ALL` lists it. #[derive(Clone, Copy, Debug)] enum EntryPoint { ExecuteTransaction, @@ -403,50 +413,59 @@ impl EntryPoint { Self::InspectOneSystemCallWithInspectorAndCaller, ]; - /// Whether the entry point takes the state off the journal, on a success and on an error. The - /// `_one` ones leave it to the caller on both, so several calls can share one journal. + /// Whether the entry point takes the state off the journal on an error, and whether it runs a + /// system call rather than a transaction. The `_one` entry points leave the journal to the + /// caller on both outcomes, so several calls can share one journal; `transact_many` takes it + /// off on an error only, leaving a success's state to the caller as they do. + const fn kind(self) -> (bool, bool) { + match self { + Self::ExecuteTransaction | + Self::Transact | + Self::TransactMany | + Self::TransactManyFinalize | + Self::Replay | + Self::TransactCommit | + Self::TransactManyCommit | + Self::ReplayCommit | + Self::InspectTx | + Self::Inspect | + Self::InspectTxCommit | + Self::InspectCommit | + Self::AlloyTransact | + Self::AlloyTransactRaw | + Self::AlloyTransactCommit => (true, false), + Self::TransactOne | Self::InspectOneTx | Self::InspectOne => (false, false), + Self::SystemCall | + Self::SystemCallWithCaller | + Self::DeprecatedTransactSystemCallFinalize | + Self::DeprecatedTransactSystemCallWithCallerFinalize | + Self::AlloyTransactSystemCall | + Self::InspectSystemCall | + Self::InspectSystemCallWithCaller | + Self::InspectSystemCallWithInspector | + Self::InspectSystemCallWithInspectorAndCaller | + Self::BlockHashesPreBlockCall | + Self::BeaconRootPreBlockCall | + Self::ApplyPendingChangesPreBlockCall => (true, true), + Self::SystemCallOne | + Self::SystemCallOneWithCaller | + Self::DeprecatedTransactSystemCall | + Self::DeprecatedTransactSystemCallWithCaller | + Self::InspectOneSystemCall | + Self::InspectOneSystemCallWithCaller | + Self::InspectOneSystemCallWithInspector | + Self::InspectOneSystemCallWithInspectorAndCaller => (false, true), + } + } + + /// Whether the entry point takes the state off the journal on an error ([`kind`](Self::kind)). const fn finalizes(self) -> bool { - !matches!( - self, - Self::TransactOne | - Self::InspectOneTx | - Self::InspectOne | - Self::SystemCallOne | - Self::SystemCallOneWithCaller | - Self::DeprecatedTransactSystemCall | - Self::DeprecatedTransactSystemCallWithCaller | - Self::InspectOneSystemCall | - Self::InspectOneSystemCallWithCaller | - Self::InspectOneSystemCallWithInspector | - Self::InspectOneSystemCallWithInspectorAndCaller - ) + self.kind().0 } - /// Whether the entry point runs a system call rather than a transaction. + /// Whether the entry point runs a system call ([`kind`](Self::kind)). const fn is_system_call(self) -> bool { - matches!( - self, - Self::SystemCall | - Self::SystemCallWithCaller | - Self::DeprecatedTransactSystemCallFinalize | - Self::DeprecatedTransactSystemCallWithCallerFinalize | - Self::AlloyTransactSystemCall | - Self::InspectSystemCall | - Self::InspectSystemCallWithCaller | - Self::InspectSystemCallWithInspector | - Self::InspectSystemCallWithInspectorAndCaller | - Self::BlockHashesPreBlockCall | - Self::BeaconRootPreBlockCall | - Self::ApplyPendingChangesPreBlockCall | - Self::SystemCallOne | - Self::SystemCallOneWithCaller | - Self::DeprecatedTransactSystemCall | - Self::DeprecatedTransactSystemCallWithCaller | - Self::InspectOneSystemCall | - Self::InspectOneSystemCallWithCaller | - Self::InspectOneSystemCallWithInspector | - Self::InspectOneSystemCallWithInspectorAndCaller - ) + self.kind().1 } /// The contract the call runs: a pre-block call's own, and otherwise the site's. @@ -463,7 +482,6 @@ impl EntryPoint { /// call, from [`SENDER`] where the entry point takes a caller — and answers its result or its /// error. The state an entry point hands back is committed to the database; what a `_one` /// entry point leaves in the journal stays there. - #[allow(deprecated)] fn run(self, evm: &mut Evm, site: Site) -> Result, String> { let (result, state) = self.run_handing_back(evm, site)?; if let Some(state) = state { @@ -481,14 +499,12 @@ impl EntryPoint { ) -> Result<(ExecutionResult, Option), String> { let to = self.target(site); let tx = || call(SENDER, to, U256::ZERO, GAS_LIMIT); - let data = Bytes::new; - let hardforks = mainnet_hardforks; - fn handed( + fn handing_back( ran: Result, EvmState>, E>, ) -> Result<(ExecutionResult, Option), String> { ran.map(|ran| (ran.result, Some(ran.state))).map_err(|error| format!("{error:?}")) } - fn kept( + fn handing_back_nothing( ran: Result, E>, ) -> Result<(ExecutionResult, Option), String> { ran.map(|result| (result, None)).map_err(|error| format!("{error:?}")) @@ -498,99 +514,112 @@ impl EntryPoint { }; match self { Self::ExecuteTransaction => { - handed(evm.execute_transaction(tx()).map(|outcome| outcome.result_and_state)) + handing_back(evm.execute_transaction(tx()).map(|outcome| outcome.result_and_state)) } - Self::Transact => handed(ExecuteEvm::transact(evm, tx())), + Self::Transact => handing_back(ExecuteEvm::transact(evm, tx())), Self::TransactMany => { // The journal holds a success until the caller finalizes it. - let results = kept(evm.transact_many(core::iter::once(tx())).map(first))?; + let results = + handing_back_nothing(evm.transact_many(core::iter::once(tx())).map(first))?; Ok((results.0, Some(evm.finalize()))) } - Self::TransactManyFinalize => handed( + Self::TransactManyFinalize => handing_back( evm.transact_many_finalize(core::iter::once(tx())) .map(|ran| ExecResultAndState::new(first(ran.result), ran.state)), ), Self::Replay => { evm.ctx_mut().set_tx(tx()); - handed(ExecuteEvm::replay(evm)) + handing_back(ExecuteEvm::replay(evm)) + } + Self::TransactCommit => { + handing_back_nothing(ExecuteCommitEvm::transact_commit(evm, tx())) } - Self::TransactCommit => kept(ExecuteCommitEvm::transact_commit(evm, tx())), Self::TransactManyCommit => { - kept(evm.transact_many_commit(core::iter::once(tx())).map(first)) + handing_back_nothing(evm.transact_many_commit(core::iter::once(tx())).map(first)) } Self::ReplayCommit => { evm.ctx_mut().set_tx(tx()); - kept(evm.replay_commit()) + handing_back_nothing(evm.replay_commit()) } - Self::InspectTx => handed(evm.inspect_tx(tx())), - Self::Inspect => handed(InspectEvm::inspect(evm, tx(), NoOpInspector)), - Self::InspectTxCommit => kept(evm.inspect_tx_commit(tx())), - Self::InspectCommit => kept(evm.inspect_commit(tx(), NoOpInspector)), - Self::AlloyTransact => handed(alloy_evm::Evm::transact(evm, tx())), - Self::AlloyTransactRaw => handed(alloy_evm::Evm::transact_raw(evm, tx())), - Self::AlloyTransactCommit => kept(alloy_evm::Evm::transact_commit(evm, tx())), - Self::TransactOne => kept(evm.transact_one(tx())), - Self::InspectOneTx => kept(evm.inspect_one_tx(tx())), - Self::InspectOne => kept(evm.inspect_one(tx(), NoOpInspector)), - Self::SystemCall => handed(evm.system_call(to, data())), + Self::InspectTx => handing_back(evm.inspect_tx(tx())), + Self::Inspect => handing_back(InspectEvm::inspect(evm, tx(), NoOpInspector)), + Self::InspectTxCommit => handing_back_nothing(evm.inspect_tx_commit(tx())), + Self::InspectCommit => handing_back_nothing(evm.inspect_commit(tx(), NoOpInspector)), + Self::AlloyTransact => handing_back(alloy_evm::Evm::transact(evm, tx())), + Self::AlloyTransactRaw => handing_back(alloy_evm::Evm::transact_raw(evm, tx())), + Self::AlloyTransactCommit => { + handing_back_nothing(alloy_evm::Evm::transact_commit(evm, tx())) + } + Self::TransactOne => handing_back_nothing(evm.transact_one(tx())), + Self::InspectOneTx => handing_back_nothing(evm.inspect_one_tx(tx())), + Self::InspectOne => handing_back_nothing(evm.inspect_one(tx(), NoOpInspector)), + Self::SystemCall => handing_back(evm.system_call(to, Bytes::new())), Self::SystemCallWithCaller => { - handed(SystemCallEvm::system_call_with_caller(evm, SENDER, to, data())) + handing_back(SystemCallEvm::system_call_with_caller(evm, SENDER, to, Bytes::new())) } Self::DeprecatedTransactSystemCallFinalize => { - handed(evm.transact_system_call_finalize(to, data())) - } - Self::DeprecatedTransactSystemCallWithCallerFinalize => { - handed(evm.transact_system_call_with_caller_finalize(SENDER, to, data())) + handing_back(evm.transact_system_call_finalize(to, Bytes::new())) } + Self::DeprecatedTransactSystemCallWithCallerFinalize => handing_back( + evm.transact_system_call_with_caller_finalize(SENDER, to, Bytes::new()), + ), Self::AlloyTransactSystemCall => { - handed(alloy_evm::Evm::transact_system_call(evm, SENDER, to, data())) + handing_back(alloy_evm::Evm::transact_system_call(evm, SENDER, to, Bytes::new())) } - Self::InspectSystemCall => handed(evm.inspect_system_call(to, data())), + Self::InspectSystemCall => handing_back(evm.inspect_system_call(to, Bytes::new())), Self::InspectSystemCallWithCaller => { - handed(evm.inspect_system_call_with_caller(SENDER, to, data())) - } - Self::InspectSystemCallWithInspector => { - handed(evm.inspect_system_call_with_inspector(to, data(), NoOpInspector)) + handing_back(evm.inspect_system_call_with_caller(SENDER, to, Bytes::new())) } + Self::InspectSystemCallWithInspector => handing_back( + evm.inspect_system_call_with_inspector(to, Bytes::new(), NoOpInspector), + ), Self::InspectSystemCallWithInspectorAndCaller => { - handed(evm.inspect_system_call_with_inspector_and_caller( + handing_back(evm.inspect_system_call_with_inspector_and_caller( SENDER, to, - data(), + Bytes::new(), NoOpInspector, )) } - Self::BlockHashesPreBlockCall => handed( - transact_blockhashes_contract_call(hardforks(), B256::repeat_byte(1), evm) + Self::BlockHashesPreBlockCall => handing_back( + transact_blockhashes_contract_call(mainnet_hardforks(), B256::repeat_byte(1), evm) .map(|ran| ran.expect("Prague is active")), ), - Self::BeaconRootPreBlockCall => handed( - transact_beacon_root_contract_call(hardforks(), Some(B256::repeat_byte(2)), evm) - .map(|ran| ran.expect("Cancun is active")), + Self::BeaconRootPreBlockCall => handing_back( + transact_beacon_root_contract_call( + mainnet_hardforks(), + Some(B256::repeat_byte(2)), + evm, + ) + .map(|ran| ran.expect("Cancun is active")), ), - Self::ApplyPendingChangesPreBlockCall => handed(transact_apply_pending_changes(evm)), - Self::SystemCallOne => kept(evm.system_call_one(to, data())), + Self::ApplyPendingChangesPreBlockCall => { + handing_back(transact_apply_pending_changes(evm)) + } + Self::SystemCallOne => handing_back_nothing(evm.system_call_one(to, Bytes::new())), Self::SystemCallOneWithCaller => { - kept(evm.system_call_one_with_caller(SENDER, to, data())) + handing_back_nothing(evm.system_call_one_with_caller(SENDER, to, Bytes::new())) } Self::DeprecatedTransactSystemCall => { - kept(SystemCallEvm::transact_system_call(evm, to, data())) + handing_back_nothing(SystemCallEvm::transact_system_call(evm, to, Bytes::new())) } Self::DeprecatedTransactSystemCallWithCaller => { - kept(evm.transact_system_call_with_caller(SENDER, to, data())) - } - Self::InspectOneSystemCall => kept(evm.inspect_one_system_call(to, data())), - Self::InspectOneSystemCallWithCaller => { - kept(evm.inspect_one_system_call_with_caller(SENDER, to, data())) + handing_back_nothing(evm.transact_system_call_with_caller(SENDER, to, Bytes::new())) } - Self::InspectOneSystemCallWithInspector => { - kept(evm.inspect_one_system_call_with_inspector(to, data(), NoOpInspector)) + Self::InspectOneSystemCall => { + handing_back_nothing(evm.inspect_one_system_call(to, Bytes::new())) } + Self::InspectOneSystemCallWithCaller => handing_back_nothing( + evm.inspect_one_system_call_with_caller(SENDER, to, Bytes::new()), + ), + Self::InspectOneSystemCallWithInspector => handing_back_nothing( + evm.inspect_one_system_call_with_inspector(to, Bytes::new(), NoOpInspector), + ), Self::InspectOneSystemCallWithInspectorAndCaller => { - kept(evm.inspect_one_system_call_with_inspector_and_caller( + handing_back_nothing(evm.inspect_one_system_call_with_inspector_and_caller( SENDER, to, - data(), + Bytes::new(), NoOpInspector, )) } @@ -611,8 +640,8 @@ fn committed(evm: &Evm) -> BTreeMap BTreeMap Date: Tue, 27 Oct 2026 17:31:39 +0800 Subject: [PATCH 70/83] test(satin): fail the entry-point table before the first frame, and retry a _one call after a failed deposit recovery --- .../mega-evm/tests/satin/reuse_after_error.rs | 80 ++++++++++++++++--- 1 file changed, 69 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/tests/satin/reuse_after_error.rs b/crates/mega-evm/tests/satin/reuse_after_error.rs index 86885ee22..f0ad26a3a 100644 --- a/crates/mega-evm/tests/satin/reuse_after_error.rs +++ b/crates/mega-evm/tests/satin/reuse_after_error.rs @@ -29,7 +29,7 @@ use revm::{ bytecode::opcode::{BALANCE, POP, SLOAD}, context::{ result::{ExecResultAndState, ExecutionResult}, - BlockEnv, ContextSetters, ContextTr, TxEnv, + BlockEnv, ContextError, ContextSetters, ContextTr, TxEnv, }, context_interface::LocalContextTr, handler::{EvmTr, SystemCallEvm}, @@ -55,6 +55,8 @@ const READS: Address = address!("0000000000000000000000000000000000e10005"); const READS_BENEFICIARY: Address = address!("0000000000000000000000000000000000e10006"); /// `SSTORE(0, 7)`. const WRITES: Address = address!("0000000000000000000000000000000000e10007"); +/// `SSTORE(0, 7)`: the contract the call that fails before its first frame targets. +const BEFORE_FRAME: Address = address!("0000000000000000000000000000000000e10008"); const BENEFICIARY: Address = address!("0000000000000000000000000000000000e1bef0"); const GAS_LIMIT: u64 = 100_000_000; /// What each sender holds before the test. @@ -253,6 +255,43 @@ fn test_an_error_in_the_failed_deposit_recovery_leaves_the_evm_clean() { assert_same_outcome(&reused, &fresh, "after the recovery's error"); } +/// The same error in the failed-deposit recovery, then a direct `transact_one` retry on the same +/// EVM with no finalize in between: the journal the error left holds no transaction and none of +/// the failed deposit's reads, so the retry has the result a fresh EVM's `transact_one` gives it +/// and leaves the database as the fresh one leaves it. +#[test] +fn test_a_transact_one_retry_after_a_failed_deposit_recovery_error_runs_as_on_a_fresh_evm() { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); + let mut db = ErrorInjectingDatabase::new(database()); + db.fail_on_account = Some(SENDER); + let mut evm = evm_over(db).with_tx_runtime_limits(limits); + evm.ctx_mut().chain_mut().tx_l1_cost = Some(U256::from(1_000)); + evm.ctx_mut().local_mut().shared_memory_buffer().borrow_mut().resize(64, 0xff); + // An error a load recorded and nothing took, for the cleanup to drop before the recovery's read + // fails: were it dropped after, the recovery's early return would leave it for the retry. + *evm.ctx_mut().error() = Err(ContextError::Custom("left behind".into())); + + let error = evm + .transact_one(over_the_limit_deposit(SENDER, 7)) + .expect_err("the recovery's read of the sender fails"); + assert!(format!("{error:?}").contains("injected basic()"), "{error:?}"); + assert!(evm.ctx_mut().error().is_ok(), "the error slot"); + + evm.ctx_mut().db_mut().fail_on_account = None; + evm.set_tx_runtime_limits(EvmTxRuntimeLimits::default()); + let next = call(SENDER, KEPT, U256::ZERO, GAS_LIMIT); + let retried = evm.transact_one(next.clone()).expect("the retry is valid"); + let mut fresh = evm_over(ErrorInjectingDatabase::new(database())); + let expected = fresh.transact_one(next).expect("the transaction is valid"); + assert!(expected.is_success(), "{expected:?}"); + assert_eq!(retried, expected, "the retry's result"); + for evm in [&mut evm, &mut fresh] { + let state = evm.finalize(); + ExecuteCommitEvm::commit(evm, state); + } + assert_eq!(committed(&evm), committed(&fresh), "what the database holds"); +} + /// The EVM every row of the entry-point table runs on. type Evm = MegaEvm; @@ -263,6 +302,7 @@ fn table_database() -> MemoryDatabase { let reads_beneficiary = writes().push_address(BENEFICIARY).append(BALANCE).append(POP); database() .account_code(WRITES, writes().stop().build()) + .account_code(BEFORE_FRAME, writes().stop().build()) .account_code(READS_BENEFICIARY, reads_beneficiary.stop().build()) .account_code(HISTORY_STORAGE_ADDRESS, writer()) .account_code(BEACON_ROOTS_ADDRESS, writer()) @@ -282,6 +322,13 @@ fn table_evm(db: ErrorInjectingDatabase, inspect: bool) -> Evm { /// Where the failing call's error comes from. #[derive(Clone, Copy, Debug)] enum Site { + /// The database fails the read of the sender's account, which a transaction's validation + /// makes: the call fails before anything is loaded for its frame. A system call that takes no + /// caller reads no sender. + Validation, + /// The database fails the read of the call's target, which pre-execution or a system call's + /// start makes before the first frame is built. + BeforeFrame, /// A child's read of slot 1, after the call's own frame wrote slot 0: the child ends with the /// error, its caller's return takes it, and the call fails with its own frame's write open in /// the journal. @@ -296,20 +343,29 @@ enum Site { } impl Site { - const ALL: [Self; 3] = [Self::Nested, Self::Preempted, Self::PostExecution]; + const ALL: [Self; 5] = + [Self::Validation, Self::BeforeFrame, Self::Nested, Self::Preempted, Self::PostExecution]; + + /// Whether a system call can fail here: it has neither post-execution nor a validated sender. + const fn reaches_system_calls(self) -> bool { + matches!(self, Self::BeforeFrame | Self::Nested) + } /// The contract a transaction or a system call of the table calls. const fn contract(self) -> Address { match self { + Self::Validation | Self::PostExecution => WRITES, + Self::BeforeFrame => BEFORE_FRAME, Self::Nested => WRITER, Self::Preempted => READS_BENEFICIARY, - Self::PostExecution => WRITES, } } - /// Makes `db` fail the read the site's call fails on. - const fn arm(self, db: &mut ErrorInjectingDatabase) { + /// Makes `db` fail the read the site's call fails on; `target` is the contract the call runs. + const fn arm(self, db: &mut ErrorInjectingDatabase, target: Address) { match self { + Self::Validation => db.fail_on_account = Some(SENDER), + Self::BeforeFrame => db.fail_on_account = Some(target), Self::Nested => db.fail_on_storage = Some((CHILD, U256::ONE)), Self::Preempted => db.fail_on_account = Some(BENEFICIARY), Self::PostExecution => db.fail_on_account = Some(BASE_FEE_RECIPIENT), @@ -647,14 +703,15 @@ fn committed(evm: &Evm) -> BTreeMap Date: Tue, 27 Oct 2026 17:31:39 +0800 Subject: [PATCH 71/83] docs: narrow the failed-call cleanup statements to what changes a later execution --- AGENTS.md | 2 +- docs/spec/upgrades/satin.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 23533c5c5..ae6f84e05 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -701,7 +701,7 @@ When the agent is requested to implement a new feature or bug fix, it should con Any logic change or modification to mega-evm should be equipped with tests if there is no specific reason of not adding tests. The agent should always consider accompanying tests or suggest to add additional tests. - **Reset per-transaction state before the next execution reads it.** - An execution that fails with an error leaves through no settlement, so a new per-transaction field of `MegaContext` is reset in `MegaContext::prepare`, unless every execution overwrites it before reading it, and a new cache in revm's context or on the EVM that a run fills is cleared in `MegaHandler::catch_error` as well as on success. + An execution that fails with an error can fail before the normal transaction cleanup (in post-execution after the root frame settled, for one), so a new per-transaction field of `MegaContext` is reset in `MegaContext::prepare`, unless every execution overwrites it before reading it, and a new cache in revm's context or on the EVM that a run fills is cleared in `MegaHandler::catch_error` as well as on success. A new public entry point that takes the state off the journal does so on an error too, and joins the entry-point table in `tests/satin/reuse_after_error.rs`; so does a provided method a revm or alloy-evm upgrade adds. - **Keep the op-revm baseline honest.** A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index ed482c12f..0218aad37 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1502,7 +1502,7 @@ A node, a stateless validator and a replay tool must agree on everything below, An address read from another state treats the old system address's transactions as the protocol's and the new one's as a user's, or the reverse. A deposit is never refused for failing validation: one that fails validation is included as a failed deposit, which bumps its sender's nonce and uses its whole gas limit. A bucket or database read the node fails to make is not a validation failure, for a deposit either: the transaction gets no outcome; a failed bucket read, a database error the database declares fatal, or any database error on a read block execution makes around the transaction is an internal error of the node, while any other database error the transaction's execution meets makes the block invalid; a builder, which has no outcome to include for that transaction, may then leave a non-deposit transaction out, but cannot build a block that must hold the deposit while the read fails. - The reference implementation keeps nothing of a transaction that got no outcome: the transactions executed after it, and the same transaction executed again once the read succeeds, execute as they would on a fresh execution environment over the same state. + The reference implementation keeps nothing that changes a later execution of a transaction that got no outcome: the transactions executed after it, and the same transaction executed again once the read succeeds, execute as they would on a fresh execution environment over the same state. - **Activation blocks.** Block execution does not work out whether a block admits only deposits: it is told, and refuses a non-deposit transaction only when told so. The chain's rule is therefore enforced by the nodes that derive and build the chain, not by the executor alone: MegaETH's op-node MUST enforce deposit-only activation blocks for Satin and for every later MegaETH fork, and a block builder MUST compute the flag from the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates. From c726f5c69883fb8a86cc04f81161ae35a18118fb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 19:26:43 +0800 Subject: [PATCH 72/83] test(satin): a caller's reservoir after its child is what it kept with what the child hands back, and the transaction's gas holds what its frame hands back --- crates/mega-evm/tests/satin/main.rs | 1 + .../tests/satin/reservoir_settlement.rs | 249 ++++++++++++++++++ 2 files changed, 250 insertions(+) create mode 100644 crates/mega-evm/tests/satin/reservoir_settlement.rs diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index d6ed1a06b..3699d6dac 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -39,6 +39,7 @@ mod pool_validation; mod precompile_gas; mod pricing_table; mod reservoir_drain; +mod reservoir_settlement; mod reservoir_share; mod reuse_after_error; mod salt; diff --git a/crates/mega-evm/tests/satin/reservoir_settlement.rs b/crates/mega-evm/tests/satin/reservoir_settlement.rs new file mode 100644 index 000000000..a3fc71e08 --- /dev/null +++ b/crates/mega-evm/tests/satin/reservoir_settlement.rs @@ -0,0 +1,249 @@ +//! What a frame's caller holds of the EIP-8037 reservoir once its frame settled into it: the part +//! of its reservoir it kept while the frame ran, and what the frame hands back on top, once that +//! has unwound the caller's outstanding spill, last in first out. The transaction's gas, whose +//! frame takes the whole reservoir, holds what its frame hands back alone. +//! +//! An inspector reads the transaction's frame's gas at the end of each `CALL` it makes, once the +//! start took the child's share out of it; the child's gas when the child ends, before revm settles +//! it; and the frame's gas again at the instruction after the `CALL`, once the child settled into +//! it. A child that failed hands back the share it was given, its draws undone; one that succeeded +//! hands back what it left, and its spill joins the caller's. + +use alloy_primitives::{address, Address, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, +}; +use revm::{ + bytecode::opcode::{CALL, INVALID, POP}, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{body_history, call, context, slot_state_gas, state_is_free}; + +const SENDER: Address = address!("0000000000000000000000000000000000740000"); +const A: Address = address!("0000000000000000000000000000000000740001"); +/// Writes a new slot and stops. +const OK: Address = address!("0000000000000000000000000000000000740002"); +/// Writes a new slot and reverts. +const REVERTER: Address = address!("0000000000000000000000000000000000740003"); +/// Writes a new slot and halts. +const HALTER: Address = address!("0000000000000000000000000000000000740004"); +/// Writes [`SPENT_SLOTS`] new slots, past any share it is given here, and stops. +const SPENDER: Address = address!("0000000000000000000000000000000000740005"); +/// Stops. +const IDLE: Address = address!("0000000000000000000000000000000000740006"); + +/// The new slots [`SPENDER`] writes. +const SPENT_SLOTS: u64 = 4; + +/// A frame's reservoir and outstanding spill. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Pools { + reservoir: u64, + spilled: u64, +} + +/// One child of the transaction's frame, from its start to its settlement. +#[derive(Clone, Copy, Debug, Default)] +struct Settled { + /// The caller's pools once the start took the child's share: what it kept. + kept: Option, + /// The reservoir the child was given. + share: u64, + /// What the child hands back: its reservoir as revm settles it, and its spill. + handed_back: Option, + /// The caller's pools once the child settled into it. + after: Option, +} + +/// Reads [`Settled`] for every child of the transaction's frame, and that frame's own reservoir as +/// it started and its pools as it ended. +#[derive(Clone, Default)] +struct Settlements { + opcode: Option, + depth: usize, + children: Vec, + /// The child that settled last, whose caller's pools the next instruction reads. + settling: Option, + frame_given: Option, + frame_ended: Option<(InstructionResult, Pools)>, +} + +const fn pools(gas: &revm::interpreter::Gas) -> Pools { + Pools { reservoir: gas.reservoir(), spilled: gas.state_gas_spilled() } +} + +impl Inspector, EthInterpreter> for Settlements { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if self.depth == 1 { + if let Some(index) = self.settling.take() { + self.children[index].after = Some(pools(&interp.gas)); + } + self.opcode = Some(interp.bytecode.opcode()); + } + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if self.depth == 1 && self.opcode.take() == Some(CALL) { + self.children.push(Settled { kept: Some(pools(&interp.gas)), ..Settled::default() }); + } + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + self.depth += 1; + match self.depth { + 1 => self.frame_given = Some(inputs.reservoir), + 2 => { + self.children.last_mut().expect("the CALL's end came first").share = + inputs.reservoir + } + _ => {} + } + None + } + + fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, outcome: &mut CallOutcome) { + let result = outcome.result.result; + let gas = &outcome.result.gas; + match self.depth { + 1 => self.frame_ended = Some((result, pools(gas))), + 2 => { + let index = self.children.len() - 1; + let child = &mut self.children[index]; + child.handed_back = Some(if result.is_ok() { + pools(gas) + } else { + Pools { reservoir: child.share, spilled: 0 } + }); + self.settling = Some(index); + } + _ => {} + } + self.depth -= 1; + } +} + +/// `A` calls each of `children` in turn, dropping the success flags, then ends with `end`. +fn calling(children: &[Address], end: u8) -> MemoryDatabase { + let mut code = BytecodeBuilder::default(); + for child in children { + code = code.call(*child, U256::ZERO).append(POP); + } + let writes = |slots: u64| { + (1..=slots) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::ONE)) + }; + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_code(A, code.append(end).build()) + .account_code(OK, writes(1).stop().build()) + .account_code(REVERTER, writes(1).revert().build()) + .account_code(HALTER, writes(1).append(INVALID).build()) + .account_code(SPENDER, writes(SPENT_SLOTS).stop().build()) + .account_code(IDLE, BytecodeBuilder::default().stop().build()) +} + +/// Runs a call to `A` over `db` at a gas limit that leaves `reservoir` once the body is paid, and +/// returns the outcome's reservoir and gas used with what [`Settlements`] read. +fn run(db: MemoryDatabase, reservoir: u64) -> (u64, u64, u64, Settlements) { + let gas_limit = TX_GAS_LIMIT_CAP + body_history(0) + reservoir; + let mut evm = MegaEvm::new(context(db)).with_inspector(Settlements::default()); + let outcome = + evm.execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)).expect("the call is valid"); + let gas_used = outcome.result.tx_gas_used(); + let reservoir = outcome.gas.reservoir_remaining; + (gas_limit, gas_used, reservoir, evm.inspector().clone()) +} + +/// What a caller that kept `kept` holds once a child that hands back `handed_back` settled into +/// it: the reservoir the child hands back unwinds the caller's spill, the child's own merged in, +/// as far as it goes, and the rest joins the part the caller kept. +const fn settled(kept: Pools, handed_back: Pools) -> Pools { + let spilled = kept.spilled + handed_back.spilled; + let unwound = if handed_back.reservoir < spilled { handed_back.reservoir } else { spilled }; + Pools { + reservoir: kept.reservoir + handed_back.reservoir - unwound, + spilled: spilled - unwound, + } +} + +/// Each child of the transaction's frame settles into what the frame kept of its reservoir: one +/// that succeeded after a write hands back what it left of its share, one that reverted or halted +/// after a write its whole share, and one that spent past its share hands back nothing and its +/// spill; the next child's share then unwinds that spill as it comes back. The frame kept two per +/// cent of its reservoir at every start, and the transaction's gas, which holds none of it, ends +/// with what the frame hands back. +#[test] +fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_hands_back() { + if state_is_free() { + return; + } + let children = [OK, REVERTER, HALTER, SPENDER, IDLE]; + let (_, _, reservoir_remaining, read) = + run(calling(&children, revm::bytecode::opcode::STOP), 4 * slot_state_gas()); + + assert_eq!(read.children.len(), children.len()); + for (child, settled_child) in children.iter().zip(&read.children) { + let kept = settled_child.kept.expect("the CALL ended"); + let handed_back = settled_child.handed_back.expect("the child ended"); + assert_eq!( + settled_child.after, + Some(settled(kept, handed_back)), + "{child}: kept {kept:?}, handed back {handed_back:?}" + ); + } + let [ok, _, _, spender, idle] = read.children[..] else { unreachable!() }; + let kept = ok.kept.expect("the CALL ended").reservoir; + assert!(kept > 0, "the frame keeps part of its reservoir: {kept}"); + assert_eq!(kept, (kept + ok.share) * 2 / 100, "two per cent of it"); + assert!(spender.handed_back.expect("ended").spilled > 0, "the spender spills"); + let idle_kept = idle.kept.expect("the CALL ended"); + assert!(idle_kept.spilled > 0 && idle.share > 0, "the idle child's share unwinds the spill"); + assert_eq!(idle.after.expect("settled").spilled, idle_kept.spilled - idle.share); + + let (result, ended) = read.frame_ended.expect("the frame ended"); + assert!(result.is_ok(), "{result:?}"); + let to_the_transaction = settled(Pools { reservoir: 0, spilled: 0 }, ended); + assert_eq!(reservoir_remaining, to_the_transaction.reservoir); +} + +/// The transaction's frame hands back what a child's would, into gas that holds nothing of the +/// reservoir it gave the frame: what the frame left after a child that kept a part of it and a +/// write of its own when it succeeds, the whole reservoir it was given when it reverts or halts. +/// A halt also burns the transaction's regular gas. +#[test] +fn test_the_transactions_gas_holds_what_its_frame_hands_back_and_nothing_more() { + if state_is_free() { + return; + } + for (end, ok) in [ + (revm::bytecode::opcode::STOP, true), + (revm::bytecode::opcode::REVERT, false), + (INVALID, false), + ] { + let code = BytecodeBuilder::default() + .call(OK, U256::ZERO) + .append(POP) + .sstore(U256::from(7), U256::ONE); + let code = + if end == revm::bytecode::opcode::REVERT { code.revert() } else { code.append(end) }; + let db = calling(&[], end).account_code(A, code.build()); + let (gas_limit, gas_used, reservoir_remaining, read) = run(db, 4 * slot_state_gas()); + + let given = read.frame_given.expect("the frame started"); + let (result, ended) = read.frame_ended.expect("the frame ended"); + assert_eq!(result.is_ok(), ok, "{end:#04x}: {result:?}"); + let expected = + if ok { settled(Pools { reservoir: 0, spilled: 0 }, ended).reservoir } else { given }; + assert_eq!(reservoir_remaining, expected, "{end:#04x}"); + if end == INVALID { + assert_eq!(gas_used + reservoir_remaining, gas_limit, "the halt burns the regular gas"); + } + } +} From 5f360e4d0b3fd171d8b067b58c1562a7f141cd9c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 19:28:32 +0800 Subject: [PATCH 73/83] refactor(evm): a precompile's answer is no longer read back for pool draws No provider the engine runs draws a pool, so the draws read back off revm's answer were none, and adopting none left the start's entry as its split opened it. The read-back and its wiring test go; the start ledger's fail-closed adoption stays, with its unit test, as the rule a provider that draws on its answer is adopted by. --- crates/mega-evm/src/evm/execution.rs | 77 +--------------------------- crates/mega-evm/src/limit/ledger.rs | 9 ++++ crates/mega-evm/src/limit/mod.rs | 2 +- 3 files changed, 12 insertions(+), 76 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9079167d9..e19252583 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -26,10 +26,7 @@ use revm::{ ContextError, ContextTr, FrameStack, Journal, JournalTr, Transaction, }, context_interface::{ - cfg::{ - gas::{GasTracker, PoolId}, - GasId, StateGasCharge, StateGasSite, - }, + cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, journaled_state::{entry::JournalEntry, JournalCheckpoint}, Host, LocalContextTr, }, @@ -691,7 +688,6 @@ impl EvmTr for MegaEvm( } } -/// Has the start ledger adopt what a precompile's provider drew on the pools of `answer`, revm's -/// answer to the start on top. A start revm refused, or answered without a provider, drew nothing. -/// -/// The fork adopts the provider's draws before the engine sees the answer, so they are read back -/// off the answer's gas: each pool's net, and, for a pool whose crossing the adoption set, that -/// the provider drew past the share, which the adoption capped its net at. The engine's provider -/// draws no pool, so the draws are none. -/// -/// It runs before the start's records are counted on the answer: the adoption replaces the -/// entry's pools. -#[inline] -fn adopt_provider_draws( - ctx: &mut MegaContext, - answer: &FrameResult, -) { - let FrameResult::Call(outcome) = answer else { return }; - if outcome.was_precompile_called { - let gas = outcome.result.gas.tracker(); - let draws = PoolId::ALL.map(|pool| crate::limit::ProviderDraw { - net: gas.pool_spent(pool), - past_a_share: gas.pool_crossing(pool), - }); - ctx.additional_limit.ledger_mut().adopt_provider_draws(draws); - } -} - /// Whether revm's start of the frame `input` asks for leaves the accounts it starts on as the /// transaction held them and journals no transfer log, so that reading them before and after the /// start ([`FrameStart::of`], [`FrameStart::count`]) would find no write record, no new account and @@ -1695,7 +1665,7 @@ mod tests { context_interface::journaled_state::account::JournaledAccountTr, interpreter::{ gas::WithheldCrossing, CallInput, CallInputs, CallValue, CreateInputs, CreateScheme, - PoolAmounts, SharedMemory, + PoolAmounts, PoolId, SharedMemory, }, }; use std::boxed::Box; @@ -2233,49 +2203,6 @@ mod tests { } } - /// A precompile's draws reach the start ledger as the provider made them on its answer's gas: - /// a draw within the ledger's share as its net, and a draw past it, capped at the share. revm - /// adopts the draws on the answer's gas first, at the shares the input carries, which revm - /// forwards whole; when a share the input carries capped them — an inspector set the caller's - /// pools — the pool's crossing says the provider drew past a share, which the ledger adopts as - /// a draw past its own. Share 10 and a draw of 11 included. - #[test] - fn test_a_precompiles_draws_reach_the_start_ledger_as_the_provider_made_them() { - use crate::limit::{Parked, DATA_SIZE_POOL}; - use revm::interpreter::CallOutcome; - let shares = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, 10); - for (input_shares, drawn, expected) in [ - (PoolAmounts::UNLIMITED, 0_i64, (10, 0)), - (PoolAmounts::UNLIMITED, 4, (6, 4)), - (PoolAmounts::UNLIMITED, 10, (0, 10)), - (PoolAmounts::UNLIMITED, 11, (0, 10)), - (PoolAmounts::UNLIMITED, 25, (0, 10)), - (PoolAmounts::UNLIMITED, -3, (13, -3)), - (shares, 11, (0, 10)), - (PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, 3), 4, (0, 10)), - ] { - let case = format!("{input_shares:?}, drawn {drawn}"); - let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let ledger = ctx.additional_limit.ledger_mut(); - ledger.park_transaction(Some(Parked::transaction(shares, 0))); - ledger.split(1, None, 0); - ledger.park(0, 0, 0); - ledger.split(2, Some(1), 1); - - let mut gas = Gas::new(100_000); - gas.tracker_mut().set_pool_spent(DATA_SIZE_POOL, drawn); - gas.tracker_mut().adopt_pool_shares(input_shares); - let mut answer = CallOutcome::new( - InterpreterResult::new(InstructionResult::Return, Bytes::new(), gas), - 0..0, - ); - answer.was_precompile_called = true; - adopt_provider_draws(&mut ctx, &FrameResult::Call(answer)); - let pools = ctx.additional_limit.ledger().top_pools(); - assert_eq!(pools[DATA_SIZE_POOL.index()], expected, "{case}"); - } - } - /// The frame start skips its reads exactly for a call that moves no value and runs no /// precompile: every call scheme, with no value and with value, to an account and to a /// precompile of the set, and a creation, with and without an endowment. diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index b9104e21f..293f76e7d 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -97,7 +97,12 @@ const UNPARKED: Parked = Parked { shares: PoolAmounts::ZERO, charge: 0, allowanc /// What a precompile's provider drew on one pool of its answer: its signed `net` draw, and whether /// it drew past a share it was held to, which the net alone cannot tell once that share capped it. +/// +/// No provider the engine runs draws a pool, so nothing but the ledger's tests builds one; a +/// provider that draws hands its draws to the ledger's adoption +/// ([`adopt_provider_draws`](StartLedger::adopt_provider_draws)) when it answers. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr(not(test), allow(dead_code))] pub(crate) struct ProviderDraw { /// The net draw. pub(crate) net: i64, @@ -446,6 +451,10 @@ impl StartLedger { /// The adoption replaces the entry's pools with the share less the provider's draw, so it runs /// before anything else is drawn on the answer: the start's own records, which the frame start /// counts on the answer once it was adopted, would otherwise be overwritten. + /// + /// No provider the engine runs draws a pool, so nothing calls it but the ledger's tests: it is + /// the rule a provider that draws on its answer is adopted by. + #[cfg_attr(not(test), allow(dead_code))] pub(crate) fn adopt_provider_draws(&mut self, draws: [ProviderDraw; PoolId::COUNT]) { let Some(entry) = self.entries.last_mut() else { return }; for pool in PoolId::ALL { diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index f9134f4ad..910fef539 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -184,7 +184,7 @@ mod ledger; mod limit; mod record; -pub(crate) use ledger::{reservoir_share, Parked, ProviderDraw, StartLedger}; +pub(crate) use ledger::{reservoir_share, Parked, StartLedger}; #[cfg(any(test, feature = "test-utils"))] pub use ledger::{LedgerPools, LedgerSettlement}; pub use limit::AdditionalLimit; From 4791951a903122e5cf390c2b8012045741b8e7fe Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 19:42:47 +0800 Subject: [PATCH 74/83] feat(evm): run on revm and op-revm forks that carry none of a frame start's four figures Pins the revm fork and the op-revm fork at the commits where the pools, the start charge, the history allowance and the reservoir share leave the fork and revm forwards and settles the reservoir as upstream does. The pins name local commits by full SHA until the forks are pushed. - Host::frame_settle gives a child's caller back the reservoir it held while the child ran (FrameSettle::held_reservoir), the part forward_start kept, on top of what revm's settlement put in place of the caller's reservoir. The transaction's gas holds a copy of its frame's reservoir, which the settlement replaced, so nothing is added back at the transaction's start, and a halted transaction's regular gas is still burned after the start charge is given back. - The pool identifier and amounts of a frame's budgets are the engine's (limit/pool.rs), exported beside LimitKind for the start ledger's test recorder. - MegaContext::admit_code_deposit takes the deposit alone, the hook's signature in the fork; the outcome and input literals lose the removed fields, and two hand-settled tests hand the frame a copy of the reservoir rather than taking it. - The schedule test asserts the engine's own constants; the rendered pricing table loses the five entries the fork no longer has; the reference holding of a child's shares runs on explicit figures; the keyless differential record's digests move where the record rendered the tracker's removed fields, and only there. --- Cargo.lock | 44 +-- Cargo.toml | 26 +- crates/mega-evm/src/evm/context.rs | 22 +- crates/mega-evm/src/evm/execution.rs | 106 +++---- crates/mega-evm/src/evm/frame.rs | 16 +- crates/mega-evm/src/evm/host.rs | 26 +- crates/mega-evm/src/evm/precompiles.rs | 3 - crates/mega-evm/src/evm/schedule.rs | 27 +- crates/mega-evm/src/lib.rs | 9 +- crates/mega-evm/src/limit/ledger.rs | 10 +- crates/mega-evm/src/limit/limit.rs | 8 +- crates/mega-evm/src/limit/mod.rs | 4 +- crates/mega-evm/src/limit/pool.rs | 81 +++++ .../mega-evm/src/system/keyless/dispatch.rs | 4 +- crates/mega-evm/src/system/oracle.rs | 3 - crates/mega-evm/src/test_utils/ledger.rs | 4 +- crates/mega-evm/tests/satin/common.rs | 10 +- .../tests/satin/inspector_cheatcodes.rs | 2 +- .../mega-evm/tests/satin/inspector_limits.rs | 10 +- crates/mega-evm/tests/satin/pricing-table.md | 7 +- crates/mega-evm/tests/satin/pricing_table.rs | 3 +- .../mega-evm/tests/satin/reservoir_share.rs | 2 +- crates/mega-evm/tests/satin/salt_refund.rs | 8 +- crates/mega-evm/tests/satin/start_ledger.rs | 5 +- .../tests/satin/synthetic_frame_gas.rs | 8 +- .../tests/system/keyless/differential.rs | 1 - crates/mega-evm/tests/system/keyless/frame.rs | 3 - .../tests/system/keyless/inspector.rs | 2 - ...erential__keyless_differential_record.snap | 276 +++++++++--------- 29 files changed, 381 insertions(+), 349 deletions(-) create mode 100644 crates/mega-evm/src/limit/pool.rs diff --git a/Cargo.lock b/Cargo.lock index 2c9548057..09feb5452 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -2384,7 +2384,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -2514,7 +2514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3316,7 +3316,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3917,7 +3917,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?rev=3d43e32029fc5cd293ab70eb0929d70e37337966#3d43e32029fc5cd293ab70eb0929d70e37337966" +source = "git+https://github.com/megaeth-labs/op-revm?rev=49de55b0155aaf3b9e56fd876fefd1e7c4974990#49de55b0155aaf3b9e56fd876fefd1e7c4974990" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "revm-bytecode 11.0.1", "revm-context 18.0.3", @@ -5227,7 +5227,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "alloy-eips 2.1.1", "alloy-provider 2.1.1", @@ -5349,7 +5349,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "revm-bytecode 11.0.1", "revm-context-interface 19.0.3", @@ -5523,7 +5523,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "alloy-eip7928 0.4.11", "bitflags 2.11.1", @@ -5594,7 +5594,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=426217bb2e76c0a41d46907eb788250e8efa107c#426217bb2e76c0a41d46907eb788250e8efa107c" +source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" dependencies = [ "alloy-eip7928 0.4.11", "k256", @@ -5764,7 +5764,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6429,7 +6429,7 @@ dependencies = [ "getrandom 0.3.3", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6985,7 +6985,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e47b7c840..5ab171e37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,20 +232,20 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "426217bb2e76c0a41d46907eb788250e8efa107c" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built # against the revm pin above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "3d43e32029fc5cd293ab70eb0929d70e37337966" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "49de55b0155aaf3b9e56fd876fefd1e7c4974990" } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index beaed5c9f..551fa2c22 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -7,10 +7,7 @@ use revm::{ BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Journal, LocalContext, Transaction, }, - context_interface::{ - cfg::{gas::GasTracker, GasId}, - context::CodeDeposit, - }, + context_interface::{cfg::GasId, context::CodeDeposit}, primitives::{Address, Bytes, StorageKey}, Database, }; @@ -734,12 +731,11 @@ impl ContextTr for MegaContext ContextTr for MegaContext, - _gas: &mut GasTracker, - ) -> Result<(), Bytes> { + fn admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { // Destroyed in this transaction: the flag revm keeps for the whole journal may stand from // an earlier transaction on it. let destroyed = self.accounts().is_destroyed(deposit.address); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index e19252583..533cb5c6e 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1659,13 +1659,17 @@ fn first_frame_records( #[cfg(test)] mod tests { use super::*; - use crate::{test_utils::MemoryDatabase, MegaSpecId}; + use crate::{ + limit::{PoolAmounts, PoolId}, + test_utils::MemoryDatabase, + MegaSpecId, + }; use alloy_primitives::{address, U256}; use revm::{ context_interface::journaled_state::account::JournaledAccountTr, interpreter::{ gas::WithheldCrossing, CallInput, CallInputs, CallValue, CreateInputs, CreateScheme, - PoolAmounts, PoolId, SharedMemory, + SharedMemory, }, }; use std::boxed::Box; @@ -1688,9 +1692,6 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: true, - charged_start: Default::default(), - pool_shares: PoolAmounts::UNLIMITED, - history_allowance: 0, })) } @@ -1726,9 +1727,6 @@ mod tests { scheme: CallScheme::StaticCall, is_static: true, charged_new_account_state_gas: false, - charged_start: Default::default(), - pool_shares: PoolAmounts::UNLIMITED, - history_allowance: 0, })), } } @@ -2095,58 +2093,59 @@ mod tests { } } - /// The engine's earlier holding of a child's shares, which ran on the fork's figures: the - /// shares revm forwarded on the input, `child`'s, held to `caps` and, for a caller whose net - /// is negative, to the share of the caller's budget by `params`, the excess given back to the - /// caller's pools, which `caller` holds. The start ledger's [`StartLedger::cap_child`] took its - /// place and is held to it. + /// A caller's pools as the engine held them on the gas tracker before the start ledger: what + /// it may still draw on each, and its net draw on each. + struct TrackerPools { + remaining: PoolAmounts, + net: [i64; PoolId::COUNT], + } + + /// `percent` per cent of `amount`, rounded down, without widening, as the gas schedule + /// computed a frame's share of a pool when the tracker carried the pools. + const fn percent_of(amount: u64, percent: u64) -> u64 { + amount / 100 * percent + amount % 100 * percent / 100 + } + + /// The engine's earlier holding of a child's shares, on the tracker's figures: the shares the + /// child was forwarded, `shares`, held to `caps` and, for a caller whose net is negative, to + /// the share of the caller's budget, two per cent of it kept, the excess given back to the + /// caller's pools. The start ledger's [`StartLedger::cap_child`] took its place and is held to + /// it. /// /// [`StartLedger::cap_child`]: crate::limit::StartLedger - fn cap_the_shares( - params: &revm::context_interface::cfg::GasParams, - caps: PoolAmounts, - caller: &mut Gas, - child: &mut FrameInit, - ) { - let FrameInput::Call(inputs) = &mut child.frame_input else { unreachable!() }; + fn cap_the_shares(caps: PoolAmounts, caller: &mut TrackerPools, shares: &mut PoolAmounts) { + let forwarded = 100 - crate::evm::FRAME_KEPT_PERCENT; for pool in PoolId::ALL { - let share = inputs.pool_shares.get(pool); + let share = shares.get(pool); let mut allowed = caps.get(pool); - let spent = caller.pool_spent(pool); + let spent = caller.net[pool.index()]; if spent < 0 { - let had = caller.pool_remaining(pool).saturating_add(share); + let had = caller.remaining.get(pool).saturating_add(share); let budget = had.saturating_add_signed(spent); - allowed = allowed.min(params.pool_forward_share(pool, budget)); + allowed = allowed.min(percent_of(budget, forwarded)); } let Some(excess) = share.checked_sub(allowed).filter(|excess| *excess != 0) else { continue; }; - caller.set_pool_remaining(pool, caller.pool_remaining(pool).saturating_add(excess)); - inputs.pool_shares.set(pool, allowed); + caller.remaining.set(pool, caller.remaining.get(pool).saturating_add(excess)); + shares.set(pool, allowed); } } - /// The start ledger holds a child's shares as the engine held them on the fork's figures - /// before the ledger decided them ([`cap_the_shares`], on a schedule that keeps 2 per cent of - /// each pool from a child, as the Satin schedule did): to the frame cap, and, for a caller - /// whose net is negative, to the share of the caller's budget, the excess given back to the - /// caller. Each case runs both on the same caller: pools limited, unlimited or empty; a net - /// of nothing, positive or negative; and a data-size cap above, at or below the share, or - /// none. + /// The start ledger holds a child's shares as the engine held them on the gas tracker before + /// the ledger decided them ([`cap_the_shares`], with two per cent of each pool kept from a + /// child): to the frame cap, and, for a caller whose net is negative, to the share of the + /// caller's budget, the excess given back to the caller. Each case runs both on the same + /// caller: pools limited, unlimited or empty; a net of nothing, positive or negative; and a + /// data-size cap above, at or below the share, or none. #[test] - fn test_the_start_ledger_holds_a_childs_shares_as_the_engine_held_them_on_the_forks() { + fn test_the_start_ledger_holds_a_childs_shares_as_the_engine_held_them_on_the_tracker() { use crate::{ evm::FRAME_KEPT_PERCENT, limit::{ Counted, Parked, StartLedger, DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL, }, - satin_gas_params, }; - let mut params = satin_gas_params(); - params.override_gas( - [DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL] - .map(|pool| (GasId::pool_kept_percent(pool), FRAME_KEPT_PERCENT)), - ); let pools = [ PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10_000).with(KV_UPDATE_POOL, 250), PoolAmounts::UNLIMITED, @@ -2172,32 +2171,33 @@ mod tests { { continue; } - let mut caller = Gas::new_with_regular_gas_and_reservoir(1_000_000, 0); - caller.tracker_mut().set_pools_remaining(pools); + let mut caller = TrackerPools { remaining: pools, net: [0; PoolId::COUNT] }; for pool in PoolId::ALL { - caller.tracker_mut().refill_pool(pool, counted.taken.get(pool)); - assert!(caller.tracker_mut().record_pool(pool, counted.added.get(pool))); + let (taken, added) = (counted.taken.get(pool), counted.added.get(pool)); + let remaining = caller.remaining.get(pool).saturating_add(taken) - added; + caller.remaining.set(pool, remaining); + caller.net[pool.index()] += added as i64 - taken as i64; } let mut ledger = StartLedger::default(); ledger.park_transaction(Some(Parked::transaction(pools, 0))); ledger.split(1, None, 0); ledger.draw(&counted); - let shares = caller.tracker_mut().forward_to_child(¶ms).pools; + let mut shares = PoolAmounts::ZERO; + for pool in PoolId::ALL { + let remaining = caller.remaining.get(pool); + let share = percent_of(remaining, 100 - FRAME_KEPT_PERCENT); + caller.remaining.set(pool, remaining - share); + shares.set(pool, share); + } ledger.park(FRAME_KEPT_PERCENT, 0, 0); ledger.split(2, Some(1), 1); - let mut child = static_call(TARGET, &[], 100_000); - child.depth = 1; - let FrameInput::Call(inputs) = &mut child.frame_input else { unreachable!() }; - inputs.pool_shares = shares; let caps = PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, cap); - cap_the_shares(¶ms, caps, &mut caller, &mut child); + cap_the_shares(caps, &mut caller, &mut shares); ledger.cap_child(caps, FRAME_KEPT_PERCENT); - let FrameInput::Call(inputs) = &child.frame_input else { unreachable!() }; - let caller_pools = caller.tracker().pools_remaining(); let held = ledger.top_shares_and_caller_pools(); - assert_eq!(held, (inputs.pool_shares, caller_pools), "{case}"); + assert_eq!(held, (shares, caller.remaining), "{case}"); } } } diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 24dbb9d06..52b695224 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -8,11 +8,12 @@ //! 1. an upfront state-gas charge the calling opcode made for the frame (a new account, a creation) //! is priced for refund when the frame failed; //! 2. the frame's gas merges into the caller's: unused regular gas back on success and revert, and -//! the frame's reservoir added to what the caller kept; +//! the frame's reservoir in place of the caller's; //! 3. the refund is refilled into the caller's reservoir; -//! 4. revm settles the frame's start, and the engine's start ledger merges the frame's budgets into -//! its caller's and gives back the start charge — what its caller paid for the records its start -//! makes — when it failed, by the result's status, as for a frame revm ran. +//! 4. revm settles the frame's start: the engine gives the caller back the part of its reservoir it +//! kept, and its start ledger merges the frame's budgets into its caller's and gives back the +//! start charge — what its caller paid for the records its start makes — when it failed, by the +//! result's status, as for a frame revm ran. //! //! The contract for a synthetic result is that it settles exactly like revm's own: its gas carries //! the reservoir the frame inherited ([`untouched_call_gas`], [`untouched_create_gas`]), never @@ -59,7 +60,6 @@ pub fn synthetic_frame_result( address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), - charged_start: Default::default(), start_mark: OutcomeMark::NONE, }), FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), @@ -81,7 +81,6 @@ pub fn synthetic_call_result( precompile_call_logs: Default::default(), charged_new_account_state_gas: inputs.charged_new_account_state_gas, charged_state_gas_address: inputs.target_address, - charged_start: Default::default(), start_mark: OutcomeMark::NONE, }) } @@ -90,7 +89,7 @@ pub fn synthetic_call_result( mod tests { use super::*; use alloy_primitives::{address, Address, U256}; - use revm::interpreter::{CallInput, CallScheme, CallValue, PoolAmounts}; + use revm::interpreter::{CallInput, CallScheme, CallValue}; const TARGET: Address = address!("0000000000000000000000000000000000001234"); @@ -108,9 +107,6 @@ mod tests { is_static: false, reservoir, charged_new_account_state_gas: charged, - charged_start: Default::default(), - pool_shares: PoolAmounts::UNLIMITED, - history_allowance: 0, } } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 1ee93cad2..b0e8ce209 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -400,13 +400,14 @@ impl revm::context_interface::Host /// it. The frame's share of the caller's reservoir is taken out of the reservoir the charge /// left and named on the start ([`FrameStart::reservoir`]), so the frame, or the answer revm /// gives in its place, inherits it, and the caller keeps the rest while the frame runs. revm - /// adds what the frame leaves of it to what the caller kept when it returns. Nothing is - /// declared on the start for the fork to carry. An opcode that starts no frame — a creation the - /// balance, the nonce or the depth refuses, an out-of-gas before the forward — never calls - /// it, and makes no records; with EIP-8037 off, such a creation calls it without the address - /// it would take, which makes none either. A start revm then refuses — a value the caller - /// cannot fund, a frame past the call-stack limit — makes no records, and the charge comes - /// back when it returns, as does what a frame that ran did not keep. + /// puts what the frame leaves of it in place of the caller's reservoir when it returns, and + /// the settlement adds back what the caller kept ([`frame_settle`](Self::frame_settle)). An + /// opcode that starts no frame — a creation the balance, the nonce or the depth refuses, an + /// out-of-gas before the forward — never calls it, and makes no records; with EIP-8037 off, + /// such a creation calls it without the address it would take, which makes none either. A + /// start revm then refuses — a value the caller cannot fund, a frame past the call-stack + /// limit — makes no records, and the charge comes back when it returns, as does what a + /// frame that ran did not keep. /// /// A charge the caller cannot pay, or a price that does not fit in a `u64`, fails the opcode /// with an out-of-gas and starts no frame, even where revm would have refused the start. The @@ -468,6 +469,14 @@ impl revm::context_interface::Host /// none. It is given back as history, as it was charged, once revm's own settlement of the /// frame is made, its upfront state-gas refund included. /// + /// revm's settlement put the reservoir the frame handed back in place of the caller's, once it + /// unwound the caller's outstanding spill; a child's caller gets back here the reservoir it + /// held while the child ran (`held_reservoir`), the part it kept at the start, on top. The + /// caller then holds what it kept and what the child handed back, whatever the order of this + /// and the refunds, which read the spill and their own amount, never the reservoir. The + /// transaction's gas holds a copy of the reservoir its frame was given, which revm's + /// settlement replaced, so nothing is added back to it. + /// /// The transaction's start ends the transaction: when its frame halted, giving the charge back /// burns every regular gas the transaction's gas holds, what the refill credited and what /// revm's settlement left alike, as revm's settlement burns a halted transaction's after each @@ -479,6 +488,9 @@ impl revm::context_interface::Host #[inline] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); + if settle.depth != 0 { + gas.set_reservoir(gas.reservoir().saturating_add(settle.held_reservoir)); + } let refund = self.additional_limit.ledger_mut().settle(&settle.into()); if refund != 0 { gas.refill_history(refund); diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 954fdde2c..bb0c3d818 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -284,9 +284,6 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, - charged_start: Default::default(), - pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, - history_allowance: 0, } } diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index e41bb0b0a..06533c329 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -14,8 +14,8 @@ //! what its caller has left, Rex6's rule, in place of EIP-150's 63/64 //! ([`FORWARD_REDUCTION_QUOTIENT`], the fork's `GasId::call_stipend_reduction`). //! -//! What else a frame start takes from its caller is the engine's, not the schedule's, and the -//! schedule keeps Amsterdam's entries for it, which take nothing: the share of its caller's pools — +//! What else a frame start takes from its caller is the engine's, not the schedule's, and is in no +//! entry of it: the share of its caller's pools — //! data size, KV updates, state growth — and of its caller's EIP-8037 reservoir a frame starts //! with, all but [`FRAME_KEPT_PERCENT`] of what the caller has left, and the history allowance a //! value-transferring call gives the frame, `HISTORY_ALLOWANCE_BYTES` at the cost per history @@ -159,7 +159,6 @@ mod tests { history::HISTORY_ALLOWANCE_BYTES, prices::{runs_at_measurement_prices, BytePrice}, }, - limit::{DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL}, }; fn osaka() -> GasParams { @@ -274,25 +273,11 @@ mod tests { } } - /// The schedule takes nothing at a frame start beyond the regular gas it forwards: it keeps - /// none of a caller's pools or reservoir from the frame and gives a value call's frame no - /// history allowance, as upstream's, so revm forwards every pool and the reservoir whole and - /// grants nothing. The engine takes the shares and grants the allowance itself, by - /// [`FRAME_KEPT_PERCENT`], 2, and `HISTORY_ALLOWANCE_BYTES`, 160. + /// What a frame start takes beyond the regular gas it forwards is the engine's, in no entry of + /// the schedule: a child keeps all but [`FRAME_KEPT_PERCENT`], 2, of its caller's reservoir and + /// budgets, and a value call's frame gets `HISTORY_ALLOWANCE_BYTES`, 160, of history. #[test] - fn test_the_schedule_leaves_a_starts_shares_and_allowance_to_the_engine() { - let satin = satin_gas_params(); - for id in [DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL] { - assert_eq!(satin.get(GasId::pool_kept_percent(id)), 0); - for pool in [0, 1, 49, 50, 99, 9_690, u64::MAX] { - assert_eq!(satin.pool_forward_share(id, pool), pool, "{pool}: the whole pool"); - } - } - assert_eq!(satin.get(GasId::reservoir_kept_percent()), 0); - for reservoir in [0, 1, 49, 50, 99, 1_000, u64::MAX] { - assert_eq!(satin.reservoir_forward_share(reservoir), reservoir, "{reservoir}"); - } - assert_eq!(satin.get(GasId::call_history_allowance()), 0); + fn test_a_starts_shares_and_allowance_are_the_engines() { assert_eq!(FRAME_KEPT_PERCENT, 2); assert_eq!(HISTORY_ALLOWANCE_BYTES, 160); } diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 8bd049186..cf0acf3c5 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -66,10 +66,11 @@ pub use external::{ }; pub use limit::{ decode_mega_limit_exceeded, log_history_bytes, AdditionalLimit, EvmTxRuntimeLimits, LimitCheck, - LimitKind, LimitStop, LimitUsage, MegaLimitExceeded, ACCESS_LIST_ADDRESS_SIZE, - ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BASE_SIZE, - TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, WRITE_RECORD_SIZE, + LimitKind, LimitStop, LimitUsage, MegaLimitExceeded, PoolAmounts, PoolId, + ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, + FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, LOG_BASE_SIZE, LOG_TOPIC_SIZE, + TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, + TX_FIXED_WRITE_RECORDS, WRITE_RECORD_SIZE, }; pub use types::{ MegaHaltReason, MegaTransaction, MegaTransactionError, MegaTxEnvelope, MegaTxType, diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 293f76e7d..5a3d227bb 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -10,7 +10,8 @@ //! ([`settle`](StartLedger::settle)), and a log's history draws the top entry's allowance first //! ([`draw_allowance`](StartLedger::draw_allowance)). The part of its EIP-8037 reservoir a caller //! keeps is the engine's rule too ([`reservoir_share`]), taken out of the caller's gas where the -//! start is made; the reservoir itself stays on the gas, which revm settles. +//! start is made and given back on top of what the child hands back when revm settles the child +//! (`Host::frame_settle`); the reservoir itself stays on the gas, which revm settles. //! //! It is driven by the start lifecycle revm owns and by nothing else: an entry opens when revm //! opens the start (`Host::frame_split`), settles when revm settles it (`Host::frame_settle`), and @@ -59,12 +60,9 @@ use alloc as std; use std::vec::Vec; -use revm::context_interface::{ - cfg::gas::{PoolAmounts, PoolId}, - host::{FrameSettle, SettleStatus}, -}; +use revm::context_interface::host::{FrameSettle, SettleStatus}; -use super::Counted; +use super::{Counted, PoolAmounts, PoolId}; /// What a start owes, decided where it is made and taken by the split that opens it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 3b6c8d15a..fb47320e2 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,11 +1,9 @@ //! The per-transaction state of the common execution layer. use alloy_primitives::Bytes; -use revm::{ - context_interface::cfg::gas::{PoolAmounts, PoolId}, - handler::FrameResult, - interpreter::InstructionResult, -}; +use revm::{handler::FrameResult, interpreter::InstructionResult}; + +use super::{PoolAmounts, PoolId}; #[cfg(not(feature = "std"))] use alloc as std; diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 910fef539..f7c52a928 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -182,6 +182,7 @@ mod ledger; #[allow(clippy::module_inception)] mod limit; +mod pool; mod record; pub(crate) use ledger::{reservoir_share, Parked, StartLedger}; @@ -189,6 +190,7 @@ pub(crate) use ledger::{reservoir_share, Parked, StartLedger}; pub use ledger::{LedgerPools, LedgerSettlement}; pub use limit::AdditionalLimit; pub(crate) use limit::{Counted, TxClass}; +pub use pool::{PoolAmounts, PoolId}; #[cfg(test)] pub(crate) use record::emits_transfer_logs; #[cfg(any(test, feature = "test-utils"))] @@ -202,7 +204,7 @@ pub(crate) use record::{ use alloy_primitives::Bytes; use alloy_sol_types::SolError; -use revm::{context::result::ExecutionResult, interpreter::PoolId}; +use revm::context::result::ExecutionResult; /// The pool of a frame's start on the start ledger that is the frame's data-size budget: the bytes /// the frame may still keep. diff --git a/crates/mega-evm/src/limit/pool.rs b/crates/mega-evm/src/limit/pool.rs new file mode 100644 index 000000000..e6150b005 --- /dev/null +++ b/crates/mega-evm/src/limit/pool.rs @@ -0,0 +1,81 @@ +//! The pools of a frame start's budgets on the start ledger: data size, KV updates and state +//! growth ([`DATA_SIZE_POOL`](super::DATA_SIZE_POOL), [`KV_UPDATE_POOL`](super::KV_UPDATE_POOL), +//! [`STATE_GROWTH_POOL`](super::STATE_GROWTH_POOL)), and an amount for each. + +/// One of a frame start's budgets on the start ledger, by index. +/// +/// The three are named by constants of the limit module; [`new`](Self::new) refuses an index +/// past them, so such a constant does not compile. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct PoolId(u8); + +impl PoolId { + /// How many budgets a frame start has. + 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 frame start 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 pool: a frame's budgets, the shares a child starts with, the frame caps, or +/// what a write draws on each. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +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: no budget. + 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 + } +} diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ef44e6c84..efb40077e 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -186,8 +186,8 @@ pub(crate) fn start( } }; // The creation's shares of the call's reservoir and budgets are taken out of the call, and its - // start charge parked, as a `CREATE` opcode's are: the creation's return adds what it left of - // the reservoir back to what the call kept, and its settlement what it left of its budgets. + // start charge parked, as a `CREATE` opcode's are: the creation's settlement gives the call + // what it left of the reservoir on top of what the call kept, and what it left of its budgets. let reservoir = ctx.forward_start(gas.tracker_mut(), deployment.on_frame_record_charge, 0); let mut create = CreateInputs::new( deployment.signer, diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index 9826675aa..6028b9461 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -150,9 +150,6 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, - charged_start: Default::default(), - pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, - history_allowance: 0, } } diff --git a/crates/mega-evm/src/test_utils/ledger.rs b/crates/mega-evm/src/test_utils/ledger.rs index 39c4f185c..505094588 100644 --- a/crates/mega-evm/src/test_utils/ledger.rs +++ b/crates/mega-evm/src/test_utils/ledger.rs @@ -4,7 +4,7 @@ //! The engine keeps a frame's budgets, its start charge and its history allowance on its own start //! ledger, not on the frame's gas: a test reads them as the ledger settled each start, once the //! transaction ran. An inspector's answer and a result whose gas an inspector replaced settle as -//! unlimited budgets whatever pools the inspector's gas carries, and a tracker an inspector +//! unlimited budgets whatever gas the inspector built, and a tracker an inspector //! restores from a snapshot leaves the ledger's draws where they were, which is what a test of //! such an inspector asserts. @@ -15,7 +15,7 @@ use std::vec::Vec; use crate::{ExternalEnvTypes, MegaContext}; use revm::Database; -pub use crate::limit::{LedgerPools, LedgerSettlement}; +pub use crate::limit::{LedgerPools, LedgerSettlement, PoolAmounts, PoolId}; /// Has `ctx`'s start ledger record every settlement from now on, across transactions, until they /// are taken. diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index f0c0349b3..71bf11936 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -6,7 +6,8 @@ use alloy_primitives::{Address, Bytes, TxKind, B256, U256}; use mega_evm::{ active_satin_prices, test_utils::{ - note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, LedgerSettlement, + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, + LedgerSettlement, PoolAmounts, PoolId, }, EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionOutcome, @@ -14,7 +15,6 @@ use mega_evm::{ use revm::{ bytecode::opcode::{PUSH0, RETURN}, context::{result::ResultAndState, BlockEnv, TxEnv}, - interpreter::{PoolAmounts, PoolId}, Database, }; @@ -301,9 +301,9 @@ pub(crate) fn body_history(calldata_len: u64) -> u64 { } /// Asserts that the start ledger settled start `start`, at `depth`, an inspector's answer, at -/// unlimited budgets, whatever pools the inspector's gas carried — the engine's own -/// `untouched_call_gas` and `untouched_create_gas` included, which carry none of the start's -/// budgets — and left the answer's caller with unlimited budgets: the frame's pools as it settled +/// unlimited budgets, whatever gas the inspector built it on — the engine's own +/// `untouched_call_gas` and `untouched_create_gas` included — and left the answer's caller with +/// unlimited budgets: the frame's pools as it settled /// and its caller's once it settled into them, all three unlimited, with no net drawn on the /// answer. pub(crate) fn assert_answered_at_unlimited_budgets( diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 5679e8d3f..ad8596184 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -321,7 +321,7 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { let settlements = take_start_ledger_settlements(evm.ctx_mut()); let resumed = crate::common::ledger_settled(&settlements, 3); assert_eq!((resumed.depth, resumed.caller.net), (1, [WRITE_RECORD_SIZE as i64, 1, 1])); - assert_eq!(resumed.caller.remaining, revm::interpreter::PoolAmounts::UNLIMITED); + assert_eq!(resumed.caller.remaining, mega_evm::test_utils::PoolAmounts::UNLIMITED); (outcome, evm.inspector().answered) }; assert_eq!(answered, 2); diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index c731c53f4..fdf32052d 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -23,7 +23,7 @@ use revm::{ interpreter::{ instructions::gas_table_spec, interpreter::EthInterpreter, interpreter_types::LoopControl, CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, InterpreterAction, - InterpreterResult, PoolId, + InterpreterResult, }, primitives::hardfork::SpecId, Database, Inspector, @@ -328,8 +328,8 @@ enum AnswerGas { Untouched, /// `Gas::new` of the call's gas limit, as Foundry answers a cheatcode: no reservoir. Fresh, - /// Fresh regular gas carrying the pools of the untouched gas after a state and a history - /// charge: charges the frame, which never ran, did not make. + /// Fresh regular gas carrying the reservoir and the state and history figures of the untouched + /// gas after a state and a history charge: charges the frame, which never ran, did not make. Charged, } @@ -356,10 +356,6 @@ impl Inspector, EthInterpreter> for AnswersB { gas.set_state_gas_spent(charged.state_gas_spent()); gas.set_state_gas_spilled(charged.state_gas_spilled()); gas.set_history_gas_spent(charged.history_gas_spent()); - for pool in PoolId::ALL { - gas.set_pool_remaining(pool, charged.pool_remaining(pool)); - gas.set_pool_spent(pool, charged.pool_spent(pool)); - } gas } }; diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index 7a63fbaad..f491908f4 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -4,7 +4,7 @@ Generated by `cargo test -p mega-evm --test satin`; the test compares this file ## Schedule entries -Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte, deposited code priced at `MegaETH`'s cost per history byte, and a frame forwarded 98 per cent of what its caller has left of its regular gas; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those applies. A frame's share of its caller's reservoir and of its data-size, KV-update and state-growth budgets, 98 per cent of what the caller has left, and the history allowance a value call gives its frame are the engine's, taken where the frame starts, and are in no entry: Satin keeps Amsterdam's, which take nothing. +Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte, deposited code priced at `MegaETH`'s cost per history byte, and a frame forwarded 98 per cent of what its caller has left of its regular gas; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those applies. A frame's share of its caller's reservoir and of its data-size, KV-update and state-growth budgets, 98 per cent of what the caller has left, and the history allowance a value call gives its frame are the engine's, taken where the frame starts, and are in no entry. | Gas id | Osaka | Amsterdam | Satin | |---|---:|---:|---:| @@ -57,11 +57,6 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | max_refund_quotient | 5 | 5 | 5 | | tx_account_write_cost | 0 | 9000 | 9000 | | tx_create_access_cost | 0 | 12000 | 12000 | -| pool2_kept_percent | 0 | 0 | 0 | -| pool1_kept_percent | 0 | 0 | 0 | -| pool0_kept_percent | 0 | 0 | 0 | -| reservoir_kept_percent | 0 | 0 | 0 | -| call_history_allowance | 0 | 0 | 0 | | code_deposit_history_gas | 0 | 0 | 88 | ## Measured transactions diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index 1644c9132..92c5fef48 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -147,8 +147,7 @@ fn render() -> String { entries where one of those applies. A frame's share of its caller's reservoir and of \ its data-size, KV-update and state-growth budgets, 98 per cent of what the caller has \ left, and the history allowance a value call gives its frame are the engine's, taken \ - where the frame starts, and are in no entry: Satin keeps Amsterdam's, which take \ - nothing.\n\n", + where the frame starts, and are in no entry.\n\n", ); out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); for slot in 0..=u8::MAX { diff --git a/crates/mega-evm/tests/satin/reservoir_share.rs b/crates/mega-evm/tests/satin/reservoir_share.rs index 0ebf30c3d..56c05c52a 100644 --- a/crates/mega-evm/tests/satin/reservoir_share.rs +++ b/crates/mega-evm/tests/satin/reservoir_share.rs @@ -3,7 +3,7 @@ //! `STATICCALL`, `CREATE` or `CREATE2` takes `remaining − remaining × 2 / 100` of what its caller //! has left after every charge it made for the start, the history of the start's records //! included, whatever regular gas the caller asks to forward. The caller keeps the rest while the -//! child runs, and the child's return adds what it left back. +//! child runs, and gets it back on top of what the child left when the child settles. //! //! An inspector reads the reservoir each start hands its frame off the frame's input, which is //! where revm puts the share it took out of the caller. diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 4eadc4e9a..1a8788396 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -407,10 +407,9 @@ fn settle_a_synthetic_failure( assert!(caller.record_state_cost(price), "the caller can pay the crowded charge"); let spilled = caller.state_gas_spilled(); - // The calling opcode hands the frame the reservoir its charge left, taken out of the caller, - // whose return adds what the frame gives back to what the caller kept. + // The calling opcode hands the frame a copy of the reservoir its charge left, which the + // frame's return replaces with what the frame gives back. let share = caller.reservoir(); - caller.forward_reservoir(share); let result = synthetic_frame_result(&input(share), InstructionResult::Revert, Bytes::new()); let mut frame = EthFrame::::default(); *frame.interpreter.gas.tracker_mut() = caller; @@ -436,9 +435,6 @@ fn charged_call_input(reservoir: u64) -> FrameInput { is_static: false, reservoir, charged_new_account_state_gas: true, - charged_start: Default::default(), - pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, - history_allowance: 0, })) } diff --git a/crates/mega-evm/tests/satin/start_ledger.rs b/crates/mega-evm/tests/satin/start_ledger.rs index 98ec373c0..d4f450818 100644 --- a/crates/mega-evm/tests/satin/start_ledger.rs +++ b/crates/mega-evm/tests/satin/start_ledger.rs @@ -17,6 +17,7 @@ use mega_evm::{ test_utils::{ neutral_cfg, neutralize_evm, record_start_ledger_settlements, take_start_ledger_settlements, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, + PoolAmounts, }, EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, WRITE_RECORD_SIZE, }; @@ -33,7 +34,6 @@ use revm::{ interpreter_types::{InputsTr, LoopControl}, CallInput, CallInputs, CallOutcome, CallScheme, CallValue, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, Interpreter, InterpreterAction, InterpreterResult, - PoolAmounts, }, primitives::CALL_STACK_LIMIT, Database, InspectSystemCallEvm, Inspector, @@ -523,9 +523,6 @@ impl Inspector, EthInterpreter> for StartsItsOwnCa is_static: false, reservoir: 0, charged_new_account_state_gas: false, - charged_start: Default::default(), - pool_shares: PoolAmounts::UNLIMITED, - history_allowance: 0, }; interp.bytecode.set_action(InterpreterAction::NewFrame(FrameInput::Call(Box::new(inputs)))); } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index ac222def3..5df18d237 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -70,9 +70,6 @@ fn call_frame_init(depth: usize) -> FrameInit { is_static: false, reservoir: RESERVOIR, charged_new_account_state_gas: false, - charged_start: Default::default(), - pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, - history_allowance: 0, })), } } @@ -521,9 +518,8 @@ fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); let caller_frame = frames.get(); let before = *caller_frame.interpreter.gas.tracker(); - // The call's opcode took the reservoir the answer carries out of the caller, which the answer's - // return adds back to what the caller kept. - caller_frame.interpreter.gas.tracker_mut().forward_reservoir(result.gas().reservoir()); + // The call's opcode handed the answer a copy of the caller's reservoir, which the answer's + // return puts back in its place. caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); let after = caller_frame.interpreter.gas.tracker(); assert_eq!(after.remaining(), before.remaining(), "a halt hands none of its gas back"); diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index d3507a816..ba110dd3a 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -959,7 +959,6 @@ impl Inspector, EthInterpreter> for Recorder { address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), - charged_start: Default::default(), start_mark: Default::default(), }) } diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 5ca3642ba..07f2362bd 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -47,9 +47,6 @@ fn call_frame(code: revm::state::Bytecode, data: Bytes, gas_limit: u64) -> Frame scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, - charged_start: Default::default(), - pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, - history_allowance: 0, })), } } diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index 8250b3d48..f17c463c2 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -75,7 +75,6 @@ impl Inspector, EthInterpreter> for Recorder { address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), - charged_start: Default::default(), start_mark: Default::default(), }) } @@ -236,7 +235,6 @@ impl Inspector for AnswersCreations { address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), - charged_start: Default::default(), start_mark: Default::default(), }) } diff --git a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap index 6be7655ad..f0a43b50f 100644 --- a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap +++ b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap @@ -4,148 +4,148 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0xc49d7ab2b636fd532a8aafde807c175cb4120d23544db47cb3e14ccca013e372", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0xdd70d1ca3a7b307ba7cb3a1ff5a006efbb474650d5b9377e5f63c733be100c4e", - "rule: arguments that do not decode @ 50000000 | keccak256=0x02847dffb84d05c98e40aa21ea3e4530c38300e8737521d13b72d8ba5679c7e4", - "rule: malformed transaction @ 50000000 | keccak256=0xc22224482c4dc8794da51ab41d3d1c4185f77804e9bffbb459860c5bcab42665", - "rule: a trailing byte @ 50000000 | keccak256=0xc411c146221a1d9107f1265694e170eb98e3313e8172f36006c7333fd6836a6b", - "rule: not a creation @ 50000000 | keccak256=0x088f9214c5ea94835b1df766a196eec1da040ddf774f942398b44ff8eb2df691", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0x9d68849d07fd9fe28469de36f0ca8ffd80a619276ae64f25cb1c2dcc5f093998", - "rule: signed at nonce 1 @ 50000000 | keccak256=0xe4edd71acc4e477d3f8b7367df3f376c4e5c7de91bae721a8b946072430c75a5", - "rule: override below the signed gas limit @ 50000000 | keccak256=0xd15bcab016904099529eeccfe263a030703f0a020417b0e238c1db361e603f61", - "rule: invalid signature @ 50000000 | keccak256=0x6e98838f0aa46f1bce758c7ebd3cbfd7069fff53ff7b2e62ab47fdb60bc05229", - "rule: signer nonce 2 @ 50000000 | keccak256=0x29f3f4b9a77eb6a29d1170bd3ee2387a5987dab90a68a0efc94fdb254aeba92b", - "rule: signer with code @ 50000000 | keccak256=0x7a7d8546eef20936d1a1bc0a404d1d3d4409cf47548acd5540441a9dcd7ff6eb", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xeb06de9554f82be298a3083a1e12f05d5bb69228d305560d0437c6a75e08ef1d", - "rule: occupied address @ 50000000 | keccak256=0x5bf6ba308b278d3c01b55b96a2189f44727408e379e050d2b8cc5934fe9ba71b", - "rule: value the signer cannot fund @ 50000000 | keccak256=0x14aaf68fb49bdf7d64de2e0b34ccaeead8c3c88fe9b132584304aab08f83419e", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xb88fd56f50517f4ba0dd1e220c6db27895313f782852910626faadb9c9ff8d1d", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xeb6f85f8f46b7b53bc5fcd498907143054d857e3314aa84c3fcc06c1a8fe72e0", - "deploys from nonce 1 @ 50000000 | keccak256=0xb81df7edb18ab9ed4de3087bf334bee52a4458b1d4ec90856227734b251549d8", - "the address already has a balance @ 50000000 | keccak256=0x947dd735cf4309adf7ff5ac4c14323eabb3899ef7a0f51a2c915b41ab0f2cea9", - "moves value @ 50000000 | keccak256=0x8d6f548db0b0354aea50814115e3cf6762348f7d1cdc9a39e3adc98cbf0d659e", - "moves value from nonce 1 @ 50000000 | keccak256=0xca714d3e1fe5c46e891d78449792a269cf3f1995a24da7a49c41f6e3eaba4a30", - "the CREATE2 factory @ 50000000 | keccak256=0xb56be4ebc822d43123ec1b408b7546120f6668983cc955db51618aa3600337f5", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x719bb8ed6d3ad4d31483fb21e874b927f6ada36f1cd6e23187c9da32755daee7", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x2bd8ed509016021153ca19eb646ec10d0d1a22892aa993185a0330ad3746bada", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0x85abff2dd878dcacc394c08927fd3def573074ab48165fefbce0f189e158a6c0", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x339b35d83b0e9a6832ec9e34452921d8b037980f451e5cbacb0aba7dda2def48", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xd0b6942feb0b4289e5c654456447a051841c3ae9485b7a0818657f1167a73d58", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0xfd916915bb325f1ad28dfece8b6e5f74d785b9ee9edf01c7e97922777e47ac57", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xe8ed512e9196f432a85373f432f975ea2e05f9f8e3f8fd3da1e10146dee08918", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x4c4ffd0686e071bd8d5eb1425a877aa6fe46691bed177000568962d7773339db", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0xaaee0b100cb4aee1545b5135dce04207925446324745c0ae9a907e302632c51b", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x987a1f4fca0ba1352b9369d2826f113ce8b7e8b1a9ca77a91161034f3a04cd01", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xc3a2f4c58895cb351eba03b7c5e292062f48f9d1b38eebc4428a80086830767f", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0xdf72e4147d9d14fb2f441ea4dede58bd32fbdb2b43905eef7c6e8d511ef0de6a", - "a constructor out of gas @ 50000000 | keccak256=0xc81b4855bbea65bc2dfab1be8c191e273e96193ac3259b340aecdf0e7417d9d0", - "the signer sends it @ 50000000 | keccak256=0x6091a84a69080e4459c02b0a8aa81c982064cc9ad2459de627bacf349ba2d781", - "the signer sends it, and it reverts @ 50000000 | keccak256=0x2aa3d7fb39b7e9773f00e84a52dfa4013d1613f8a5f60a5c95c89f649df561ce", - "a delegated signer @ 50000000 | keccak256=0x7c8c540b4df92a35101d29016d14abec166703cbd839e972a81bd919fe5781cd", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x5c991e23288b57b9b3b50d2d4a2c7007c09eef5801eca99de67cb580ebe335c4", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xf4105216d3a71300ea11775154aa73b51df8def725eb5b2ee4ed059ac2d87826", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x9f290c5e1b39f09e2e41aceee4c660636e97279b4ac20ef119a0bc09c29e85b1", - "limit: compute, nonce 0 @ 50000000 | keccak256=0x1c3537636cf791f7a30535f2fc89b719e0a7d91b98d2ea2ee6df2668dd05f1b8", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0xbd9123386b0baef9fc54162d49ca085866e13dc8c5d804eb53109e83cf16adc9", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x8343e8e5893153f698e49d918be880b04b9dfc6714e2474b16a18185991816b5", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x3fe719ae2087a91c92f64f52963195563213b034dfe2dc17c12119de42bf8571", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x9ff5771100c956032e1fdf9abb1d223e899d755c8279129366adb89e747f9ffb", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x3483f1dab7f09e977d83c84cc88d1ae5fd9a3c5536fec4aa56deacc027175a57", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xf0f75c887dd7a54f531d8fc37c10e5e5f1fbc6fdb8a1e6056fae3ea739fb67c6", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x23f53fca9b56d35087b510cbbf615ace5fa2bd0d0b64a163f115c559f67a1c5c", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xc846628fdba2bf1b45a887a32335b357ba7c648ab70d697cce3aee16bf615068", + "rule: value @ 50000000 | keccak256=0x70efa1acc6606a24ed2001d41f9e6ac401ef411f46c929dee5043aa06be58810", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0x67d4381e1b358e4694b07b0a18728c4e6e3f1c91077391acab6ceed782e46d29", + "rule: arguments that do not decode @ 50000000 | keccak256=0xd2827c7aec63978452165c7595a034877c8771d7e504b7dea3f3fbc0aa15b5db", + "rule: malformed transaction @ 50000000 | keccak256=0x53e169618aad04c59acaa0e61bf9a259e42b3994e3df64ec789329dd04a03472", + "rule: a trailing byte @ 50000000 | keccak256=0x562d6c884cab4c6ca986bead04dc90661c3dd59026842d504f1a785f109ebde9", + "rule: not a creation @ 50000000 | keccak256=0x3931ffdc0411acf5f321a32fd6fbd0c8b9cd6fc15367d7c222838b2fc4ea9543", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0xf1790e8bea46c362feeb1df1248b98b01b49bbc09fc65d98b7115c1c62dae29f", + "rule: signed at nonce 1 @ 50000000 | keccak256=0xd530dcbaa455e42dea19995fc375f2820b11a754de9de9449e1cc94de1cd3c90", + "rule: override below the signed gas limit @ 50000000 | keccak256=0x38f956a3c77cc6277358eed1c37efbaaf1c8395a1b7f636557c79d4d10bd4b5c", + "rule: invalid signature @ 50000000 | keccak256=0xf5c63e312cfdc749521203895c1285c808f7b75cdfe450a3373886cfc483d2f7", + "rule: signer nonce 2 @ 50000000 | keccak256=0x1df4b39c2977f3c87e509a625071ede72cc178f6b3223bfe782afe53290a58e2", + "rule: signer with code @ 50000000 | keccak256=0xabddaf8853eb78b9173a941c821eacf6f99802f58d3468ad77733304b09df430", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xc78ad48afdd9001f381a0adfc0cae161686cf6ee5e5a6ca14fdb3ed6cca97d59", + "rule: occupied address @ 50000000 | keccak256=0x96edc259014ac2c99fefdefe81f2a7e3115478617546afa13ed78a17a20d5f3b", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x56c9e35e8a022786c2d4373670a0e1a104d799e84a520f594aa3384abd0018f4", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xaf969a7082886d0e4cf5afea2b20867ef5e120ab1fb8bf890032fbad5684cd59", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xa070e0164517815cf14a57192c9b7cb76ba4e182124febf91be0320a83efd149", + "deploys from nonce 1 @ 50000000 | keccak256=0xdb9a5d1313d9e12e11bc0766501e290031c22f73af8df11494857015acf7c729", + "the address already has a balance @ 50000000 | keccak256=0x02b5a107b926e0a0b867fc256cb3ab403382e9d7acfbc8cd16b1e17f2caba734", + "moves value @ 50000000 | keccak256=0x4f625126760c064a90bf9ab495a6f42dc9f2a91db86771d44d803c762dd3f285", + "moves value from nonce 1 @ 50000000 | keccak256=0x3f725d461e52c0392f80eaf6200af7a5d799d917f4aab6a62dde15a85bf11054", + "the CREATE2 factory @ 50000000 | keccak256=0x1ab746976b43499851c0deb1bfddaf798f1f7c889dbf0398a4a7e80f158662bb", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x55ea2bb23dade17a76b767000640469d37aed89924ef185bde1fd3f8ca1861f2", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x7bbb859d05d2c5079346f4b5c4adb2514271e60342bc508c7cd657b78536630b", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xd70f77f32871fedaffd9be868aa73be297b5b39af8d812a9227a6e7637eec2b7", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x1df5d50f7cd9ca327d52d3f5e7e52c52b59376acc988fede8f6b7212a1f1906a", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x2fc750cc4eeabe6870d1b9cce22fe77f7b9dd66df3ff9d9d546365944ec89f86", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x85f487e3f21dd23012cac9ee26741ecfe43b68d8a170f0ca429c23831068022d", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xf1e561d3cba6267a8326ab81ded8f8edffc72b4beb15c1abe6853a7f48101e77", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0xb8c8bafe75039598f433f1d7d20942d0ca7b2b0beed86f65f58f0ff194079ba9", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x2e8a101e9df5be12528cbf24cb30f1bebeeecc5df2b5268d29f9416ac175c451", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x306935b3351c2363335d1d972683d7ffbf967c9ad6404fcb8dfeb79051dbf3c9", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x1bb85e30bce7c14e98b25a0e1d9b6c2e895fe1f46c17f9472b1f21cf6ef62077", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x062278078c36e5eed12c3c3abefdd94d8e9f0a0125d272780a61565117a0f57e", + "a constructor out of gas @ 50000000 | keccak256=0xad13ba28e89f0c5d77c97fb7267b61a6e0d3ff587346ee7613371b175b54e4de", + "the signer sends it @ 50000000 | keccak256=0x07d09a10d770e7389731b55c2e6b57d23042735f561a001df883fc31075d8fce", + "the signer sends it, and it reverts @ 50000000 | keccak256=0xcdbd6d53d5b79f49e8d12db6ccc916d493cc1517be04994352e9379bfb03f78a", + "a delegated signer @ 50000000 | keccak256=0x19e5acb7f0ba435282dbbd816a80ea2b6cae219728d174e33ca777cef49ba2bc", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x6937a8cd14af128f65787d290aeb2f74b2c566c12822b8584049b094069d7557", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x03ea2d6ba86920a73c4fae1f9a328142ced7164fa707002594212fbfa32fc1ab", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x6f92465c464e4f71bb87b572126bdd5c3e8c722266f515ec81cd44f1cc05f7fa", + "limit: compute, nonce 0 @ 50000000 | keccak256=0x719b68a8c50d953107b708eedcca301ce7be644adb045eaeef4dd5c2df4f27a3", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x77099302d2c2175a512849c6f19cdb408a56309bb9b67e836881dd475b3455a0", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x3e96f6426d3b9178434293bfd3e94e69770d55722f51a162788bf6001e2c9e49", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0xec7133b31e08dc890d5e9f1d9d94ef97abefd01a30649e8c8ac497b27fc7d9a6", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xfcd346c7219b7697bd07956e48b347aba0a4d80eaf30c6d26516913c4fdcc18a", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x58a87ce6c75938b6dc28b4f35a6d37dd2c6054d7e33fed9a2218b2ea3530bf3f", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xe69b6012c385e2d2ef05a565eab6d9718035e9ebbf45f913c25f7fdaa8b32495", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x37e82390d17d9359b12421f823b3641f70ffda00505a00a328a201cabd536c4f", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x084321871ea7833360460d033aea4fee0a57dd8f2a5bb2d3b94e45cf20d22c86", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0xeb76b302232049dc90fc7c6246ec751c99e807d173ffc92c1666f10a63ca6967", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0xb5f05b3f02de07063b2021ea8e1e40b23674b96d397add127ca7034bdf93460f", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x78aa6bdc2d19d6a899a638e128c00b1477217a56a8edccfcfaaf38cd4ddfb537", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xa8c303aacf72c79a5aa7303cc75637d69fdd658574dfcafb300566c5bc088695", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0xbc257c0ea2c50d6a0b757f045123f4a5e95c46e9f2f994425ef59fcf19d8dca5", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0xeec0d8719b0e7f5bb57e20897c96b42ab2f58615e598e56e5226b76e21ad2f52", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x067fccfd9852612f2ba625c45dfd0768d674690eb8f00f1a5e067b99b5bbdf31", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x223b55bcdda152f6c01a32b8ab40e59de61bff5cae9c33f1b09ccf242cc61836", - "not dispatched: version() @ 50000000 | keccak256=0xc33a3a154b6162feee1c3feff7124221b9f44451e5ac583fd042f6a6435f3734", - "not dispatched: no selector @ 50000000 | keccak256=0x3fb4950f994b33c1e69c1a35fecf5c31f17a4aa43ba784b72139f6b30618a139", - "not dispatched: from a contract @ 50000000 | keccak256=0x6e09a48c63b9291e9562f3275e22b02fc6b7eb886664d75c0e7f1cc59cc24650", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0xf7e7dc2d3f65aa42d043a25b31825ec05736a447e597cff1c7a25be0529ffd99", - "no contract code @ 50000000 | keccak256=0xe0ed629008123f447ef2ebf1519e199500e2e80ad661415f6dc1ccabbf8f818a", - "a system call @ 50000000 | keccak256=0xffdd1ae43372ff52bdbf864c1b5a623f86644901454aee23a239e57205bca821", - "rule: value @ 400000000 | keccak256=0x4d07710426aff7e9b40809a278e9b6f1fee2f8d98eb7865256bdeb88a5273bf7", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0x9b3e0e3be9faf8cbf74d4a815cc0672512110714cd6332c173f684061ad68bfc", - "rule: arguments that do not decode @ 400000000 | keccak256=0xa95007810eda03a41b376b35f04aa9e3f326c587e39510535d399f0e26acf021", - "rule: malformed transaction @ 400000000 | keccak256=0x6c1d478fb1840b6ee3c84f20b01537ef5e1ec6df3803fad664752d2ac8360a48", - "rule: a trailing byte @ 400000000 | keccak256=0xb6e29d55c7e5c46542ba5d98c21dc1aff26c4279353a6bc758a41c7dbae637b7", - "rule: not a creation @ 400000000 | keccak256=0x5dcd141edc7741305fa3e91ad98891636ff460a296c750977391a4ee255563a0", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0xa88f727a1a7eb8d1ecdc9b51abe9e8fa2f7dcf9f7cb4e2b28bbcc951dc650ec1", - "rule: signed at nonce 1 @ 400000000 | keccak256=0x2477f74ad56b183160a9319e2c982144ce8cd6a6acdda7a77b1038e5789519a6", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x5f8974a99a53657a6f493cfc86e60f0ce7aba5b998dd256b52ae5cb865cf27bc", - "rule: invalid signature @ 400000000 | keccak256=0xbbcc676b1e59eee0f0330059f20fdc5df56d6c6593ae661273be4bd0ad52de72", - "rule: signer nonce 2 @ 400000000 | keccak256=0xb813d5b1903e4a8ee729a5e733b56d854e5435e7c1a821da1cbc76a48b27db11", - "rule: signer with code @ 400000000 | keccak256=0x9809ee122cce398ebc43cf5a77527caa40999a4b93ddd715ab8ed9f5670c6291", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x63f5534341bc6896fd1ff853b911bb52d516650307860a4f5682b445d299feea", - "rule: occupied address @ 400000000 | keccak256=0x2a3d25f5a60a72a39d573aca80740d4b519ef702343f88e323086c1ada90d205", - "rule: value the signer cannot fund @ 400000000 | keccak256=0xc68f3e19e35532d7bc7e997cff5d57e6345d5ec374d68a366059eb22585d05c8", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x87067be71dd4d42e8c97d0799004a5d606674bb4b64e3f7a184786001c65835c", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x323efe7003fa4a7ca7bc4a59f7bdffaa4b88ffdf7e5a09dc0d8dd9968265de31", - "deploys from nonce 1 @ 400000000 | keccak256=0x7c5eb36ea36aa8653744de5c89413ade2a7b966f8b3cb0e817548898cb4e8bc7", - "the address already has a balance @ 400000000 | keccak256=0x0820ff4222aafcc0ed512a719fd2c5f2855e4499914f35c56bddc884737b6f96", - "moves value @ 400000000 | keccak256=0x563f55401ee2b1bb38a295eed971814624a2625a4a286cb640bfba57ed73bd06", - "moves value from nonce 1 @ 400000000 | keccak256=0xc9ba03a5c1c7201d2e472d33ef3dcd3b9cc18176685b585e42bc085432859c32", - "the CREATE2 factory @ 400000000 | keccak256=0x95db537f470d1db81bbcf46fd31fb22c79f458469bf4fa4eeb8fc031d8afab22", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x189f60aaf33de771c4b9bbb49d4e5e212b51c65d23e1cf43861669f5b49e1fa3", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x29771ac8486f3c5cc050dba5bdcc0c012884c27d441df1247651ac284bdf0b69", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x6d1d2438dbc55a163416ae888dc23b6b7d635793855adee2619083a8549398ca", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xb7d5a6c033f0018be8bdf38e37f5e062f816fc9c7d97c7c7f690897ffc4158b0", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x9d63d0227f6d37f5fda76be17e16ef02c2e928bde5c0e295ce1386b7331df030", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x7ac15ad59dde01f3554883788d2c7ba6babe8b211958ee0745db5bb7528138be", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0xfb68d486cc5d8c2f889f8aeac3883919ef6f8b78a8da33419e4c47ee362988a3", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x043dd4b84dbea3a3d310605643d4145f91d530feb5d52489623b10ffc80b8033", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x29404ee1f940082709ca013592fa131f67eb29c1c7b2703a2cb1259f100254f1", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0xe390fc3b57ecf5531103928ac6da0015ae0f0a3fa551098a218757e4debfad29", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x346ca9e1ae46d69480cd0b388f6ddb69f6fb2592a41baa52d1479d12d58110af", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0xa2e16f9a2cb9018e6ba5d9526f2bc013d1bb94b119614249b4b98dd79a22efd3", - "a constructor out of gas @ 400000000 | keccak256=0xfeda9604e09c6288226f5b2c85b606ad10ce83ec98e14073b1bc1765c0927a2b", - "the signer sends it @ 400000000 | keccak256=0x3be7311d374e28a3a54cd9350016b4efa9bf376db4073cc742aeccf137461855", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xf1405cc47dcd6dbabd5603fc9b2aefc96573e6d237daaded9b90cfddd67e2092", - "a delegated signer @ 400000000 | keccak256=0x20c9f1c4bef08f79ee64bf5e3692a416122ffd331d51fa7462004588b8979918", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x374277d33aae64acec716fb716339177a9108c514bf764b7321e15fb6a4c1409", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x20bf7e2873056beedd7ca19b20e56dd913e4cf07e1721996a3388cd5bc493daf", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x2eee569fa02148b5ac520d5940d1b65e99552d02338a05f74c48e843699503d2", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x08c4a1e36db53c33bfd259554b5782d4c4478b67fa0c4c5f57b6c2f6c6332b1b", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x339759bcc0c2ab8a8f876e0d45bf8fbcdb0a45e78ade4f12a527dae7d1ab6b5b", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x4fe739ef1dd5ed7987d62b4e7eb886ce9a23e8e81ca5a92079d1d9e5d429b54e", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x6a2cacdbcb3d9ec6550f50035854b54bdcc748774deb11fb6650e06658b5d9d6", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x69e249a049d570fdfa87f44706e51f5d5c8df3f9615a3f50e04ca36058e5d5aa", - "limit: compute, nonce 1 @ 400000000 | keccak256=0xd99dfa9a3692a42f7a975082fba152a429a03c1d30ba621ab163c8d9979443fc", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x5f7a019e0bb3a3c0b2114c66247500a6957c658866b1ad5095d2eb3f16fc1336", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xb71dce0aa5217c9e5caedb3075d74c78e2fe124203f9da7ba19b30cebc51bcb1", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x767c6338db5d1aebcbd7d97b0b5bc8a197c4a29c41685b7135c85d16d6192f7e", + "limit: the default limits @ 50000000 | keccak256=0x919892378222c40706e814a238a1ee4f944b46bb866c6e817f601b25ab75b1d3", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0xd4d2aaed70e8037c8a580082c3a455d5b2621458ab2e185757e7f34c134d5094", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x3e77cd1122e5a36a2f263588bc31ee121153522339429c5d22a5a6edd18c2cc2", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x79784d636eedee5ab3156e061522cedd82bd44f40f5ecc31a75a41f7be2974f1", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x2770955b8680edbc970045b5bcfc9dc6b600c85a79d49aaacb5204a17373e53e", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x4016516a62f99801431f01b9ab845454efe2f0bdb8cebaa6b9aeddaf54b10dd3", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x88429a0c2b61cf28a39034867b63f3c1beffeeb1585dec174263c0d022569d00", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x00495742d5b3b72af8bc0edca3c894c807ff0ca253fb4db9d2117682a64006bb", + "not dispatched: version() @ 50000000 | keccak256=0x71a50aa1874824302b03d490d18fad98f4ee6c67c5e070f0f6c612c103c68fce", + "not dispatched: no selector @ 50000000 | keccak256=0x803c0e37355e9089a6b22f814fd5dd49e3fcbee17d268f639980683f9520ff01", + "not dispatched: from a contract @ 50000000 | keccak256=0x1a46ddada15cc027f867ea5dc0124733491439bc3a587799a8d04ae6b82a1015", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x1ed714441d5f5b08e8d82f2a27d53a8cf60560a686928e6850f43db84987ffd7", + "no contract code @ 50000000 | keccak256=0xd070c6166a53661bc3203f16a69707d9e8846b3c1737d22cbfff5a7a5f6f67c8", + "a system call @ 50000000 | keccak256=0x23867bfad6c1f95ee8422b2c15dfb47ab157163fecdb69f6e142f50971b86ea2", + "rule: value @ 400000000 | keccak256=0xb00b12499990c15c1599808de7903b34b5ed9beb8673675a5a9aa77fafa9015b", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0xab45a43f5e1a4faa1af944c4016c3dce4436e6ec00814fc78ad3897c791321f2", + "rule: arguments that do not decode @ 400000000 | keccak256=0xdc686f081e53b20b0eb44e645c0efc0a34c584ebccc694f6ba79c6f9a0cedcdf", + "rule: malformed transaction @ 400000000 | keccak256=0xa14ab3686735b259326aeefd8ffde19e7d03ca5f6710a8278d3c20b3588941c7", + "rule: a trailing byte @ 400000000 | keccak256=0xe3dd6f5f1d180e13aa45ac712b48ae4124f1f24283214c1aa69d30174cb444e1", + "rule: not a creation @ 400000000 | keccak256=0x228398e161b11148e9c04b5732a72a116f61e8682066063a104ac1065d76ba47", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x70e03ab019a3197e2beb416b2733c1fbfecfcb4a65f8426d33c0acdac8240f8a", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x0cb600cae0b629f42c3dd757e88a46f22d4a560e44f3638566453f9ffd5f495e", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x7bdc52f604cdd3f736d5044d4255ad3147ffb3205377c6adaad530fb6c45a342", + "rule: invalid signature @ 400000000 | keccak256=0x89ace74ee50426587d8c4d77ec5e73120ab42ffb793fd90a1a36042bfa6c3578", + "rule: signer nonce 2 @ 400000000 | keccak256=0xe5d29781298581917c3cbb3811521a98a7f1faaa6dc808eb317fc6cbfac7a4bc", + "rule: signer with code @ 400000000 | keccak256=0xe1a8336834a3b2bc39e8ec606532fe58987837155833513489670f5ee48a02cd", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x19d8abae07d5f60cc71d626a2fe05b52f49634f5a9bbd8dbc46eba04b0be153a", + "rule: occupied address @ 400000000 | keccak256=0x9c400b1873c619f57bbce100b0733b6abee2e89fed0634afffbb5170fa5b7545", + "rule: value the signer cannot fund @ 400000000 | keccak256=0xd0f45281316372225586ac044d825ca80e866f48389ab48ebe3076a037091c17", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0xaddfe60e384511929bc3915941afff9ed661f9b9d36eb5597ba64f15bfc62966", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0xbc03379378902229c9993b4430c02703af25c6632886c104493ca8f3a2f0dbcf", + "deploys from nonce 1 @ 400000000 | keccak256=0x9d7e11c1028204bdf6588c73e713b10084c132131312ff827866d63dd4318070", + "the address already has a balance @ 400000000 | keccak256=0x5e7138f7e8ab1a58e38637ee096125f705ac2b72cd4d28123d563bf85e577e29", + "moves value @ 400000000 | keccak256=0x78de09b3f6b8474e0cb7dbd6b14109ef974f219da90eb9237001dd8dd4ad20be", + "moves value from nonce 1 @ 400000000 | keccak256=0x2690289cad93a5c30acdbb39c84faddd0fddbba12c5127619464a141dd1fcd59", + "the CREATE2 factory @ 400000000 | keccak256=0x8fcc1f818461f802fa686a10bcace2b06481553aeaaec17587de4597df3b61f2", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xc13c20e0990cd146c07d62a4841e4bdb4108209cf1c6198557d22b209ce1637c", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xafcfbab9602ba7854d37050b7d9d4de693f7b5155bd9e82ffbe431309634ada3", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x14e4b2ecadf5c5b8de262f29ab527880c3b89f6238751675807c53fe78ff0cc2", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xf02bfc9aa63148fcbbc9a954168625c0be2bd6fb33f83acf227547c3ec11fae6", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x87b86bfafee294f67d1167ea8400b5395d667f8f5d5b48ba09d732a96ba18525", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x07260a9fadf457dd238f0f3731a5c7410ee88ec525ce384b5f0a4aa39759feb4", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0xa0792622b4ea74af6d05f1743376c73106310c58533c1ac129a7b63b978de355", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x2ca62b6c2400a6e5d1beb27ce072fe5a6f76aca8955ad850f481c9c39f0faec3", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x353cfb678009b8a64bcf235bdcab14c59c8e38fa15d77903b57957963e1c50e4", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x829c4a203fe9f614d49a78d00f02dc19d665be5959385f34a08e206d6df86837", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x87e563ac4638ed7a1cb7b28ac746f5fe7529f78beb2f34d331089e3ec5b0a5fe", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x1d754d06fdd43ae1b115f1d8394ecb6157ad0dd01ba6e2204701459ec4f4db7d", + "a constructor out of gas @ 400000000 | keccak256=0x8a165953e7d6b780e095bba69394619c602f95b4572c1b1af3ee37b18cf8be66", + "the signer sends it @ 400000000 | keccak256=0x3c5ed1a7b0f26ec3125e8488415cc4685b9953387eb8c1876adb9006e83bfac4", + "the signer sends it, and it reverts @ 400000000 | keccak256=0xda4adad654303fb7efc3c45a1853248c4353fadb078119da44b7cca407bb697c", + "a delegated signer @ 400000000 | keccak256=0xd1a2bb70319354c0d740f3da55a587c30393154536ffa531e7277488042401bb", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xf5b740432d179042db6967e150b24334f6ebbe89c93463ec21392a10638c8867", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x669c28012fbf83b3fd8e1b4e7f55870a204f03976f759e8a403e8d6d28d4beaa", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xa474fe8793c49f08bba482b9c9bc75f0f58f45974ee479f4a6d84731ac0968dd", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x40d23c09775632cc70ddc91895b903311247acf7af67f94c12af1e732399a48a", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x4d4a97c2a94ff55a369d67540f7ef37a9a09eb2bebcfa283ebb93661a1b4b21f", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x7c84b6ab291fe88f6d9824e8b944804ed070bd6985c2428026a546466e80b464", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xd0854bb20fdf914624a7119d0fd53f57d1a97ea3cf491e00cf238cd01bd7babd", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x22575bf011874b0d59ac9b2e43a59a5a21dc4b123150bc1272bb599ff2a464dc", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x0af21d7722fa8d4326b54c604d9dd6860d75a1e99aabfe7311c3595bcdbb232f", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x15f213ecf86068b2a34ab80a0b6b7536184bed6652c6a4437663e67052e8acb6", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x5a7032e41e19498cd7dc56c2c2cd9d3c3d239bbb3943bcbd1fc2218cb4227562", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xd9851d97da36ec9bd032e42b9ea43ac1b31d630e5a5278f8b783ed25d9d53d5e", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0xbccf72c35c794ed4a468f7c50b639c61c15045a55de3b75563a9ae4803ac21cd", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0xe478387eb2857945c73febad81abd3a8ef5539a672cce804801b5d2a785a5cda", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xbd0eb9c45f3e22c7f452b8fc16e058214a319cc3e8a5f82852252671de8300a5", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x52bc553677f1510d3ddd64c533eea801d21c94ad4ac513680509aa5e89f1c0e4", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xfbdfc6e4bd66c2d5e26b0acaa20a934d90f8b7c492038837b9dff1ddd7d94b44", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x6391a8de0634663ecb2b3d77e7bf7c665c892bcb3fc48b14d71da691d25f4d51", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0xc67dedb0a0040ca724f77cfaa51eb451a25e444cce28da474f1fa2a5d9204d20", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x37b81702269dbafd8ab389fd7123378cef7dd7ea1923cca320f51d91c5bcd86b", - "not dispatched: version() @ 400000000 | keccak256=0x929430c2e162ee777eb160f952e2549abd657be498b82747fe7a7fbb6c93396b", - "not dispatched: no selector @ 400000000 | keccak256=0xae609007e6eea2f71723749724023318c9c592bf4766e1c5b8d2f3a4da21c0e9", - "not dispatched: from a contract @ 400000000 | keccak256=0xbf337c59e8ac9e59051396559b9046750fb7717cd2042234e84a936c9d5e8d21", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x3e9c7e73294f2847bbc0ea2c208c6f34207c0ac74f66b979a5963394a174743e", - "no contract code @ 400000000 | keccak256=0x0e672d81fabef2d7ec5ff4e00068af0eaaa17cc54639da162494110562a3f668", - "a system call @ 400000000 | keccak256=0x227c05675e38bf85232621aa01168f5b4ca3c532274fa5b2fddc3dd2a52a640b", - "out of gas: the overhead @ 161535 | keccak256=0x7d9405d494d1c43dad43a9569deb75e2ad74a235efb2146a7f6bd47aef411198", - "out of gas: the signer's account @ 162536 | keccak256=0xa4d8c7e70321a73bf60c7b99eac76e515f66226cef7d3542e7df1ea36b525eca", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0xcb8d53bb967c26325dd785067c121f01fb481dc5f51a72200badfda86229760e", - "out of gas: the creation's charges @ 163024 | keccak256=0xed048cedb2a4a666be8883453c76dd137360c95a83ecea4a8058d24815f9e2bf", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x1887556707b93eb287304ef081ab8fd6b5c92e4b274b2de9e9044eb1f9be9146", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0x5a3bdad32567cbad138ccd255d8506cb053d98cc9d8b7e0cd14a0a9c851d467a", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x20ac0e5458c94b7754449e2506e92df19f11fa088ffdae2d069de0f9d33f8a26", - "rule: init code over the limit @ 150000000 | keccak256=0xab6a40e0c6c384f8c45bb3209a50cf90b6be674af3a3a008759a63d04e647487", - "rule: init code over the limit @ 2000000000 | keccak256=0xbd687283e7812531af3c16c5d89bf30cad7e0d8812243887be14c6efb92971f5" + "limit: the default limits @ 400000000 | keccak256=0xc0d3aca720daba088d71be9f88183cae938edef047c5bfdf498b17c5d75953d7", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x62d2175645da243a667798024fc434fa9d12ccb3b03d1f1aee814fc6be569122", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x7dcb32ba5e7bb600eb771f257101f5d98a53232efacf4e1d02c78c481d7a029b", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xa3feede8f1b69038dd7d5c942bb6d211494b5ddc0c5bdfd370a937da02fd315f", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xf768d159e67a14db48c7540608fd0ce6a0d5820b4f2b07465be1d577b80be8f8", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x5367a815bbe23e5d0f6465c233f44921672d6f79f6ea37d2695361a2528684fb", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x2066b1925807f12c83de2fc0243297994a28cd2ca298c710ffd2ccd90446916f", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x98f07a08f6e0392985b7c2541ea2baa5b9cf4a33566edf9e51d2ab7fedb97ee8", + "not dispatched: version() @ 400000000 | keccak256=0xb3d9e971f62fcc67aac97321c2adce9d671ab5a2069e2684de36c3475da7efd9", + "not dispatched: no selector @ 400000000 | keccak256=0x133abd242588d520143eabdedfa24c00e2ee1f392efb12e3af58cfce3a051ff5", + "not dispatched: from a contract @ 400000000 | keccak256=0xe273d69f5c4a40d8e1a2baec6807bc7cbc14f7466aa7da1d628cf84050b4afcb", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x8bb00c81518baaebed8e7d465cac07eabd9bb8fd1f2168bb675181bf6f281803", + "no contract code @ 400000000 | keccak256=0x57a5964833c89bbee89ffcf23e1585a9720f831ba488301937f16d28627c58d7", + "a system call @ 400000000 | keccak256=0x9a9e25f65352a78b4821e39a66d1621bbd6d0fdf1e14955c05be3733619934da", + "out of gas: the overhead @ 161535 | keccak256=0xc83eefbcd1c2bd1b79b3bb8de86da7fa9a024240d70675258b1dd465a0af9d08", + "out of gas: the signer's account @ 162536 | keccak256=0xabd1dd2575c43ad8db140cf5cf3a148138a8c09f632e3dbbe7522fbc8e3c1b72", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x89fd19771ed21bd9962d7a115102f72550e3fa2c983ea297787794afda42709b", + "out of gas: the creation's charges @ 163024 | keccak256=0x19c6965f489129ac0afbece2fee046674d4d433a89910040f2e77fcf2caa7c9d", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0xd7f16815dab34f0f28d789cb6cbccde59e3d655ba31700b55f8d9bf38b1a39a5", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0xafabbf8e69b4ee84877639db23817337ab163d602a795fa6e13f2bc7a95976da", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x031b252c8c04569195a8bea5d8bf730d57440fa07b21674f4ceb3656b0fb6bba", + "rule: init code over the limit @ 150000000 | keccak256=0x9847bb9edead678c560d676d258c01854a0d882b495854a9e7ea7923bdfffb94", + "rule: init code over the limit @ 2000000000 | keccak256=0xf7949b8ae857d9eb689ab1a96b0795d150698f13795c880b330fe388ca949434" ], "summary": { - "bytes": 2582112, + "bytes": 2443212, "cases": 139, "lines": 11452, "runs": 556 From 610e5a31f91cbccbf8bffbe6dca096e88b6bcc82 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 19:42:47 +0800 Subject: [PATCH 75/83] docs: the forks carry none of a start's four figures, and the engine gives a child's caller back the reservoir it kept --- .claude/skills/satin-review/SKILL.md | 15 +++++++-------- AGENTS.md | 19 +++++++++---------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index cb49ca864..6640d3ba6 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -70,13 +70,12 @@ Each change is stated here in plain words with its reason; the specification has revm's frame run returns an action set on a frame before it runs, without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`: a `keylessDeploy` call's creation and answer, and the stop of a caller a child left over a limit, come back through revm's own run. The run-result hook (`EvmTr::frame_run_result`) is called once a frame's run returns, before the inspector's `call_end`, `create_end` and `frame_end` and before `frame_return_result`; gas detention turns a crossing into the stop there, so inspectors and tracers see the stop the caller gets. Why: both are points in the middle of revm's own loop that mega-evm cannot reach from outside, which is what the fork is for, and with them the engine has no frame run of its own. -- **The engine decides the four figures of a frame start, and the fork forwards whole.** - The fork carries four figures of a start on the frame's gas: the three pools with their nets, the part of the reservoir the caller keeps, the start charge and the history allowance. - The engine now decides all four itself, in every build: the budgets, the start charge and the allowance on its start ledger (`src/limit/ledger.rs`), an entry per start driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and the reservoir's share where the start is made (`MegaContext::forward_start`, named to revm on `FrameStart::reservoir`). - The fork's figures are inert: the Satin schedule keeps Amsterdam's zero in `pool_kept_percent`, `reservoir_kept_percent` and `call_history_allowance`, so revm forwards every pool and the reservoir whole and grants no allowance; the engine declares no start charge on a start or on the first frame's input, puts no pool on a tracker and draws none; its synthetic answers carry neither pools nor a charge. +- **The engine decides the four figures of a frame start, and the fork carries none.** + The four figures of a start are the three budgets with their nets, the part of the reservoir the caller keeps, the start charge and the history allowance. + The engine decides all four itself, in every build: the budgets, the start charge and the allowance on its start ledger (`src/limit/ledger.rs`), an entry per start driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and the reservoir's share where the start is made (`MegaContext::forward_start`, named to revm on `FrameStart::reservoir`). + The fork forwards and settles the reservoir as upstream does: the settlement puts the reservoir the child hands back in place of the caller's, and `frame_settle` adds back the part the caller kept (`FrameSettle::held_reservoir`) at a child's settlement, not at the transaction's, whose gas held a copy of its frame's reservoir. A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history, and after a halt of the transaction's own frame burns the transaction's regular gas, as revm's settlement did after its own refund, so regular gas an inspector's extra reservoir unwound is not kept; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). - The ledger is not checked against the fork's figures, which do not mean the same once the fork forwards whole. - The inspector shapes whose results change, each accepted: an answer built on gas whose pools the inspector set, or with the input's start charge copied, settles at unlimited budgets with no charge back; a tracker an inspector restores from a snapshot leaves the ledger's draws and the allowance where they were; and an inspector that replaces a value call's interpreter leaves the frame its allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas. + The inspector shapes whose results change, each accepted: an answer built on gas whose pools the inspector set, or with the input's start charge copied, while the fork still carried them, settles at unlimited budgets with no charge back; a tracker an inspector restores from a snapshot leaves the ledger's draws and the allowance where they were; and an inspector that replaces a value call's interpreter leaves the frame its allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas. A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`). Why: the figures are the engine's decisions, and the fork carries them only until they leave it. - **Writes and frame starts are metered in the fork's instruction hooks.** @@ -351,12 +350,12 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **Where:** `src/evm/schedule.rs`, `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` (SALT pricing), `state_gas_price` in `src/evm/host.rs`, the Amsterdam opcode activation in `src/evm/instructions.rs`. - **Check:** - Every regular entry is Amsterdam's; state creation is paid once, in state gas. - - The regular-gas forward is a schedule entry, `call_stipend_reduction` = 50; the shares of the reservoir and the three budgets are the engine's (`FRAME_KEPT_PERCENT` = 2), and the schedule's `reservoir_kept_percent` and `pool_kept_percent` are Amsterdam's zero; the neutral configuration keeps EIP-150's 63/64 and forwards the whole reservoir and budgets, whatever schedule it is given. + - The regular-gas forward is a schedule entry, `call_stipend_reduction` = 50; the shares of the reservoir and the three budgets are the engine's (`FRAME_KEPT_PERCENT` = 2), in no schedule entry; the neutral configuration keeps EIP-150's 63/64 and forwards the whole reservoir and budgets, whatever schedule it is given. - State gas = schedule entry × bucket multiplier `m`; regular gas never scales. A failed capacity lookup is a node fault: the transaction gets no outcome and is not settled, and the node reports an internal error with the cause. - History gas uses the limit layer's byte table, so a record's history bytes are its data size; the three sites where the totals part are in the `src/limit/mod.rs` module doc, "The byte table". - A deposit, a protocol-produced transaction and a system call pay no history gas. - - The history allowance (`HISTORY_ALLOWANCE_BYTES`, 160 bytes; `history_allowance_gas()` in `src/evm/history.rs`, kept on the start ledger, the schedule's `call_history_allowance` being zero) draws only on a log's charge. + - The history allowance (`HISTORY_ALLOWANCE_BYTES`, 160 bytes; `history_allowance_gas()` in `src/evm/history.rs`, kept on the start ledger, in no schedule entry) draws only on a log's charge. - The EIP-7623 floor is still computed and validated. - The constants are provisional; a build with `satin-price-override` must never reach a node. - **Spec:** §2, §4, §5, §6, §7, §8, §9. diff --git a/AGENTS.md b/AGENTS.md index ae6f84e05..be2d3f300 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -112,10 +112,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `CompletedWrite` and `FrameStartKind` are exhaustive on purpose, so the engine's matches over them carry no wildcard arm and a new kind is a compile error here. - The actions the engine makes for a frame outside an instruction — a `keylessDeploy` call's creation and its answer, and the stop of a frame a child returned into over a limit — come back through revm's own frame run, plain or inspected: the fork's run returns an action set on a frame's interpreter before it runs without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`, so the engine's `frame_run` only forwards to revm's. A frame's own end is decided in the fork's run-result hook (`EvmTr::frame_run_result`), which revm's plain and inspected loops call once a frame's run returns and before the inspector's `call_end`, `create_end` and `frame_end` and `frame_return_result`: gas detention's classification is made there, so an inspector sees the stop the caller gets. -- The fork pins at a published commit of its byte-pool branch, and op-revm at a published commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), both by revision until the fork's review is done. - The byte-pool branch carries three resource pools on every frame's gas tracker, each forwarded at every start as the schedule's share (`GasId::pool_kept_percent`) and settled as the reservoir is, the reservoir's own share (`GasId::reservoir_kept_percent`), a start charge the frame-start hook may declare on the start (`FrameStart::charge`) and the history allowance a value call gives its child (`GasId::call_history_allowance`). - The engine uses none of these four figures: the Satin schedule keeps Amsterdam's zero in the three entries, so the fork forwards every pool and the reservoir whole and grants no allowance; the engine declares no start charge; and the engine keeps the budgets, the start charges and the allowances on its own start ledger. - What the engine uses of the branch is the child's reservoir the frame-start hook names (`FrameStart::reservoir`): the engine takes the child's share of the caller's reservoir itself, and revm's settlement adds what the child left to what the caller kept; a creation's address on its start (`FrameStart::target`) and a `SELFDESTRUCT`'s moved balance on its completed write (`CompletedWrite::SelfDestruct::balance`). +- The fork pins at a commit of its hooks branch, and op-revm at a commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), both by revision until the fork's review is done. + The fork carries no per-start budget, start charge or allowance, and forwards and settles the reservoir as upstream does: a child's input copies the caller's reservoir, or carries the one the frame-start hook names (`FrameStart::reservoir`), and the child's return replaces the caller's reservoir with what the child left. + The engine keeps the budgets, the start charges and the allowances on its own start ledger, and takes the child's share of the caller's reservoir itself, naming it on the start; the caller's part it gives back in `Host::frame_settle`, which revm hands the reservoir the caller held (`FrameSettle::held_reservoir`), at a child's settlement and not at the transaction's, whose gas held a copy of the reservoir its frame was given. + It also uses a creation's address on its start (`FrameStart::target`) and a `SELFDESTRUCT`'s moved balance on its completed write (`CompletedWrite::SelfDestruct::balance`). The fork does not split a system call's gas or report the reservoir on `ResultGas`: Satin does both itself (`MegaHandler::tx_gas`, `AdditionalLimit::reservoir_remaining`), and its op-revm baselines run op-revm through a reference handler that does the same (`tests/shared/op_reference.rs`). Its switch back to revm 40.0.3's journal semantics (`CfgEnv::legacy_journal_semantics`) is the legacy engine's: Satin's spec and neutral configurations fix it off. - The op-revm fork prices its size-limited precompiles through that hook, which upstream op-revm does not, so gas detention decides a call to the BN254 pairing or a BLS12-381 MSM or pairing from its price rather than running it on the allowance. @@ -443,9 +443,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **The frame-start hook.** revm's `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it (`MegaContext::frame_starting`) after every charge they make and after the forward is taken from the caller, before they build the frame's input: it charges the caller the history of the records the start makes, out of what the caller kept, and parks the part the frame's own records cost as the start's charge on the start ledger, which revm's split of the start takes and the start's settlement gives back to the caller when the frame fails; the history of a creator's nonce record is charged there and not part of the start's charge, the record outliving the creation. The hook only prices, and counts nothing: a start's records are counted once revm decided it, and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision and nothing is given back. - The hook then takes the frame's share of the caller's reservoir out of the caller and names it on the start (`MegaContext::forward_start`, `FrameStart::reservoir`), which revm puts on the frame's input, so a built frame and an answered start both inherit a share of the reservoir the charge left: `remaining − remaining × 2 / 100` (`FRAME_KEPT_PERCENT` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs, and the child's return adds what it left back to what the caller kept, unwinding the caller's outstanding spill first (revm's `absorb_returned_reservoir`); it parks the frame's shares of the caller's budgets, taken out of the caller's entry, beside the charge, and, for a value-transferring `CALL` or `CALLCODE`, the frame's history allowance. + The hook then takes the frame's share of the caller's reservoir out of the caller and names it on the start (`MegaContext::forward_start`, `FrameStart::reservoir`), which revm puts on the frame's input, so a built frame and an answered start both inherit a share of the reservoir the charge left: `remaining − remaining × 2 / 100` (`FRAME_KEPT_PERCENT` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs; the child's return puts what it left in place of the caller's reservoir, unwinding the caller's outstanding spill first (revm's `absorb_returned_reservoir`), and the engine adds the part the caller kept back on top (`Host::frame_settle`, from `FrameSettle::held_reservoir`); it parks the frame's shares of the caller's budgets, taken out of the caller's entry, beside the charge, and, for a value-transferring `CALL` or `CALLCODE`, the frame's history allowance. A keyless deployment's creation takes the same shares of what the call has left after the call's start charges (`keyless::start`, through `forward_start`). - The transaction's own frame and a system call's outermost frame take the whole reservoir (the fork's `forward_all_to_child`), and the neutral configuration, on the fixture fork's schedule, gives every child the whole. + The transaction's own frame and a system call's outermost frame take the whole reservoir, of which the transaction's gas keeps a copy that the frame's return replaces, so nothing is added back there; the neutral configuration gives every child the whole. A caller that cannot pay, or a price that does not fit, gets the forward back and the halt's record re-written, and the opcode fails out of gas without starting a frame. The records the hook prices are one rule over caller, target and value (`Accounts::start_records`), asked at the opcode, a creation's at the address it takes (`FrameStart::target`); the records counted on the started frame's pool are those revm's start made, read off the journal once revm decided it, and a price that differs from them is settled by the start's credit. A call that transfers no value, of any scheme, makes no record whatever the journal holds, and the hook charges it nothing without reading the journal (`limit::start_makes_no_records`; a debug build reads it and asserts there is nothing to charge). @@ -470,12 +470,11 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **A start's figures are the engine's, on its start ledger.** The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding what the start owes and holds: its budgets with their nets, its start charge and its history allowance; it is driven by the start lifecycle hooks alone, and pairs nothing: revm's record says which start settles. What a start owes is parked where it is decided — `frame_starting`, the keyless builder, the first frame's input (`first_frame_input`) — and taken by revm's split; every draw `AdditionalLimit` makes is on the top entry; the frame cap is applied where the caller suspends (`cap_child`); and a settlement merges by status and revm's inspector flags, giving the start charge back to the caller's gas on a failure, and on a creation that took no address, through `Host::frame_settle`, where revm settles the start, after its own settlement of the frame; for a transaction's start whose frame halted, the hook then burns every regular gas the transaction's gas holds, as revm's settlement burned it after each refund of its own, which leaves revm's consumption of a hook's credit after a halt nothing to consume. - An inspector's answer and a result whose tracker an inspector replaced settle as unlimited budgets; neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back; the figures an inspector puts on an input, an answer or a result — pools, a start charge, an allowance, through the fork's fields — are not read, and a tracker it restores from a snapshot, or an interpreter it replaces, leaves the ledger's draws and the frame's allowance where they were. + An inspector's answer and a result whose tracker an inspector replaced settle as unlimited budgets; neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back; nothing an inspector puts on an input, an answer or a result decides a budget, a start charge or an allowance, and a tracker it restores from a snapshot, or an interpreter it replaces, leaves the ledger's draws and the frame's allowance where they were. A value call's frame keeps its history allowance when an inspector replaces its interpreter, as when it restores a snapshot: an accepted change for such an inspector, since the replaced interpreter's fresh gas held no allowance while the allowance was on the frame's gas. The history allowance a value call gives its child is the entry's; only a log draws on it, first, in the completed-write hook. - A precompile's draws on its answer, which no provider of the engine makes, are adopted fail-closed against the share (`StartLedger::adopt_provider_draws`). - The fork's figures are inert: the schedule forwards every pool and the reservoir whole and grants no allowance, and the engine declares no start charge, puts no pool on a tracker and draws none. - A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`, `take_start_ledger_settlements`). + A precompile's draws on its answer, which no provider of the engine makes, would be adopted fail-closed against the share (`StartLedger::adopt_provider_draws`): a provider that draws hands its draws to that rule when it answers. + A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`, `take_start_ledger_settlements`), in the engine's own pool types (`PoolAmounts`, `PoolId`, `limit/pool.rs`). - **The stop.** A limit stops the frame that crosses it with a revert, never a halt, whether the limit is the transaction's or the frame's own budget: the frame reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` (`AdditionalLimit::crossed`, for the data size and gas detention's compute stop alike, answering the exemption), what it counted goes with its frame, and its caller resumes as after any revert. There is no latch: a caller that resumes is within every limit — but where a failure below it put back a record a frame above made while a hint the failed frame sent stays, which stops the caller as it resumes (below) — is held to what the transaction has left, and is stopped in turn by a write or a charge of its own that crosses one, so the transaction never keeps more than its data-size limit and never computes past detention's limit; a caller that catches the stop and ends lets the transaction succeed. From c8aab45146007b80ee2bcf7d45aa63be4142a045 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 20:17:26 +0800 Subject: [PATCH 76/83] chore(deps): pin the revm fork at 4c8f0d43 and op-revm at 8c0db939 --- Cargo.lock | 44 ++++++++++++++++++++++---------------------- Cargo.toml | 26 +++++++++++++------------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 09feb5452..61e1dbb7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2384,7 +2384,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2514,7 +2514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3316,7 +3316,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3917,7 +3917,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?rev=49de55b0155aaf3b9e56fd876fefd1e7c4974990#49de55b0155aaf3b9e56fd876fefd1e7c4974990" +source = "git+https://github.com/megaeth-labs/op-revm?rev=8c0db939291e1c4cbf2375782d1483bc371d6b94#8c0db939291e1c4cbf2375782d1483bc371d6b94" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "revm-bytecode 11.0.1", "revm-context 18.0.3", @@ -5227,7 +5227,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "alloy-eips 2.1.1", "alloy-provider 2.1.1", @@ -5349,7 +5349,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "revm-bytecode 11.0.1", "revm-context-interface 19.0.3", @@ -5523,7 +5523,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "alloy-eip7928 0.4.11", "bitflags 2.11.1", @@ -5594,7 +5594,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=87ded5c7c7ac009edc48033772e2e51bc6708aed#87ded5c7c7ac009edc48033772e2e51bc6708aed" +source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" dependencies = [ "alloy-eip7928 0.4.11", "k256", @@ -5764,7 +5764,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6429,7 +6429,7 @@ dependencies = [ "getrandom 0.3.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6985,7 +6985,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 5ab171e37..d23238546 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,20 +232,20 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "87ded5c7c7ac009edc48033772e2e51bc6708aed" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built # against the revm pin above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "49de55b0155aaf3b9e56fd876fefd1e7c4974990" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "8c0db939291e1c4cbf2375782d1483bc371d6b94" } From e459b8e45b33a2d66bb8a80a7b93c6b01fce0f5e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 20:17:26 +0800 Subject: [PATCH 77/83] test(satin): the reservoir settlement test names the funding it reads, and halts the transaction's frame after a value transfer above and below the cap --- .../tests/satin/reservoir_settlement.rs | 164 ++++++++++++------ 1 file changed, 107 insertions(+), 57 deletions(-) diff --git a/crates/mega-evm/tests/satin/reservoir_settlement.rs b/crates/mega-evm/tests/satin/reservoir_settlement.rs index a3fc71e08..56e593999 100644 --- a/crates/mega-evm/tests/satin/reservoir_settlement.rs +++ b/crates/mega-evm/tests/satin/reservoir_settlement.rs @@ -1,7 +1,8 @@ //! What a frame's caller holds of the EIP-8037 reservoir once its frame settled into it: the part //! of its reservoir it kept while the frame ran, and what the frame hands back on top, once that -//! has unwound the caller's outstanding spill, last in first out. The transaction's gas, whose -//! frame takes the whole reservoir, holds what its frame hands back alone. +//! has unwound the caller's outstanding spill, last in first out. The transaction's frame is given +//! the whole reservoir, of which the transaction's gas keeps a copy until the frame settles, and +//! the transaction's gas then holds what its frame hands back alone. //! //! An inspector reads the transaction's frame's gas at the end of each `CALL` it makes, once the //! start took the child's share out of it; the child's gas when the child ends, before revm settles @@ -12,7 +13,10 @@ use alloy_primitives::{address, Address, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, - test_utils::{BytecodeBuilder, MemoryDatabase}, + test_utils::{ + record_start_ledger_settlements, take_start_ledger_settlements, BytecodeBuilder, + MemoryDatabase, + }, MegaContext, MegaEvm, }; use revm::{ @@ -24,7 +28,7 @@ use revm::{ Database, Inspector, }; -use crate::common::{body_history, call, context, slot_state_gas, state_is_free}; +use crate::common::{body_history, call, context, history_is_free, slot_state_gas, state_is_free}; const SENDER: Address = address!("0000000000000000000000000000000000740000"); const A: Address = address!("0000000000000000000000000000000000740001"); @@ -42,48 +46,54 @@ const IDLE: Address = address!("0000000000000000000000000000000000740006"); /// The new slots [`SPENDER`] writes. const SPENT_SLOTS: u64 = 4; -/// A frame's reservoir and outstanding spill. +/// What funds a frame's state and history charges beside its regular gas: its reservoir, and the +/// spill those charges made onto its regular gas that is still outstanding. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Pools { +struct Funding { reservoir: u64, spilled: u64, } +impl Funding { + /// No reservoir and no spill. + const NONE: Self = Self { reservoir: 0, spilled: 0 }; +} + /// One child of the transaction's frame, from its start to its settlement. #[derive(Clone, Copy, Debug, Default)] -struct Settled { - /// The caller's pools once the start took the child's share: what it kept. - kept: Option, +struct Child { + /// The caller's funding once the start took the child's share: what it kept. + kept: Option, /// The reservoir the child was given. share: u64, /// What the child hands back: its reservoir as revm settles it, and its spill. - handed_back: Option, - /// The caller's pools once the child settled into it. - after: Option, + handed_back: Option, + /// The caller's funding once the child settled into it. + after: Option, } -/// Reads [`Settled`] for every child of the transaction's frame, and that frame's own reservoir as -/// it started and its pools as it ended. +/// Reads [`Child`] for every child of the transaction's frame, and that frame's own reservoir as +/// it started and its funding as it ended. #[derive(Clone, Default)] struct Settlements { opcode: Option, depth: usize, - children: Vec, - /// The child that settled last, whose caller's pools the next instruction reads. + children: Vec, + /// The child that settled last, whose caller's funding the next instruction reads. settling: Option, frame_given: Option, - frame_ended: Option<(InstructionResult, Pools)>, + frame_ended: Option<(InstructionResult, Funding)>, } -const fn pools(gas: &revm::interpreter::Gas) -> Pools { - Pools { reservoir: gas.reservoir(), spilled: gas.state_gas_spilled() } +const fn funding(gas: &revm::interpreter::Gas) -> Funding { + Funding { reservoir: gas.reservoir(), spilled: gas.state_gas_spilled() } } impl Inspector, EthInterpreter> for Settlements { fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { if self.depth == 1 { if let Some(index) = self.settling.take() { - self.children[index].after = Some(pools(&interp.gas)); + self.children[index].after = Some(funding(&interp.gas)); } self.opcode = Some(interp.bytecode.opcode()); } @@ -91,7 +101,7 @@ impl Inspector, EthInterpreter> for Settlements { fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { if self.depth == 1 && self.opcode.take() == Some(CALL) { - self.children.push(Settled { kept: Some(pools(&interp.gas)), ..Settled::default() }); + self.children.push(Child { kept: Some(funding(&interp.gas)), ..Child::default() }); } } @@ -112,14 +122,14 @@ impl Inspector, EthInterpreter> for Settlements { let result = outcome.result.result; let gas = &outcome.result.gas; match self.depth { - 1 => self.frame_ended = Some((result, pools(gas))), + 1 => self.frame_ended = Some((result, funding(gas))), 2 => { let index = self.children.len() - 1; let child = &mut self.children[index]; child.handed_back = Some(if result.is_ok() { - pools(gas) + funding(gas) } else { - Pools { reservoir: child.share, spilled: 0 } + Funding { reservoir: child.share, spilled: 0 } }); self.settling = Some(index); } @@ -149,25 +159,47 @@ fn calling(children: &[Address], end: u8) -> MemoryDatabase { .account_code(IDLE, BytecodeBuilder::default().stop().build()) } -/// Runs a call to `A` over `db` at a gas limit that leaves `reservoir` once the body is paid, and -/// returns the outcome's reservoir and gas used with what [`Settlements`] read. -fn run(db: MemoryDatabase, reservoir: u64) -> (u64, u64, u64, Settlements) { - let gas_limit = TX_GAS_LIMIT_CAP + body_history(0) + reservoir; +/// A call to `A`, as it ended. +struct Run { + gas_limit: u64, + gas_used: u64, + reservoir_remaining: u64, + /// The history gas the start ledger gave back to the transaction's gas at its start's + /// settlement: the start charge, or nothing. + start_refund: u64, + read: Settlements, +} + +/// The gas limit that leaves `reservoir` once the body is paid. +fn leaving(reservoir: u64) -> u64 { + TX_GAS_LIMIT_CAP + body_history(0) + reservoir +} + +/// Runs a call to `A` carrying `value` over `db` at `gas_limit`. +fn run(db: MemoryDatabase, gas_limit: u64, value: u64) -> Run { let mut evm = MegaEvm::new(context(db)).with_inspector(Settlements::default()); - let outcome = - evm.execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)).expect("the call is valid"); - let gas_used = outcome.result.tx_gas_used(); - let reservoir = outcome.gas.reservoir_remaining; - (gas_limit, gas_used, reservoir, evm.inspector().clone()) + record_start_ledger_settlements(evm.ctx_mut()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::from(value), gas_limit)) + .expect("the call is valid"); + let settlements = take_start_ledger_settlements(evm.ctx_mut()); + let start = settlements.iter().find(|settled| settled.depth == 0).expect("the start settled"); + Run { + gas_limit, + gas_used: outcome.result.tx_gas_used(), + reservoir_remaining: outcome.gas.reservoir_remaining, + start_refund: start.refund, + read: evm.inspector().clone(), + } } /// What a caller that kept `kept` holds once a child that hands back `handed_back` settled into /// it: the reservoir the child hands back unwinds the caller's spill, the child's own merged in, /// as far as it goes, and the rest joins the part the caller kept. -const fn settled(kept: Pools, handed_back: Pools) -> Pools { +const fn after_settlement(kept: Funding, handed_back: Funding) -> Funding { let spilled = kept.spilled + handed_back.spilled; let unwound = if handed_back.reservoir < spilled { handed_back.reservoir } else { spilled }; - Pools { + Funding { reservoir: kept.reservoir + handed_back.reservoir - unwound, spilled: spilled - unwound, } @@ -185,16 +217,16 @@ fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_ha return; } let children = [OK, REVERTER, HALTER, SPENDER, IDLE]; - let (_, _, reservoir_remaining, read) = - run(calling(&children, revm::bytecode::opcode::STOP), 4 * slot_state_gas()); + let Run { reservoir_remaining, read, .. } = + run(calling(&children, revm::bytecode::opcode::STOP), leaving(4 * slot_state_gas()), 0); assert_eq!(read.children.len(), children.len()); - for (child, settled_child) in children.iter().zip(&read.children) { - let kept = settled_child.kept.expect("the CALL ended"); - let handed_back = settled_child.handed_back.expect("the child ended"); + for (child, settled) in children.iter().zip(&read.children) { + let kept = settled.kept.expect("the CALL ended"); + let handed_back = settled.handed_back.expect("the child ended"); assert_eq!( - settled_child.after, - Some(settled(kept, handed_back)), + settled.after, + Some(after_settlement(kept, handed_back)), "{child}: kept {kept:?}, handed back {handed_back:?}" ); } @@ -209,23 +241,29 @@ fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_ha let (result, ended) = read.frame_ended.expect("the frame ended"); assert!(result.is_ok(), "{result:?}"); - let to_the_transaction = settled(Pools { reservoir: 0, spilled: 0 }, ended); + let to_the_transaction = after_settlement(Funding::NONE, ended); assert_eq!(reservoir_remaining, to_the_transaction.reservoir); } -/// The transaction's frame hands back what a child's would, into gas that holds nothing of the -/// reservoir it gave the frame: what the frame left after a child that kept a part of it and a -/// write of its own when it succeeds, the whole reservoir it was given when it reverts or halts. -/// A halt also burns the transaction's regular gas. +/// The transaction's frame hands back what a child's would, into gas whose copy of the reservoir it +/// gave the frame the settlement replaces, nothing added back: what the frame left after a child +/// that kept a part of it and a write of its own when it succeeds, the whole reservoir it was +/// given when it reverts or halts. A halt of a frame whose value transfer was charged a start +/// charge gives the charge back first and then burns the transaction's regular gas: above the cap +/// the charge comes back into the reservoir; below it, where the charge spilled onto the +/// transaction's regular gas, it comes back there and is burned with the rest. #[test] fn test_the_transactions_gas_holds_what_its_frame_hands_back_and_nothing_more() { if state_is_free() { return; } - for (end, ok) in [ - (revm::bytecode::opcode::STOP, true), - (revm::bytecode::opcode::REVERT, false), - (INVALID, false), + let above = leaving(4 * slot_state_gas()); + for (end, ok, value, gas_limit) in [ + (revm::bytecode::opcode::STOP, true, 0, above), + (revm::bytecode::opcode::REVERT, false, 0, above), + (INVALID, false, 0, above), + (INVALID, false, 1, above), + (INVALID, false, 1, 30_000_000), ] { let code = BytecodeBuilder::default() .call(OK, U256::ZERO) @@ -234,16 +272,28 @@ fn test_the_transactions_gas_holds_what_its_frame_hands_back_and_nothing_more() let code = if end == revm::bytecode::opcode::REVERT { code.revert() } else { code.append(end) }; let db = calling(&[], end).account_code(A, code.build()); - let (gas_limit, gas_used, reservoir_remaining, read) = run(db, 4 * slot_state_gas()); + let Run { gas_limit, gas_used, reservoir_remaining, start_refund, read } = + run(db, gas_limit, value); + let case = format!("{end:#04x}, value {value}, gas limit {gas_limit}"); let given = read.frame_given.expect("the frame started"); let (result, ended) = read.frame_ended.expect("the frame ended"); - assert_eq!(result.is_ok(), ok, "{end:#04x}: {result:?}"); - let expected = - if ok { settled(Pools { reservoir: 0, spilled: 0 }, ended).reservoir } else { given }; - assert_eq!(reservoir_remaining, expected, "{end:#04x}"); + assert_eq!(result.is_ok(), ok, "{case}: {result:?}"); + assert_eq!(start_refund != 0, value != 0 && !ok && !history_is_free(), "{case}"); + let expected = if ok { + after_settlement(Funding::NONE, ended).reservoir + } else if gas_limit > TX_GAS_LIMIT_CAP { + given + start_refund + } else { + 0 + }; + assert_eq!(reservoir_remaining, expected, "{case}"); if end == INVALID { - assert_eq!(gas_used + reservoir_remaining, gas_limit, "the halt burns the regular gas"); + assert_eq!( + gas_used + reservoir_remaining, + gas_limit, + "{case}: the halt burns the regular gas" + ); } } } From 79c5ef1bf017b2a7bfde30d523d2bceec1b2440d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 20:17:26 +0800 Subject: [PATCH 78/83] refactor(test-utils): the pool types come from the crate root alone --- crates/mega-evm/src/test_utils/ledger.rs | 8 ++++---- crates/mega-evm/tests/satin/common.rs | 10 ++++------ crates/mega-evm/tests/satin/inspector_cheatcodes.rs | 2 +- crates/mega-evm/tests/satin/start_ledger.rs | 3 +-- 4 files changed, 10 insertions(+), 13 deletions(-) diff --git a/crates/mega-evm/src/test_utils/ledger.rs b/crates/mega-evm/src/test_utils/ledger.rs index 505094588..e08856312 100644 --- a/crates/mega-evm/src/test_utils/ledger.rs +++ b/crates/mega-evm/src/test_utils/ledger.rs @@ -4,9 +4,9 @@ //! The engine keeps a frame's budgets, its start charge and its history allowance on its own start //! ledger, not on the frame's gas: a test reads them as the ledger settled each start, once the //! transaction ran. An inspector's answer and a result whose gas an inspector replaced settle as -//! unlimited budgets whatever gas the inspector built, and a tracker an inspector -//! restores from a snapshot leaves the ledger's draws where they were, which is what a test of -//! such an inspector asserts. +//! unlimited budgets whatever gas the inspector built, and a tracker an inspector restores from a +//! snapshot leaves the ledger's draws where they were, which is what a test of such an inspector +//! asserts. #[cfg(not(feature = "std"))] use alloc as std; @@ -15,7 +15,7 @@ use std::vec::Vec; use crate::{ExternalEnvTypes, MegaContext}; use revm::Database; -pub use crate::limit::{LedgerPools, LedgerSettlement, PoolAmounts, PoolId}; +pub use crate::limit::{LedgerPools, LedgerSettlement}; /// Has `ctx`'s start ledger record every settlement from now on, across transactions, until they /// are taken. diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 71bf11936..24518ed4c 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -6,11 +6,10 @@ use alloy_primitives::{Address, Bytes, TxKind, B256, U256}; use mega_evm::{ active_satin_prices, test_utils::{ - note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, - LedgerSettlement, PoolAmounts, PoolId, + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, LedgerSettlement, }, EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionOutcome, + MegaTransaction, MegaTransactionOutcome, PoolAmounts, PoolId, }; use revm::{ bytecode::opcode::{PUSH0, RETURN}, @@ -303,9 +302,8 @@ pub(crate) fn body_history(calldata_len: u64) -> u64 { /// Asserts that the start ledger settled start `start`, at `depth`, an inspector's answer, at /// unlimited budgets, whatever gas the inspector built it on — the engine's own /// `untouched_call_gas` and `untouched_create_gas` included — and left the answer's caller with -/// unlimited budgets: the frame's pools as it settled -/// and its caller's once it settled into them, all three unlimited, with no net drawn on the -/// answer. +/// unlimited budgets: the frame's pools as it settled and its caller's once it settled into them, +/// all three unlimited, with no net drawn on the answer. pub(crate) fn assert_answered_at_unlimited_budgets( settlements: &[LedgerSettlement], start: u32, diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index ad8596184..6a296f7a5 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -321,7 +321,7 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { let settlements = take_start_ledger_settlements(evm.ctx_mut()); let resumed = crate::common::ledger_settled(&settlements, 3); assert_eq!((resumed.depth, resumed.caller.net), (1, [WRITE_RECORD_SIZE as i64, 1, 1])); - assert_eq!(resumed.caller.remaining, mega_evm::test_utils::PoolAmounts::UNLIMITED); + assert_eq!(resumed.caller.remaining, mega_evm::PoolAmounts::UNLIMITED); (outcome, evm.inspector().answered) }; assert_eq!(answered, 2); diff --git a/crates/mega-evm/tests/satin/start_ledger.rs b/crates/mega-evm/tests/satin/start_ledger.rs index d4f450818..1df041d7c 100644 --- a/crates/mega-evm/tests/satin/start_ledger.rs +++ b/crates/mega-evm/tests/satin/start_ledger.rs @@ -17,9 +17,8 @@ use mega_evm::{ test_utils::{ neutral_cfg, neutralize_evm, record_start_ledger_settlements, take_start_ledger_settlements, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, - PoolAmounts, }, - EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, WRITE_RECORD_SIZE, + EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, PoolAmounts, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ADDRESS, CALL, GAS, POP, PUSH0, REVERT, STOP}, From 06cd5a3f724f4728fca4337f2de7c56c2a420b30 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 20:17:27 +0800 Subject: [PATCH 79/83] test(evm): drop the schedule test that only restated two constants the share and spec-number tests pin --- crates/mega-evm/src/evm/schedule.rs | 30 +++++++++-------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 06533c329..555557d5c 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -15,14 +15,14 @@ //! ([`FORWARD_REDUCTION_QUOTIENT`], the fork's `GasId::call_stipend_reduction`). //! //! What else a frame start takes from its caller is the engine's, not the schedule's, and is in no -//! entry of it: the share of its caller's pools — -//! data size, KV updates, state growth — and of its caller's EIP-8037 reservoir a frame starts -//! with, all but [`FRAME_KEPT_PERCENT`] of what the caller has left, and the history allowance a -//! value-transferring call gives the frame, `HISTORY_ALLOWANCE_BYTES` at the cost per history -//! byte, are decided where the start is made (`MegaContext::forward_start`) and kept on the -//! engine's start ledger. A pool's share is `floor(remaining × 98 / 100)`, and the reservoir's -//! `remaining − remaining × 2 / 100`, so a caller keeps nothing of a reservoir below 50; the -//! transaction's own frame and a system call's outermost frame take the whole reservoir. +//! entry of it: the share of its caller's pools — data size, KV updates, state growth — and of its +//! caller's EIP-8037 reservoir a frame starts with, all but [`FRAME_KEPT_PERCENT`] of what the +//! caller has left, and the history allowance a value-transferring call gives the frame, +//! `HISTORY_ALLOWANCE_BYTES` at the cost per history byte, are decided where the start is made +//! (`MegaContext::forward_start`) and kept on the engine's start ledger. A pool's share is +//! `floor(remaining × 98 / 100)`, and the reservoir's `remaining − remaining × 2 / 100`, so a +//! caller keeps nothing of a reservoir below 50; the transaction's own frame and a system call's +//! outermost frame take the whole reservoir. //! //! Every regular-gas price is Amsterdam's, so state creation is split between the two dimensions //! as Amsterdam splits it: the regular part is the access and write work EIP-8038 prices, and the @@ -155,10 +155,7 @@ mod tests { constants::{ ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, SLOT_STATE_GAS, }, - evm::{ - history::HISTORY_ALLOWANCE_BYTES, - prices::{runs_at_measurement_prices, BytePrice}, - }, + evm::prices::{runs_at_measurement_prices, BytePrice}, }; fn osaka() -> GasParams { @@ -273,15 +270,6 @@ mod tests { } } - /// What a frame start takes beyond the regular gas it forwards is the engine's, in no entry of - /// the schedule: a child keeps all but [`FRAME_KEPT_PERCENT`], 2, of its caller's reservoir and - /// budgets, and a value call's frame gets `HISTORY_ALLOWANCE_BYTES`, 160, of history. - #[test] - fn test_a_starts_shares_and_allowance_are_the_engines() { - assert_eq!(FRAME_KEPT_PERCENT, 2); - assert_eq!(HISTORY_ALLOWANCE_BYTES, 160); - } - /// A call or creation forwards at most `remaining − remaining × 2 / 100` of its caller's /// regular gas, Rex6's rule, which the fork's EIP-150 reduction gives with a quotient of 50; /// upstream's is 64, the 63/64 rule. From adf458244f532cbb51f8221397f5dca040d3dc5d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 27 Oct 2026 20:17:27 +0800 Subject: [PATCH 80/83] docs: no provider adopts pool draws today, the schedule has no entry for a start's shares, and the module table lists the pool types --- .claude/skills/satin-review/SKILL.md | 4 ++-- AGENTS.md | 4 ++-- crates/mega-evm/src/limit/ledger.rs | 5 +++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 6640d3ba6..270856820 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -75,9 +75,9 @@ Each change is stated here in plain words with its reason; the specification has The engine decides all four itself, in every build: the budgets, the start charge and the allowance on its start ledger (`src/limit/ledger.rs`), an entry per start driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and the reservoir's share where the start is made (`MegaContext::forward_start`, named to revm on `FrameStart::reservoir`). The fork forwards and settles the reservoir as upstream does: the settlement puts the reservoir the child hands back in place of the caller's, and `frame_settle` adds back the part the caller kept (`FrameSettle::held_reservoir`) at a child's settlement, not at the transaction's, whose gas held a copy of its frame's reservoir. A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history, and after a halt of the transaction's own frame burns the transaction's regular gas, as revm's settlement did after its own refund, so regular gas an inspector's extra reservoir unwound is not kept; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). - The inspector shapes whose results change, each accepted: an answer built on gas whose pools the inspector set, or with the input's start charge copied, while the fork still carried them, settles at unlimited budgets with no charge back; a tracker an inspector restores from a snapshot leaves the ledger's draws and the allowance where they were; and an inspector that replaces a value call's interpreter leaves the frame its allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas. + The inspector shapes whose results changed when the engine took the figures over, each accepted: an answer built on gas whose pools the inspector set, or with the input's start charge copied, which an inspector can no longer build, now that the fork carries neither; a tracker an inspector restores from a snapshot leaves the ledger's draws and the allowance where they were; and an inspector that replaces a value call's interpreter leaves the frame its allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas. A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`). - Why: the figures are the engine's decisions, and the fork carries them only until they leave it. + Why: the figures are the engine's decisions, and the fork carries none of them. - **Writes and frame starts are metered in the fork's instruction hooks.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, the frame's own part is parked on the start ledger as the start's charge, which its settlement gives back when the frame fails, and the frame's share of the caller's reservoir is taken and named on the start (`FrameStart::reservoir`). diff --git a/AGENTS.md b/AGENTS.md index be2d3f300..8a60340d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -143,7 +143,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_start`) — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | | `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | | `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.rs`) | | `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | | `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | | `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | @@ -163,7 +163,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat op-revm includes a deposit that fails validation as a failed deposit rather than refusing it, so for a deposit or a promoted system-address transaction the error says it would fail. Gas above the 200M execution cap goes to the EIP-8037 reservoir. - The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with three changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte; the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`); and a call or creation forwards at most `remaining − remaining × 2 / 100` of the caller's regular gas, Rex6's rule in place of EIP-150's 63/64 (`GasId::call_stipend_reduction`). - The rest of what a start takes is the engine's, not the schedule's, which keeps Amsterdam's zero there: a child starts with 98/100 of its caller's reservoir and of each of its three budgets (`FRAME_KEPT_PERCENT`, the part the caller keeps), and a value call's child with a history allowance of `HISTORY_ALLOWANCE_BYTES` at the cost per history byte, decided where the start is made (`MegaContext::forward_start`). + The rest of what a start takes is the engine's, in no entry of the schedule: a child starts with 98/100 of its caller's reservoir and of each of its three budgets (`FRAME_KEPT_PERCENT`, the part the caller keeps), and a value call's child with a history allowance of `HISTORY_ALLOWANCE_BYTES` at the cost per history byte, decided where the start is made (`MegaContext::forward_start`). Every regular-gas entry is Amsterdam's, EIP-8038's state-access prices included, so creating state costs the access and the write in regular gas and the new state itself in state gas alone, as upstream. The static opcode prices, which revm keeps in the instruction table, are Amsterdam's too (`satin_gas_table`): they part from the Osaka base's only in EIP-8038's 200-gas base of `EXTCODESIZE` and `EXTCODECOPY`. It is built once per process, with a second copy that prices that entry at zero for a transaction exempt from history gas (`satin_gas_params_history_exempt`); the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 5a3d227bb..81d8e033f 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -45,9 +45,10 @@ //! creating frame, a creator's nonce record on the creator once its creation returned //! ([`draw`](StartLedger::draw)). With no start open, as for a frame a test drives by hand, there //! is no frame budget. -//! - **A precompile's draws are adopted when it answers**, fail-closed: a draw past the share +//! - **A precompile's draws would be adopted when it answers**, fail-closed: a draw past the share //! empties the pool and caps the net at the share, whatever the answer's status -//! ([`adopt_provider_draws`](StartLedger::adopt_provider_draws)). +//! ([`adopt_provider_draws`](StartLedger::adopt_provider_draws)). No provider the engine runs +//! draws a pool, so nothing adopts any today. //! - **A settlement** merges the child's entry into its caller's ([`settle`](StartLedger::settle)): //! on success the child's remaining pools join what the caller kept and its nets the caller's; on //! a revert or a halt its draws are undone, and its whole share comes back. The start charge From dd007b9a9f80895281dda7bb79f24d72c579fffd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 28 Oct 2026 09:08:56 +0800 Subject: [PATCH 81/83] test(limit): the start ledger's caller-net rule and an answer's rebuild are pinned, and two comparisons no mutant can tell apart are gone - A unit test pins that only a caller's negative net holds its child's share to the caller's budget: a net back at zero after a take-back and a draw again holds the child to the frame cap alone. - A unit test pins that an answer rebuilt on its caller's forward puts its start back at its shares, undrawn. - `signed` saturates through `i64::try_from`, with no comparison at `i64::MAX`, where `>` and `>=` agreed. - A precompile's draw is held to its share with `min`: a draw at, past or within the share gives what the two branches gave, without the comparisons whose `>`/`>=` forms agreed at zero and at the share. --- crates/mega-evm/src/limit/ledger.rs | 72 +++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 15 deletions(-) diff --git a/crates/mega-evm/src/limit/ledger.rs b/crates/mega-evm/src/limit/ledger.rs index 81d8e033f..465f1afee 100644 --- a/crates/mega-evm/src/limit/ledger.rs +++ b/crates/mega-evm/src/limit/ledger.rs @@ -167,12 +167,8 @@ impl Pools { } /// `amount` as a signed net, saturating. -const fn signed(amount: u64) -> i64 { - if amount > i64::MAX as u64 { - i64::MAX - } else { - amount as i64 - } +fn signed(amount: u64) -> i64 { + i64::try_from(amount).unwrap_or(i64::MAX) } /// `kept` per cent of `amount`, rounded down: the part of its reservoir a caller keeps when it @@ -459,16 +455,15 @@ impl StartLedger { for pool in PoolId::ALL { let (index, share) = (pool.index(), entry.shares.get(pool)); let ProviderDraw { net: drawn, past_a_share } = draws[index]; - if past_a_share || (drawn > 0 && drawn as u64 > share) { - entry.pools.remaining.set(pool, 0); - entry.pools.net[index] = signed(share); + // A draw past the share is held to it: the whole share drawn, nothing left. + let (remaining, net) = if past_a_share { + (0, signed(share)) } else { - entry - .pools - .remaining - .set(pool, share.saturating_add_signed(drawn.saturating_neg())); - entry.pools.net[index] = drawn; - } + let net = drawn.min(signed(share)); + (share.saturating_add_signed(net.saturating_neg()), net) + }; + entry.pools.remaining.set(pool, remaining); + entry.pools.net[index] = net; } } @@ -798,6 +793,53 @@ mod tests { assert_eq!(adopted(unlimited, i64::MAX, true), (0, i64::MAX), "marked past a share"); } + /// A caller's net decides whether its child's share is held to the share of the caller's + /// budget: one whose net is back at zero — it took back a draw before the start and drew it + /// again after — holds the child to the frame cap alone, though the share the child took was + /// counted on more than the caller's budget now holds; one whose net is below zero holds it to + /// the share of that budget, the excess going back to the caller. + #[test] + fn test_only_a_callers_negative_net_holds_its_childs_share_to_its_budget() { + let pools = PoolAmounts::ZERO.with(DATA_SIZE_POOL, 1_000); + let taken_back = Counted { + added: PoolAmounts::ZERO, + taken: PoolAmounts::ZERO.with(DATA_SIZE_POOL, 10), + transfer_log: false, + }; + // Drawn again, the net is zero and the child keeps its 989; not drawn again, the net is + // -10, the caller's budget 21 + 989 - 10 = 1,000, of which the child may have 980, and the + // 9 past it go back to the caller. + for (drawn_again, held) in [(10, (989, 11)), (0, (980, 30))] { + let mut ledger = opened(pools); + ledger.draw(&taken_back); + // 1,010 left: the child's share is 98 per cent of it, rounded down, 989. + ledger.park(KEPT, 0, 0); + ledger.draw(&Counted::bytes(drawn_again)); + ledger.split(2, Some(1), 1); + ledger.cap_child(PoolAmounts::UNLIMITED, KEPT); + let (shares, caller) = ledger.top_shares_and_caller_pools(); + assert_eq!( + (shares.get(DATA_SIZE_POOL), caller.get(DATA_SIZE_POOL)), + held, + "drawn again {drawn_again}" + ); + } + } + + /// An answer rebuilt on the gas its caller forwarded puts the start back at its shares, + /// undrawn, whatever was drawn on it before. + #[test] + fn test_a_rebuilt_answer_puts_its_start_back_at_its_shares() { + let mut ledger = opened(POOLS); + ledger.park(KEPT, 0, 0); + ledger.split(2, Some(1), 1); + let shares = ledger.entries[1].shares; + ledger.draw(&Counted::bytes(100)); + assert_ne!(top(&ledger).remaining, shares, "drawn"); + ledger.rebuild_on_shares(); + assert_eq!(top(&ledger), Pools::of(shares)); + } + /// A log's history draws the allowance first and pays the rest; with no start open it pays all. #[test] fn test_the_allowance_is_drawn_first() { From 75eb153e7e428c2266e02eb624d46633c3fbf8e2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 28 Oct 2026 10:36:23 +0800 Subject: [PATCH 82/83] docs: the review guide names the fork heads the patch blocks pin, and an inspector has no budget field left to write --- .claude/skills/satin-review/SKILL.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 270856820..61d685c74 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -32,7 +32,7 @@ The guide describes the code at `cz/feat/satin-w2` with #407 merged into it and Satin is a new spec: simpler semantics win over parity with the legacy engine. - Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates. Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code. -- Fork code: the `megaeth-labs/revm` fork at `426217bb2e76c0a41d46907eb788250e8efa107c` and the `megaeth-labs/op-revm` fork at `3d43e32029fc5cd293ab70eb0929d70e37337966`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. +- Fork code: the `megaeth-labs/revm` fork at `4c8f0d43b70f2175f9ce0132cc343283f9a29548` and the `megaeth-labs/op-revm` fork at `8c0db939291e1c4cbf2375782d1483bc371d6b94`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. Their diff is not part of this pull request. A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour. The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks). @@ -372,7 +372,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing (a frame that fails, or a start revm refuses before it bumps a nonce or moves a value), and its records are those revm then made. - A pre-block system call runs on the plain system-call path, with no callback. - `test_utils::ReadOnlyObserver` checks, in debug builds, that an inspector a test declares an observer writes nothing back: a tripwire for tests, not a proof. - - The start ledger settles an inspector's answer and a replaced tracker at unlimited budgets, and gives no start charge back for an answer or a rebuilt outcome; the pools, charge and allowance fields an inspector writes on an input, an answer or a result are not read, a restored tracker snapshot leaves the ledger's draws standing, and a replaced interpreter leaves the frame its allowance; the tests of such inspectors read what the ledger settled. + - The start ledger settles an inspector's answer and a replaced tracker at unlimited budgets, and gives no start charge back for an answer or a rebuilt outcome; an inspector has no budget, start-charge or allowance field to write on an input, an answer or a result, since the engine keeps all three on its ledger, a restored tracker snapshot leaves the ledger's draws standing, and a replaced interpreter leaves the frame its allowance; the tests of such inspectors read what the ledger settled. - **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer), the entries on inspectors. ### Node surface, validation and the stateless witness From 5e3f30ad4692f3815105dea1368f789f032ddd2b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 29 Oct 2026 09:09:11 +0800 Subject: [PATCH 83/83] refactor(limit): check that every pool amount is zero by pattern, not by an index loop --- crates/mega-evm/src/limit/pool.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/src/limit/pool.rs b/crates/mega-evm/src/limit/pool.rs index e6150b005..480298a14 100644 --- a/crates/mega-evm/src/limit/pool.rs +++ b/crates/mega-evm/src/limit/pool.rs @@ -69,13 +69,7 @@ impl PoolAmounts { /// 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 + // One element per pool: the pattern stops compiling if the pool count changes. + matches!(self.0, [0, 0, 0]) } }