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