Skip to content
This repository was archived by the owner on Nov 11, 2026. It is now read-only.
Merged
52 changes: 51 additions & 1 deletion crates/evm2/src/evm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ pub use state::{
AccountChangeRef, AccountChanges, AccountFlags, AccountHandle, AccountInfo,
BlockStateAccumulator, JournalEntry, NoopChangeSink, PendingState, State, StateChangeSink,
StateChangeSource, StateCheckpoint, StateInner, StateSnapshot, StorageChange, StorageHandle,
StorageOverlay, StorageSlot, StorageSlotHandle, Tee, Tracked,
StorageOverlay, StorageSlot, StorageSlotHandle, Tee, Tracked, TxStateChanges,
};

pub(crate) mod prewarm_set;
Expand Down Expand Up @@ -4636,6 +4636,56 @@ mod tests {
assert!(!next.account_changes().find(|c| c.address == target).unwrap().touched);
}

#[test]
fn changes_inspect_transaction_state_before_commit_or_discard() {
let caller = Address::repeat_byte(0xaa);
let target = Address::repeat_byte(0x11);
// SSTORE(0, 1)
let code = vec![op::PUSH1, 1, op::PUSH0, op::SSTORE, op::STOP];
let mut database = InMemoryDB::default();
database.insert_account_info(
&target,
AccountInfo::default().with_nonce(1).with_code(legacy_bytecode(code)),
);
let mut evm = Evm::<BaseEvmTypes>::new(
SpecId::CANCUN,
BlockEnvExt::default(),
ethereum_tx_registry(SpecId::CANCUN),
database,
Precompiles::base(SpecId::CANCUN),
);
let tx = Recovered::new_unchecked(
TxEnvelope::Legacy(TxLegacy {
to: TxKind::Call(target),
gas_limit: 100_000,
..Default::default()
}),
caller,
);

let executed = evm.transact(&tx).unwrap();
assert!(executed.result().status);
let changes = executed.changes();
assert!(!changes.is_empty());
assert_eq!(changes.account_info(&caller).unwrap().nonce, 1);
let slot = changes.account_changes_for(&target).unwrap().storage.slots[&Word::ZERO].value;
assert_eq!(slot.current, Word::from(1));
let mut in_place = changes.account_changes().map(|c| c.address).collect::<Vec<_>>();
in_place.sort();
let _ = executed.discard();

// Discarding after inspection leaves the accepted state unchanged, so the same transaction
// executes again, and its detached state reports the same accounts.
let executed = evm.transact(&tx).unwrap();
assert!(executed.result().status);
let pending = executed.detach().pending_state;
let mut detached =
pending.changes().account_changes().map(|c| c.address).collect::<Vec<_>>();
detached.sort();
assert_eq!(in_place, detached);
assert_eq!(pending.changes().account_info(&caller).unwrap().nonce, 1);
}

#[derive(Default)]
struct CallCounter {
calls: usize,
Expand Down
27 changes: 4 additions & 23 deletions crates/evm2/src/evm/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub use block::BlockStateAccumulator;
#[cfg(feature = "account-ext")]
pub use extension::AccountExtension;
pub use journal::{JournalEntry, StateCheckpoint};
pub use pending::PendingState;
pub use pending::{PendingState, TxStateChanges};
pub use storage::{StorageHandle, StorageOverlay, StorageSlot, StorageSlotHandle};
pub use stream::{
AccountChangeRef, AccountChanges, NoopChangeSink, StateChangeSink, StateChangeSource,
Expand Down Expand Up @@ -981,29 +981,10 @@ impl<'a> State<'a> {
Ok(())
}

/// Visits transaction state changes in database application order: each account's bytecode
/// and storage precede its metadata.
///
/// This borrows changes directly from the transaction layer without detaching it and does not
/// mutate the accepted overlay.
pub(crate) fn visit_transaction_changes<S: StateChangeSink>(
&self,
sink: &mut S,
) -> Result<(), S::Error> {
for changes in self.transaction_account_changes() {
changes.visit(sink)?;
}
Ok(())
}

/// Returns each account loaded by the transaction with its changes, in an unspecified order.
///
/// This borrows the transaction layer without detaching it.
/// Returns a borrowed view of the transaction layer's changes, without detaching it.
#[inline]
pub(crate) fn transaction_account_changes(&self) -> impl Iterator<Item = AccountChanges<'_>> {
self.accounts.iter().map(|(&address, account)| {
account.changes(address, self.selfdestructs.contains(&address))
})
pub(crate) fn transaction_changes(&self) -> TxStateChanges<'_> {
TxStateChanges::new(&self.accounts, &self.selfdestructs)
}

/// Detaches the transaction overlay into an owned [`PendingState`].
Expand Down
81 changes: 75 additions & 6 deletions crates/evm2/src/evm/state/pending.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,23 @@ impl PendingState {
self.accounts.values().any(|account| account.is_changed() || account.storage.is_changed())
}

/// Returns a borrowed view of the transaction's changes.
#[inline]
pub const fn changes(&self) -> TxStateChanges<'_> {
TxStateChanges::new(&self.accounts, &self.selfdestructs)
}

/// Returns each loaded account's changes, in an unspecified account order.
#[inline]
pub fn account_changes(&self) -> impl Iterator<Item = AccountChanges<'_>> {
self.accounts.iter().map(|(&address, account)| {
account.changes(address, self.selfdestructs.contains(&address))
})
self.changes().account_changes()
}

/// Returns the changes of the account at `address`, or `None` if the transaction did not load
/// it.
#[inline]
pub fn account_changes_for(&self, address: &Address) -> Option<AccountChanges<'_>> {
self.accounts
.get(address)
.map(|account| account.changes(*address, self.selfdestructs.contains(address)))
self.changes().account_changes_for(address)
}
}

Expand All @@ -125,6 +127,73 @@ impl StateChangeSource for PendingState {
/// Changed accounts — including created or selfdestructed accounts whose info ended up
/// unchanged — go through [`StateChangeSink::account`]; loaded-but-unchanged entries go
/// through the read callbacks.
fn visit<S: StateChangeSink>(&self, sink: &mut S) -> Result<(), S::Error> {
self.changes().visit(sink)
}
}

/// A borrowed view of one transaction's state changes, whether still attached to the EVM or
/// detached into a [`PendingState`].
///
/// Returned by [`ExecutedTx::changes`](crate::ExecutedTx::changes), which borrows the
/// transaction layer in place, and by [`PendingState::changes`]. It lets a caller inspect what a
/// transaction wrote before deciding to commit or discard it, without detaching the state.
#[derive(Clone, Copy, Debug, Default)]
pub struct TxStateChanges<'a> {
inner: Option<(&'a AddressMap<Account>, &'a AddressSet)>,
}

impl<'a> TxStateChanges<'a> {
#[inline]
pub(crate) const fn new(
accounts: &'a AddressMap<Account>,
selfdestructs: &'a AddressSet,
) -> Self {
Self { inner: Some((accounts, selfdestructs)) }
}

/// Returns a view with no changes.
#[inline]
pub const fn empty() -> Self {
Self { inner: None }
}

/// Returns whether the transaction loaded no accounts and no storage.
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.is_none_or(|(accounts, _)| accounts.is_empty())
}

/// Returns the current account information when the transaction loaded the account and it
/// exists after the transaction.
#[inline]
pub fn account_info(&self, address: &Address) -> Option<&'a AccountInfo> {
self.inner?.0.get(address).and_then(|account| account.present.as_ref())
}

/// Returns each loaded account's changes, in an unspecified account order.
#[inline]
pub fn account_changes(self) -> impl Iterator<Item = AccountChanges<'a>> {
self.inner.into_iter().flat_map(|(accounts, selfdestructs)| {
accounts.iter().map(|(&address, account)| {
account.changes(address, selfdestructs.contains(&address))
})
})
}

/// Returns the changes of the account at `address`, or `None` if the transaction did not load
/// it.
#[inline]
pub fn account_changes_for(&self, address: &Address) -> Option<AccountChanges<'a>> {
let (accounts, selfdestructs) = self.inner?;
accounts
.get(address)
.map(|account| account.changes(*address, selfdestructs.contains(address)))
}
}

impl StateChangeSource for TxStateChanges<'_> {
/// Visits the transaction's loaded entries as [`PendingState`]'s implementation does.
fn visit<S: StateChangeSink>(&self, sink: &mut S) -> Result<(), S::Error> {
for changes in self.account_changes() {
changes.visit(sink)?;
Expand Down
36 changes: 29 additions & 7 deletions crates/evm2/src/evm/tx.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Transaction execution lifecycle and result types.

use super::{AccountChanges, BlockStateAccumulator, Evm, PendingState, StateChangeSink};
use super::{
AccountChanges, BlockStateAccumulator, Evm, PendingState, StateChangeSink, StateChangeSource,
TxStateChanges,
};
use crate::{EvmTypesHost, interpreter::InstrStop};
use alloc::vec::Vec;
use alloy_primitives::{Address, Bytes, Log};
Expand Down Expand Up @@ -264,10 +267,21 @@ impl<'evm, 'host, T: EvmTypesHost> ExecutedTx<'evm, 'host, T> {
/// and then [`commit`](Self::commit) or [`discard`](Self::discard) the transaction.
#[inline]
pub fn account_changes(&self) -> impl Iterator<Item = AccountChanges<'_>> {
self.has_pending_state()
.then(|| self.evm.state.transaction_account_changes())
.into_iter()
.flatten()
self.changes().account_changes()
}

/// Returns a borrowed view of the transaction's state changes.
///
/// Like [`account_changes`](Self::account_changes), this borrows the transaction state in
/// place, so a caller can inspect what the transaction wrote, including single accounts and
/// storage slots, before deciding to [`commit`](Self::commit) or [`discard`](Self::discard).
#[inline]
pub fn changes(&self) -> TxStateChanges<'_> {
if self.has_pending_state() {
self.evm.state.transaction_changes()
} else {
TxStateChanges::empty()
}
}

/// Accepts the transaction state into the internal accepted overlay.
Expand Down Expand Up @@ -297,7 +311,7 @@ impl<'evm, 'host, T: EvmTypesHost> ExecutedTx<'evm, 'host, T> {
sink: &mut S,
) -> Result<TxResult<T>, S::Error> {
if self.has_pending_state() {
self.evm.state.visit_transaction_changes(sink)?;
self.evm.state.transaction_changes().visit(sink)?;
self.commit_pending_state();
}
Ok(self.take_result())
Expand All @@ -322,7 +336,7 @@ impl<'evm, 'host, T: EvmTypesHost> ExecutedTx<'evm, 'host, T> {
sink: &mut S,
) -> Result<TxResult<T>, S::Error> {
if self.has_pending_state() {
self.evm.state.visit_transaction_changes(sink)?;
self.evm.state.transaction_changes().visit(sink)?;
self.clear_pending_state();
}
Ok(self.take_result())
Expand All @@ -344,6 +358,14 @@ impl<'evm, 'host, T: EvmTypesHost> ExecutedTx<'evm, 'host, T> {
}
}

impl<T: EvmTypesHost> StateChangeSource for ExecutedTx<'_, '_, T> {
/// Visits the transaction's changes in place, as [`PendingState`]'s implementation does for
/// detached state.
fn visit<S: StateChangeSink>(&self, sink: &mut S) -> Result<(), S::Error> {
self.changes().visit(sink)
}
}

impl<T: EvmTypesHost> Drop for ExecutedTx<'_, '_, T> {
#[inline]
fn drop(&mut self) {
Expand Down
19 changes: 0 additions & 19 deletions crates/evm2/src/interpreter/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ pub struct Interpreter<'frame, 'host, T: EvmTypesHost> {
pub(in crate::interpreter) gas: Gas,
pub(in crate::interpreter) result: Result,
error: Option<ExecutionError>,
step_gas_before: u64,
failed_charge: Option<u64>,
spec: SpecId,
features: EvmFeatures,
is_static: bool,
Expand Down Expand Up @@ -88,8 +86,6 @@ impl<'frame, 'host, T: EvmTypesHost> Interpreter<'frame, 'host, T> {
memory: Memory::new(),
result: Ok(()),
error: None,
step_gas_before: 0,
failed_charge: None,
output: 0..0,
tx_env: None,
message: None,
Expand All @@ -114,8 +110,6 @@ impl<'frame, 'host, T: EvmTypesHost> Interpreter<'frame, 'host, T> {
self.memory.clear();
self.result = Ok(());
self.error = None;
self.step_gas_before = 0;
self.failed_charge = None;
self.output = 0..0;
self.tx_env = Some(tx_env);
self.message = Some(message);
Expand Down Expand Up @@ -267,15 +261,6 @@ impl<'frame, 'host, T: EvmTypesHost> Interpreter<'frame, 'host, T> {
self.result = result;
}

/// Returns the execution gas the current step attempted to charge when it ran out of gas.
///
/// Only set during an inspector's `step_end`, where the remaining gas has already been
/// zeroed after the failed charge.
#[inline]
pub const fn failed_charge(&self) -> Option<u64> {
self.failed_charge
}

/// Sets the current instruction result to `stop`.
#[inline]
pub const fn set_stop(&mut self, stop: InstrStop) {
Expand Down Expand Up @@ -719,8 +704,6 @@ impl<'frame, 'host, T: EvmTypesHost> InterpreterState<'frame, 'host, T> {
let mut inspector = self.0.inspector.unwrap_unchecked();
inspector.as_mut().step(&mut self.0);
}
self.0.step_gas_before = self.0.gas.remaining();
self.0.failed_charge = None;
}

#[inline]
Expand All @@ -729,8 +712,6 @@ impl<'frame, 'host, T: EvmTypesHost> InterpreterState<'frame, 'host, T> {
self.0.stack_len = stack_len;
if self.0.result.is_err_and(InstrStop::is_out_of_gas) {
cold_path();
self.0.failed_charge =
Some(self.0.step_gas_before.wrapping_sub(self.0.gas.remaining()));
// Failed charges may leave a wrapped counter until frame settlement.
self.0.gas.set_remaining(0);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/evm2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub mod evm;
pub use evm::config::EvmTypesHost;
pub use evm::{
AccountInfo, BlockStateAccumulator, Evm, ExecutedTx, InterpreterRunner, JournalEntry,
PendingState, TxResult, TxResultExt, TxResultWithState, config,
PendingState, TxResult, TxResultExt, TxResultWithState, TxStateChanges, config,
config::{
BaseEvmConfig, BaseEvmConfigSelector, BaseEvmTypes, EvmConfig, EvmConfigSelector, EvmTypes,
ExecutionConfig,
Expand Down
Loading
Loading