ethrex_levm/vm.rs
1use crate::{
2 TransientStorage,
3 account::LevmAccount,
4 call_frame::{CallFrame, Stack},
5 db::gen_db::GeneralizedDatabase,
6 debug::DebugMode,
7 environment::Environment,
8 errors::{
9 ContextResult, ExceptionalHalt, ExecutionReport, InternalError, OpcodeResult, TxResult,
10 VMError,
11 },
12 gas_cost::{
13 STATE_BYTES_PER_AUTH_BASE, STATE_BYTES_PER_NEW_ACCOUNT, STATE_BYTES_PER_STORAGE_SET,
14 cost_per_state_byte as compute_cost_per_state_byte,
15 },
16 hooks::{
17 backup_hook::BackupHook,
18 hook::{Hook, get_hooks},
19 },
20 memory::{CallData, Memory},
21 opcode_tracer::LevmOpcodeTracer,
22 opcodes::OpCodeFn,
23 precompiles::{
24 self, SIZE_PRECOMPILES_CANCUN, SIZE_PRECOMPILES_PRAGUE, SIZE_PRECOMPILES_PRE_CANCUN,
25 },
26 tracing::LevmCallTracer,
27 validation_observer::ValidationObserver,
28};
29use bytes::Bytes;
30use ethrex_common::seeded_hash::{SeededHashMap, SeededHashSet};
31use ethrex_common::{
32 Address, BigEndianHash, H256, U256,
33 tracing::CallType,
34 types::{
35 AccessListEntry, Code, Fork, Frame, FrameMode, InitcodeBuffer, Log, Transaction, TxType,
36 block_access_list::BlockAccessListCheckpoint, fee_config::FeeConfig,
37 },
38};
39use ethrex_crypto::Crypto;
40use rustc_hash::{FxHashMap, FxHashSet};
41use std::{
42 cell::{OnceCell, RefCell},
43 collections::{BTreeMap, BTreeSet},
44 mem,
45 rc::Rc,
46};
47
48/// Storage mapping from slot key to value.
49pub type Storage = FxHashMap<U256, H256>;
50
51/// Addresses accessed by a transaction (EIP-2929). Seeded: contracts choose which
52/// addresses they touch.
53pub type AccessedAddresses = SeededHashSet<Address>;
54/// Storage slots accessed by a transaction, per address (EIP-2929). Seeded: contracts
55/// choose the slot keys.
56pub type AccessedStorageSlots = SeededHashMap<Address, SeededHashSet<H256>>;
57
58/// Specifies whether the VM operates in L1 or L2 mode.
59#[derive(Debug, Clone, Copy, Default)]
60pub enum VMType {
61 /// Standard Ethereum L1 execution.
62 #[default]
63 L1,
64 /// L2 rollup execution with additional fee handling.
65 L2(FeeConfig),
66}
67
68/// Execution substate that tracks changes during transaction execution.
69///
70/// The substate maintains all information that may need to be reverted if a
71/// call fails, including:
72/// - Self-destructed accounts
73/// - Accessed addresses and storage slots (for EIP-2929 gas accounting)
74/// - Created accounts
75/// - Gas refunds
76/// - Transient storage (EIP-1153)
77/// - Event logs
78///
79/// # Backup Mechanism
80///
81/// The substate supports checkpointing via [`push_backup`] and restoration via
82/// [`revert_backup`] or commitment via [`commit_backup`]. This is used to handle
83/// nested calls where inner calls may fail and need to be reverted.
84///
85/// Most fields are private by design. The backup mechanism only works correctly
86/// if data modifications are append-only.
87#[derive(Debug, Default)]
88pub struct Substate {
89 /// Parent checkpoint for reverting on failure.
90 parent: Option<Box<Self>>,
91 /// Fork of the enclosing transaction. Lets the warmth helpers treat precompile addresses as
92 /// always-warm without occupying a hashset slot (EIP-2929). Constant for a tx, so it is
93 /// carried forward across `push_backup` checkpoints.
94 fork: Fork,
95 /// Accounts marked for self-destruction (deleted at end of transaction).
96 selfdestruct_set: FxHashSet<Address>,
97 /// Addresses accessed during execution (for EIP-2929 warm/cold gas costs).
98 /// Precompiles are NOT stored here; they are warm by construction (see `is_warm_precompile`).
99 accessed_addresses: AccessedAddresses,
100 /// Storage slots accessed per address (for EIP-2929 warm/cold gas costs).
101 accessed_storage_slots: AccessedStorageSlots,
102 /// Accounts created during this transaction.
103 created_accounts: FxHashSet<Address>,
104 /// Accumulated gas refund (e.g., from storage clears).
105 pub refunded_gas: u64,
106 /// Transient storage (EIP-1153), cleared at end of transaction.
107 transient_storage: TransientStorage,
108 /// Event logs emitted during execution.
109 logs: Vec<Log>,
110}
111
112impl Substate {
113 pub fn from_accesses(
114 fork: Fork,
115 accessed_addresses: AccessedAddresses,
116 accessed_storage_slots: AccessedStorageSlots,
117 ) -> Self {
118 Self {
119 parent: None,
120 fork,
121 selfdestruct_set: FxHashSet::default(),
122 accessed_addresses,
123 accessed_storage_slots,
124 created_accounts: FxHashSet::default(),
125 refunded_gas: 0,
126 transient_storage: TransientStorage::default(),
127 logs: Vec::new(),
128 }
129 }
130
131 /// Whether `address` is a precompile that the EVM treats as warm from the start of the tx
132 /// (EIP-2929), exactly matching the addresses `Substate::initialize` used to pre-seed.
133 ///
134 /// Replicates the pre-seed *precisely* — the contiguous range `0x01..=max_for_fork` plus the
135 /// post-Osaka P256VERIFY address `0x100` — and is intentionally `vm_type`-independent, since
136 /// the old pre-seed was too. (Using `precompiles::is_precompile`, which gates `0x100` on L2
137 /// for any fork, would change L2 pre-Osaka warmth — a consensus difference, not an opt.)
138 #[inline]
139 fn is_warm_precompile(&self, address: &Address) -> bool {
140 // Fast reject: every pre-seeded precompile has 18 leading zero bytes (max is `0x01_00`),
141 // so real contract/EOA addresses bail out here, off the hot warmth path.
142 if address.0[..18] != [0u8; 18] {
143 return false;
144 }
145 let n = u16::from_be_bytes([address.0[18], address.0[19]]);
146 let max_contiguous: u64 = match self.fork {
147 f if f >= Fork::Prague => SIZE_PRECOMPILES_PRAGUE,
148 f if f >= Fork::Cancun => SIZE_PRECOMPILES_CANCUN,
149 _ => SIZE_PRECOMPILES_PRE_CANCUN,
150 };
151 (n >= 1 && u64::from(n) <= max_contiguous) || (n == 0x100 && self.fork >= Fork::Osaka)
152 }
153
154 /// Push a checkpoint that can be either reverted or committed. All data up to this point is
155 /// still accessible.
156 pub fn push_backup(&mut self) {
157 let parent = mem::take(self);
158 self.refunded_gas = parent.refunded_gas;
159 // Carry the fork forward so child checkpoints keep the same precompile-warmth view.
160 self.fork = parent.fork;
161 self.parent = Some(Box::new(parent));
162 }
163
164 /// Pop and merge with the last backup.
165 ///
166 /// Does nothing if the substate has no backup.
167 pub fn commit_backup(&mut self) {
168 if let Some(parent) = self.parent.as_mut() {
169 let mut delta = mem::take(parent);
170 mem::swap(self, &mut delta);
171
172 self.selfdestruct_set.extend(delta.selfdestruct_set);
173 self.accessed_addresses.extend(delta.accessed_addresses);
174 for (address, slot_set) in delta.accessed_storage_slots {
175 self.accessed_storage_slots
176 .entry(address)
177 .or_default()
178 .extend(slot_set);
179 }
180 self.created_accounts.extend(delta.created_accounts);
181 self.refunded_gas = delta.refunded_gas;
182 self.transient_storage.extend(delta.transient_storage);
183 self.logs.extend(delta.logs);
184 }
185 }
186
187 /// Discard current changes and revert to last backup.
188 ///
189 /// Does nothing if the substate has no backup.
190 pub fn revert_backup(&mut self) {
191 if let Some(parent) = self.parent.as_mut() {
192 *self = mem::take(parent);
193 }
194 }
195
196 /// Return an iterator over all selfdestruct addresses.
197 pub fn iter_selfdestruct(&self) -> impl Iterator<Item = &Address> {
198 struct Iter<'a> {
199 parent: Option<&'a Substate>,
200 iter: std::collections::hash_set::Iter<'a, Address>,
201 }
202
203 impl<'a> Iterator for Iter<'a> {
204 type Item = &'a Address;
205
206 fn next(&mut self) -> Option<Self::Item> {
207 let next_item = self.iter.next();
208 if next_item.is_none()
209 && let Some(parent) = self.parent
210 {
211 self.parent = parent.parent.as_deref();
212 self.iter = parent.selfdestruct_set.iter();
213
214 return self.next();
215 }
216
217 next_item
218 }
219 }
220
221 Iter {
222 parent: self.parent.as_deref(),
223 iter: self.selfdestruct_set.iter(),
224 }
225 }
226
227 /// Mark an address as selfdestructed and return whether is was already marked.
228 pub fn add_selfdestruct(&mut self, address: Address) -> bool {
229 if self.selfdestruct_set.contains(&address) {
230 return true;
231 }
232
233 let is_present = self
234 .parent
235 .as_ref()
236 .map(|parent| parent.is_selfdestruct(&address))
237 .unwrap_or_default();
238
239 is_present || !self.selfdestruct_set.insert(address)
240 }
241
242 /// Return whether an address is already marked as selfdestructed.
243 pub fn is_selfdestruct(&self, address: &Address) -> bool {
244 self.selfdestruct_set.contains(address)
245 || self
246 .parent
247 .as_ref()
248 .map(|parent| parent.is_selfdestruct(address))
249 .unwrap_or_default()
250 }
251
252 /// Build an access list from all accessed storage slots.
253 pub fn make_access_list(&self) -> Vec<AccessListEntry> {
254 let mut entries = BTreeMap::<Address, BTreeSet<H256>>::new();
255
256 let mut current = self;
257 loop {
258 for (address, slot_set) in ¤t.accessed_storage_slots {
259 entries
260 .entry(*address)
261 .or_default()
262 .extend(slot_set.iter().copied());
263 }
264
265 current = match current.parent.as_deref() {
266 Some(x) => x,
267 None => break,
268 };
269 }
270
271 entries
272 .into_iter()
273 .map(|(address, storage_keys)| AccessListEntry {
274 address,
275 storage_keys: storage_keys.into_iter().collect(),
276 })
277 .collect()
278 }
279
280 /// Mark an address as accessed and return whether the slot was cold.
281 pub fn add_accessed_slot(&mut self, address: Address, key: H256) -> bool {
282 if self
283 .accessed_storage_slots
284 .get(&address)
285 .is_some_and(|set| set.contains(&key))
286 {
287 return false;
288 }
289
290 let is_present = self
291 .parent
292 .as_ref()
293 .map(|parent| parent.is_slot_accessed(&address, &key))
294 .unwrap_or_default();
295
296 // Note: Do not simplify this expression, it uses `||` to avoid executing the right hand
297 // expression if not necessary.
298 #[expect(clippy::nonminimal_bool, reason = "order of evaluation matters")]
299 !(is_present
300 || !self
301 .accessed_storage_slots
302 .entry(address)
303 .or_default()
304 .insert(key))
305 }
306
307 /// Return whether an address has already been accessed.
308 pub fn is_slot_accessed(&self, address: &Address, key: &H256) -> bool {
309 self.accessed_storage_slots
310 .get(address)
311 .map(|slot_set| slot_set.contains(key))
312 .unwrap_or_default()
313 || self
314 .parent
315 .as_ref()
316 .map(|parent| parent.is_slot_accessed(address, key))
317 .unwrap_or_default()
318 }
319
320 /// Returns all accessed storage slots for a given address.
321 /// Used by SELFDESTRUCT to record storage reads in BAL per EIP-7928:
322 /// "SELFDESTRUCT: Include modified/read storage keys as storage_read"
323 pub fn get_accessed_storage_slots(&self, address: &Address) -> BTreeSet<H256> {
324 let mut slots = BTreeSet::new();
325
326 // Collect from current substate
327 if let Some(slot_set) = self.accessed_storage_slots.get(address) {
328 slots.extend(slot_set.iter().copied());
329 }
330
331 // Collect from parent substates recursively
332 if let Some(parent) = self.parent.as_ref() {
333 slots.extend(parent.get_accessed_storage_slots(address));
334 }
335
336 slots
337 }
338
339 /// Mark an address as accessed and return whether the address was cold.
340 pub fn add_accessed_address(&mut self, address: Address) -> bool {
341 // Precompiles are warm from tx start (EIP-2929) without occupying a hashset slot. Returns
342 // `false` (not cold) so cold-access gas is never charged — identical to the old pre-seed.
343 if self.is_warm_precompile(&address) {
344 return false;
345 }
346
347 if self.accessed_addresses.contains(&address) {
348 return false;
349 }
350
351 let is_present = self
352 .parent
353 .as_ref()
354 .map(|parent| parent.is_address_accessed(&address))
355 .unwrap_or_default();
356
357 // Note: Do not simplify this expression, it uses `||` to avoid executing the right hand
358 // expression if not necessary.
359 #[expect(clippy::nonminimal_bool, reason = "order of evaluation matters")]
360 !(is_present || !self.accessed_addresses.insert(address))
361 }
362
363 /// Return whether an address has already been accessed.
364 pub fn is_address_accessed(&self, address: &Address) -> bool {
365 // Precompiles are always warm; the chain shares one `fork`, so this is consistent across
366 // sub-frame substates.
367 self.is_warm_precompile(address)
368 || self.accessed_addresses.contains(address)
369 || self
370 .parent
371 .as_ref()
372 .map(|parent| parent.is_address_accessed(address))
373 .unwrap_or_default()
374 }
375
376 /// Mark an address as a new account and return whether is was already marked.
377 pub fn add_created_account(&mut self, address: Address) -> bool {
378 if self.created_accounts.contains(&address) {
379 return true;
380 }
381
382 let is_present = self
383 .parent
384 .as_ref()
385 .map(|parent| parent.is_account_created(&address))
386 .unwrap_or_default();
387
388 is_present || !self.created_accounts.insert(address)
389 }
390
391 /// Return whether an address has already been marked as a new account.
392 pub fn is_account_created(&self, address: &Address) -> bool {
393 self.created_accounts.contains(address)
394 || self
395 .parent
396 .as_ref()
397 .map(|parent| parent.is_account_created(address))
398 .unwrap_or_default()
399 }
400
401 /// Return the data associated with a transient storage entry, or zero if not present.
402 pub fn get_transient(&self, to: &Address, key: &U256) -> U256 {
403 self.transient_storage
404 .get(&(*to, *key))
405 .copied()
406 .unwrap_or_else(|| {
407 self.parent
408 .as_ref()
409 .map(|parent| parent.get_transient(to, key))
410 .unwrap_or_default()
411 })
412 }
413
414 /// Return the data associated with a transient storage entry, or zero if not present.
415 pub fn set_transient(&mut self, to: &Address, key: &U256, value: U256) {
416 self.transient_storage.insert((*to, *key), value);
417 }
418
419 /// Clear all transient storage (used between frames in frame transactions).
420 pub fn clear_transient_storage(&mut self) {
421 self.transient_storage.clear();
422 }
423
424 /// Extract all logs in order.
425 pub fn extract_logs(&self) -> Vec<Log> {
426 fn inner(substrate: &Substate, target: &mut Vec<Log>) {
427 if let Some(parent) = substrate.parent.as_deref() {
428 inner(parent, target);
429 }
430
431 target.extend_from_slice(&substrate.logs);
432 }
433
434 let mut logs = Vec::new();
435 inner(self, &mut logs);
436
437 logs
438 }
439
440 /// Return a clone of the current sub-substate's logs only, excluding parent logs.
441 /// Used by EIP-8141 frame execution to capture per-frame log deltas for
442 /// `frame_receipts[i].logs`. Must be called after `push_backup()` and before
443 /// `commit_backup()` to return only the logs emitted during the current scope.
444 pub fn current_logs(&self) -> Vec<Log> {
445 self.logs.clone()
446 }
447
448 /// Number of logs in the current scope, without cloning them. Used to slice
449 /// out a single frame's logs after `run_execution` has already committed the
450 /// frame's backup up into this scope.
451 pub fn logs_len(&self) -> usize {
452 self.logs.len()
453 }
454
455 /// Push a log record.
456 pub fn add_log(&mut self, log: Log) {
457 self.logs.push(log);
458 }
459}
460
461/// The LEVM (Lambda EVM) execution engine.
462///
463/// The VM executes Ethereum transactions by processing EVM bytecode. It maintains
464/// a call stack, memory, and tracks all state changes during execution.
465///
466/// # Execution Model
467///
468/// 1. Transaction is validated (nonce, balance, gas limit)
469/// 2. Initial call frame is created with transaction data
470/// 3. Opcodes are executed sequentially until completion or error
471/// 4. State changes are committed or reverted based on success
472///
473/// # Call Stack
474///
475/// Nested calls (CALL, DELEGATECALL, etc.) push new frames onto `call_frames`.
476/// Each frame has its own memory, stack, and execution context. The `current_call_frame`
477/// is always the active frame being executed.
478///
479/// # Hooks
480///
481/// The VM supports hooks for extending functionality (e.g., tracing, debugging).
482/// Hooks are called at various points during execution and implement pre/post-execution
483/// logic. L2-specific behavior (such as fee handling) is implemented via hooks.
484///
485/// # Example
486///
487/// ```ignore
488/// let mut vm = VM::new(env, db, &tx, tracer, vm_type, &NativeCrypto);
489/// let report = vm.execute()?;
490/// if report.is_success() {
491/// println!("Gas used: {}, Output: {:?}", report.gas_used, report.output);
492/// } else {
493/// println!("Transaction reverted");
494/// }
495/// ```
496/// EIP-8141 §Behavior: the top-level `frame.value` transfer
497/// reverts the frame if the sender's balance is strictly less than the
498/// amount being sent. Factored out so the decision can be unit-tested
499/// without bringing up a full VM state.
500pub fn frame_value_exceeds_balance(sender_balance: U256, frame_value: U256) -> bool {
501 sender_balance < frame_value
502}
503
504/// Context for frame transaction (EIP-8141) execution.
505/// This is set when executing a frame transaction and is used by
506/// APPROVE, TXPARAM, FRAMEDATALOAD, and FRAMEDATACOPY opcodes.
507#[derive(Debug, Clone)]
508pub struct FrameTxContext {
509 /// Whether the sender has approved (APPROVE scope `APPROVE_EXECUTION` or
510 /// `APPROVE_EXECUTION_AND_PAYMENT`).
511 pub sender_approved: bool,
512 /// The address that approved payment, set by `APPROVE_PAYMENT` or
513 /// `APPROVE_EXECUTION_AND_PAYMENT`. Per the latest EIP-8141 spec this is the
514 /// single source of truth for whether payment has been approved: when this
515 /// is `Some(_)`, the transaction has a `payer`; when `None`, it does not.
516 pub payer_address: Option<Address>,
517 /// Per-frame execution results (status, gas_used, logs).
518 /// `status` is a `FRAME_RECEIPT_STATUS_*` code (0 = failure, 1 = success,
519 /// 3 = skipped due to failed atomic batch).
520 pub frame_results: Vec<(u8, u64, Vec<Log>)>,
521 /// Index of the currently executing frame
522 pub current_frame_index: usize,
523 /// The sig_hash of the frame transaction
524 pub sig_hash: H256,
525 /// The full frame transaction (for TXPARAM access)
526 pub tx: ethrex_common::types::FrameTransaction,
527 /// Whether APPROVE was called in the current frame
528 pub approve_called_in_current_frame: bool,
529 /// Cached `FrameTransaction::max_gas()`. Computing it re-encodes every frame
530 /// and signature, so it must not run per-opcode (TXPARAM 0x06,
531 /// compute_tx_max_cost). Computed once at tx entry.
532 pub max_gas: u64,
533 /// The block's EIP-4844 blob base fee, captured at tx entry. `max_cost`
534 /// collects the blob fee at this rate, not at `max_fee_per_blob_gas`
535 /// (EIP-8141 §Gas accounting), and `load_tx_param` has no `Environment`
536 /// handle to read it from.
537 pub blob_base_fee: U256,
538}
539
540impl FrameTxContext {
541 /// Capture the approval state at atomic-batch entry. A batch revert rolls
542 /// back the payer's balance deduction and the sender nonce increment, so
543 /// approvals granted inside the batch must be rolled back with it —
544 /// otherwise a reverted APPROVE would leave the transaction authorized
545 /// by a frame whose effects no longer exist.
546 pub fn approval_snapshot(&self) -> (bool, Option<Address>) {
547 (self.sender_approved, self.payer_address)
548 }
549
550 /// Restore the approval state captured by `approval_snapshot` when the
551 /// enclosing atomic batch reverts. Approvals granted before the batch
552 /// are unaffected (the snapshot includes them).
553 pub fn restore_approvals(&mut self, snapshot: (bool, Option<Address>)) {
554 let (sender_approved, payer_address) = snapshot;
555 self.sender_approved = sender_approved;
556 self.payer_address = payer_address;
557 }
558}
559
560/// Snapshot of `call_frame_backup`'s key-space taken by [`VM::enter_prepare_region`]
561/// at the start of the atomic prepare region (EIP-8037 auth + prepare-dispatch
562/// charges). `original_accounts_info` / `original_account_storage_slots` are
563/// first-write-wins maps keyed by address, so a plain entry-count marker can't
564/// tell which keys are region-added; recording the pre-region key sets lets
565/// [`VM::fail_prepare_region`] revert exactly the region's writes while leaving
566/// the earlier sender nonce-bump / fee-deduction backup entries intact.
567/// `inserted_code_hashes` is an append-only `Vec`, so its pre-region length is
568/// enough to identify the region-added tail.
569#[derive(Debug, Default)]
570pub struct PrepareRegionBackupMarker {
571 /// Addresses already backed up in `original_accounts_info` before the region.
572 accounts: SeededHashSet<Address>,
573 /// Addresses already backed up in `original_account_storage_slots` before the region.
574 storage: SeededHashSet<Address>,
575 /// Length of `inserted_code_hashes` before the region.
576 code_hashes_len: usize,
577 /// Region-entry state of every account already backed up before the region
578 /// (notably the sender, post-fee/post-nonce). The marker excludes these from
579 /// the region rollback to preserve their pre-region writes, but first-write-wins
580 /// backup means an in-region write to one of them (e.g. a self-sponsored EIP-7702
581 /// authorization on the sender) leaves no new backup entry. `fail_prepare_region`
582 /// restores these to the captured state, reverting the in-region write while
583 /// keeping the pre-region nonce bump / fee deduction.
584 entry_state: SeededHashMap<Address, LevmAccount>,
585 /// BAL recorder checkpoint at region entry, so an applied-then-reverted
586 /// delegation's code/nonce changes are discarded (demoted to an access-only
587 /// touch) rather than leaking into the block access list.
588 bal_checkpoint: Option<BlockAccessListCheckpoint>,
589}
590
591/// Result of [`VM::simulate_validation_prefix`] (EIP-8141 mempool simulation).
592#[derive(Debug, Clone)]
593pub struct PrefixSimResult {
594 /// Whether any prefix frame reverted (fatal for validation).
595 pub any_revert: bool,
596 /// The payer established by the prefix, if any.
597 pub payer_address: Option<Address>,
598 /// Whether the sender was approved by a verify/pay frame.
599 pub sender_approved: bool,
600 /// Total simulated gas used across the prefix frames.
601 pub total_gas_used: u64,
602}
603
604pub struct VM<'a> {
605 /// Stack of parent call frames (for nested calls).
606 pub call_frames: Vec<CallFrame>,
607 /// The currently executing call frame.
608 pub current_call_frame: CallFrame,
609 /// Block and transaction environment.
610 pub env: Environment,
611 /// Whether transaction fees must cover the block base fee.
612 pub validate_base_fee: bool,
613 /// Execution substate (accessed addresses, logs, refunds, etc.).
614 pub substate: Substate,
615 /// Database for reading/writing account state.
616 pub db: &'a mut GeneralizedDatabase,
617 /// The transaction being executed. Borrowed for the VM's lifetime (the caller owns it for at
618 /// least that long), avoiding a per-tx deep clone of the access/authorization lists.
619 pub tx: &'a Transaction,
620 /// Execution hooks for tracing and debugging.
621 pub hooks: Vec<Rc<RefCell<dyn Hook>>>,
622 /// Original storage values before transaction (for SSTORE gas calculation),
623 /// keyed first by account to avoid hashing the full tuple on each access.
624 /// Seeded: contracts choose the keys at both levels.
625 pub storage_original_values: SeededHashMap<Address, SeededHashMap<H256, U256>>,
626 /// Call tracer for execution tracing.
627 pub tracer: LevmCallTracer,
628 /// Opcode (EIP-3155) tracer. Disabled by default; zero overhead when inactive.
629 pub opcode_tracer: LevmOpcodeTracer,
630 /// EIP-8141 mempool validation-trace observer. Disabled by default; active
631 /// only during `simulate_frame_validation_prefix`. Read only behind
632 /// `if self.validation_observer.active`, so an inactive observer adds one
633 /// branch to the dispatch loop and nothing more (mirrors `opcode_tracer`).
634 pub validation_observer: ValidationObserver,
635 /// Debug mode for development diagnostics.
636 pub debug_mode: DebugMode,
637 /// Pool of reusable stacks to reduce allocations.
638 pub stack_pool: Vec<Stack>,
639 /// Pool of reusable initcode buffers for CREATE frames. A buffer returns here when its
640 /// frame ends, so a contract that issues many CREATEs reuses one allocation instead of
641 /// copying its initcode into a fresh one each time. Inside zkVM guests whose bump
642 /// allocators never free, those fresh copies are never reclaimed and exhaust the heap.
643 pub initcode_pool: Vec<InitcodeBuffer>,
644 /// VM type (L1 or L2 with fee config).
645 pub vm_type: VMType,
646 /// Frame transaction context (EIP-8141). Set when executing a frame tx.
647 pub frame_tx_context: Option<FrameTxContext>,
648
649 /// Whether the top-level call-frame backup must be PRESERVED (deep-cloned) on the
650 /// revert / invalid-tx paths because a `BackupHook` will read it in `finalize_execution`
651 /// to build the tx-level undo snapshot. Derived from the installed `hooks` (via
652 /// [`Hook::reads_top_level_backup`]) rather than from `vm_type`, so it stays correct if
653 /// hook wiring changes; `add_hook` keeps it in sync for the `BackupHook` that
654 /// `stateless_execute` installs after construction. False for normal L1 block execution
655 /// (no `BackupHook`), where the backup is dead once the cache is restored and can be moved
656 /// out instead of cloned.
657 pub(crate) preserve_top_level_backup: bool,
658 /// EIP-8037: Accumulated state gas for this transaction (Amsterdam+).
659 /// Signed: goes negative when inline refunds exceed gross charges in the local frame
660 /// (e.g. SSTORE 0→x→0 restoration matching an ancestor's charge).
661 pub state_gas_used: i64,
662 /// EIP-8037: State gas reservoir pre-funded from excess gas_limit (Amsterdam+).
663 pub state_gas_reservoir: u64,
664 /// EIP-8037: Initial reservoir at tx start (before any execution). Captured in
665 /// add_intrinsic_gas so block-dimensional regular gas can be computed
666 /// independently of mid-tx reservoir activity (auth refunds, SSTORE credits).
667 pub state_gas_reservoir_initial: u64,
668 /// EIP-8037: Cumulative state gas that spilled to regular gas during execution
669 /// (when reservoir was insufficient). Subtracted when computing dimensional
670 /// regular gas for block accounting — EELS charge_state_gas spills don't
671 /// increment regular_gas_used.
672 pub state_gas_spill: u64,
673 /// EIP-8037: Dynamic cost per state byte (computed from block_gas_limit, Amsterdam+).
674 pub cost_per_state_byte: u64,
675 /// EIP-8037: State gas for new account creation (STATE_BYTES_PER_NEW_ACCOUNT * cost_per_state_byte).
676 pub state_gas_new_account: u64,
677 /// EIP-8037: State gas for storage slot creation (STATE_BYTES_PER_STORAGE_SET * cost_per_state_byte).
678 pub state_gas_storage_set: u64,
679 /// EIP-8037: State gas for the 23-byte EIP-7702 delegation indicator
680 /// (STATE_BYTES_PER_AUTH_BASE * cost_per_state_byte). Charged in-region by
681 /// `eip7702_set_access_code` (EELS `set_delegation`) once per authority when a
682 /// net-new delegation indicator is written, and never credited back.
683 pub state_gas_auth_base: u64,
684 /// EIP-8037: intrinsic state gas (`tx_env.intrinsic_state_gas` in EELS). Captured at
685 /// `add_intrinsic_gas` time. ethrex lumps intrinsic + execution into `state_gas_used`,
686 /// so on top-level error this field is what we leave behind when refunding the
687 /// execution portion to the reservoir — block accounting then bills the intrinsic
688 /// (matches EELS `tx_state_gas = intrinsic_state_gas + tx_output.state_gas_used`).
689 pub intrinsic_state_gas: u64,
690 /// EIP-8037: set by `prepare_execution` when the in-region value-to-not-alive
691 /// `NEW_ACCOUNT` charge fires (a value-bearing call to a not-yet-alive
692 /// recipient). Consumed once, at the top of `run_execution`, to decide
693 /// whether an Amsterdam precompile-halt must roll the charge back (the
694 /// recipient never materializes on halt).
695 pub value_new_account_charged: bool,
696 /// EIP-8037: `current_call_frame.state_gas_used_at_entry` captured by
697 /// `enter_prepare_region` right before the atomic prepare region (EIP-7702
698 /// auth + prepare-dispatch charges) begins. `fail_prepare_region` rewinds the
699 /// frame's `state_gas_used` back to this pre-region baseline on an internal OOG,
700 /// mirroring EELS `restore_tx_state(prep_snapshot)`.
701 pub prep_baseline_state_gas: i64,
702 /// EIP-8037: `state_gas_reservoir` captured by `enter_prepare_region`. The
703 /// `set_delegation` auth lock-in zeroes the frame spill, so `fail_prepare_region`
704 /// cannot reconstruct the pre-region reservoir from `refill_frame_state_gas`
705 /// arithmetic; it restores this captured value directly (EELS
706 /// `message.state_gas_reservoir = prep_reservoir`).
707 pub prep_baseline_reservoir: u64,
708 /// EIP-8037: cumulative `state_gas_spill` captured by `enter_prepare_region`, so
709 /// `fail_prepare_region` restores block-accounting spill to its pre-region value
710 /// (the region's spilled state gas is fully rolled back / burned as regular).
711 pub prep_baseline_state_gas_spill: u64,
712 /// EIP-8037: pre-region key-space snapshot of `call_frame_backup`, recorded by
713 /// `enter_prepare_region`. Lets `fail_prepare_region` revert only region-added
714 /// writes, leaving the sender nonce-bump / fee-deduction entries intact.
715 pub prep_region_backup_marker: PrepareRegionBackupMarker,
716 /// EIP-8037: set by `fail_prepare_region` when an internal OOG rolls back the
717 /// atomic prepare region. Consumed by `run_execution`, which turns it into a
718 /// full-gas revert `ContextResult` (mirrors EELS depth-0
719 /// `except ExceptionalHalt: evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`)
720 /// instead of a tx-level rejection `Err` that would wrongly invalidate the block.
721 pub pending_prep_oog: bool,
722 /// The opcode table mapping opcodes to opcode handlers for fast lookup.
723 /// A shared `&'static` reference to a per-fork table that is `const`-built once for the
724 /// whole process (immutable), so each VM holds only a pointer instead of a 2 KB inline copy.
725 pub(crate) opcode_table: &'static [OpCodeFn; 256],
726 /// Crypto provider for cryptographic operations.
727 pub crypto: &'a dyn Crypto,
728 /// Optional stateless validator for the EXECUTE precompile.
729 /// `None` on VMs that never dispatch EXECUTE (guest program, witness
730 /// generation, the stateless validator itself) — those paths can't supply
731 /// one without a dependency cycle or recursion.
732 pub stateless_validator: Option<&'a dyn crate::StatelessValidator>,
733}
734
735/// secp256k1 group order `n`.
736const SECP256K1_N: [u8; 32] = [
737 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
738 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41,
739];
740/// secp256k1 `n / 2`.
741const SECP256K1_N_HALF: [u8; 32] = [
742 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
743 0x5d, 0x57, 0x6e, 0x73, 0x57, 0xa4, 0x50, 0x1d, 0xdf, 0xe9, 0x2f, 0x46, 0x68, 0x1b, 0x20, 0xa0,
744];
745/// P-256 (secp256r1) group order `n`.
746const SECP256R1_N: [u8; 32] = [
747 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
748 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,
749];
750/// P-256 (secp256r1) `n / 2`.
751const SECP256R1_N_HALF: [u8; 32] = [
752 0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
753 0xde, 0x73, 0x7d, 0x56, 0xd3, 0x8b, 0xcf, 0x42, 0x79, 0xdc, 0xe5, 0x61, 0x7e, 0x31, 0x92, 0xa8,
754];
755
756/// True when the big-endian 32-byte scalar is in `(0, upper)`.
757fn scalar_below(scalar: &[u8], upper: &[u8; 32]) -> bool {
758 scalar.iter().any(|&b| b != 0) && scalar < &upper[..]
759}
760
761/// True when the big-endian 32-byte scalar is in `(0, upper]`.
762fn scalar_at_most(scalar: &[u8], upper: &[u8; 32]) -> bool {
763 scalar.iter().any(|&b| b != 0) && scalar <= &upper[..]
764}
765
766/// Validate every EIP-8141 outer signature against the canonical `sig_hash`.
767/// Returns false if any signature is malformed or invalid. Verification gas is
768/// intrinsic (already in `standard_gas_limit`), so a scratch budget is used for the
769/// crypto precompiles and their deduction is ignored.
770#[expect(
771 clippy::indexing_slicing,
772 reason = "signature length is checked before each fixed-offset slice"
773)]
774pub fn validate_frame_signatures(
775 signatures: &[ethrex_common::types::FrameSignature],
776 sig_hash: ethrex_common::H256,
777 sender: ethrex_common::Address,
778 fork: Fork,
779 crypto: &dyn Crypto,
780) -> bool {
781 use ethrex_common::types::{
782 FRAME_SIG_SCHEME_ARBITRARY, FRAME_SIG_SCHEME_P256, FRAME_SIG_SCHEME_SECP256K1,
783 };
784 for sig in signatures {
785 // Resolve the signed message.
786 let msg: [u8; 32] = match sig.msg.len() {
787 0 => sig_hash.0,
788 32 => {
789 let mut m = [0u8; 32];
790 m.copy_from_slice(&sig.msg);
791 if m == [0u8; 32] {
792 return false;
793 }
794 m
795 }
796 _ => return false,
797 };
798 let mut scratch_gas = u64::MAX;
799 match sig.scheme {
800 FRAME_SIG_SCHEME_SECP256K1 => {
801 if sig.signature.len() != 65 {
802 return false;
803 }
804 let v = sig.signature[0];
805 let r = &sig.signature[1..33];
806 let s = &sig.signature[33..65];
807 // EIP-8141 requires a canonical signature: `v` is a bare recovery
808 // id (0 or 1), `0 < r < n`, and low-s per EIP-2 (`0 < s <= n/2`),
809 // so each signature has exactly one encoding.
810 if v > 1 || !scalar_below(r, &SECP256K1_N) || !scalar_at_most(s, &SECP256K1_N_HALF)
811 {
812 return false;
813 }
814 // The ecrecover precompile takes `v` in EVM form (27 or 28).
815 let mut calldata = vec![0u8; 128];
816 calldata[..32].copy_from_slice(&msg);
817 calldata[63] = v.saturating_add(27);
818 calldata[64..96].copy_from_slice(r);
819 calldata[96..128].copy_from_slice(s);
820 let Ok(result) =
821 crate::precompiles::ecrecover(&calldata, &mut scratch_gas, fork, crypto)
822 else {
823 return false;
824 };
825 if result.len() != 32 {
826 return false;
827 }
828 let recovered = ethrex_common::Address::from_slice(&result[12..]);
829 if recovered == ethrex_common::Address::zero() {
830 return false;
831 }
832 // Per EIP-8141, an absent signer resolves to tx.sender (used for
833 // introspection too); the recovered key must equal the resolved signer.
834 if recovered != sig.signer.unwrap_or(sender) {
835 return false;
836 }
837 }
838 FRAME_SIG_SCHEME_P256 => {
839 if sig.signature.len() != 128 {
840 return false;
841 }
842 let r = &sig.signature[0..32];
843 let s = &sig.signature[32..64];
844 let qx = &sig.signature[64..96];
845 let qy = &sig.signature[96..128];
846 // EIP-8141 requires `0 < r < n` and low-s (`0 < s <= n/2`) so each
847 // signature has one encoding. P256VERIFY itself accepts high-s, so
848 // signers must normalize `s` to `n - s` before use.
849 if !scalar_below(r, &SECP256R1_N) || !scalar_at_most(s, &SECP256R1_N_HALF) {
850 return false;
851 }
852 // signer = keccak256(qx || qy)[12:] (NO domain separator)
853 let mut pk = Vec::with_capacity(64);
854 pk.extend_from_slice(qx);
855 pk.extend_from_slice(qy);
856 let h = ethrex_crypto::keccak::keccak_hash(&pk);
857 // Per EIP-8141, an absent signer resolves to tx.sender (used for
858 // introspection too); the derived key must equal the resolved signer.
859 if ethrex_common::Address::from_slice(&h[12..]) != sig.signer.unwrap_or(sender) {
860 return false;
861 }
862 let mut calldata = vec![0u8; 160];
863 calldata[..32].copy_from_slice(&msg);
864 calldata[32..64].copy_from_slice(r);
865 calldata[64..96].copy_from_slice(s);
866 calldata[96..128].copy_from_slice(qx);
867 calldata[128..160].copy_from_slice(qy);
868 let Ok(result) =
869 crate::precompiles::p_256_verify(&calldata, &mut scratch_gas, fork, crypto)
870 else {
871 return false;
872 };
873 if result.len() != 32 || result[31] != 1 {
874 return false;
875 }
876 }
877 FRAME_SIG_SCHEME_ARBITRARY => {
878 // ARBITRARY: no protocol crypto; the signer must be empty. A
879 // custom verifier reads the raw bytes via SIGPARAM 0x04.
880 if sig.signer.is_some() {
881 return false;
882 }
883 }
884 _ => return false,
885 }
886 }
887 true
888}
889
890/// Find the end of the atomic batch containing `failed_idx`, per EIP-8141:
891/// a batch is a maximal contiguous run of frames whose ATOMIC_BATCH_FLAG is
892/// set, terminated by the first frame without the flag. Static validation
893/// guarantees no VERIFY frame carries the flag or terminates a batch, so every
894/// frame in the returned range is DEFAULT or SENDER. Returns the index of the
895/// batch's terminating frame.
896///
897/// Exposed (hidden) for the `ethrex-test` crate's frame-batch unit tests; not
898/// part of the stable public API.
899#[doc(hidden)]
900pub fn find_batch_end(frames: &[Frame], failed_idx: usize) -> usize {
901 frames
902 .get(failed_idx..)
903 .and_then(|rest| rest.iter().position(|f| !f.is_atomic_batch()))
904 .map(|offset| failed_idx.saturating_add(offset))
905 .unwrap_or(failed_idx)
906}
907
908impl<'a> VM<'a> {
909 /// Constructs a VM, allocating a fresh 32 KB root call-frame stack.
910 ///
911 /// Hot block execution should prefer [`VM::new_pooled`], which draws the root stack from a
912 /// reusable pool instead of allocating + zeroing one per transaction.
913 pub fn new(
914 env: Environment,
915 db: &'a mut GeneralizedDatabase,
916 tx: &'a Transaction,
917 tracer: LevmCallTracer,
918 vm_type: VMType,
919 crypto: &'a dyn Crypto,
920 stateless_validator: Option<&'a dyn crate::StatelessValidator>,
921 ) -> Result<Self, VMError> {
922 Self::new_with_root_stack(
923 env,
924 db,
925 tx,
926 tracer,
927 vm_type,
928 crypto,
929 stateless_validator,
930 Stack::default(),
931 Memory::default(),
932 )
933 }
934
935 /// Like [`VM::new`], but draws the root call-frame stack from `stack_pool` (falling back to a
936 /// fresh `Stack::default()` only when the pool is empty) and adopts the remaining pooled
937 /// stacks for sub-call frames. This avoids the per-tx 32 KB stack alloc+zero on a warm pool —
938 /// the dominant allocation for transfer-heavy blocks, where the root frame is the only frame.
939 ///
940 /// It also adopts `initcode_pool` as the VM's pool of CREATE initcode buffers, so a
941 /// transaction reuses the buffers an earlier one left.
942 ///
943 /// Pair with [`VM::reclaim_into`] after execution to return every stack (root + sub-frame)
944 /// to `stack_pool`, the root memory buffer to `memory_pool` and the initcode buffers to
945 /// `initcode_pool`, so the next tx reuses them.
946 #[allow(clippy::too_many_arguments)]
947 pub fn new_pooled(
948 env: Environment,
949 db: &'a mut GeneralizedDatabase,
950 tx: &'a Transaction,
951 tracer: LevmCallTracer,
952 vm_type: VMType,
953 crypto: &'a dyn Crypto,
954 stateless_validator: Option<&'a dyn crate::StatelessValidator>,
955 stack_pool: &mut Vec<Stack>,
956 memory_pool: &mut Vec<Memory>,
957 initcode_pool: &mut Vec<InitcodeBuffer>,
958 ) -> Result<Self, VMError> {
959 // Reuse a pooled stack for the root frame. `clear()` only resets the offset (no zeroing),
960 // which is sound because the EVM never reads stack slots it didn't write — the same
961 // invariant that already makes sub-frame pooling safe.
962 let mut root_stack = stack_pool.pop().unwrap_or_default();
963 root_stack.clear();
964 // Reuse a pooled root memory buffer (capacity retained from a prior tx, contents dropped).
965 // `reclaim_into` truncates it to length 0, so `resize`'s zero-fill invariant holds. Only
966 // the root buffer is pooled: sub-frame memories are `Rc` clones of it (`next_memory`).
967 let mut root_memory = memory_pool.pop().unwrap_or_default();
968 root_memory.reset_for_reuse();
969 let mut vm = Self::new_with_root_stack(
970 env,
971 db,
972 tx,
973 tracer,
974 vm_type,
975 crypto,
976 stateless_validator,
977 root_stack,
978 root_memory,
979 )?;
980 // Adopt the caller's pooled stacks for sub-frames; returned via `reclaim_into`.
981 mem::swap(&mut vm.stack_pool, stack_pool);
982 // Likewise the initcode buffers. A pool that started empty with every transaction would
983 // make each one allocate its buffers afresh and drop them with its VM, which a zkVM
984 // guest's bump allocator never reclaims.
985 mem::swap(&mut vm.initcode_pool, initcode_pool);
986 Ok(vm)
987 }
988
989 /// Returns this VM's reusable buffers to the caller's pools so the next transaction reuses
990 /// them instead of allocating: every stack (root call-frame stack plus any sub-frame stacks
991 /// still pooled internally) to `stack_pool`, the root memory buffer to `memory_pool`, and the
992 /// pooled initcode buffers to `initcode_pool`.
993 /// Must run on both the success and error paths of [`VM::execute`].
994 pub fn reclaim_into(
995 mut self,
996 stack_pool: &mut Vec<Stack>,
997 memory_pool: &mut Vec<Memory>,
998 initcode_pool: &mut Vec<InitcodeBuffer>,
999 ) {
1000 // Hand the internal sub-frame pool back to the caller first.
1001 mem::swap(&mut self.stack_pool, stack_pool);
1002 mem::swap(&mut self.initcode_pool, initcode_pool);
1003 // Then reclaim the root frame's stack. Moving it out by value (VM/CallFrame have no Drop)
1004 // avoids leaving a fresh 32 KB `Stack::default()` placeholder behind — which a
1005 // `mem::take`/`mem::replace` against an empty pool would force, defeating the win on
1006 // exactly the transfer-only blocks (no sub-frames ever seed the pool) we target.
1007 let mut root_stack = self.current_call_frame.stack;
1008 root_stack.clear();
1009 stack_pool.push(root_stack);
1010 // Reclaim the root memory buffer with its grown capacity. `reset_for_reuse` truncates it
1011 // to length 0 (capacity kept) so the next tx's `resize` zero-fills correctly.
1012 //
1013 // Every call frame shares the same `Rc<RefCell<Vec<u8>>>` buffer, so on the error path the
1014 // ancestor frames left in `call_frames` (error propagation unwinds out of `execute` without
1015 // popping them) still hold clones. Drop them first so the buffer is `Rc`-unique on BOTH
1016 // paths before we clear it — otherwise the clear would propagate to a frame still holding a
1017 // reference. `CallFrame` has no `Drop` and these frames are never read again, so dropping
1018 // them early is free. The frame left current on the error path may be a callee whose
1019 // arguments are a view of the buffer (`CallData`), which holds a clone as well.
1020 self.call_frames.clear();
1021 self.current_call_frame.calldata = CallData::default();
1022 let mut root_memory = self.current_call_frame.memory;
1023 debug_assert_eq!(
1024 Rc::strong_count(&root_memory.buffer),
1025 1,
1026 "root memory buffer must be Rc-unique at reclaim; a frame is still holding it and \
1027 would observe the reset_for_reuse clear",
1028 );
1029 root_memory.reset_for_reuse();
1030 memory_pool.push(root_memory);
1031 }
1032
1033 #[allow(clippy::too_many_arguments)]
1034 fn new_with_root_stack(
1035 env: Environment,
1036 db: &'a mut GeneralizedDatabase,
1037 tx: &'a Transaction,
1038 tracer: LevmCallTracer,
1039 vm_type: VMType,
1040 crypto: &'a dyn Crypto,
1041 stateless_validator: Option<&'a dyn crate::StatelessValidator>,
1042 root_stack: Stack,
1043 root_memory: Memory,
1044 ) -> Result<Self, VMError> {
1045 db.tx_backup = None; // If BackupHook is enabled, it will contain backup at the end of tx execution.
1046
1047 let mut substate = Substate::initialize(&env, tx)?;
1048
1049 let (callee, is_create) = Self::get_tx_callee(tx, db, &env, &mut substate)?;
1050
1051 let fork = env.config.fork;
1052
1053 #[expect(
1054 clippy::arithmetic_side_effects,
1055 reason = "byte-count constants are small (<200) and cpsb is bounded by block_gas_limit/year formula"
1056 )]
1057 let (cpsb, state_gas_new_account, state_gas_storage_set, state_gas_auth_base) =
1058 if fork >= Fork::Amsterdam {
1059 let cpsb = compute_cost_per_state_byte(env.block_gas_limit);
1060 (
1061 cpsb,
1062 STATE_BYTES_PER_NEW_ACCOUNT * cpsb,
1063 STATE_BYTES_PER_STORAGE_SET * cpsb,
1064 STATE_BYTES_PER_AUTH_BASE * cpsb,
1065 )
1066 } else {
1067 (0, 0, 0, 0)
1068 };
1069
1070 // Derive whether the top-level backup must be preserved from the installed hooks rather
1071 // than from `vm_type`. The flag's real meaning is "a hook reads the top-level backup in
1072 // `finalize_execution`," which today is the `BackupHook` on L2 / stateless. Deriving it
1073 // keeps the flag correct if hook wiring ever changes (e.g. a future `vm_type` that adds
1074 // `BackupHook`, or L2 dropping it), and `add_hook` keeps it in sync for the `BackupHook`
1075 // that `stateless_execute` installs after construction. L1 block execution installs no
1076 // `BackupHook` (see `l1_hooks`), so the backup is dead once the cache is restored.
1077 let hooks = get_hooks(&vm_type);
1078 let preserve_top_level_backup = hooks
1079 .iter()
1080 .any(|hook| hook.borrow().reads_top_level_backup());
1081
1082 let mut vm = Self {
1083 call_frames: Vec::new(),
1084 substate,
1085 db,
1086 tx,
1087 hooks,
1088 storage_original_values: Default::default(),
1089 tracer,
1090 opcode_tracer: LevmOpcodeTracer::disabled(),
1091 validation_observer: ValidationObserver::disabled(),
1092 debug_mode: DebugMode::disabled(),
1093 stack_pool: Vec::new(),
1094 initcode_pool: Vec::new(),
1095 vm_type,
1096 preserve_top_level_backup,
1097 state_gas_used: 0,
1098 state_gas_reservoir: 0,
1099 state_gas_reservoir_initial: 0,
1100 state_gas_spill: 0,
1101 cost_per_state_byte: cpsb,
1102 state_gas_new_account,
1103 state_gas_storage_set,
1104 state_gas_auth_base,
1105 intrinsic_state_gas: 0,
1106 value_new_account_charged: false,
1107 prep_baseline_state_gas: 0,
1108 prep_baseline_reservoir: 0,
1109 prep_baseline_state_gas_spill: 0,
1110 prep_region_backup_marker: PrepareRegionBackupMarker::default(),
1111 pending_prep_oog: false,
1112 current_call_frame: CallFrame::new(
1113 env.origin,
1114 callee,
1115 Address::default(), // Will be assigned at the end of prepare_execution
1116 Code::default(), // Will be assigned at the end of prepare_execution
1117 tx.value(),
1118 tx.data().clone().into(),
1119 false,
1120 env.gas_limit,
1121 0,
1122 true,
1123 is_create,
1124 0,
1125 0,
1126 root_stack,
1127 root_memory,
1128 ),
1129 env,
1130 validate_base_fee: true,
1131 frame_tx_context: None,
1132 opcode_table: VM::build_opcode_table(fork),
1133 crypto,
1134 stateless_validator,
1135 };
1136
1137 let call_type = if is_create {
1138 CallType::CREATE
1139 } else {
1140 CallType::CALL
1141 };
1142 vm.tracer.enter(
1143 call_type,
1144 vm.env.origin,
1145 callee,
1146 vm.tx.value(),
1147 vm.env.gas_limit,
1148 &vm.tx.data().clone().into(),
1149 )?;
1150
1151 #[cfg(feature = "debug")]
1152 {
1153 // Enable debug mode for printing in Solidity contracts.
1154 vm.debug_mode.enabled = true;
1155 }
1156
1157 Ok(vm)
1158 }
1159
1160 fn add_hook(&mut self, hook: impl Hook + 'static) {
1161 // Keep `preserve_top_level_backup` in sync: a hook added after construction (e.g. the
1162 // `BackupHook` in `stateless_execute`) may read the top-level backup in `finalize_execution`.
1163 self.preserve_top_level_backup |= hook.reads_top_level_backup();
1164 self.hooks.push(Rc::new(RefCell::new(hook)));
1165 }
1166
1167 /// EIP-8037: Charge state gas, drawing from reservoir first, spilling to gas_remaining if exhausted.
1168 ///
1169 /// Must only be called for Amsterdam+ forks. All call sites must guard with
1170 /// `fork >= Fork::Amsterdam` before invoking this method.
1171 #[expect(
1172 clippy::arithmetic_side_effects,
1173 reason = "arithmetic proven safe by min()"
1174 )]
1175 pub fn increase_state_gas(&mut self, gas: u64) -> Result<(), VMError> {
1176 debug_assert!(
1177 self.env.config.fork >= Fork::Amsterdam,
1178 "increase_state_gas called pre-Amsterdam"
1179 );
1180 // Draw from reservoir first; only spill to gas_remaining if reservoir exhausted
1181 let from_reservoir = self.state_gas_reservoir.min(gas);
1182 // Safe: from_reservoir <= gas
1183 let spill = gas - from_reservoir;
1184 if spill > 0 {
1185 // Charge spill from gas_remaining first — if OOG, return early
1186 // without mutating reservoir or state_gas_used (matches EELS behavior)
1187 self.current_call_frame.increase_consumed_gas(spill)?;
1188 }
1189 // Safe: from_reservoir = min(reservoir, gas) so reservoir >= from_reservoir
1190 self.state_gas_reservoir -= from_reservoir;
1191 // Only increment state_gas_used AFTER the charge succeeds.
1192 // state_gas_used is i64; tx gas_limit caps charges well below i64::MAX.
1193 self.state_gas_used = self
1194 .state_gas_used
1195 .checked_add(i64::try_from(gas).map_err(|_| InternalError::Overflow)?)
1196 .ok_or(InternalError::Overflow)?;
1197 // Track the spill for block-accounting: EELS charge_state_gas spills
1198 // don't count toward regular_gas_used for the regular dimension.
1199 self.state_gas_spill = self
1200 .state_gas_spill
1201 .checked_add(spill)
1202 .ok_or(InternalError::Overflow)?;
1203 // Per-frame spill: EELS charge_state_gas does `frame_state_gas_spilled += remainder`.
1204 // LIFO refund source; propagated to parent on child success.
1205 self.current_call_frame.frame_state_gas_spilled = self
1206 .current_call_frame
1207 .frame_state_gas_spilled
1208 .checked_add(spill)
1209 .ok_or(InternalError::Overflow)?;
1210 Ok(())
1211 }
1212
1213 /// EIP-8037 `credit_state_gas_refund`: refund `amount` LIFO, mirroring EELS. The portion
1214 /// spilled past the reservoir into this frame's `gas_remaining` (`frame_state_gas_spilled`)
1215 /// is returned to `gas_remaining` first; only the remainder flows to the shared reservoir.
1216 /// `state_gas_used` drops by the full `amount` (may go negative when the matching charge lives
1217 /// in an ancestor frame). Block accounting: both spill counters drop by the
1218 /// `gas_remaining`-credited portion only, never the full `amount`. Amsterdam+ only.
1219 #[expect(
1220 clippy::arithmetic_side_effects,
1221 reason = "subtractions proven safe by min()"
1222 )]
1223 pub fn credit_state_gas_refund(&mut self, amount: u64) -> Result<(), VMError> {
1224 debug_assert!(
1225 self.env.config.fork >= Fork::Amsterdam,
1226 "credit_state_gas_refund called pre-Amsterdam"
1227 );
1228 // LIFO: drain the frame's spill (gas borrowed from gas_remaining) first.
1229 let from_gas_left = self.current_call_frame.frame_state_gas_spilled.min(amount);
1230 // Return the spilled portion to gas_remaining (i64).
1231 self.current_call_frame.gas_remaining = self
1232 .current_call_frame
1233 .gas_remaining
1234 .checked_add(i64::try_from(from_gas_left).map_err(|_| InternalError::Overflow)?)
1235 .ok_or(InternalError::Overflow)?;
1236 // Safe: from_gas_left = min(spill, amount) <= frame_state_gas_spilled.
1237 self.current_call_frame.frame_state_gas_spilled -= from_gas_left;
1238 // Block accounting: the refilled spill is no longer regular gas.
1239 self.state_gas_spill = self
1240 .state_gas_spill
1241 .checked_sub(from_gas_left)
1242 .ok_or(InternalError::Underflow)?;
1243 // The remainder of the refund flows into the shared reservoir.
1244 // Safe: from_gas_left = min(spill, amount) <= amount.
1245 let to_reservoir = amount - from_gas_left;
1246 self.state_gas_reservoir = self
1247 .state_gas_reservoir
1248 .checked_add(to_reservoir)
1249 .ok_or(InternalError::Overflow)?;
1250 // state_gas_used always drops by the full amount (may go negative).
1251 self.state_gas_used = self
1252 .state_gas_used
1253 .checked_sub(i64::try_from(amount).map_err(|_| InternalError::Overflow)?)
1254 .ok_or(InternalError::Overflow)?;
1255 Ok(())
1256 }
1257
1258 /// Refund the EIP-8037 new-account state gas when `charged` is true. Used by the
1259 /// CALL paths where a value-bearing call to an empty account charged the new-account
1260 /// state gas but no account ends up created (insufficient balance, max depth, child
1261 /// revert / failed precompile).
1262 #[inline]
1263 pub fn refund_new_account_state_gas(&mut self, charged: bool) -> Result<(), VMError> {
1264 if charged {
1265 self.credit_state_gas_refund(self.state_gas_new_account)?;
1266 }
1267 Ok(())
1268 }
1269
1270 /// EIP-8037 `repay_state_gas_spill` (EELS `incorporate_child`, success arm): once a
1271 /// successful child's gas has merged into this frame, the reservoir repays the spill
1272 /// still outstanding, up to what the reservoir holds.
1273 ///
1274 /// A refund can land in a different frame than the charge it undoes: the refunding
1275 /// frame's spill may be smaller than the refund, so the excess credits the reservoir
1276 /// even though the charge drew from `gas_remaining`. The merge is where the claim
1277 /// (this frame's spill) and the credit (the reservoir) first share a frame, so that
1278 /// is where the two pools settle between themselves.
1279 ///
1280 /// No state creation is undone, so `state_gas_used` does not move: the gas only
1281 /// crosses back between the pools it drifted across. Both settlements stay
1282 /// unchanged, which is what makes this repayment billing-neutral:
1283 /// - user gas (`gas_limit - gas_remaining - state_gas_reservoir`) is unchanged
1284 /// because `gas_remaining` rises by exactly what the reservoir loses;
1285 /// - the EIP-7778 regular dimension subtracts the cumulative `state_gas_spill`, so
1286 /// that counter drops by the repayment too — the reservoir (the state dimension)
1287 /// covered the charge after all, so it must stop being billed as regular gas.
1288 ///
1289 /// A failed child repays nothing: its rollback already restored the state whose
1290 /// removal any refund credited.
1291 #[expect(
1292 clippy::arithmetic_side_effects,
1293 reason = "subtractions proven safe by min()"
1294 )]
1295 pub fn repay_state_gas_spill(&mut self) -> Result<(), VMError> {
1296 debug_assert!(
1297 self.env.config.fork >= Fork::Amsterdam,
1298 "repay_state_gas_spill called pre-Amsterdam"
1299 );
1300 let repayment = self
1301 .state_gas_reservoir
1302 .min(self.current_call_frame.frame_state_gas_spilled);
1303 if repayment == 0 {
1304 return Ok(());
1305 }
1306 self.current_call_frame.gas_remaining = self
1307 .current_call_frame
1308 .gas_remaining
1309 .checked_add(i64::try_from(repayment).map_err(|_| InternalError::Overflow)?)
1310 .ok_or(InternalError::Overflow)?;
1311 // Safe: repayment = min(reservoir, frame spill) <= both.
1312 self.state_gas_reservoir -= repayment;
1313 self.current_call_frame.frame_state_gas_spilled -= repayment;
1314 // Block accounting: every frame spill is mirrored in the cumulative counter, so
1315 // it covers this repayment (`checked_sub` guards the invariant regardless).
1316 self.state_gas_spill = self
1317 .state_gas_spill
1318 .checked_sub(repayment)
1319 .ok_or(InternalError::Underflow)?;
1320 // EELS asserts the claim and the credit cannot both survive a repayment.
1321 debug_assert!(
1322 self.state_gas_reservoir == 0 || self.current_call_frame.frame_state_gas_spilled == 0
1323 );
1324 Ok(())
1325 }
1326
1327 /// EIP-8037 `refill_frame_state_gas`: roll back this frame's state gas in LIFO
1328 /// order on revert or exceptional halt, mirroring EELS `refill_frame_state_gas`.
1329 ///
1330 /// `entry` is the value of `state_gas_used` when this frame began executing
1331 /// (`current_call_frame.state_gas_used_at_entry`). The frame's net charge is
1332 /// `frame_used = state_gas_used - entry`. Of that, `frame_state_gas_spilled` was
1333 /// drawn from `gas_remaining` (spilled past the reservoir) and the remainder came
1334 /// from the reservoir. LIFO refill returns the spilled portion to `gas_remaining`
1335 /// first and the rest to the reservoir, restoring the exact pools the charges drew
1336 /// from. `state_gas_used` is rolled back to `entry` and the per-frame spill counter
1337 /// is cleared.
1338 ///
1339 /// Revert-vs-halt equivalence (load-bearing): on revert, the spilled gas returns to
1340 /// `gas_remaining` (raising the sender refund / lowering raw_consumed) while
1341 /// `state_gas_spill` drops by the same amount, so the regular dimension in
1342 /// `refund_sender` (default_hook) drops by exactly the refilled spill. On exceptional
1343 /// halt the caller subsequently sets `gas_remaining = 0` and burns it to the regular
1344 /// dimension — but `state_gas_spill` was already decremented here, so the spilled gas
1345 /// stays counted as regular. Both paths are correct.
1346 ///
1347 /// Must only be called for Amsterdam+ forks.
1348 pub fn refill_frame_state_gas(&mut self, entry: i64) -> Result<(), VMError> {
1349 debug_assert!(
1350 self.env.config.fork >= Fork::Amsterdam,
1351 "refill_frame_state_gas called pre-Amsterdam"
1352 );
1353 // The frame's net state-gas charge since it began executing. May be
1354 // negative when the frame's inline refunds (e.g. an SSTORE clearing a
1355 // slot an ancestor set) exceeded its own gross charges.
1356 let frame_used = self
1357 .state_gas_used
1358 .checked_sub(entry)
1359 .ok_or(InternalError::Underflow)?;
1360 let spilled = self.current_call_frame.frame_state_gas_spilled;
1361 // LIFO invariant: any remaining spill is undrained own-charge, so it
1362 // implies frame_used >= 0. A net-negative frame_used only arises after
1363 // credit_state_gas_refund has already drained all spill (spilled == 0).
1364 debug_assert!(
1365 frame_used >= 0 || spilled == 0,
1366 "negative frame_used with positive spill violates LIFO invariant \
1367 (frame_used={frame_used}, spilled={spilled})"
1368 );
1369 // LIFO: return the spilled portion (borrowed from gas_remaining) first.
1370 self.current_call_frame.gas_remaining = self
1371 .current_call_frame
1372 .gas_remaining
1373 .checked_add(i64::try_from(spilled).map_err(|_| InternalError::Overflow)?)
1374 .ok_or(InternalError::Overflow)?;
1375 // The remainder (drawn from the reservoir) flows back to the reservoir.
1376 let to_reservoir = frame_used
1377 .checked_sub(i64::try_from(spilled).map_err(|_| InternalError::Overflow)?)
1378 .ok_or(InternalError::Overflow)?;
1379 // `to_reservoir` is negative in the cross-ancestor refund case
1380 // (frame_used < 0); clamp so the reservoir never goes negative.
1381 let reservoir_signed =
1382 i64::try_from(self.state_gas_reservoir).map_err(|_| InternalError::Overflow)?;
1383 self.state_gas_reservoir = u64::try_from(
1384 reservoir_signed
1385 .checked_add(to_reservoir)
1386 .ok_or(InternalError::Overflow)?
1387 .max(0),
1388 )
1389 .map_err(|_| InternalError::Overflow)?;
1390 // Roll back state_gas_used to the frame's entry baseline.
1391 self.state_gas_used = entry;
1392 // Block accounting: the refilled spill is no longer regular gas.
1393 self.state_gas_spill = self
1394 .state_gas_spill
1395 .checked_sub(spilled)
1396 .ok_or(InternalError::Underflow)?;
1397 self.current_call_frame.frame_state_gas_spilled = 0;
1398 Ok(())
1399 }
1400
1401 /// EIP-8037: enters the atomic prepare region (EELS `interpreter.py`'s depth-0
1402 /// `try` around `set_delegation` + `prepare_dispatch`, `interpreter.py:353-375`).
1403 /// Must be called in `prepare_execution`, after the sender nonce bump and fee
1404 /// deduction (those survive a region rollback) but before the type-4 auth
1405 /// handling (the first region charge). Captures the pre-region state-gas
1406 /// baseline and the `call_frame_backup` key-space so `fail_prepare_region` can
1407 /// later undo exactly the region's writes.
1408 pub fn enter_prepare_region(&mut self) {
1409 self.prep_baseline_state_gas = self.current_call_frame.state_gas_used_at_entry;
1410 self.prep_baseline_reservoir = self.state_gas_reservoir;
1411 self.prep_baseline_state_gas_spill = self.state_gas_spill;
1412 let backup = &self.current_call_frame.call_frame_backup;
1413 let accounts: SeededHashSet<Address> =
1414 backup.original_accounts_info.keys().copied().collect();
1415 let storage: SeededHashSet<Address> = backup
1416 .original_account_storage_slots
1417 .keys()
1418 .copied()
1419 .collect();
1420 let code_hashes_len = backup.inserted_code_hashes.len();
1421 // Capture the region-entry state of every already-backed-up account so a
1422 // self-sponsored EIP-7702 authorization (or any in-region write to a
1423 // pre-region-touched account) can be reverted without disturbing its
1424 // pre-region nonce/fee writes. See `PrepareRegionBackupMarker::entry_state`.
1425 let entry_state: SeededHashMap<Address, LevmAccount> = accounts
1426 .iter()
1427 .filter_map(|address| {
1428 self.db
1429 .current_accounts_state
1430 .get(address)
1431 .map(|account| (*address, account.clone()))
1432 })
1433 .collect();
1434 let bal_checkpoint = self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1435 self.prep_region_backup_marker = PrepareRegionBackupMarker {
1436 accounts,
1437 storage,
1438 code_hashes_len,
1439 entry_state,
1440 bal_checkpoint,
1441 };
1442 }
1443
1444 /// EIP-8037: rolls back the atomic prepare region on an internal OOG from any of
1445 /// its charges (7702 auth, CREATE/value `NEW_ACCOUNT`, recipient delegation-resolve).
1446 /// Restores every `call_frame_backup` entry added since `enter_prepare_region`
1447 /// (leaving the earlier sender nonce-bump / fee-deduction entries untouched),
1448 /// refills the frame's state gas back to the pre-region baseline, and sets
1449 /// `pending_prep_oog` so `run_execution` turns this into a full-gas revert
1450 /// instead of a tx-level rejection `Err` (which would wrongly invalidate the
1451 /// block). Mirrors EELS `restore_tx_state(prep_snapshot)` + `refill_frame_state_gas`
1452 /// (`interpreter.py:366-374`).
1453 pub fn fail_prepare_region(&mut self) {
1454 let marker = std::mem::take(&mut self.prep_region_backup_marker);
1455 let mut backup = std::mem::take(&mut self.current_call_frame.call_frame_backup);
1456
1457 // Restore + drop every account backup entry added during the region.
1458 let region_accounts: Vec<Address> = backup
1459 .original_accounts_info
1460 .keys()
1461 .filter(|address| !marker.accounts.contains(*address))
1462 .copied()
1463 .collect();
1464 for address in region_accounts {
1465 if let Some(account) = backup.original_accounts_info.remove(&address)
1466 && let Some(current_account) = self.db.current_accounts_state.get_mut(&address)
1467 {
1468 current_account.info = account.info;
1469 current_account.status = account.status;
1470 current_account.has_storage = account.has_storage;
1471 current_account.exists = account.exists;
1472 }
1473 }
1474
1475 // Restore + drop every storage backup entry added during the region.
1476 let region_storage: Vec<Address> = backup
1477 .original_account_storage_slots
1478 .keys()
1479 .filter(|address| !marker.storage.contains(*address))
1480 .copied()
1481 .collect();
1482 for address in region_storage {
1483 if let Some(slots) = backup.original_account_storage_slots.remove(&address)
1484 && let Some(current_account) = self.db.current_accounts_state.get_mut(&address)
1485 {
1486 for (key, value) in slots {
1487 current_account.storage.insert(key, value);
1488 }
1489 }
1490 }
1491
1492 // Evict codes the region inserted, mirroring `restore_cache_state`: a stale
1493 // by-hash cache entry would hide a later read of the same hash from the store.
1494 for code_hash in backup
1495 .inserted_code_hashes
1496 .split_off(marker.code_hashes_len)
1497 {
1498 self.db.codes.remove(&code_hash);
1499 }
1500
1501 self.current_call_frame.call_frame_backup = backup;
1502
1503 // Revert in-region writes to accounts that were already backed up before the
1504 // region (the marker filter above leaves these untouched to preserve their
1505 // pre-region nonce/fee writes, but first-write-wins backup means an in-region
1506 // write — e.g. a self-sponsored EIP-7702 authorization writing the sender's
1507 // delegation code + auth nonce bump — created no new backup entry). Restoring
1508 // to the region-entry snapshot undoes the in-region write while keeping the
1509 // pre-region writes baked into that snapshot. Mirrors EELS `restore_tx_state`.
1510 for (address, entry_account) in marker.entry_state {
1511 if let Some(current) = self.db.current_accounts_state.get_mut(&address) {
1512 current.info = entry_account.info;
1513 current.status = entry_account.status;
1514 current.has_storage = entry_account.has_storage;
1515 current.exists = entry_account.exists;
1516 }
1517 }
1518
1519 // Roll back the BAL recorder to region entry so an applied-then-reverted
1520 // delegation's code/nonce changes are discarded (demoted to an access-only
1521 // touch, matching EELS `restore_tx_state`). `restore` preserves touched
1522 // addresses — including the pre-charge authority touches recorded during
1523 // `set_delegation` — so a reverted authority still appears as an access.
1524 if let Some(checkpoint) = marker.bal_checkpoint
1525 && let Some(recorder) = self.db.bal_recorder.as_mut()
1526 {
1527 recorder.restore(checkpoint);
1528 }
1529
1530 // Rewind the state-gas machinery to the pre-region snapshot. The
1531 // `set_delegation` auth lock-in re-seeds `state_gas_used_at_entry` and zeroes
1532 // the frame spill, so `refill_frame_state_gas` (which derives the reservoir
1533 // credit from the frame spill) would leave the reservoir over-credited by the
1534 // locked-in auth state gas. Restore `state_gas_used`, the reservoir, and the
1535 // cumulative spill to the values captured by `enter_prepare_region`, and clear
1536 // the frame spill — this fully reverts the region's state charges (auth +
1537 // prepare-dispatch) regardless of the lock-in. Mirrors EELS
1538 // `restore_tx_state(prep_snapshot)` + `message.state_gas_reservoir = prep_reservoir`
1539 // (`interpreter.py:365-369`). `gas_remaining` is left as-is: the failing charge
1540 // already drove it negative, so `run_execution` burns all gas (EELS
1541 // `evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`).
1542 self.state_gas_used = self.prep_baseline_state_gas;
1543 self.state_gas_reservoir = self.prep_baseline_reservoir;
1544 self.state_gas_spill = self.prep_baseline_state_gas_spill;
1545 self.current_call_frame.frame_state_gas_spilled = 0;
1546 self.pending_prep_oog = true;
1547 }
1548
1549 /// Executes a whole external transaction. Performing validations at the beginning.
1550 pub fn execute(&mut self) -> Result<ExecutionReport, VMError> {
1551 // Detect frame transaction and branch to specialized execution
1552 if self.tx.tx_type() == TxType::Frame {
1553 return self.execute_frame_tx();
1554 }
1555
1556 if let Err(e) = self.prepare_execution() {
1557 // Restore cache to state previous to this Tx execution because this Tx is invalid.
1558 // Consume the backup unless a `BackupHook` will read it (L2 / stateless); on L1 it
1559 // is dead once the cache is restored.
1560 if self.preserve_top_level_backup {
1561 self.restore_cache_state()?;
1562 } else {
1563 self.restore_cache_state_consuming()?;
1564 }
1565 return Err(e);
1566 }
1567
1568 // Clear callframe backup so that changes made in prepare_execution are written in stone.
1569 // We want to apply these changes even if the Tx reverts. E.g. Incrementing sender nonce
1570 self.current_call_frame.call_frame_backup.clear();
1571
1572 // Empty bytecode would only execute STOP; skip the dispatch loop.
1573 // The BAL checkpoint below is intentionally skipped: a codeless transfer cannot
1574 // fail past this point and has no inner calls, so there's nothing to roll back.
1575 if self.is_simple_transfer_fast_path() {
1576 // EIP-8037: no `refill_frame_state_gas` needed here — a codeless transfer always
1577 // succeeds, runs no opcodes, and charges no execution state gas, so the frame's
1578 // `frame_state_gas_spilled` is 0 and `state_gas_used` equals its entry baseline.
1579 #[expect(clippy::as_conversions, reason = "gas_remaining is non-negative here")]
1580 let gas_used = self
1581 .current_call_frame
1582 .gas_limit
1583 .checked_sub(self.current_call_frame.gas_remaining as u64)
1584 .ok_or(InternalError::Underflow)?;
1585 let context_result = ContextResult {
1586 result: TxResult::Success,
1587 gas_used,
1588 gas_spent: gas_used,
1589 output: Bytes::new(),
1590 };
1591 return self.finalize_execution(context_result);
1592 }
1593
1594 // EIP-7928: Take a BAL checkpoint AFTER clearing the backup. This captures the state
1595 // after prepare_execution (nonce increment, etc.) but before actual execution.
1596 // When the top-level call fails, we restore to this checkpoint so that inner call
1597 // state changes (like value transfers) are reverted from the BAL.
1598 self.current_call_frame.call_frame_backup.bal_checkpoint =
1599 self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1600
1601 // EIP-8037: skip the CREATE nonce bump / endowment / collision check when the
1602 // atomic prepare region OOG'd (`pending_prep_oog`). EELS raises in
1603 // `prepare_dispatch` before `process_create_message` runs, so the contract is
1604 // never created — `run_execution` below emits the full-gas revert. Bumping the
1605 // nonce here would leave a phantom nonce=1 the region rollback can't reach.
1606 if !self.pending_prep_oog && self.is_create()? {
1607 // Create contract, reverting the Tx if address is already occupied.
1608 if let Some(context_result) = self.handle_create_transaction()? {
1609 let report = self.finalize_execution(context_result)?;
1610 return Ok(report);
1611 }
1612 }
1613
1614 self.substate.push_backup();
1615 let context_result = self.run_execution()?;
1616
1617 let report = self.finalize_execution(context_result)?;
1618
1619 Ok(report)
1620 }
1621
1622 /// Execute a frame transaction (EIP-8141).
1623 /// This bypasses the normal prepare/finalize hooks and orchestrates per-frame execution.
1624 fn execute_frame_tx(&mut self) -> Result<ExecutionReport, VMError> {
1625 use crate::errors::TxResult;
1626
1627 // EIP-8141 fork gating: reject frame transactions observed in a block or
1628 // submitted to any non-mempool entry point before Hegota activates.
1629 if self.env.config.fork < Fork::Hegota {
1630 return Err(VMError::TxValidation(
1631 crate::errors::TxValidationError::FrameTxPreFork,
1632 ));
1633 }
1634
1635 let frame_tx = match &self.tx {
1636 Transaction::FrameTransaction(ft) => ft.clone(),
1637 _ => unreachable!(),
1638 };
1639
1640 // Simplified validation (skip balance deduction, nonce increment, value transfer, EOA check)
1641 // Keep: gas limit checks, fee validation, nonce mismatch check.
1642 // The EOA-check skip is required by EIP-8141 §Transaction origination:
1643 // EIP-3607 must not apply to frame transactions, so the sender may have
1644 // contract code (SENDER frames legitimately originate from contract
1645 // accounts).
1646 let sender = frame_tx.sender;
1647
1648 // Validate static constraints (frame count, reserved modes, atomic batch flags)
1649 if let Err(_e) = frame_tx.validate_static_constraints() {
1650 return Err(VMError::TxValidation(
1651 crate::errors::TxValidationError::InvalidFrameTransaction,
1652 ));
1653 }
1654
1655 // Check nonce matches
1656 let sender_info = self.db.get_account(sender)?.info.clone();
1657 if sender_info.nonce != frame_tx.nonce {
1658 return Err(VMError::TxValidation(
1659 crate::errors::TxValidationError::NonceMismatch {
1660 expected: sender_info.nonce,
1661 actual: frame_tx.nonce,
1662 },
1663 ));
1664 }
1665
1666 // Check priority fee <= max fee
1667 if frame_tx.max_priority_fee_per_gas > frame_tx.max_fee_per_gas {
1668 return Err(VMError::TxValidation(
1669 crate::errors::TxValidationError::PriorityGreaterThanMaxFeePerGas {
1670 priority_fee: U256::from(frame_tx.max_priority_fee_per_gas),
1671 max_fee_per_gas: U256::from(frame_tx.max_fee_per_gas),
1672 },
1673 ));
1674 }
1675
1676 // Check max_fee >= base_fee
1677 if U256::from(frame_tx.max_fee_per_gas) < self.env.base_fee_per_gas {
1678 return Err(VMError::TxValidation(
1679 crate::errors::TxValidationError::InsufficientMaxFeePerGas,
1680 ));
1681 }
1682
1683 // EIP-4844 INSUFFICIENT_MAX_FEE_PER_BLOB_GAS: a blob-carrying tx whose
1684 // max_fee_per_blob_gas is below the block's base blob fee is invalid. The
1685 // frame path is self-contained and never runs the default hook's
1686 // validate_max_fee_per_blob_gas, so it is enforced here. APPROVE charges
1687 // the blob fee at the base rate unconditionally, so without this a frame tx
1688 // below the base blob fee would execute and silently overpay rather than be
1689 // rejected — a divergence from a conformant client that rejects it.
1690 if !frame_tx.blob_versioned_hashes.is_empty()
1691 && frame_tx.max_fee_per_blob_gas < self.env.base_blob_fee_per_gas
1692 {
1693 return Err(VMError::TxValidation(
1694 crate::errors::TxValidationError::InsufficientMaxFeePerBlobGas {
1695 base_fee_per_blob_gas: self.env.base_blob_fee_per_gas,
1696 tx_max_fee_per_blob_gas: frame_tx.max_fee_per_blob_gas,
1697 },
1698 ));
1699 }
1700
1701 // Initialize FrameTxContext
1702 let sig_hash = frame_tx.compute_sig_hash();
1703 let max_gas = frame_tx.max_gas();
1704 self.frame_tx_context = Some(FrameTxContext {
1705 sender_approved: false,
1706 payer_address: None,
1707 frame_results: Vec::new(),
1708 current_frame_index: 0,
1709 sig_hash,
1710 tx: frame_tx.clone(),
1711 approve_called_in_current_frame: false,
1712 max_gas,
1713 blob_base_fee: self.env.base_blob_fee_per_gas,
1714 });
1715
1716 // EIP-8141: every outer signature must validate
1717 // before any frame executes; otherwise the whole transaction is invalid.
1718 if !validate_frame_signatures(
1719 &frame_tx.signatures,
1720 sig_hash,
1721 frame_tx.sender,
1722 self.env.config.fork,
1723 self.crypto,
1724 ) {
1725 return Err(VMError::TxValidation(
1726 crate::errors::TxValidationError::InvalidFrameTransaction,
1727 ));
1728 }
1729
1730 // Tx-level rollback accumulator: if the tx is later declared invalid
1731 // after frames committed, restore `db.current_accounts_state` so the
1732 // payload builder (which reuses the shared db across txs) sees no
1733 // residue — same Err contract as non-frame `execute()`. The per-frame
1734 // backup is cleared between independent frames (and at batch entry), so
1735 // each frame's original values are absorbed here (first-seen-wins)
1736 // before that clear destroys them. Substate is per-VM and discarded on
1737 // Err, so it needs no snapshot.
1738 let mut tx_level_backup = crate::call_frame::CallFrameBackup {
1739 bal_checkpoint: self.db.bal_recorder.as_ref().map(|r| r.checkpoint()),
1740 ..Default::default()
1741 };
1742
1743 // ENTRY_POINT address used as caller for DEFAULT/VERIFY frames
1744 let entry_point = ethrex_common::types::frame_tx_entry_point();
1745
1746 let mut all_logs: Vec<Log> = Vec::new();
1747 let sum_frame_gas_limits: u64 = frame_tx
1748 .frames
1749 .iter()
1750 .map(|f| f.gas_limit)
1751 .fold(0u64, |acc, g| acc.saturating_add(g));
1752 // The non-frame part of `standard_gas_limit`, not of `max_gas`: when the
1753 // calldata floor dominates, the extra reservation is not intrinsic gas and
1754 // is applied once at settlement instead.
1755 let intrinsic_gas = frame_tx
1756 .mandatory_gas()
1757 .saturating_add(frame_tx.data_cost());
1758 let mut total_gas_used: u64 = intrinsic_gas;
1759 let mut tx_invalid = false;
1760
1761 // Atomic batching state: track whether we're inside a batch and
1762 // which frames belong to it so we can revert them all on failure.
1763 let mut in_atomic_batch = false;
1764 let mut batch_start_idx: usize = 0;
1765 let mut batch_logs_start: usize = 0;
1766 let mut batch_approval_snapshot: (bool, Option<Address>) = (false, None);
1767 let mut batch_bal_checkpoint: Option<BlockAccessListCheckpoint> = None;
1768 // EIP-8037: snapshot the shared `state_gas_used` at batch entry so a batch
1769 // revert (which unrolls every in-batch frame's state) also drops the state
1770 // gas those frames accumulated.
1771 let mut state_gas_used_at_batch_entry: i64 = 0;
1772 let mut skip_until_batch_end: Option<usize> = None; // skip remaining frames in a failed batch
1773
1774 // Execute frames sequentially
1775 for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
1776 // If we're skipping frames due to an atomic batch revert, record
1777 // the frame with status SKIPPED. Per EIP-8141, the
1778 // gas allotted to skipped frames is refunded at the end of the
1779 // transaction, so we record `gas_used = 0` and do NOT add the
1780 // frame's `gas_limit` to `total_gas_used`.
1781 //
1782 // Note (EIP-8141): an expiry verifier frame has flags
1783 // == 0, so it can only be a batch TERMINATOR, never a flagged
1784 // member. A failed batch therefore skips a trailing expiry frame
1785 // and its deadline is not checked at execution time. This is
1786 // benign, not a bypass: `compute_sig_hash` commits to the full
1787 // frame layout (modes, flags incl. the atomic-batch flag, targets,
1788 // and the expiry deadline), and the VERIFY signature is recovered
1789 // over that hash — so no relayer/proposer can wrap a signed tx's
1790 // expiry frame in a failing batch. Only the sender can build this
1791 // layout, and doing so merely disarms their own expiry. The normal
1792 // pattern (a standalone expiry VERIFY frame, not batched) is fully
1793 // enforced. The skip itself is spec-mandated batch semantics; do
1794 // not change it unilaterally — that would be a consensus divergence.
1795 if let Some(end_idx) = skip_until_batch_end {
1796 if frame_idx <= end_idx {
1797 let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
1798 InternalError::Custom("missing frame tx context".to_string()),
1799 ))?;
1800 ctx.current_frame_index = frame_idx;
1801 ctx.frame_results.push((
1802 ethrex_common::types::FRAME_RECEIPT_STATUS_SKIPPED,
1803 0,
1804 Vec::new(),
1805 ));
1806 if frame_idx == end_idx {
1807 skip_until_batch_end = None;
1808 in_atomic_batch = false;
1809 }
1810 continue;
1811 }
1812 skip_until_batch_end = None;
1813 in_atomic_batch = false;
1814 }
1815
1816 // Clear the outer call-frame backup at the start of each independent
1817 // frame so that a later frame's failure-path `restore_cache_state()`
1818 // only reverts that frame's own effects — not APPROVE/state deltas
1819 // produced by earlier, already-successful frames. Inside an open
1820 // atomic batch we keep accumulating, since a batch revert needs to
1821 // undo every in-batch frame's effects together.
1822 if !in_atomic_batch {
1823 // Absorb this frame's originals into the tx-level accumulator
1824 // before clearing, so an invalid-tx exit can still roll back
1825 // every committed frame's state (see `tx_level_backup`).
1826 tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
1827 self.current_call_frame.call_frame_backup.clear();
1828 }
1829
1830 // Start a new atomic batch if this frame has the batch flag
1831 // and we're not already in one.
1832 if !in_atomic_batch && frame.is_atomic_batch() {
1833 self.substate.push_backup(); // batch-level snapshot
1834 // EIP-7928: the batch's state changes must leave the block access
1835 // list as well when the batch unrolls, or the builder records
1836 // writes the block does not contain and the block fails its own
1837 // BAL validation on re-execution.
1838 batch_bal_checkpoint = self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1839 // The outer call-frame backup is already empty here: the
1840 // `!in_atomic_batch` block above absorbed it into
1841 // `tx_level_backup` and cleared it on entry to this frame, so
1842 // the batch starts accumulating a clean, self-contained set of
1843 // state changes that batch-revert can undo wholesale.
1844 in_atomic_batch = true;
1845 batch_start_idx = frame_idx;
1846 batch_logs_start = all_logs.len();
1847 state_gas_used_at_batch_entry = self.state_gas_used;
1848 // Snapshot approvals at batch entry: a batch revert must also
1849 // roll back approvals granted inside the batch (their balance
1850 // and nonce effects are reverted with the substate).
1851 batch_approval_snapshot = self
1852 .frame_tx_context
1853 .as_ref()
1854 .map(|c| c.approval_snapshot())
1855 .unwrap_or((false, None));
1856 }
1857
1858 let ctx =
1859 self.frame_tx_context
1860 .as_mut()
1861 .ok_or(VMError::Internal(InternalError::Custom(
1862 "missing frame tx context".to_string(),
1863 )))?;
1864 ctx.current_frame_index = frame_idx;
1865 ctx.approve_called_in_current_frame = false;
1866
1867 let target = frame.target.unwrap_or(sender);
1868
1869 // Determine caller and static mode per frame mode
1870 let (caller, is_static) = match frame.execution_mode() {
1871 FrameMode::Default => (entry_point, false),
1872 FrameMode::Verify => (entry_point, true),
1873 FrameMode::Sender => {
1874 // SENDER mode requires sender_approved
1875 let ctx = self.frame_tx_context.as_ref().ok_or(VMError::Internal(
1876 InternalError::Custom("missing frame tx context".to_string()),
1877 ))?;
1878 if !ctx.sender_approved {
1879 tx_invalid = true;
1880 break;
1881 }
1882 (sender, false)
1883 }
1884 };
1885
1886 // Set env.origin for this frame (ORIGIN opcode reads this)
1887 self.env.origin = caller;
1888
1889 // Resolve any EIP-7702 delegation at the resolved target. For a non-delegated
1890 // target this is equivalent to `db.get_account_code(target)`; for a delegated
1891 // target it follows the 0xef0100 || addr indicator and returns the delegatee's
1892 // bytecode plus the resolved code_address. EIP-8141 §Execution step 1 requires
1893 // delegated targets to execute the delegatee's code while keeping ADDRESS/storage
1894 // tied to the delegator — which is why `to` below stays `target` but the
1895 // CallFrame receives the resolved `code_address`. Mirrors the pattern used at
1896 // top-level tx entry in default_hook::set_bytecode_and_code_address.
1897 //
1898 // access_cost is intentionally discarded: this frame entry is analogous to a
1899 // top-level tx entry (a call from 0xaa / tx.sender, not a CALL opcode), and
1900 // default_hook.rs drops the same cost there. EIP-8141 §Execution is silent on
1901 // billing the 7702 access cost for `resolved_target`, so we keep frame-entry
1902 // behavior consistent with tx-entry behavior.
1903 let (is_delegation_7702, _access_cost, code_address, bytecode) =
1904 crate::utils::eip7702_get_code(
1905 self.db,
1906 &mut self.substate,
1907 target,
1908 self.env.config.fork,
1909 )?;
1910
1911 // Mirror default_hook::set_bytecode_and_code_address: when delegation was
1912 // followed, record the delegatee (code_address) as touched in BAL so EIP-7928
1913 // reconstructors see the cross-address read.
1914 if is_delegation_7702 && let Some(recorder) = self.db.bal_recorder.as_mut() {
1915 recorder.record_touched_address(code_address);
1916 }
1917
1918 // Log count of the scope this frame's backup will be committed into.
1919 // The CallFrame branch below relies on `run_execution` having already
1920 // committed the frame (merging its logs up into this scope), then
1921 // slices `[substate_logs_before..]` to recover exactly this frame's
1922 // logs without re-committing.
1923 let substate_logs_before = self.substate.logs_len();
1924
1925 // Push substate backup for per-frame state isolation
1926 self.substate.push_backup();
1927
1928 // EIP-8141 top-level value transfer: the outer
1929 // frame call owns CALLVALUE delivery. We only CHECK affordability
1930 // here; the actual transfer runs inside whichever branch executes
1931 // the frame, so it is recorded in the backup that branch restores on
1932 // failure (fixes the value-leak where a reverting contract-target
1933 // SENDER frame kept the funds). Static validation guarantees only
1934 // SENDER frames reach here with a non-zero value.
1935 let value_transfer_reverted = if !frame.value.is_zero() {
1936 let sender_balance = self.db.get_account(sender)?.info.balance;
1937 frame_value_exceeds_balance(sender_balance, frame.value)
1938 } else {
1939 false
1940 };
1941
1942 // Performs the deferred SENDER-frame value transfer + EIP-7708 log.
1943 // Invoked in BOTH execution branches so the transfer is recorded in
1944 // the call_frame_backup that branch's failure path restores.
1945 macro_rules! do_frame_value_transfer {
1946 () => {
1947 if !frame.value.is_zero() && !value_transfer_reverted {
1948 self.transfer(sender, target, frame.value)?;
1949 // EIP-7708 / traceTransfers log parity with
1950 // default_hook::transfer_value: which logs apply is decided in
1951 // `push_eth_transfer_logs`.
1952 self.add_eth_transfer_logs(sender, target, frame.value);
1953 }
1954 };
1955 }
1956
1957 // EIP-8037: capture state-gas accounting before the frame runs so a
1958 // reverted frame (which commits no state) can be rolled back to
1959 // contribute zero state gas. The reservoir/spill are captured too:
1960 // each frame is gas-isolated, so an inline state-gas refund (e.g. an
1961 // SSTORE 0->N->0 clear, which credits the reservoir) inside one frame
1962 // must NOT carry over to a later frame's charges — the reservoir is
1963 // reset to this entry value after the frame completes.
1964 let state_gas_used_at_frame_entry = self.state_gas_used;
1965 let state_gas_reservoir_at_frame_entry = self.state_gas_reservoir;
1966 let state_gas_spill_at_frame_entry = self.state_gas_spill;
1967
1968 let (frame_success, frame_gas_used, frame_logs) = if value_transfer_reverted {
1969 self.substate.revert_backup();
1970 self.restore_cache_state()?;
1971 (false, frame.gas_limit, Vec::new())
1972 } else if bytecode.is_empty() && !is_delegation_7702 {
1973 // Default code runs only when the target has NEITHER code NOR a delegation
1974 // indicator (EIP-8141 §Execution). After eip7702_get_code,
1975 // bytecode is the delegatee's code when delegated, so a delegation to an
1976 // empty delegatee still falls into the CallFrame branch below and returns
1977 // success without executing anything — NOT into the default-code path.
1978 // current_call_frame is the OUTER frame here; its backup is the
1979 // one this branch's failure path restores, so the deferred
1980 // transfer is correctly undone on a default-code revert.
1981 do_frame_value_transfer!();
1982 use crate::opcode_handlers::frame_tx::execute_default_code;
1983 match execute_default_code(self, frame, target) {
1984 Ok((success, gas_used, logs)) => {
1985 if success {
1986 // Capture this frame's substate logs (incl. the
1987 // EIP-7708 transfer log added by
1988 // do_frame_value_transfer!) BEFORE commit_backup
1989 // merges them into the parent — mirrors the
1990 // CallFrame branch. execute_default_code returns its
1991 // own logs separately, so include both.
1992 let mut this_frame_logs = self.substate.current_logs();
1993 this_frame_logs.extend(logs);
1994 self.substate.commit_backup();
1995 (true, gas_used, this_frame_logs)
1996 } else {
1997 self.substate.revert_backup();
1998 self.restore_cache_state()?;
1999 (false, gas_used, Vec::new())
2000 }
2001 }
2002 Err(_) => {
2003 self.substate.revert_backup();
2004 self.restore_cache_state()?;
2005 (false, frame.gas_limit, Vec::new())
2006 }
2007 }
2008 } else {
2009 // Normal code execution via CallFrame. msg_value carries
2010 // `frame.value` so the contract sees the correct CALLVALUE
2011 // (EIP-8141 §Behavior), but `should_transfer_value` stays
2012 // false because the deferred `do_frame_value_transfer!()` below
2013 // (invoked after the frame swap) owns the transfer — the inner
2014 // CALL machinery must not move the funds a second time.
2015 let call_frame = CallFrame::new(
2016 caller, // msg_sender
2017 target, // to (delegator; ADDRESS/storage)
2018 code_address, // code_address (delegatee when 7702)
2019 bytecode, // bytecode (delegatee's code when 7702)
2020 frame.value, // msg_value -- CALLVALUE
2021 frame.data.clone().into(), // calldata
2022 is_static, // is_static
2023 frame.gas_limit, // gas_limit
2024 0, // depth
2025 false, // should_transfer_value (do_frame_value_transfer! handles it)
2026 false, // is_create
2027 0, // ret_offset
2028 0, // ret_size
2029 self.stack_pool.pop().unwrap_or_default(), // stack
2030 Memory::default(), // memory
2031 );
2032
2033 let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
2034 let saved_call_frames = mem::take(&mut self.call_frames);
2035
2036 // current_call_frame is now the INNER frame, so the deferred
2037 // transfer records into the inner backup that the revert failure
2038 // path (self.substate.revert_backup + restore_cache_state)
2039 // restores — fixing the value-leak on a reverting SENDER frame.
2040 do_frame_value_transfer!();
2041
2042 let frame_result = self.run_execution();
2043
2044 let result = match frame_result {
2045 Ok(ctx_result) => {
2046 let gas_used = ctx_result.gas_used;
2047 let success = ctx_result.is_success();
2048
2049 if success {
2050 // The inner frame is the initial call frame (call_frames
2051 // was emptied above), so `run_execution` already ran
2052 // `handle_state_backup` and committed this frame's backup,
2053 // merging its logs up into the scope measured by
2054 // `substate_logs_before`. Recover exactly this frame's logs
2055 // by slicing off everything that predated it — do NOT commit
2056 // again (a second commit would collapse an extra backup
2057 // level, breaking atomic-batch rollback) and do NOT read
2058 // `current_logs()` wholesale (it now also holds prior frames'
2059 // logs, which would duplicate them into frame_receipts[i]).
2060 let mut merged_logs = self.substate.current_logs();
2061 let this_frame_logs = merged_logs.split_off(substate_logs_before);
2062 (true, gas_used, this_frame_logs)
2063 } else {
2064 // A normal EVM revert reaches `handle_state_backup` inside
2065 // `run_execution`, which already reverted the backup and
2066 // restored the cache for this frame; repeating it here would
2067 // revert an extra level.
2068 (false, gas_used, Vec::new())
2069 }
2070 }
2071 Err(_e) => {
2072 // A `VMError` propagates out of `run_execution` before it reaches
2073 // `handle_state_backup`, so this frame's backup is still live and
2074 // must be reverted (and the cache restored) here.
2075 self.substate.revert_backup();
2076 self.restore_cache_state()?;
2077 (false, frame.gas_limit, Vec::new())
2078 }
2079 };
2080
2081 // Restore call frame state
2082 let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
2083 self.call_frames = saved_call_frames;
2084
2085 // When a frame succeeds inside an atomic batch, its state
2086 // changes must remain revertable at batch-revert time. Merge
2087 // the finished frame's backup into the outer call-frame backup
2088 // so that `restore_cache_state()` invoked by batch-revert can
2089 // undo them — and so the next clear-and-absorb folds them into
2090 // `tx_level_backup` too. Outside a batch, the finished frame's
2091 // backup never reaches the outer call frame, so absorb it
2092 // directly into `tx_level_backup` here; otherwise an invalid-tx
2093 // exit could not roll back this committed frame's state.
2094 if result.0 {
2095 if in_atomic_batch {
2096 self.merge_call_frame_backup_with_parent(
2097 &finished_frame.call_frame_backup,
2098 )?;
2099 } else {
2100 tx_level_backup.absorb(&finished_frame.call_frame_backup);
2101 }
2102 }
2103
2104 self.stack_pool.push(finished_frame.stack);
2105
2106 result
2107 };
2108
2109 // EIP-8037: a failed frame's state changes were reverted above, so it
2110 // creates no state and must contribute zero state gas. Roll the shared
2111 // `state_gas_used` back to this frame's entry value (the cache/substate
2112 // were already restored in the failure arms). Successful frames keep
2113 // their accumulated state gas.
2114 if !frame_success {
2115 self.state_gas_used = state_gas_used_at_frame_entry;
2116 }
2117 // EIP-8037: frames are gas-isolated, so the state-gas reservoir/spill
2118 // must not leak across the frame boundary. A reservoir credit from an
2119 // inline refund inside this frame (or a reverted frame's inflated
2120 // reservoir) would otherwise subsidize the next frame's state charges
2121 // (drawn before any spill to gas_remaining). Reset both to this frame's
2122 // entry value unconditionally — a successful frame already folded its
2123 // inline refund into `state_gas_used`, so the leftover reservoir credit
2124 // is spent and must be dropped.
2125 self.state_gas_reservoir = state_gas_reservoir_at_frame_entry;
2126 self.state_gas_spill = state_gas_spill_at_frame_entry;
2127
2128 total_gas_used = total_gas_used
2129 .checked_add(frame_gas_used)
2130 .ok_or(VMError::Internal(InternalError::Overflow))?;
2131 all_logs.extend(frame_logs.clone());
2132
2133 // Store frame result in context
2134 let ctx =
2135 self.frame_tx_context
2136 .as_mut()
2137 .ok_or(VMError::Internal(InternalError::Custom(
2138 "missing frame tx context".to_string(),
2139 )))?;
2140 let status_code = if frame_success {
2141 ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS
2142 } else {
2143 ethrex_common::types::FRAME_RECEIPT_STATUS_FAILURE
2144 };
2145 ctx.frame_results
2146 .push((status_code, frame_gas_used, frame_logs));
2147
2148 // Atomic batch: if a frame in the batch reverted, revert the
2149 // batch-level snapshot and skip remaining frames in the batch.
2150 if in_atomic_batch && !frame_success {
2151 self.substate.revert_backup(); // revert batch-level snapshot
2152 self.restore_cache_state()?;
2153 // EIP-7928: drop the batch's recorded changes. `restore` re-files a
2154 // freshly-written slot as a read and leaves `touched_addresses`
2155 // alone, so the accesses the batch made still appear -- only the
2156 // reverted changes go.
2157 if let Some(checkpoint) = batch_bal_checkpoint.take()
2158 && let Some(recorder) = self.db.bal_recorder.as_mut()
2159 {
2160 recorder.restore(checkpoint);
2161 }
2162 // EIP-8037: the whole batch unrolled, so none of its frames created
2163 // state — drop the state gas accumulated since batch entry.
2164 self.state_gas_used = state_gas_used_at_batch_entry;
2165
2166 // EIP-8141: frames that executed before the failure retain their
2167 // execution status and gas used; only their logs are discarded,
2168 // together with the state changes the unroll drops. `total_gas_used`
2169 // therefore stands as executed, and the failing frame keeps the gas
2170 // the single-frame path already charged it (actual `gas_used` for a
2171 // `REVERT`, the full `gas_limit` for an exceptional halt).
2172 let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
2173 InternalError::Custom("missing frame tx context".to_string()),
2174 ))?;
2175 for result in ctx
2176 .frame_results
2177 .get_mut(batch_start_idx..=frame_idx)
2178 .into_iter()
2179 .flatten()
2180 {
2181 result.2 = Vec::new();
2182 }
2183 // Roll back approvals granted inside the reverted batch.
2184 ctx.restore_approvals(batch_approval_snapshot);
2185 // Remove only logs from the batch, preserving pre-batch logs
2186 all_logs.truncate(batch_logs_start);
2187
2188 // Spec: a reverted VERIFY frame invalidates the transaction even
2189 // inside an atomic batch. The batch unroll above already rolled
2190 // back state/approvals; validity is a tx-level decision. (The
2191 // failing `frame` here is the one that triggered the revert.)
2192 if frame.execution_mode() == FrameMode::Verify {
2193 tx_invalid = true;
2194 break;
2195 }
2196
2197 // Find the end of this batch (the first frame at or after the
2198 // failing one without the flag)
2199 let batch_end = find_batch_end(&frame_tx.frames, frame_idx);
2200
2201 if batch_end > frame_idx {
2202 skip_until_batch_end = Some(batch_end);
2203 } else {
2204 in_atomic_batch = false;
2205 }
2206 self.substate.clear_transient_storage();
2207 continue;
2208 }
2209
2210 // If this is the last frame of a batch (a frame without the flag), commit the batch
2211 if in_atomic_batch && !frame.is_atomic_batch() {
2212 self.substate.commit_backup(); // commit batch-level snapshot
2213 in_atomic_batch = false;
2214 }
2215
2216 // VERIFY frame enforcement: a reverted
2217 // VERIFY frame invalidates the transaction. A VERIFY frame that
2218 // succeeds WITHOUT calling APPROVE is valid (e.g. the expiry
2219 // verifier frame). A reverted VERIFY frame invalidates the tx;
2220 // batched VERIFY reverts are handled in the atomic-batch-revert
2221 // branch above (which also sets tx_invalid).
2222 if frame.execution_mode() == FrameMode::Verify && !frame_success {
2223 tx_invalid = true;
2224 break;
2225 }
2226
2227 // Clear transient storage between frames
2228 self.substate.clear_transient_storage();
2229 }
2230
2231 // Post-execution, per EIP-8141: "verify that `payer` has been set
2232 // (i.e. `payer != None`). If `payer` is set, refund any unpaid gas to
2233 // the payer. If it is not, the whole transaction is invalid."
2234 let ctx =
2235 self.frame_tx_context
2236 .as_ref()
2237 .ok_or(VMError::Internal(InternalError::Custom(
2238 "missing frame tx context".to_string(),
2239 )))?;
2240 if ctx.payer_address.is_none() {
2241 tx_invalid = true;
2242 }
2243
2244 if tx_invalid {
2245 // TX is invalid — Err must leave `db.current_accounts_state`
2246 // unchanged from before the tx (same contract as non-frame
2247 // `execute()`). Absorb the last live frame's backup (it has not
2248 // been cleared yet), then restore every absorbed frame's effects.
2249 // Substate is per-VM and discarded when this VM drops, so no
2250 // substate revert is needed.
2251 tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2252 crate::utils::restore_cache_state(self.db, tx_level_backup)?;
2253 return Err(VMError::TxValidation(
2254 crate::errors::TxValidationError::InvalidFrameTransaction,
2255 ));
2256 }
2257
2258 // Take ownership of frame context
2259 let ctx = self
2260 .frame_tx_context
2261 .take()
2262 .ok_or(VMError::Internal(InternalError::Custom(
2263 "missing frame tx context".to_string(),
2264 )))?;
2265 let payer = ctx.payer_address.unwrap_or(sender);
2266
2267 // EIP-8141 gas finalization. EIP-3529 storage refunds accumulate into a
2268 // single transaction-scoped counter across frames — `substate.refunded_gas`,
2269 // which a reverted frame or an unrolled atomic batch drops along with its
2270 // state changes — and are applied once here, capped at a fifth of the gas
2271 // used before refunds. The EIP-7623 calldata floor then applies to the frame
2272 // and signature data: the mandatory costs are always charged, and the data
2273 // cost is floored against what execution actually consumed.
2274 let mandatory_gas = frame_tx.mandatory_gas();
2275 let applied_refund = self
2276 .substate
2277 .refunded_gas
2278 .min(total_gas_used / crate::hooks::default_hook::MAX_REFUND_QUOTIENT);
2279 let data_and_execution = total_gas_used
2280 .saturating_sub(applied_refund)
2281 .saturating_sub(mandatory_gas);
2282 let total_gas_used =
2283 mandatory_gas.saturating_add(data_and_execution.max(frame_tx.calldata_floor_gas()));
2284
2285 // Gas refunds: the payer was debited the transaction's `max_cost` at
2286 // APPROVE (`max_gas` at `max_fee_per_gas`, plus the blob cost already at
2287 // the base rate, `compute_tx_max_cost`, §Gas accounting). What the payer
2288 // owes is the effective-rate cost of the gas actually used plus the same
2289 // base-rate blob burn, so the blob terms cancel and the burn is collected
2290 // exactly once and never refunded. Everything above that is returned here.
2291 // Intrinsic gas is inside `total_gas_used`, so it stays non-refundable.
2292 // When max_fee == effective_gas_price this reduces exactly to the unused
2293 // -frame-gas refund: max·T + B − e·U − B = e·(T − U).
2294 let effective_gas_price = self.env.gas_price;
2295 let charged = crate::opcode_handlers::frame_tx::compute_tx_max_cost(&ctx)
2296 .map_err(|_| VMError::Internal(InternalError::Overflow))?;
2297 let blob_burn = crate::utils::calculate_blob_gas_cost(
2298 &ctx.tx.blob_versioned_hashes,
2299 self.env.base_blob_fee_per_gas,
2300 )?;
2301 let owed = effective_gas_price
2302 .checked_mul(U256::from(total_gas_used))
2303 .and_then(|gas_owed| gas_owed.checked_add(blob_burn))
2304 .ok_or(VMError::Internal(InternalError::Overflow))?;
2305 // charged >= owed always: effective <= max_fee (by construction of the
2306 // effective price), the blob terms are identical, and total_gas_used <=
2307 // max_gas (frames are bounded by their limits, and the floor is charged
2308 // on both sides).
2309 let refund_amount = charged
2310 .checked_sub(owed)
2311 .ok_or(VMError::Internal(InternalError::Underflow))?;
2312
2313 self.increase_account_balance(payer, refund_amount)?;
2314
2315 // Pay coinbase. Mirror `pay_coinbase` on the normal-tx path so a frame
2316 // transaction has the same coinbase BlockAccessList / witness footprint:
2317 // EIP-7928 requires the coinbase to appear in the BAL for any user tx even
2318 // when the priority fee is zero, and EELS reads the coinbase account
2319 // unconditionally during fee transfer (so EIP-8025 witnesses record its
2320 // trie path even at zero fee). A frame tx is always a user tx, never a
2321 // system call, even when its effective gas price is zero (possible on a
2322 // chain whose base fee is zero).
2323 let priority_fee = effective_gas_price.saturating_sub(self.env.base_fee_per_gas);
2324 let coinbase_fee = priority_fee
2325 .checked_mul(U256::from(total_gas_used))
2326 .ok_or(VMError::Internal(InternalError::Overflow))?;
2327 if !self.env.is_system_call
2328 && let Some(recorder) = self.db.bal_recorder.as_mut()
2329 {
2330 recorder.record_touched_address(self.env.coinbase);
2331 }
2332 if coinbase_fee.is_zero() {
2333 // Zero priority fee: still read the coinbase so its witness/BAL trie
2334 // path (incl. an exclusion proof if absent) is recorded.
2335 self.db.get_account(self.env.coinbase)?;
2336 } else {
2337 self.increase_account_balance(self.env.coinbase, coinbase_fee)?;
2338 }
2339
2340 // EIP-8141: finalize self-destructs at tx end, mirroring the default
2341 // finalize hook ordering (refund -> coinbase -> delete). SELFDESTRUCT is
2342 // unrestricted during frame execution (the banned-opcode set only applies
2343 // to the mempool validation prefix), so a frame may mark same-tx-created
2344 // accounts for deletion (EIP-6780). Without this they leak into the
2345 // post-state. `iter_selfdestruct` walks the full substate chain, so a
2346 // single call here covers every committed frame. Any EIP-7708 burn logs
2347 // emitted (rare: only when a destroyed account later received ETH in the
2348 // same tx) are appended to the tx-level aggregate `all_logs`: the per-frame
2349 // consensus receipts have no slot for end-of-tx logs, but the header and
2350 // receipt blooms are derived from these aggregate logs (receipt.rs,
2351 // payload.rs), so they must be recorded there.
2352 //
2353 // KNOWN SPEC GAP (cross-client interop): these tx-end burn logs are in the
2354 // aggregate bloom but NOT in any per-frame consensus receipt, so a client
2355 // that re-derives the type-0x06 logs_bloom purely from the canonical
2356 // per-frame logs would compute a different bloom (part of the block hash).
2357 // ethrex producer and validator agree (both execute over the live
2358 // aggregate), so this is not an intra-client split; it only bites
2359 // cross-client and only for this rare destroy-after-receiving-ETH case.
2360 // EIP-7708 is silent on receipt placement and EIP-8141's frame receipt has
2361 // no tx-level logs slot, so the canonical home is genuinely undefined; do
2362 // not pin one (e.g. attribute to the last frame) unilaterally — confirm the
2363 // bloom-derivation rule against another client / the devnet first.
2364 let logs_before = self.substate.current_logs().len();
2365 crate::hooks::default_hook::delete_self_destruct_accounts(self)?;
2366 let mut logs_after = self.substate.current_logs();
2367 if logs_after.len() > logs_before {
2368 all_logs.extend(logs_after.split_off(logs_before));
2369 }
2370
2371 // Frame txs short-circuit the hook/finalize path, so the BackupHook never
2372 // runs and `db.tx_backup` stays None on the success path. A block builder
2373 // can execute a frame tx successfully and then reject it (e.g. the EIP-8037
2374 // 2D-gas overflow post-check, or an L2 invalid cross-chain message), calling
2375 // `undo_last_tx` — which needs the top-level backup to roll the committed
2376 // state back; otherwise the excluded tx's mutations leak into later txs and
2377 // the built block's state root diverges from re-execution. Populate it here
2378 // exactly as `BackupHook::finalize_execution` would: `tx_level_backup` holds
2379 // every committed frame's originals, and the outer call-frame backup now also
2380 // holds the refund/coinbase/self-destruct originals. Gated on
2381 // `preserve_top_level_backup` so it is set only when a hook reads it (L2);
2382 // on L1 the field is never consulted.
2383 if self.preserve_top_level_backup {
2384 tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2385 self.db.tx_backup = Some(tx_level_backup);
2386 }
2387
2388 // Derive top-level status from ALL frames: the transaction succeeded
2389 // only if every executed frame succeeded; a reverted or skipped frame of
2390 // ANY mode (SENDER, DEFAULT, VERIFY) yields a failed top-level status
2391 // (analogous to status 0 in standard transactions). This MUST match the
2392 // consensus-receipt derivation in `Receipt` decoding (receipt.rs), which
2393 // re-derives `succeeded` from the per-frame statuses ALONE — the
2394 // consensus `frame_receipt` carries no frame mode, so an all-frames rule
2395 // is the only definition the encode side (here) and a wire/trie decode
2396 // can compute identically. Deriving from SENDER frames only would make a
2397 // freshly-executed receipt's `status` disagree with the same receipt
2398 // decoded from consensus bytes. (A reverted VERIFY frame already
2399 // invalidated the tx above via `tx_invalid`; this additionally covers
2400 // reverted SENDER/DEFAULT frames, which do not.)
2401 let any_frame_reverted = ctx
2402 .frame_results
2403 .iter()
2404 .any(|(status, _, _)| *status != ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS);
2405
2406 let result = if any_frame_reverted {
2407 TxResult::Revert(VMError::RevertOpcode)
2408 } else {
2409 TxResult::Success
2410 };
2411
2412 // EIP-8037: report the transaction's net state gas (same formula as the
2413 // normal-tx path in default_hook). `total_gas_used` already includes the
2414 // state gas — it spilled into each frame's gas_remaining, exactly as for any
2415 // sub-TX_MAX_GAS_LIMIT transaction whose reservoir is 0 — so reporting
2416 // `state_gas_used` here lets the block-level regular/state split
2417 // (regular = gas_used - state_gas_used) attribute it to the state dimension
2418 // instead of billing the whole amount as regular gas.
2419 let state_gas_used =
2420 u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
2421
2422 // Unused frame gas in GAS UNITS for the report — distinct from the wei
2423 // refund above (which also returns the max-vs-effective fee delta).
2424 let frame_gas_used = total_gas_used.saturating_sub(intrinsic_gas);
2425 let gas_refund = sum_frame_gas_limits.saturating_sub(frame_gas_used);
2426
2427 let report = ExecutionReport {
2428 result,
2429 gas_used: total_gas_used,
2430 gas_spent: total_gas_used,
2431 gas_refunded: gas_refund,
2432 state_gas_used,
2433 output: Bytes::new(),
2434 logs: all_logs,
2435 payer_address: ctx.payer_address,
2436 frame_results: Some(ctx.frame_results),
2437 };
2438
2439 Ok(report)
2440 }
2441
2442 /// EIP-8141 mempool entry point: set up the frame-tx context and observer,
2443 /// then simulate the validation prefix.
2444 ///
2445 /// Performs the frame-tx preamble (static constraints, nonce, fee sanity,
2446 /// `FrameTxContext` init, outer-signature validation) — the same checks
2447 /// `execute_frame_tx` runs before any frame — then activates the
2448 /// [`ValidationObserver`](crate::validation_observer::ValidationObserver) for
2449 /// `sender` with the prefix's `deploy_index`, runs the prefix via
2450 /// [`VM::simulate_validation_prefix`], and returns the raw simulation
2451 /// result. Does NOT charge or refund gas. `canonical_paymaster_pay_frame`
2452 /// is the index of a canonical paymaster's pay frame (always `None` today,
2453 /// OQ1); when set, the access-restriction skip fires for that frame.
2454 pub fn run_frame_validation_prefix(
2455 &mut self,
2456 frame_indices: &[usize],
2457 deploy_index: Option<usize>,
2458 canonical_paymaster_pay_frame: Option<usize>,
2459 ) -> Result<PrefixSimResult, VMError> {
2460 use crate::validation_observer::ValidationObserver;
2461
2462 if self.env.config.fork < Fork::Hegota {
2463 return Err(VMError::TxValidation(
2464 crate::errors::TxValidationError::FrameTxPreFork,
2465 ));
2466 }
2467
2468 let frame_tx = match &self.tx {
2469 Transaction::FrameTransaction(ft) => ft.clone(),
2470 _ => {
2471 return Err(VMError::Internal(InternalError::Custom(
2472 "run_frame_validation_prefix called on non-frame tx".to_string(),
2473 )));
2474 }
2475 };
2476
2477 let sender = frame_tx.sender;
2478
2479 if frame_tx.validate_static_constraints().is_err() {
2480 return Err(VMError::TxValidation(
2481 crate::errors::TxValidationError::InvalidFrameTransaction,
2482 ));
2483 }
2484
2485 let sender_info = self.db.get_account(sender)?.info.clone();
2486 if sender_info.nonce != frame_tx.nonce {
2487 return Err(VMError::TxValidation(
2488 crate::errors::TxValidationError::NonceMismatch {
2489 expected: sender_info.nonce,
2490 actual: frame_tx.nonce,
2491 },
2492 ));
2493 }
2494
2495 if frame_tx.max_priority_fee_per_gas > frame_tx.max_fee_per_gas {
2496 return Err(VMError::TxValidation(
2497 crate::errors::TxValidationError::PriorityGreaterThanMaxFeePerGas {
2498 priority_fee: U256::from(frame_tx.max_priority_fee_per_gas),
2499 max_fee_per_gas: U256::from(frame_tx.max_fee_per_gas),
2500 },
2501 ));
2502 }
2503
2504 if U256::from(frame_tx.max_fee_per_gas) < self.env.base_fee_per_gas {
2505 return Err(VMError::TxValidation(
2506 crate::errors::TxValidationError::InsufficientMaxFeePerGas,
2507 ));
2508 }
2509
2510 let sig_hash = frame_tx.compute_sig_hash();
2511 let max_gas = frame_tx.max_gas();
2512 self.frame_tx_context = Some(FrameTxContext {
2513 sender_approved: false,
2514 payer_address: None,
2515 frame_results: Vec::new(),
2516 current_frame_index: 0,
2517 sig_hash,
2518 tx: frame_tx.clone(),
2519 approve_called_in_current_frame: false,
2520 max_gas,
2521 blob_base_fee: self.env.base_blob_fee_per_gas,
2522 });
2523
2524 if !validate_frame_signatures(
2525 &frame_tx.signatures,
2526 sig_hash,
2527 frame_tx.sender,
2528 self.env.config.fork,
2529 self.crypto,
2530 ) {
2531 return Err(VMError::TxValidation(
2532 crate::errors::TxValidationError::InvalidFrameTransaction,
2533 ));
2534 }
2535
2536 let expiry_verifier = ethrex_common::types::frame_tx_expiry_verifier();
2537 let mut observer = ValidationObserver::new(sender, deploy_index, expiry_verifier);
2538 observer.canonical_paymaster_pay_frame = canonical_paymaster_pay_frame;
2539 self.validation_observer = observer;
2540
2541 self.simulate_validation_prefix(frame_indices)
2542 }
2543
2544 /// EIP-8141 mempool validation-prefix simulation (local peer policy).
2545 ///
2546 /// Runs ONLY the validation-prefix frames (the verify/pay/deploy frames that
2547 /// must execute before the transaction's payer is established) of a frame
2548 /// transaction, under an active [`ValidationObserver`](crate::validation_observer::ValidationObserver),
2549 /// then stops as soon as the payer has been set. Reuses the real frame
2550 /// execution primitives (`eip7702_get_code`, `execute_default_code`,
2551 /// `run_execution`, substate backups, value transfer) over the DEFAULT/VERIFY
2552 /// subset that prefixes are restricted to (Phase 1 structural rules forbid
2553 /// SENDER and atomic-batch frames in the prefix), so it dispatches real
2554 /// opcodes through the real handlers — not a separate mini-EVM.
2555 ///
2556 /// `frame_indices` are the prefix frame indices (in order), as identified by
2557 /// `FrameTransaction::validation_prefix`; expiry-verifier frames interleaved
2558 /// in the prefix are run too (they may appear between prefix frames). The
2559 /// caller must have set `frame_tx_context` and activated the observer.
2560 ///
2561 /// Returns [`PrefixSimResult`] describing the outcome. Does NOT charge fees
2562 /// or refund gas (mempool simulation only); state changes accumulate in the
2563 /// shared `db` and are discarded by the caller (a fresh simulation database).
2564 pub fn simulate_validation_prefix(
2565 &mut self,
2566 frame_indices: &[usize],
2567 ) -> Result<PrefixSimResult, VMError> {
2568 let frame_tx = match &self.tx {
2569 Transaction::FrameTransaction(ft) => ft.clone(),
2570 _ => {
2571 return Err(VMError::Internal(InternalError::Custom(
2572 "simulate_validation_prefix called on non-frame tx".to_string(),
2573 )));
2574 }
2575 };
2576
2577 let sender = frame_tx.sender;
2578 let entry_point = ethrex_common::types::frame_tx_entry_point();
2579
2580 let mut total_gas_used: u64 = 0;
2581 let mut any_revert = false;
2582 // The highest prefix-frame index we must run before stopping. We run the
2583 // prefix in source order, executing every frame from 0 up to and
2584 // including the last prefix index (covering interleaved expiry frames).
2585 let last_prefix_idx = frame_indices.iter().copied().max();
2586
2587 for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
2588 // Stop once the whole prefix has run (and the payer break below).
2589 if let Some(stop) = last_prefix_idx {
2590 if frame_idx > stop {
2591 break;
2592 }
2593 } else {
2594 break;
2595 }
2596
2597 // Each independent prefix frame starts with a clean call-frame backup
2598 // so a later frame's failure only reverts its own effects.
2599 self.current_call_frame.call_frame_backup.clear();
2600
2601 let ctx =
2602 self.frame_tx_context
2603 .as_mut()
2604 .ok_or(VMError::Internal(InternalError::Custom(
2605 "missing frame tx context".to_string(),
2606 )))?;
2607 ctx.current_frame_index = frame_idx;
2608 ctx.approve_called_in_current_frame = false;
2609
2610 let target = frame.target.unwrap_or(sender);
2611
2612 // Sync observer per-frame fields before the frame runs.
2613 self.validation_observer.current_frame_index = frame_idx;
2614 self.validation_observer.current_frame_mode = frame.mode;
2615
2616 // Prefix frames are DEFAULT (deploy) or VERIFY only; both run with
2617 // ENTRY_POINT as caller (DEFAULT not static, VERIFY static).
2618 let (caller, is_static) = match frame.execution_mode() {
2619 FrameMode::Default => (entry_point, false),
2620 FrameMode::Verify => (entry_point, true),
2621 FrameMode::Sender => {
2622 // Structural rules exclude SENDER frames from the prefix.
2623 return Err(VMError::Internal(InternalError::Custom(
2624 "SENDER frame in validation prefix".to_string(),
2625 )));
2626 }
2627 };
2628
2629 self.env.origin = caller;
2630
2631 let (is_delegation_7702, _access_cost, code_address, bytecode) =
2632 crate::utils::eip7702_get_code(
2633 self.db,
2634 &mut self.substate,
2635 target,
2636 self.env.config.fork,
2637 )?;
2638
2639 self.substate.push_backup();
2640
2641 let value_transfer_reverted = if !frame.value.is_zero() {
2642 let sender_balance = self.db.get_account(sender)?.info.balance;
2643 frame_value_exceeds_balance(sender_balance, frame.value)
2644 } else {
2645 false
2646 };
2647
2648 let (frame_success, frame_gas_used) = if value_transfer_reverted {
2649 self.substate.revert_backup();
2650 self.restore_cache_state()?;
2651 (false, frame.gas_limit)
2652 } else if bytecode.is_empty() && !is_delegation_7702 {
2653 // Default-code path (target has neither code nor a delegation).
2654 if !frame.value.is_zero() {
2655 self.transfer(sender, target, frame.value)?;
2656 }
2657 use crate::opcode_handlers::frame_tx::execute_default_code;
2658 match execute_default_code(self, frame, target) {
2659 Ok((success, gas_used, _logs)) => {
2660 if success {
2661 self.substate.commit_backup();
2662 (true, gas_used)
2663 } else {
2664 self.substate.revert_backup();
2665 self.restore_cache_state()?;
2666 (false, gas_used)
2667 }
2668 }
2669 Err(_) => {
2670 self.substate.revert_backup();
2671 self.restore_cache_state()?;
2672 (false, frame.gas_limit)
2673 }
2674 }
2675 } else {
2676 // Normal code execution via a child CallFrame.
2677 let call_frame = CallFrame::new(
2678 caller,
2679 target,
2680 code_address,
2681 bytecode,
2682 frame.value,
2683 frame.data.clone().into(),
2684 is_static,
2685 frame.gas_limit,
2686 0,
2687 false,
2688 false,
2689 0,
2690 0,
2691 self.stack_pool.pop().unwrap_or_default(),
2692 Memory::default(),
2693 );
2694
2695 let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
2696 let saved_call_frames = mem::take(&mut self.call_frames);
2697
2698 if !frame.value.is_zero() {
2699 self.transfer(sender, target, frame.value)?;
2700 }
2701
2702 let frame_result = self.run_execution();
2703
2704 let result = match frame_result {
2705 Ok(ctx_result) => {
2706 let gas_used = ctx_result.gas_used;
2707 // The inner frame is the initial call frame, so `run_execution`
2708 // already committed (success) or reverted + restored the cache
2709 // (revert) this frame's backup via `handle_state_backup`. Only a
2710 // `VMError` (the `Err` arm) leaves the backup live for us to undo.
2711 (ctx_result.is_success(), gas_used)
2712 }
2713 Err(_e) => {
2714 self.substate.revert_backup();
2715 self.restore_cache_state()?;
2716 (false, frame.gas_limit)
2717 }
2718 };
2719
2720 let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
2721 self.call_frames = saved_call_frames;
2722 self.stack_pool.push(finished_frame.stack);
2723
2724 result
2725 };
2726
2727 total_gas_used = total_gas_used
2728 .checked_add(frame_gas_used)
2729 .ok_or(VMError::Internal(InternalError::Overflow))?;
2730
2731 if !frame_success {
2732 any_revert = true;
2733 }
2734
2735 // A reverted prefix frame is fatal: the transaction can never reach a
2736 // valid payer through a reverted verify/pay/deploy frame.
2737 if !frame_success {
2738 break;
2739 }
2740
2741 self.substate.clear_transient_storage();
2742
2743 // Stop as soon as the payer has been set (the prefix is complete).
2744 if self
2745 .frame_tx_context
2746 .as_ref()
2747 .and_then(|c| c.payer_address)
2748 .is_some()
2749 {
2750 break;
2751 }
2752 }
2753
2754 let ctx =
2755 self.frame_tx_context
2756 .as_ref()
2757 .ok_or(VMError::Internal(InternalError::Custom(
2758 "missing frame tx context".to_string(),
2759 )))?;
2760
2761 Ok(PrefixSimResult {
2762 any_revert,
2763 payer_address: ctx.payer_address,
2764 sender_approved: ctx.sender_approved,
2765 total_gas_used,
2766 })
2767 }
2768
2769 /// Must run after `prepare_execution` so EIP-7702 delegation is already resolved into
2770 /// `bytecode`.
2771 #[inline(always)]
2772 fn is_simple_transfer_fast_path(&self) -> bool {
2773 !self.current_call_frame.is_create
2774 && self.current_call_frame.bytecode.is_empty()
2775 // Privileged L2 txs can leave gas negative; let the slow path surface that as OOG.
2776 && self.current_call_frame.gas_remaining >= 0
2777 && self.tx.authorization_list().is_none()
2778 // Precompiles dispatch via run_execution even with empty bytecode.
2779 && !self.address_is_precompile(&self.current_call_frame.to)
2780 }
2781
2782 /// [`precompiles::is_precompile`], honoring simulation-only relocations from
2783 /// `movePrecompileToAddress`. Identical to the plain check on consensus paths,
2784 /// where `db.precompile_moves` is `None`.
2785 pub(crate) fn address_is_precompile(&self, address: &Address) -> bool {
2786 precompiles::is_precompile_with_moves(
2787 address,
2788 self.env.config.fork,
2789 self.vm_type,
2790 self.db.precompile_moves.as_deref(),
2791 )
2792 }
2793
2794 /// The address whose precompile implementation should execute for a call to
2795 /// `address` (identity mapping unless `address` is a relocation destination).
2796 pub(crate) fn effective_precompile_address(&self, address: Address) -> Address {
2797 precompiles::effective_precompile_address(address, self.db.precompile_moves.as_deref())
2798 }
2799
2800 /// Main execution loop.
2801 pub fn run_execution(&mut self) -> Result<ContextResult, VMError> {
2802 // If gas is already exhausted (negative), fail immediately.
2803 // This can happen when intrinsic gas exceeds the gas limit in privileged L2 transactions.
2804 // Without this check, casting negative gas_remaining to u64 would wrap to a huge value.
2805 if self.current_call_frame.gas_remaining < 0 {
2806 return Ok(ContextResult {
2807 result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2808 gas_used: self.current_call_frame.gas_limit,
2809 gas_spent: self.current_call_frame.gas_limit,
2810 output: Bytes::new(),
2811 });
2812 }
2813
2814 // EIP-8037: the atomic prepare region rolled back (one of its charges — 7702
2815 // auth, CREATE/value NEW_ACCOUNT, recipient delegation-resolve — OOG'd).
2816 // Burn all gas and revert the tx rather than rejecting it as invalid (which
2817 // would wrongly invalidate the block). Mirrors EELS depth-0
2818 // `except ExceptionalHalt: evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`
2819 // (`interpreter.py:366-374`).
2820 if self.pending_prep_oog {
2821 return Ok(ContextResult {
2822 result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2823 gas_used: self.current_call_frame.gas_limit,
2824 gas_spent: self.current_call_frame.gas_limit,
2825 output: Bytes::new(),
2826 });
2827 }
2828
2829 // A charged value-to-not-alive NEW_ACCOUNT means the recipient was not yet alive
2830 // at tx start and the tx transfers value. If the recipient is a precompile that
2831 // then exceptionally halts/reverts, the account is never materialized, so the
2832 // charge is rolled back in the precompile branch below (mirrors EELS
2833 // `refill_frame_state_gas`). Set in-region by `prepare_execution`.
2834 let top_frame_new_account_charged = self.value_new_account_charged;
2835
2836 #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
2837 if self.address_is_precompile(&self.current_call_frame.to) {
2838 // `execute_precompile` itself never touches state gas (it only mutates
2839 // `gas_remaining`; it takes `&self`, so it cannot change `state_gas_used` /
2840 // `state_gas_reservoir` / `state_gas_spill`) — the assert below guards that. The
2841 // in-region EIP-2780 value-to-not-alive NEW_ACCOUNT charge (`prepare_execution`),
2842 // however, IS frame state gas, and on an exceptional halt/revert it must be
2843 // rolled back (see below). `self` is borrowed by field rather than via
2844 // `&mut self.current_call_frame` so the refund call, which needs `&mut self`,
2845 // can run after `execute_precompile`.
2846 let state_gas_used_before_precompile = self.state_gas_used;
2847 let precompile_gas_limit = self.current_call_frame.gas_limit;
2848 let mut gas_remaining = self.current_call_frame.gas_remaining as u64;
2849 let result = self.execute_precompile(
2850 self.current_call_frame.code_address,
2851 &self.current_call_frame.calldata,
2852 precompile_gas_limit,
2853 &mut gas_remaining,
2854 );
2855
2856 debug_assert_eq!(
2857 self.state_gas_used, state_gas_used_before_precompile,
2858 "precompile execution must not mutate state_gas_used"
2859 );
2860
2861 // EIP-8037 Amsterdam 2D accounting recomputes `block_gas_used` from
2862 // `raw_consumed = gas_limit - gas_remaining` inside `refund_sender`. On a
2863 // top-level precompile exceptional halt, `handle_precompile_result` already
2864 // sets `ContextResult.gas_used = gas_limit`, but `gas_remaining` retains the
2865 // untouched forwarded amount — under Amsterdam that would make the block
2866 // report only the intrinsic portion. Zero it so the block matches the
2867 // `gas_used = gas_limit` contract from `handle_precompile_result`, and roll
2868 // back the in-region value NEW_ACCOUNT charge (the recipient is never materialized
2869 // on halt) so the burned gas counts entirely as regular gas, matching EELS
2870 // `refill_frame_state_gas`. Pre-Amsterdam reads `ctx_result.gas_used` directly
2871 // and is unaffected by this path either way.
2872 if self.env.config.fork >= Fork::Amsterdam
2873 && let Ok(ctx) = &result
2874 && !ctx.is_success()
2875 {
2876 gas_remaining = 0;
2877 self.refund_new_account_state_gas(top_frame_new_account_charged)?;
2878 }
2879
2880 self.current_call_frame.gas_remaining = gas_remaining as i64;
2881
2882 return result;
2883 }
2884
2885 // Specialize the dispatch loop on whether a struct-log tracer is active.
2886 // The `!TRACED` variant compiles out every tracer branch and capture call,
2887 // leaving a minimal hot loop (the common, non-traced case).
2888 match (self.opcode_tracer.active, self.validation_observer.active) {
2889 (false, false) => self.run_dispatch::<false, false>(),
2890 (false, true) => self.run_dispatch::<false, true>(),
2891 (true, false) => self.run_dispatch::<true, false>(),
2892 (true, true) => self.run_dispatch::<true, true>(),
2893 }
2894 }
2895
2896 /// Opcode dispatch loop, monomorphized over whether a struct-log tracer is
2897 /// active. With `TRACED = false` the compiler eliminates the tracer branches
2898 /// and the cold `trace_*_step` calls entirely, so the hot loop body stays
2899 /// minimal; the traced variant keeps the cold helpers out of line.
2900 fn run_dispatch<const TRACED: bool, const VALIDATING: bool>(
2901 &mut self,
2902 ) -> Result<ContextResult, VMError> {
2903 let mut error = OnceCell::<VMError>::new();
2904
2905 #[cfg(feature = "perf_opcode_timings")]
2906 let mut timings = crate::timings::OPCODE_TIMINGS.lock().expect("poison");
2907
2908 // Copy the `&'static` table pointer once; it doesn't borrow `self`, so dispatch can still
2909 // pass `self` mutably to the handler without reloading the pointer each iteration.
2910 let opcode_table = self.opcode_table;
2911
2912 loop {
2913 // Capture pc BEFORE advance_pc() — this is the address of the current opcode.
2914 let pc_of_current_op = self.current_call_frame.pc;
2915 let opcode = self.current_call_frame.next_opcode();
2916 self.advance_pc();
2917
2918 // EIP-8141 mempool validation-trace observer (single branch on the
2919 // fast path when inactive). Enforces the banned-opcode set and the
2920 // sequential `GAS`-before-`*CALL` rule before the handler runs.
2921 if VALIDATING {
2922 self.check_validation_banned_opcode(opcode);
2923 }
2924
2925 // Struct-log pre-step capture (compiled out entirely when !TRACED).
2926 let gas_before_op = if TRACED {
2927 self.trace_pre_step(opcode, pc_of_current_op)
2928 } else {
2929 0
2930 };
2931
2932 #[cfg(feature = "perf_opcode_timings")]
2933 let opcode_time_start = std::time::Instant::now();
2934
2935 #[allow(clippy::indexing_slicing, clippy::as_conversions)]
2936 let op_result = opcode_table[opcode as usize].call(self, &mut error);
2937
2938 #[cfg(feature = "perf_opcode_timings")]
2939 {
2940 let time = opcode_time_start.elapsed();
2941 timings.update(opcode, time);
2942 }
2943
2944 // Struct-log post-step (compiled out entirely when !TRACED).
2945 if TRACED {
2946 self.trace_post_step(gas_before_op, &error);
2947 }
2948
2949 let result = match op_result {
2950 OpcodeResult::Continue => continue,
2951 OpcodeResult::Halt => match error.take() {
2952 None => self.handle_opcode_result()?,
2953 Some(error) => self.handle_opcode_error(error)?,
2954 },
2955 };
2956
2957 // Return the ExecutionReport if the executed callframe was the first one.
2958 if self.is_initial_call_frame() {
2959 // Consume the backup (move it out) unless a `BackupHook` will read it afterward
2960 // to build the tx-level undo snapshot (L2 / stateless). On L1 nothing reads it
2961 // once the cache is restored, so cloning it would be dead work.
2962 self.handle_state_backup(&result, !self.preserve_top_level_backup)?;
2963 return Ok(result);
2964 }
2965
2966 // Handle interaction between child and parent callframe.
2967 self.handle_return(&result)?;
2968 }
2969 }
2970
2971 /// EIP-8141 validation-trace banned-opcode check (mempool simulation only).
2972 ///
2973 /// Called once per dispatch-loop iteration, AFTER the opcode is fetched and
2974 /// BEFORE the handler runs, gated by `self.validation_observer.active`. Byte
2975 /// values are pinned against `opcodes.rs`.
2976 ///
2977 /// Static bans: `ORIGIN`, `GASPRICE`, `BLOCKHASH`, `COINBASE`, `TIMESTAMP`
2978 /// (except when the current frame's target is EXPIRY_VERIFIER), `NUMBER`,
2979 /// `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBHASH`, `BLOBBASEFEE`, `INVALID`,
2980 /// `SELFDESTRUCT`, `BALANCE`, `SELFBALANCE`, `TLOAD`, `TSTORE`, and `CALLCODE`
2981 /// in non-deploy prefix frames (ERC-7562 bans CALLCODE in validation;
2982 /// DELEGATECALL is allowed subject to the CALL-family trace rules in the
2983 /// handlers). `SSTORE`/`CREATE`/`CREATE2` are allowed only inside the deploy
2984 /// frame and are enforced in their handlers (state-write rules), not here.
2985 ///
2986 /// Sequential `GAS` rule: `GAS` is allowed only immediately before a
2987 /// `*CALL` (`CALL`/`CALLCODE`/`DELEGATECALL`/`STATICCALL`). We detect this by
2988 /// remembering `last_opcode`: if the previous iteration was `GAS` and this
2989 /// opcode is NOT a `*CALL`, the prior `GAS` was illegal.
2990 pub fn check_validation_banned_opcode(&mut self, opcode: u8) {
2991 use crate::validation_observer::FrameSimViolation;
2992
2993 // Opcode bytes, pinned against `opcodes.rs`. The literal values are
2994 // asserted equal to the `Opcode` enum discriminants by
2995 // `validation_observer_opcode_byte_pins` below (avoids a `const`-context
2996 // `as` cast, which the workspace clippy config denies).
2997 const ORIGIN: u8 = 0x32;
2998 const GASPRICE: u8 = 0x3A;
2999 const BLOCKHASH: u8 = 0x40;
3000 const COINBASE: u8 = 0x41;
3001 const TIMESTAMP: u8 = 0x42;
3002 const NUMBER: u8 = 0x43;
3003 const PREVRANDAO: u8 = 0x44;
3004 const GASLIMIT: u8 = 0x45;
3005 const BASEFEE: u8 = 0x48;
3006 const BLOBHASH: u8 = 0x49;
3007 const BLOBBASEFEE: u8 = 0x4A;
3008 const INVALID: u8 = 0xFE;
3009 const SELFDESTRUCT: u8 = 0xFF;
3010 const BALANCE: u8 = 0x31;
3011 const SELFBALANCE: u8 = 0x47;
3012 const TLOAD: u8 = 0x5C;
3013 const TSTORE: u8 = 0x5D;
3014 const GAS: u8 = 0x5A;
3015 const CALL: u8 = 0xF1;
3016 const CALLCODE: u8 = 0xF2;
3017 const DELEGATECALL: u8 = 0xF4;
3018 const STATICCALL: u8 = 0xFA;
3019
3020 let is_call_family = matches!(opcode, CALL | CALLCODE | DELEGATECALL | STATICCALL);
3021
3022 // Sequential GAS rule: a `GAS` on the previous iteration is only legal if
3023 // THIS opcode is a `*CALL`. Evaluate before updating `last_opcode`.
3024 if self.validation_observer.last_opcode == GAS && !is_call_family {
3025 self.validation_observer
3026 .record_violation(FrameSimViolation::BannedOpcode(GAS));
3027 }
3028
3029 // Carry `GAS` forward for the next iteration's check; reset otherwise.
3030 self.validation_observer.last_opcode = if opcode == GAS { GAS } else { 0 };
3031
3032 let banned = match opcode {
3033 ORIGIN | GASPRICE | BLOCKHASH | COINBASE | NUMBER | PREVRANDAO | GASLIMIT | BASEFEE
3034 | BLOBHASH | BLOBBASEFEE | INVALID | SELFDESTRUCT | BALANCE | SELFBALANCE | TLOAD
3035 | TSTORE => true,
3036 // TIMESTAMP is permitted only when the currently executing contract
3037 // IS the EXPIRY_VERIFIER predeploy (checked by code_address so the
3038 // rule tracks the executing contract at every call depth, not just the
3039 // top-level frame target). A nested call FROM an expiry frame INTO
3040 // another contract is correctly banned; a nested call INTO the
3041 // predeploy from any frame is correctly allowed.
3042 TIMESTAMP => {
3043 self.current_call_frame.code_address != self.validation_observer.expiry_verifier
3044 }
3045 // CALLCODE is banned in non-deploy prefix frames (ERC-7562).
3046 CALLCODE => !self.validation_observer.in_deploy_frame(),
3047 _ => false,
3048 };
3049
3050 if banned {
3051 self.validation_observer
3052 .record_violation(FrameSimViolation::BannedOpcode(opcode));
3053 }
3054 }
3055
3056 /// EIP-8141 validation-trace `SLOAD` check (mempool simulation only).
3057 ///
3058 /// `SLOAD` is allowed only when the storage owner (`address`, the executing
3059 /// frame's `to`) is the transaction sender. Records the touched slot for the
3060 /// admission-time revalidation affected-set.
3061 pub fn validation_check_sload(&mut self, address: Address, slot: H256) {
3062 use crate::validation_observer::FrameSimViolation;
3063 if self.validation_observer.in_canonical_pay_frame() {
3064 return;
3065 }
3066 if address == self.validation_observer.sender {
3067 self.validation_observer.touched_sender_slots.push(slot);
3068 } else {
3069 self.validation_observer
3070 .record_violation(FrameSimViolation::StorageReadNonSender);
3071 }
3072 }
3073
3074 /// EIP-8141 validation-trace `SSTORE` check (mempool simulation only).
3075 ///
3076 /// `SSTORE` is allowed only inside the deploy frame AND only when the storage
3077 /// owner (`address`, the executing frame's `to`) is the transaction sender.
3078 pub fn validation_check_sstore(&mut self, address: Address, slot: H256) {
3079 use crate::validation_observer::FrameSimViolation;
3080 if self.validation_observer.in_canonical_pay_frame() {
3081 return;
3082 }
3083 if self.validation_observer.in_deploy_frame() && address == self.validation_observer.sender
3084 {
3085 self.validation_observer.touched_sender_slots.push(slot);
3086 } else {
3087 self.validation_observer
3088 .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
3089 }
3090 }
3091
3092 /// EIP-8141 validation-trace state-creation check for `CREATE`/`CREATE2`
3093 /// (mempool simulation only). Contract creation is a state write permitted
3094 /// only inside the deploy frame.
3095 pub fn validation_check_create(&mut self) {
3096 use crate::validation_observer::FrameSimViolation;
3097 if self.validation_observer.in_canonical_pay_frame() {
3098 return;
3099 }
3100 if !self.validation_observer.in_deploy_frame() {
3101 self.validation_observer
3102 .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
3103 }
3104 }
3105
3106 /// EIP-8141 validation-trace `CALL*`/`EXTCODE*` target check (mempool
3107 /// simulation only).
3108 ///
3109 /// The target must be an existing account or a precompile and must NOT be
3110 /// EIP-7702-delegated, except the sender running its own default code (the
3111 /// sender is exempt — its existence is a transaction precondition and it may
3112 /// have no code). `is_delegation_7702` is the flag already computed by
3113 /// `eip7702_get_code` in the CALL-family handlers, threaded in to avoid a
3114 /// second delegation resolution (and the `&mut VM` / `&mut db` borrow
3115 /// conflict a dispatch-loop stack-peek would create).
3116 pub fn validation_check_call_target(
3117 &mut self,
3118 target: Address,
3119 is_delegation_7702: bool,
3120 ) -> Result<(), VMError> {
3121 use crate::validation_observer::FrameSimViolation;
3122 if self.validation_observer.in_canonical_pay_frame() {
3123 return Ok(());
3124 }
3125 // The sender is always a legitimate target (its existence is a tx
3126 // precondition; it may legitimately have no code).
3127 if target == self.validation_observer.sender {
3128 return Ok(());
3129 }
3130 // A delegated target is disallowed in validation.
3131 if is_delegation_7702 {
3132 self.validation_observer
3133 .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
3134 return Ok(());
3135 }
3136 // Precompiles are always valid targets.
3137 if precompiles::is_precompile(&target, self.env.config.fork, self.vm_type) {
3138 return Ok(());
3139 }
3140 // Otherwise the target must be an existing (non-empty) account.
3141 if self.db.get_account(target)?.is_empty() {
3142 self.validation_observer
3143 .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
3144 }
3145 Ok(())
3146 }
3147
3148 /// EIP-8141 validation-trace `EXTCODE*` target check (mempool simulation
3149 /// only). Like [`VM::validation_check_call_target`], but resolves the
3150 /// EIP-7702 delegation flag itself (the EXTCODE handlers do not call
3151 /// `eip7702_get_code`). The `substate.add_accessed_address` warming the
3152 /// EXTCODE gas already performed has happened; resolving here only follows a
3153 /// delegation indicator to read its flag, mirroring the CALL-family path.
3154 pub fn validation_check_extcode_target(&mut self, target: Address) -> Result<(), VMError> {
3155 if self.validation_observer.in_canonical_pay_frame()
3156 || target == self.validation_observer.sender
3157 {
3158 return Ok(());
3159 }
3160 let (is_delegation_7702, _access_cost, _code_address, _bytecode) =
3161 crate::utils::eip7702_get_code(
3162 self.db,
3163 &mut self.substate,
3164 target,
3165 self.env.config.fork,
3166 )?;
3167 self.validation_check_call_target(target, is_delegation_7702)
3168 }
3169
3170 /// Struct-log pre-step capture, split out of the interpreter loop and kept
3171 /// cold + non-inlined so the hot dispatch loop stays small (this code is
3172 /// only reached when a struct-log tracer is active). Returns `gas_before`.
3173 #[cold]
3174 #[inline(never)]
3175 fn trace_pre_step(&mut self, opcode: u8, pc_of_current_op: usize) -> u64 {
3176 #[expect(
3177 clippy::as_conversions,
3178 reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3179 )]
3180 let gas_before = self.current_call_frame.gas_remaining.max(0) as u64;
3181 #[expect(
3182 clippy::as_conversions,
3183 reason = "call depth bounded by STACK_LIMIT=1024, fits in u32"
3184 )]
3185 let depth = (self.call_frames.len() as u32).saturating_add(1);
3186 let refund = self.substate.refunded_gas;
3187 let stack_view = self.collect_stack_for_trace();
3188 let mem_view = self.collect_memory_for_trace();
3189 // mem_size always reflects actual memory size, regardless of enable_memory.
3190 #[expect(
3191 clippy::as_conversions,
3192 reason = "memory size is bounded by gas; fits in u64"
3193 )]
3194 let mem_size_for_trace = self.current_call_frame.memory.len() as u64;
3195 let storage_kv = self.read_storage_for_trace(opcode);
3196 let return_data = if self.opcode_tracer.cfg.enable_return_data {
3197 self.current_call_frame.sub_return_data.clone()
3198 } else {
3199 Bytes::new()
3200 };
3201 #[expect(
3202 clippy::as_conversions,
3203 reason = "pc is usize, fits in u64 on supported targets"
3204 )]
3205 let pc_u64 = pc_of_current_op as u64;
3206 self.opcode_tracer.pre_step_capture(
3207 pc_u64,
3208 opcode,
3209 gas_before,
3210 depth,
3211 refund,
3212 &stack_view,
3213 &mem_view,
3214 mem_size_for_trace,
3215 &return_data,
3216 storage_kv,
3217 );
3218 gas_before
3219 }
3220
3221 /// Struct-log post-step: patch gas_cost, refund-after-op, and error into the
3222 /// buffered entry. Cold + non-inlined for the same reason as `trace_pre_step`.
3223 #[cold]
3224 #[inline(never)]
3225 fn trace_post_step(&mut self, gas_before_op: u64, error: &OnceCell<VMError>) {
3226 #[expect(
3227 clippy::as_conversions,
3228 reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3229 )]
3230 let gas_after = self.current_call_frame.gas_remaining.max(0) as u64;
3231 // Prefer the explicit opcode-overhead cost written by CALL/CREATE handlers;
3232 // fall back to the gas diff for all other opcodes.
3233 let gas_cost = self
3234 .opcode_tracer
3235 .last_opcode_gas_cost
3236 .take()
3237 .unwrap_or_else(|| gas_before_op.saturating_sub(gas_after));
3238 // refund-after-op matches geth's structLogger timing: for SSTORE and
3239 // (pre-London) SELFDESTRUCT, the refund counter shown is the value
3240 // *after* the opcode's accounting applied.
3241 let refund_after = self.substate.refunded_gas;
3242 let err_str = error.get().map(|e| e.to_string());
3243 self.opcode_tracer
3244 .finalize_step(gas_cost, refund_after, err_str.as_deref());
3245 }
3246
3247 /// Executes the precompile at `code_address` (a relocation destination resolves to the
3248 /// precompile it hosts) and handles the output that it returns, generating a report.
3249 /// The precompile reads `calldata` in place, even when it is a range of caller memory.
3250 pub fn execute_precompile(
3251 &self,
3252 code_address: Address,
3253 calldata: &CallData,
3254 gas_limit: u64,
3255 gas_remaining: &mut u64,
3256 ) -> Result<ContextResult, VMError> {
3257 let precompile_address = self.effective_precompile_address(code_address);
3258 let output = calldata.with_slice(|input| {
3259 precompiles::execute_precompile(
3260 precompile_address,
3261 input,
3262 gas_remaining,
3263 self.env.config.fork,
3264 self.db.store.precompile_cache(),
3265 self.crypto,
3266 self.stateless_validator,
3267 )
3268 })?;
3269 Self::handle_precompile_result(output, gas_limit, *gas_remaining)
3270 }
3271
3272 /// True if external transaction is a contract creation
3273 pub fn is_create(&self) -> Result<bool, InternalError> {
3274 Ok(self.current_call_frame.is_create)
3275 }
3276
3277 /// Emit every ETH-transfer log that applies to `value` moving `from` → `to`.
3278 ///
3279 /// Two independent logs exist and both are emitted when both apply:
3280 /// * the consensus EIP-7708 log from SYSTEM_ADDRESS, Amsterdam+ only. The EIP
3281 /// excludes self-transfers, since no balance changes.
3282 /// * the informational `eth_simulateV1` traceTransfers log from the
3283 /// TRACE_TRANSFER_ADDRESS sentinel. It is fork-independent and includes
3284 /// self-transfers, so what a client sees for the flag keeps its shape across
3285 /// Amsterdam activation rather than silently emptying out; geth's tracer is
3286 /// fork-independent for the same reason.
3287 ///
3288 /// `trace_to` is the recipient the trace log names. It differs from `to` only for
3289 /// CALLCODE, where the value stays with the caller: see
3290 /// [`VM::add_call_eth_transfer_logs`].
3291 fn push_eth_transfer_logs(
3292 &mut self,
3293 from: Address,
3294 to: Address,
3295 trace_to: Address,
3296 value: U256,
3297 ) {
3298 if value.is_zero() {
3299 return;
3300 }
3301 if self.env.config.fork >= Fork::Amsterdam && from != to {
3302 let log = crate::utils::create_eth_transfer_log(
3303 ethrex_common::constants::SYSTEM_ADDRESS,
3304 from,
3305 to,
3306 value,
3307 );
3308 self.substate.add_log(log);
3309 }
3310 if self.env.trace_eth_transfers {
3311 let log = crate::utils::create_eth_transfer_log(
3312 crate::constants::TRACE_TRANSFER_ADDRESS,
3313 from,
3314 trace_to,
3315 value,
3316 );
3317 self.substate.add_log(log);
3318 }
3319 }
3320
3321 /// Emit the ETH-transfer logs for `value` moving `from` → `to`.
3322 #[inline]
3323 pub fn add_eth_transfer_logs(&mut self, from: Address, to: Address, value: U256) {
3324 self.push_eth_transfer_logs(from, to, to, value);
3325 }
3326
3327 /// Message-call variant of [`VM::add_eth_transfer_logs`]. `callcode_target` is
3328 /// `Some` only for CALLCODE, whose value never leaves the caller: `to` is the
3329 /// caller itself, which suppresses the consensus log as a self-transfer, while the
3330 /// trace log still names the callee, as geth's tracer does (its `OnEnter` hook
3331 /// excludes DELEGATECALL and nothing else).
3332 #[inline]
3333 pub fn add_call_eth_transfer_logs(
3334 &mut self,
3335 from: Address,
3336 to: Address,
3337 callcode_target: Option<Address>,
3338 value: U256,
3339 ) {
3340 self.push_eth_transfer_logs(from, to, callcode_target.unwrap_or(to), value);
3341 }
3342
3343 /// Executes without making changes to the cache.
3344 pub fn stateless_execute(&mut self) -> Result<ExecutionReport, VMError> {
3345 // Add backup hook to restore state after execution. `add_hook` flips
3346 // `preserve_top_level_backup` on via `Hook::reads_top_level_backup`, so the backup is
3347 // cloned (not moved out) on the revert paths even though this VM was built with L1 `vm_type`.
3348 self.add_hook(BackupHook::default());
3349 let report = self.execute()?;
3350 // Restore cache to the state before execution.
3351 self.db.undo_last_transaction()?;
3352 Ok(report)
3353 }
3354
3355 fn prepare_execution(&mut self) -> Result<(), VMError> {
3356 // Clone each hook's `Rc` (cheap refcount bump) so the borrow on `self.hooks` is released
3357 // and `self` can be passed mutably — without `self.hooks.clone()`'s per-tx `Vec` realloc.
3358 // `self.hooks` is not mutated during the loop, so `get(i)` is always `Some` in range.
3359 for i in 0..self.hooks.len() {
3360 if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3361 hook.borrow_mut().prepare_execution(self)?;
3362 }
3363 }
3364
3365 Ok(())
3366 }
3367
3368 fn finalize_execution(
3369 &mut self,
3370 mut ctx_result: ContextResult,
3371 ) -> Result<ExecutionReport, VMError> {
3372 // EIP-8037: On top-level tx failure (REVERT, ExceptionalHalt, or OOG), the
3373 // execution portion of state gas has already been refilled into the reservoir by
3374 // the top-frame `refill_frame_state_gas` (seeded at the post-intrinsic baseline in
3375 // `add_intrinsic_gas` and fired on revert/halt in `handle_opcode_error` /
3376 // `handle_opcode_result`). The intrinsic portion stays in `state_gas_used` so block
3377 // accounting bills it. No reservoir-move is performed here. A create-tx collision
3378 // rolls its own in-region `NEW_ACCOUNT` charge (if any) back to the frame's entry
3379 // baseline inside `handle_create_transaction`'s collision branch, so there is
3380 // nothing left to refill here either (see that function).
3381 //
3382 // EIP-8037: there is no longer a separate create-failure `NEW_ACCOUNT`
3383 // refund here. The charge itself (`prepare_execution`) is now
3384 // conditioned on `get_pre_state_account(created_addr) == EMPTY_ACCOUNT`, so it
3385 // simply never fires for an already-alive target (positive balance implies
3386 // non-empty pre-state) and is rolled back by `handle_create_transaction` on
3387 // collision — matching EELS v7, which drops the created-target-alive output flag
3388 // entirely because `prepare_dispatch` never runs for a colliding create.
3389
3390 // See `prepare_execution`: per-hook `Rc::clone` avoids the `self.hooks.clone()` realloc.
3391 for i in 0..self.hooks.len() {
3392 if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3393 hook.borrow_mut()
3394 .finalize_execution(self, &mut ctx_result)?;
3395 }
3396 }
3397
3398 self.tracer.exit_context(&ctx_result, true)?;
3399
3400 // Struct-log end-of-tx capture: record final output, gas used, and revert error.
3401 // gas matches geth's `executionResult.Gas` which is post-refund (`receipt.GasUsed`).
3402 if self.opcode_tracer.active {
3403 self.opcode_tracer.output = ctx_result.output.clone();
3404 self.opcode_tracer.gas_used = ctx_result.gas_spent;
3405 self.opcode_tracer.error = match ctx_result.result {
3406 TxResult::Revert(ref err) => Some(err.to_string()),
3407 _ => None,
3408 };
3409 }
3410
3411 // Only include logs if transaction succeeded. When a transaction reverts,
3412 // no logs should be emitted (including EIP-7708 Transfer logs).
3413 let logs = if ctx_result.is_success() {
3414 self.substate.extract_logs()
3415 } else {
3416 Vec::new()
3417 };
3418
3419 // EIP-8037: `state_gas_used` is already net (signed; credits decrement it
3420 // inline), so `tx_state_gas = intrinsic_state_gas + state_gas_used` exactly
3421 // (EELS `fork.py::process_transaction`, which no longer carries a separate
3422 // tx-level refund channel). Clamp at zero — `state_gas_used` may be negative when
3423 // inline refunds exceed gross charges.
3424 let net_state_gas_used: u64 =
3425 u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
3426
3427 let report = ExecutionReport {
3428 result: ctx_result.result.clone(),
3429 gas_used: ctx_result.gas_used,
3430 gas_spent: ctx_result.gas_spent,
3431 gas_refunded: self.substate.refunded_gas,
3432 state_gas_used: net_state_gas_used,
3433 output: std::mem::take(&mut ctx_result.output),
3434 logs,
3435 payer_address: None,
3436 frame_results: None,
3437 };
3438
3439 Ok(report)
3440 }
3441
3442 // ── Struct-log helper methods ─────────────────────────────────────────────
3443
3444 /// Collects the current stack in bottom-first order for struct-log emission.
3445 ///
3446 /// LEVM stack is top-first in memory (`values[offset]` = top), so we reverse
3447 /// the active slice to produce the bottom-first wire format geth uses.
3448 /// Returns an empty `Vec` when `cfg.disable_stack` is true.
3449 pub fn collect_stack_for_trace(&self) -> Vec<U256> {
3450 use crate::constants::STACK_LIMIT;
3451 if self.opcode_tracer.cfg.disable_stack {
3452 return Vec::new();
3453 }
3454 let s = &self.current_call_frame.stack;
3455 // offset <= STACK_LIMIT by stack invariant.
3456 s.values
3457 .get(s.offset..STACK_LIMIT)
3458 .map(|slice| slice.iter().rev().copied().collect())
3459 .unwrap_or_default()
3460 }
3461
3462 /// Collects the live memory bytes for the current frame.
3463 ///
3464 /// Returns an empty `Vec` when `cfg.enable_memory` is false or memory is empty.
3465 pub fn collect_memory_for_trace(&self) -> Vec<u8> {
3466 if !self.opcode_tracer.cfg.enable_memory {
3467 return Vec::new();
3468 }
3469 self.current_call_frame.memory.live_bytes()
3470 }
3471
3472 /// Pre-reads the storage key/value for the current SLOAD or SSTORE opcode.
3473 ///
3474 /// Returns `None` when:
3475 /// - `cfg.disable_storage` is set, or
3476 /// - `opcode` is not SLOAD (0x54) or SSTORE (0x55), or
3477 /// - the stack is empty (guard against underflow before the handler runs), or
3478 /// - the storage read fails for any reason (including `AccountNotFound` —
3479 /// the trace omits the entry rather than emitting an ambiguous zero).
3480 ///
3481 /// For SLOAD: key = `stack.top`; value = the *current* stored value read from the DB.
3482 /// For SSTORE: key = `stack.top`, value = `stack[top-1]` (the new value being written).
3483 pub fn read_storage_for_trace(&mut self, opcode: u8) -> Option<(H256, H256)> {
3484 const SLOAD: u8 = 0x54;
3485 const SSTORE: u8 = 0x55;
3486
3487 if self.opcode_tracer.cfg.disable_storage {
3488 return None;
3489 }
3490 if opcode != SLOAD && opcode != SSTORE {
3491 return None;
3492 }
3493
3494 // Need at least one element on stack for SLOAD, two for SSTORE.
3495 use crate::constants::STACK_LIMIT;
3496 let offset = self.current_call_frame.stack.offset;
3497 if offset >= STACK_LIMIT {
3498 return None; // stack empty
3499 }
3500
3501 // SLOAD/SSTORE operate on the call's storage context (`to`), not the code's
3502 // address. Under DELEGATECALL/CALLCODE these differ.
3503 let addr = self.current_call_frame.to;
3504
3505 let stack_values = &self.current_call_frame.stack.values;
3506 let key_u256 = *stack_values.get(offset)?;
3507 let key = BigEndianHash::from_uint(&key_u256);
3508
3509 if opcode == SLOAD {
3510 // Omit the entry on any read failure (incl. account not yet cached);
3511 // a zero value would be indistinguishable from a legitimate never-written slot.
3512 let v = self.get_storage_value(addr, key).ok()?;
3513 let value = BigEndianHash::from_uint(&v);
3514 Some((key, value))
3515 } else {
3516 // SSTORE: need two stack elements.
3517 let next_offset = offset.checked_add(1)?;
3518 if next_offset >= STACK_LIMIT {
3519 return None;
3520 }
3521 // values[offset+1] is the new value being written (second from top = stack[top-1]).
3522 let value_u256 = *self.current_call_frame.stack.values.get(next_offset)?;
3523 let value = BigEndianHash::from_uint(&value_u256);
3524 Some((key, value))
3525 }
3526 }
3527}
3528
3529impl Substate {
3530 /// Initializes the VM substate, mainly adding addresses to the "accessed_addresses" field and the same with storage slots
3531 pub fn initialize(env: &Environment, tx: &Transaction) -> Result<Substate, VMError> {
3532 let fork = env.config.fork;
3533
3534 // Add sender and recipient to accessed accounts [https://www.evm.codes/about#access_list]
3535 // Precompiles are NO LONGER inserted here — they are warm by construction (see
3536 // `is_warm_precompile`), removing the ~20-entry floor that used to dominate this set. The
3537 // remaining working set is small (sender + coinbase + recipient + access-list/touched
3538 // addresses; real p99 ~7), so a capacity of 8 covers most txs with little waste.
3539 let mut initial_accessed_addresses =
3540 AccessedAddresses::with_capacity_and_hasher(8, Default::default());
3541 // Storage slots are ~98% empty (p95 0, p99 4), so `default()` (alloc-free until first
3542 // insert) beats pre-sizing, which would tax the common empty case.
3543 let mut initial_accessed_storage_slots = AccessedStorageSlots::default();
3544
3545 // Add Tx sender to accessed accounts
3546 initial_accessed_addresses.insert(env.origin);
3547
3548 // [EIP-3651] - Add coinbase to accessed accounts after Shanghai
3549 if fork >= Fork::Shanghai {
3550 initial_accessed_addresses.insert(env.coinbase);
3551 }
3552
3553 // Add access lists contents to accessed accounts and accessed storage slots.
3554 // Iterate by reference (`Address`/`H256` are `Copy`); the old `.clone()` deep-copied
3555 // the whole `Vec<(Address, Vec<H256>)>` per tx just to read it.
3556 for (address, keys) in tx.access_list() {
3557 initial_accessed_addresses.insert(*address);
3558 // Access lists can have different entries even for the same address, that's why we check if there's an existing set instead of considering it empty
3559 let warm_slots = initial_accessed_storage_slots.entry(*address).or_default();
3560 for slot in keys {
3561 warm_slots.insert(*slot);
3562 }
3563 }
3564
3565 let substate = Substate::from_accesses(
3566 fork,
3567 initial_accessed_addresses,
3568 initial_accessed_storage_slots,
3569 );
3570
3571 Ok(substate)
3572 }
3573}
3574
3575// Test-support surface for the EIP-8037 state-gas reservoir/clamp-spill unit tests, which live
3576// in the `ethrex-test` crate (`test/tests/levm/eip8037_reservoir_tests.rs`) per the repo's
3577// test-location convention but must drive crate-private VM internals. Everything here is
3578// `#[doc(hidden)]` and exposes only what those tests touch: a fixture-free VM harness plus a
3579// handful of reservoir accessors. The harness builds the VM via struct literal to sidestep
3580// `VM::new`'s DB reads (which would pull `ethrex-storage`/`ethrex-blockchain` into levm and form
3581// a dependency cycle), keeping the two-pool arithmetic isolated.
3582#[doc(hidden)]
3583impl<'a> VM<'a> {
3584 /// Gas budget seeded into the harness top frame; large enough that spills never run it OOG.
3585 pub const STATE_GAS_HARNESS_FRAME_GAS: u64 = 1_000_000;
3586
3587 /// Builds a fixture-free VM on `fork` with a single top frame and the given starting
3588 /// `state_gas_reservoir`. `db`/`tx`/`crypto` are borrowed for the VM's lifetime but never
3589 /// read (the frame is built directly, so no account/storage/code loads occur).
3590 pub fn new_state_gas_harness(
3591 fork: Fork,
3592 db: &'a mut GeneralizedDatabase,
3593 tx: &'a Transaction,
3594 crypto: &'a dyn Crypto,
3595 state_gas_reservoir: u64,
3596 ) -> VM<'a> {
3597 let env = Environment {
3598 config: crate::environment::EVMConfig::new(
3599 fork,
3600 crate::environment::EVMConfig::canonical_values(fork),
3601 ),
3602 gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3603 block_gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3604 ..Default::default()
3605 };
3606 let current_call_frame = CallFrame::new(
3607 Address::default(),
3608 Address::default(),
3609 Address::default(),
3610 Code::default(),
3611 U256::zero(),
3612 CallData::default(),
3613 false,
3614 Self::STATE_GAS_HARNESS_FRAME_GAS,
3615 0,
3616 true,
3617 false,
3618 0,
3619 0,
3620 Stack::default(),
3621 Memory::default(),
3622 );
3623 VM {
3624 call_frames: Vec::new(),
3625 current_call_frame,
3626 env,
3627 validate_base_fee: true,
3628 substate: Substate::default(),
3629 db,
3630 tx,
3631 hooks: Vec::new(),
3632 storage_original_values: Default::default(),
3633 tracer: LevmCallTracer::disabled(),
3634 opcode_tracer: LevmOpcodeTracer::disabled(),
3635 debug_mode: DebugMode::disabled(),
3636 stack_pool: Vec::new(),
3637 initcode_pool: Vec::new(),
3638 vm_type: VMType::L1,
3639 preserve_top_level_backup: false,
3640 state_gas_used: 0,
3641 state_gas_reservoir,
3642 state_gas_reservoir_initial: state_gas_reservoir,
3643 state_gas_spill: 0,
3644 cost_per_state_byte: 0,
3645 state_gas_new_account: 0,
3646 state_gas_storage_set: 0,
3647 state_gas_auth_base: 0,
3648 intrinsic_state_gas: 0,
3649 value_new_account_charged: false,
3650 prep_baseline_state_gas: 0,
3651 prep_baseline_reservoir: 0,
3652 prep_baseline_state_gas_spill: 0,
3653 prep_region_backup_marker: PrepareRegionBackupMarker::default(),
3654 pending_prep_oog: false,
3655 opcode_table: VM::build_opcode_table(fork),
3656 crypto,
3657 stateless_validator: None,
3658 validation_observer: ValidationObserver::disabled(),
3659 frame_tx_context: None,
3660 }
3661 }
3662
3663 pub fn state_gas_reservoir(&self) -> u64 {
3664 self.state_gas_reservoir
3665 }
3666 pub fn state_gas_used(&self) -> i64 {
3667 self.state_gas_used
3668 }
3669 pub fn state_gas_spill(&self) -> u64 {
3670 self.state_gas_spill
3671 }
3672 pub fn state_gas_new_account(&self) -> u64 {
3673 self.state_gas_new_account
3674 }
3675 pub fn set_state_gas_new_account(&mut self, v: u64) {
3676 self.state_gas_new_account = v;
3677 }
3678 /// Seeds the post-intrinsic baseline (mirrors `add_intrinsic_gas`): both the VM-level
3679 /// `state_gas_used` and the top frame's entry snapshot.
3680 pub fn seed_state_gas_baseline(&mut self, used: i64) {
3681 self.state_gas_used = used;
3682 self.current_call_frame.state_gas_used_at_entry = used;
3683 }
3684 pub fn frame_state_gas_used_at_entry(&self) -> i64 {
3685 self.current_call_frame.state_gas_used_at_entry
3686 }
3687 pub fn frame_gas_remaining(&self) -> i64 {
3688 self.current_call_frame.gas_remaining
3689 }
3690 pub fn set_frame_gas_remaining(&mut self, v: i64) {
3691 self.current_call_frame.gas_remaining = v;
3692 }
3693 pub fn frame_state_gas_spilled(&self) -> u64 {
3694 self.current_call_frame.frame_state_gas_spilled
3695 }
3696}