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 `repay_state_gas_spill` (EELS `incorporate_child`, success arm): once a
1241 /// successful child's gas has merged into this frame, the reservoir repays the spill
1242 /// still outstanding, up to what the reservoir holds.
1243 ///
1244 /// A refund can land in a different frame than the charge it undoes: the refunding
1245 /// frame's spill may be smaller than the refund, so the excess credits the reservoir
1246 /// even though the charge drew from `gas_remaining`. The merge is where the claim
1247 /// (this frame's spill) and the credit (the reservoir) first share a frame, so that
1248 /// is where the two pools settle between themselves.
1249 ///
1250 /// No state creation is undone, so `state_gas_used` does not move: the gas only
1251 /// crosses back between the pools it drifted across. Both settlements stay
1252 /// unchanged, which is what makes this repayment billing-neutral:
1253 /// - user gas (`gas_limit - gas_remaining - state_gas_reservoir`) is unchanged
1254 /// because `gas_remaining` rises by exactly what the reservoir loses;
1255 /// - the EIP-7778 regular dimension subtracts the cumulative `state_gas_spill`, so
1256 /// that counter drops by the repayment too — the reservoir (the state dimension)
1257 /// covered the charge after all, so it must stop being billed as regular gas.
1258 ///
1259 /// A failed child repays nothing: its rollback already restored the state whose
1260 /// removal any refund credited.
1261 #[expect(
1262 clippy::arithmetic_side_effects,
1263 reason = "subtractions proven safe by min()"
1264 )]
1265 pub fn repay_state_gas_spill(&mut self) -> Result<(), VMError> {
1266 debug_assert!(
1267 self.env.config.fork >= Fork::Amsterdam,
1268 "repay_state_gas_spill called pre-Amsterdam"
1269 );
1270 let repayment = self
1271 .state_gas_reservoir
1272 .min(self.current_call_frame.frame_state_gas_spilled);
1273 if repayment == 0 {
1274 return Ok(());
1275 }
1276 self.current_call_frame.gas_remaining = self
1277 .current_call_frame
1278 .gas_remaining
1279 .checked_add(i64::try_from(repayment).map_err(|_| InternalError::Overflow)?)
1280 .ok_or(InternalError::Overflow)?;
1281 // Safe: repayment = min(reservoir, frame spill) <= both.
1282 self.state_gas_reservoir -= repayment;
1283 self.current_call_frame.frame_state_gas_spilled -= repayment;
1284 // Block accounting: every frame spill is mirrored in the cumulative counter, so
1285 // it covers this repayment (`checked_sub` guards the invariant regardless).
1286 self.state_gas_spill = self
1287 .state_gas_spill
1288 .checked_sub(repayment)
1289 .ok_or(InternalError::Underflow)?;
1290 // EELS asserts the claim and the credit cannot both survive a repayment.
1291 debug_assert!(
1292 self.state_gas_reservoir == 0 || self.current_call_frame.frame_state_gas_spilled == 0
1293 );
1294 Ok(())
1295 }
1296
1297 /// EIP-8037 `refill_frame_state_gas`: roll back this frame's state gas in LIFO
1298 /// order on revert or exceptional halt, mirroring EELS `refill_frame_state_gas`.
1299 ///
1300 /// `entry` is the value of `state_gas_used` when this frame began executing
1301 /// (`current_call_frame.state_gas_used_at_entry`). The frame's net charge is
1302 /// `frame_used = state_gas_used - entry`. Of that, `frame_state_gas_spilled` was
1303 /// drawn from `gas_remaining` (spilled past the reservoir) and the remainder came
1304 /// from the reservoir. LIFO refill returns the spilled portion to `gas_remaining`
1305 /// first and the rest to the reservoir, restoring the exact pools the charges drew
1306 /// from. `state_gas_used` is rolled back to `entry` and the per-frame spill counter
1307 /// is cleared.
1308 ///
1309 /// Revert-vs-halt equivalence (load-bearing): on revert, the spilled gas returns to
1310 /// `gas_remaining` (raising the sender refund / lowering raw_consumed) while
1311 /// `state_gas_spill` drops by the same amount, so the regular dimension in
1312 /// `refund_sender` (default_hook) drops by exactly the refilled spill. On exceptional
1313 /// halt the caller subsequently sets `gas_remaining = 0` and burns it to the regular
1314 /// dimension — but `state_gas_spill` was already decremented here, so the spilled gas
1315 /// stays counted as regular. Both paths are correct.
1316 ///
1317 /// Must only be called for Amsterdam+ forks.
1318 pub fn refill_frame_state_gas(&mut self, entry: i64) -> Result<(), VMError> {
1319 debug_assert!(
1320 self.env.config.fork >= Fork::Amsterdam,
1321 "refill_frame_state_gas called pre-Amsterdam"
1322 );
1323 // The frame's net state-gas charge since it began executing. May be
1324 // negative when the frame's inline refunds (e.g. an SSTORE clearing a
1325 // slot an ancestor set) exceeded its own gross charges.
1326 let frame_used = self
1327 .state_gas_used
1328 .checked_sub(entry)
1329 .ok_or(InternalError::Underflow)?;
1330 let spilled = self.current_call_frame.frame_state_gas_spilled;
1331 // LIFO invariant: any remaining spill is undrained own-charge, so it
1332 // implies frame_used >= 0. A net-negative frame_used only arises after
1333 // credit_state_gas_refund has already drained all spill (spilled == 0).
1334 debug_assert!(
1335 frame_used >= 0 || spilled == 0,
1336 "negative frame_used with positive spill violates LIFO invariant \
1337 (frame_used={frame_used}, spilled={spilled})"
1338 );
1339 // LIFO: return the spilled portion (borrowed from gas_remaining) first.
1340 self.current_call_frame.gas_remaining = self
1341 .current_call_frame
1342 .gas_remaining
1343 .checked_add(i64::try_from(spilled).map_err(|_| InternalError::Overflow)?)
1344 .ok_or(InternalError::Overflow)?;
1345 // The remainder (drawn from the reservoir) flows back to the reservoir.
1346 let to_reservoir = frame_used
1347 .checked_sub(i64::try_from(spilled).map_err(|_| InternalError::Overflow)?)
1348 .ok_or(InternalError::Overflow)?;
1349 // `to_reservoir` is negative in the cross-ancestor refund case
1350 // (frame_used < 0); clamp so the reservoir never goes negative.
1351 let reservoir_signed =
1352 i64::try_from(self.state_gas_reservoir).map_err(|_| InternalError::Overflow)?;
1353 self.state_gas_reservoir = u64::try_from(
1354 reservoir_signed
1355 .checked_add(to_reservoir)
1356 .ok_or(InternalError::Overflow)?
1357 .max(0),
1358 )
1359 .map_err(|_| InternalError::Overflow)?;
1360 // Roll back state_gas_used to the frame's entry baseline.
1361 self.state_gas_used = entry;
1362 // Block accounting: the refilled spill is no longer regular gas.
1363 self.state_gas_spill = self
1364 .state_gas_spill
1365 .checked_sub(spilled)
1366 .ok_or(InternalError::Underflow)?;
1367 self.current_call_frame.frame_state_gas_spilled = 0;
1368 Ok(())
1369 }
1370
1371 /// EIP-8037: enters the atomic prepare region (EELS `interpreter.py`'s depth-0
1372 /// `try` around `set_delegation` + `prepare_dispatch`, `interpreter.py:353-375`).
1373 /// Must be called in `prepare_execution`, after the sender nonce bump and fee
1374 /// deduction (those survive a region rollback) but before the type-4 auth
1375 /// handling (the first region charge). Captures the pre-region state-gas
1376 /// baseline and the `call_frame_backup` key-space so `fail_prepare_region` can
1377 /// later undo exactly the region's writes.
1378 pub fn enter_prepare_region(&mut self) {
1379 self.prep_baseline_state_gas = self.current_call_frame.state_gas_used_at_entry;
1380 self.prep_baseline_reservoir = self.state_gas_reservoir;
1381 self.prep_baseline_state_gas_spill = self.state_gas_spill;
1382 let backup = &self.current_call_frame.call_frame_backup;
1383 let accounts: FxHashSet<Address> = backup.original_accounts_info.keys().copied().collect();
1384 let storage: FxHashSet<Address> = backup
1385 .original_account_storage_slots
1386 .keys()
1387 .copied()
1388 .collect();
1389 let code_hashes_len = backup.inserted_code_hashes.len();
1390 // Capture the region-entry state of every already-backed-up account so a
1391 // self-sponsored EIP-7702 authorization (or any in-region write to a
1392 // pre-region-touched account) can be reverted without disturbing its
1393 // pre-region nonce/fee writes. See `PrepareRegionBackupMarker::entry_state`.
1394 let entry_state: FxHashMap<Address, LevmAccount> = accounts
1395 .iter()
1396 .filter_map(|address| {
1397 self.db
1398 .current_accounts_state
1399 .get(address)
1400 .map(|account| (*address, account.clone()))
1401 })
1402 .collect();
1403 let bal_checkpoint = self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1404 self.prep_region_backup_marker = PrepareRegionBackupMarker {
1405 accounts,
1406 storage,
1407 code_hashes_len,
1408 entry_state,
1409 bal_checkpoint,
1410 };
1411 }
1412
1413 /// EIP-8037: rolls back the atomic prepare region on an internal OOG from any of
1414 /// its charges (7702 auth, CREATE/value `NEW_ACCOUNT`, recipient delegation-resolve).
1415 /// Restores every `call_frame_backup` entry added since `enter_prepare_region`
1416 /// (leaving the earlier sender nonce-bump / fee-deduction entries untouched),
1417 /// refills the frame's state gas back to the pre-region baseline, and sets
1418 /// `pending_prep_oog` so `run_execution` turns this into a full-gas revert
1419 /// instead of a tx-level rejection `Err` (which would wrongly invalidate the
1420 /// block). Mirrors EELS `restore_tx_state(prep_snapshot)` + `refill_frame_state_gas`
1421 /// (`interpreter.py:366-374`).
1422 pub fn fail_prepare_region(&mut self) {
1423 let marker = std::mem::take(&mut self.prep_region_backup_marker);
1424 let mut backup = std::mem::take(&mut self.current_call_frame.call_frame_backup);
1425
1426 // Restore + drop every account backup entry added during the region.
1427 let region_accounts: Vec<Address> = backup
1428 .original_accounts_info
1429 .keys()
1430 .filter(|address| !marker.accounts.contains(*address))
1431 .copied()
1432 .collect();
1433 for address in region_accounts {
1434 if let Some(account) = backup.original_accounts_info.remove(&address)
1435 && let Some(current_account) = self.db.current_accounts_state.get_mut(&address)
1436 {
1437 current_account.info = account.info;
1438 current_account.status = account.status;
1439 current_account.has_storage = account.has_storage;
1440 current_account.exists = account.exists;
1441 }
1442 }
1443
1444 // Restore + drop every storage backup entry added during the region.
1445 let region_storage: Vec<Address> = backup
1446 .original_account_storage_slots
1447 .keys()
1448 .filter(|address| !marker.storage.contains(*address))
1449 .copied()
1450 .collect();
1451 for address in region_storage {
1452 if let Some(slots) = backup.original_account_storage_slots.remove(&address)
1453 && let Some(current_account) = self.db.current_accounts_state.get_mut(&address)
1454 {
1455 for (key, value) in slots {
1456 current_account.storage.insert(key, value);
1457 }
1458 }
1459 }
1460
1461 // Evict codes the region inserted, mirroring `restore_cache_state`: a stale
1462 // by-hash cache entry would hide a later read of the same hash from the store.
1463 for code_hash in backup
1464 .inserted_code_hashes
1465 .split_off(marker.code_hashes_len)
1466 {
1467 self.db.codes.remove(&code_hash);
1468 }
1469
1470 self.current_call_frame.call_frame_backup = backup;
1471
1472 // Revert in-region writes to accounts that were already backed up before the
1473 // region (the marker filter above leaves these untouched to preserve their
1474 // pre-region nonce/fee writes, but first-write-wins backup means an in-region
1475 // write — e.g. a self-sponsored EIP-7702 authorization writing the sender's
1476 // delegation code + auth nonce bump — created no new backup entry). Restoring
1477 // to the region-entry snapshot undoes the in-region write while keeping the
1478 // pre-region writes baked into that snapshot. Mirrors EELS `restore_tx_state`.
1479 for (address, entry_account) in marker.entry_state {
1480 if let Some(current) = self.db.current_accounts_state.get_mut(&address) {
1481 current.info = entry_account.info;
1482 current.status = entry_account.status;
1483 current.has_storage = entry_account.has_storage;
1484 current.exists = entry_account.exists;
1485 }
1486 }
1487
1488 // Roll back the BAL recorder to region entry so an applied-then-reverted
1489 // delegation's code/nonce changes are discarded (demoted to an access-only
1490 // touch, matching EELS `restore_tx_state`). `restore` preserves touched
1491 // addresses — including the pre-charge authority touches recorded during
1492 // `set_delegation` — so a reverted authority still appears as an access.
1493 if let Some(checkpoint) = marker.bal_checkpoint
1494 && let Some(recorder) = self.db.bal_recorder.as_mut()
1495 {
1496 recorder.restore(checkpoint);
1497 }
1498
1499 // Rewind the state-gas machinery to the pre-region snapshot. The
1500 // `set_delegation` auth lock-in re-seeds `state_gas_used_at_entry` and zeroes
1501 // the frame spill, so `refill_frame_state_gas` (which derives the reservoir
1502 // credit from the frame spill) would leave the reservoir over-credited by the
1503 // locked-in auth state gas. Restore `state_gas_used`, the reservoir, and the
1504 // cumulative spill to the values captured by `enter_prepare_region`, and clear
1505 // the frame spill — this fully reverts the region's state charges (auth +
1506 // prepare-dispatch) regardless of the lock-in. Mirrors EELS
1507 // `restore_tx_state(prep_snapshot)` + `message.state_gas_reservoir = prep_reservoir`
1508 // (`interpreter.py:365-369`). `gas_remaining` is left as-is: the failing charge
1509 // already drove it negative, so `run_execution` burns all gas (EELS
1510 // `evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`).
1511 self.state_gas_used = self.prep_baseline_state_gas;
1512 self.state_gas_reservoir = self.prep_baseline_reservoir;
1513 self.state_gas_spill = self.prep_baseline_state_gas_spill;
1514 self.current_call_frame.frame_state_gas_spilled = 0;
1515 self.pending_prep_oog = true;
1516 }
1517
1518 /// Executes a whole external transaction. Performing validations at the beginning.
1519 pub fn execute(&mut self) -> Result<ExecutionReport, VMError> {
1520 // Detect frame transaction and branch to specialized execution
1521 if self.tx.tx_type() == TxType::Frame {
1522 return self.execute_frame_tx();
1523 }
1524
1525 if let Err(e) = self.prepare_execution() {
1526 // Restore cache to state previous to this Tx execution because this Tx is invalid.
1527 // Consume the backup unless a `BackupHook` will read it (L2 / stateless); on L1 it
1528 // is dead once the cache is restored.
1529 if self.preserve_top_level_backup {
1530 self.restore_cache_state()?;
1531 } else {
1532 self.restore_cache_state_consuming()?;
1533 }
1534 return Err(e);
1535 }
1536
1537 // Clear callframe backup so that changes made in prepare_execution are written in stone.
1538 // We want to apply these changes even if the Tx reverts. E.g. Incrementing sender nonce
1539 self.current_call_frame.call_frame_backup.clear();
1540
1541 // Empty bytecode would only execute STOP; skip the dispatch loop.
1542 // The BAL checkpoint below is intentionally skipped: a codeless transfer cannot
1543 // fail past this point and has no inner calls, so there's nothing to roll back.
1544 if self.is_simple_transfer_fast_path() {
1545 // EIP-8037: no `refill_frame_state_gas` needed here — a codeless transfer always
1546 // succeeds, runs no opcodes, and charges no execution state gas, so the frame's
1547 // `frame_state_gas_spilled` is 0 and `state_gas_used` equals its entry baseline.
1548 #[expect(clippy::as_conversions, reason = "gas_remaining is non-negative here")]
1549 let gas_used = self
1550 .current_call_frame
1551 .gas_limit
1552 .checked_sub(self.current_call_frame.gas_remaining as u64)
1553 .ok_or(InternalError::Underflow)?;
1554 let context_result = ContextResult {
1555 result: TxResult::Success,
1556 gas_used,
1557 gas_spent: gas_used,
1558 output: Bytes::new(),
1559 };
1560 return self.finalize_execution(context_result);
1561 }
1562
1563 // EIP-7928: Take a BAL checkpoint AFTER clearing the backup. This captures the state
1564 // after prepare_execution (nonce increment, etc.) but before actual execution.
1565 // When the top-level call fails, we restore to this checkpoint so that inner call
1566 // state changes (like value transfers) are reverted from the BAL.
1567 self.current_call_frame.call_frame_backup.bal_checkpoint =
1568 self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1569
1570 // EIP-8037: skip the CREATE nonce bump / endowment / collision check when the
1571 // atomic prepare region OOG'd (`pending_prep_oog`). EELS raises in
1572 // `prepare_dispatch` before `process_create_message` runs, so the contract is
1573 // never created — `run_execution` below emits the full-gas revert. Bumping the
1574 // nonce here would leave a phantom nonce=1 the region rollback can't reach.
1575 if !self.pending_prep_oog && self.is_create()? {
1576 // Create contract, reverting the Tx if address is already occupied.
1577 if let Some(context_result) = self.handle_create_transaction()? {
1578 let report = self.finalize_execution(context_result)?;
1579 return Ok(report);
1580 }
1581 }
1582
1583 self.substate.push_backup();
1584 let context_result = self.run_execution()?;
1585
1586 let report = self.finalize_execution(context_result)?;
1587
1588 Ok(report)
1589 }
1590
1591 /// Execute a frame transaction (EIP-8141).
1592 /// This bypasses the normal prepare/finalize hooks and orchestrates per-frame execution.
1593 fn execute_frame_tx(&mut self) -> Result<ExecutionReport, VMError> {
1594 use crate::errors::TxResult;
1595
1596 // EIP-8141 fork gating: reject frame transactions observed in a block or
1597 // submitted to any non-mempool entry point before Hegota activates.
1598 if self.env.config.fork < Fork::Hegota {
1599 return Err(VMError::TxValidation(
1600 crate::errors::TxValidationError::FrameTxPreFork,
1601 ));
1602 }
1603
1604 let frame_tx = match &self.tx {
1605 Transaction::FrameTransaction(ft) => ft.clone(),
1606 _ => unreachable!(),
1607 };
1608
1609 // Simplified validation (skip balance deduction, nonce increment, value transfer, EOA check)
1610 // Keep: gas limit checks, fee validation, nonce mismatch check.
1611 // The EOA-check skip is required by EIP-8141 §Transaction origination:
1612 // EIP-3607 must not apply to frame transactions, so the sender may have
1613 // contract code (SENDER frames legitimately originate from contract
1614 // accounts).
1615 let sender = frame_tx.sender;
1616
1617 // Validate static constraints (frame count, reserved modes, atomic batch flags)
1618 if let Err(_e) = frame_tx.validate_static_constraints() {
1619 return Err(VMError::TxValidation(
1620 crate::errors::TxValidationError::InvalidFrameTransaction,
1621 ));
1622 }
1623
1624 // Check nonce matches
1625 let sender_info = self.db.get_account(sender)?.info.clone();
1626 if sender_info.nonce != frame_tx.nonce {
1627 return Err(VMError::TxValidation(
1628 crate::errors::TxValidationError::NonceMismatch {
1629 expected: sender_info.nonce,
1630 actual: frame_tx.nonce,
1631 },
1632 ));
1633 }
1634
1635 // Check priority fee <= max fee
1636 if frame_tx.max_priority_fee_per_gas > frame_tx.max_fee_per_gas {
1637 return Err(VMError::TxValidation(
1638 crate::errors::TxValidationError::PriorityGreaterThanMaxFeePerGas {
1639 priority_fee: U256::from(frame_tx.max_priority_fee_per_gas),
1640 max_fee_per_gas: U256::from(frame_tx.max_fee_per_gas),
1641 },
1642 ));
1643 }
1644
1645 // Check max_fee >= base_fee
1646 if U256::from(frame_tx.max_fee_per_gas) < self.env.base_fee_per_gas {
1647 return Err(VMError::TxValidation(
1648 crate::errors::TxValidationError::InsufficientMaxFeePerGas,
1649 ));
1650 }
1651
1652 // EIP-4844 INSUFFICIENT_MAX_FEE_PER_BLOB_GAS: a blob-carrying tx whose
1653 // max_fee_per_blob_gas is below the block's base blob fee is invalid. The
1654 // frame path is self-contained and never runs the default hook's
1655 // validate_max_fee_per_blob_gas, so it is enforced here. APPROVE charges
1656 // the blob fee at the base rate unconditionally, so without this a frame tx
1657 // below the base blob fee would execute and silently overpay rather than be
1658 // rejected — a divergence from a conformant client that rejects it.
1659 if !frame_tx.blob_versioned_hashes.is_empty()
1660 && frame_tx.max_fee_per_blob_gas < self.env.base_blob_fee_per_gas
1661 {
1662 return Err(VMError::TxValidation(
1663 crate::errors::TxValidationError::InsufficientMaxFeePerBlobGas {
1664 base_fee_per_blob_gas: self.env.base_blob_fee_per_gas,
1665 tx_max_fee_per_blob_gas: frame_tx.max_fee_per_blob_gas,
1666 },
1667 ));
1668 }
1669
1670 // Initialize FrameTxContext
1671 let sig_hash = frame_tx.compute_sig_hash();
1672 let max_gas = frame_tx.max_gas();
1673 self.frame_tx_context = Some(FrameTxContext {
1674 sender_approved: false,
1675 payer_address: None,
1676 frame_results: Vec::new(),
1677 current_frame_index: 0,
1678 sig_hash,
1679 tx: frame_tx.clone(),
1680 approve_called_in_current_frame: false,
1681 max_gas,
1682 blob_base_fee: self.env.base_blob_fee_per_gas,
1683 });
1684
1685 // EIP-8141: every outer signature must validate
1686 // before any frame executes; otherwise the whole transaction is invalid.
1687 if !validate_frame_signatures(
1688 &frame_tx.signatures,
1689 sig_hash,
1690 frame_tx.sender,
1691 self.env.config.fork,
1692 self.crypto,
1693 ) {
1694 return Err(VMError::TxValidation(
1695 crate::errors::TxValidationError::InvalidFrameTransaction,
1696 ));
1697 }
1698
1699 // Tx-level rollback accumulator: if the tx is later declared invalid
1700 // after frames committed, restore `db.current_accounts_state` so the
1701 // payload builder (which reuses the shared db across txs) sees no
1702 // residue — same Err contract as non-frame `execute()`. The per-frame
1703 // backup is cleared between independent frames (and at batch entry), so
1704 // each frame's original values are absorbed here (first-seen-wins)
1705 // before that clear destroys them. Substate is per-VM and discarded on
1706 // Err, so it needs no snapshot.
1707 let mut tx_level_backup = crate::call_frame::CallFrameBackup {
1708 bal_checkpoint: self.db.bal_recorder.as_ref().map(|r| r.checkpoint()),
1709 ..Default::default()
1710 };
1711
1712 // ENTRY_POINT address used as caller for DEFAULT/VERIFY frames
1713 let entry_point = ethrex_common::types::frame_tx_entry_point();
1714
1715 let mut all_logs: Vec<Log> = Vec::new();
1716 let sum_frame_gas_limits: u64 = frame_tx
1717 .frames
1718 .iter()
1719 .map(|f| f.gas_limit)
1720 .fold(0u64, |acc, g| acc.saturating_add(g));
1721 // The non-frame part of `standard_gas_limit`, not of `max_gas`: when the
1722 // calldata floor dominates, the extra reservation is not intrinsic gas and
1723 // is applied once at settlement instead.
1724 let intrinsic_gas = frame_tx
1725 .mandatory_gas()
1726 .saturating_add(frame_tx.data_cost());
1727 let mut total_gas_used: u64 = intrinsic_gas;
1728 let mut tx_invalid = false;
1729
1730 // Atomic batching state: track whether we're inside a batch and
1731 // which frames belong to it so we can revert them all on failure.
1732 let mut in_atomic_batch = false;
1733 let mut batch_start_idx: usize = 0;
1734 let mut batch_logs_start: usize = 0;
1735 let mut batch_approval_snapshot: (bool, Option<Address>) = (false, None);
1736 let mut batch_bal_checkpoint: Option<BlockAccessListCheckpoint> = None;
1737 // EIP-8037: snapshot the shared `state_gas_used` at batch entry so a batch
1738 // revert (which unrolls every in-batch frame's state) also drops the state
1739 // gas those frames accumulated.
1740 let mut state_gas_used_at_batch_entry: i64 = 0;
1741 let mut skip_until_batch_end: Option<usize> = None; // skip remaining frames in a failed batch
1742
1743 // Execute frames sequentially
1744 for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
1745 // If we're skipping frames due to an atomic batch revert, record
1746 // the frame with status SKIPPED. Per EIP-8141, the
1747 // gas allotted to skipped frames is refunded at the end of the
1748 // transaction, so we record `gas_used = 0` and do NOT add the
1749 // frame's `gas_limit` to `total_gas_used`.
1750 //
1751 // Note (EIP-8141): an expiry verifier frame has flags
1752 // == 0, so it can only be a batch TERMINATOR, never a flagged
1753 // member. A failed batch therefore skips a trailing expiry frame
1754 // and its deadline is not checked at execution time. This is
1755 // benign, not a bypass: `compute_sig_hash` commits to the full
1756 // frame layout (modes, flags incl. the atomic-batch flag, targets,
1757 // and the expiry deadline), and the VERIFY signature is recovered
1758 // over that hash — so no relayer/proposer can wrap a signed tx's
1759 // expiry frame in a failing batch. Only the sender can build this
1760 // layout, and doing so merely disarms their own expiry. The normal
1761 // pattern (a standalone expiry VERIFY frame, not batched) is fully
1762 // enforced. The skip itself is spec-mandated batch semantics; do
1763 // not change it unilaterally — that would be a consensus divergence.
1764 if let Some(end_idx) = skip_until_batch_end {
1765 if frame_idx <= end_idx {
1766 let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
1767 InternalError::Custom("missing frame tx context".to_string()),
1768 ))?;
1769 ctx.current_frame_index = frame_idx;
1770 ctx.frame_results.push((
1771 ethrex_common::types::FRAME_RECEIPT_STATUS_SKIPPED,
1772 0,
1773 Vec::new(),
1774 ));
1775 if frame_idx == end_idx {
1776 skip_until_batch_end = None;
1777 in_atomic_batch = false;
1778 }
1779 continue;
1780 }
1781 skip_until_batch_end = None;
1782 in_atomic_batch = false;
1783 }
1784
1785 // Clear the outer call-frame backup at the start of each independent
1786 // frame so that a later frame's failure-path `restore_cache_state()`
1787 // only reverts that frame's own effects — not APPROVE/state deltas
1788 // produced by earlier, already-successful frames. Inside an open
1789 // atomic batch we keep accumulating, since a batch revert needs to
1790 // undo every in-batch frame's effects together.
1791 if !in_atomic_batch {
1792 // Absorb this frame's originals into the tx-level accumulator
1793 // before clearing, so an invalid-tx exit can still roll back
1794 // every committed frame's state (see `tx_level_backup`).
1795 tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
1796 self.current_call_frame.call_frame_backup.clear();
1797 }
1798
1799 // Start a new atomic batch if this frame has the batch flag
1800 // and we're not already in one.
1801 if !in_atomic_batch && frame.is_atomic_batch() {
1802 self.substate.push_backup(); // batch-level snapshot
1803 // EIP-7928: the batch's state changes must leave the block access
1804 // list as well when the batch unrolls, or the builder records
1805 // writes the block does not contain and the block fails its own
1806 // BAL validation on re-execution.
1807 batch_bal_checkpoint = self.db.bal_recorder.as_ref().map(|r| r.checkpoint());
1808 // The outer call-frame backup is already empty here: the
1809 // `!in_atomic_batch` block above absorbed it into
1810 // `tx_level_backup` and cleared it on entry to this frame, so
1811 // the batch starts accumulating a clean, self-contained set of
1812 // state changes that batch-revert can undo wholesale.
1813 in_atomic_batch = true;
1814 batch_start_idx = frame_idx;
1815 batch_logs_start = all_logs.len();
1816 state_gas_used_at_batch_entry = self.state_gas_used;
1817 // Snapshot approvals at batch entry: a batch revert must also
1818 // roll back approvals granted inside the batch (their balance
1819 // and nonce effects are reverted with the substate).
1820 batch_approval_snapshot = self
1821 .frame_tx_context
1822 .as_ref()
1823 .map(|c| c.approval_snapshot())
1824 .unwrap_or((false, None));
1825 }
1826
1827 let ctx =
1828 self.frame_tx_context
1829 .as_mut()
1830 .ok_or(VMError::Internal(InternalError::Custom(
1831 "missing frame tx context".to_string(),
1832 )))?;
1833 ctx.current_frame_index = frame_idx;
1834 ctx.approve_called_in_current_frame = false;
1835
1836 let target = frame.target.unwrap_or(sender);
1837
1838 // Determine caller and static mode per frame mode
1839 let (caller, is_static) = match frame.execution_mode() {
1840 FrameMode::Default => (entry_point, false),
1841 FrameMode::Verify => (entry_point, true),
1842 FrameMode::Sender => {
1843 // SENDER mode requires sender_approved
1844 let ctx = self.frame_tx_context.as_ref().ok_or(VMError::Internal(
1845 InternalError::Custom("missing frame tx context".to_string()),
1846 ))?;
1847 if !ctx.sender_approved {
1848 tx_invalid = true;
1849 break;
1850 }
1851 (sender, false)
1852 }
1853 };
1854
1855 // Set env.origin for this frame (ORIGIN opcode reads this)
1856 self.env.origin = caller;
1857
1858 // Resolve any EIP-7702 delegation at the resolved target. For a non-delegated
1859 // target this is equivalent to `db.get_account_code(target)`; for a delegated
1860 // target it follows the 0xef0100 || addr indicator and returns the delegatee's
1861 // bytecode plus the resolved code_address. EIP-8141 §Execution step 1 requires
1862 // delegated targets to execute the delegatee's code while keeping ADDRESS/storage
1863 // tied to the delegator — which is why `to` below stays `target` but the
1864 // CallFrame receives the resolved `code_address`. Mirrors the pattern used at
1865 // top-level tx entry in default_hook::set_bytecode_and_code_address.
1866 //
1867 // access_cost is intentionally discarded: this frame entry is analogous to a
1868 // top-level tx entry (a call from 0xaa / tx.sender, not a CALL opcode), and
1869 // default_hook.rs drops the same cost there. EIP-8141 §Execution is silent on
1870 // billing the 7702 access cost for `resolved_target`, so we keep frame-entry
1871 // behavior consistent with tx-entry behavior.
1872 let (is_delegation_7702, _access_cost, code_address, bytecode) =
1873 crate::utils::eip7702_get_code(
1874 self.db,
1875 &mut self.substate,
1876 target,
1877 self.env.config.fork,
1878 )?;
1879
1880 // Mirror default_hook::set_bytecode_and_code_address: when delegation was
1881 // followed, record the delegatee (code_address) as touched in BAL so EIP-7928
1882 // reconstructors see the cross-address read.
1883 if is_delegation_7702 && let Some(recorder) = self.db.bal_recorder.as_mut() {
1884 recorder.record_touched_address(code_address);
1885 }
1886
1887 // Log count of the scope this frame's backup will be committed into.
1888 // The CallFrame branch below relies on `run_execution` having already
1889 // committed the frame (merging its logs up into this scope), then
1890 // slices `[substate_logs_before..]` to recover exactly this frame's
1891 // logs without re-committing.
1892 let substate_logs_before = self.substate.logs_len();
1893
1894 // Push substate backup for per-frame state isolation
1895 self.substate.push_backup();
1896
1897 // EIP-8141 top-level value transfer: the outer
1898 // frame call owns CALLVALUE delivery. We only CHECK affordability
1899 // here; the actual transfer runs inside whichever branch executes
1900 // the frame, so it is recorded in the backup that branch restores on
1901 // failure (fixes the value-leak where a reverting contract-target
1902 // SENDER frame kept the funds). Static validation guarantees only
1903 // SENDER frames reach here with a non-zero value.
1904 let value_transfer_reverted = if !frame.value.is_zero() {
1905 let sender_balance = self.db.get_account(sender)?.info.balance;
1906 frame_value_exceeds_balance(sender_balance, frame.value)
1907 } else {
1908 false
1909 };
1910
1911 // Performs the deferred SENDER-frame value transfer + EIP-7708 log.
1912 // Invoked in BOTH execution branches so the transfer is recorded in
1913 // the call_frame_backup that branch's failure path restores.
1914 macro_rules! do_frame_value_transfer {
1915 () => {
1916 if !frame.value.is_zero() && !value_transfer_reverted {
1917 self.transfer(sender, target, frame.value)?;
1918 // EIP-7708 log parity with default_hook::transfer_value:
1919 // only Amsterdam+ and only when sender != target.
1920 if self.env.config.fork >= Fork::Amsterdam && sender != target {
1921 let log =
1922 crate::utils::create_eth_transfer_log(sender, target, frame.value);
1923 self.substate.add_log(log);
1924 }
1925 }
1926 };
1927 }
1928
1929 // EIP-8037: capture state-gas accounting before the frame runs so a
1930 // reverted frame (which commits no state) can be rolled back to
1931 // contribute zero state gas. The reservoir/spill are captured too:
1932 // each frame is gas-isolated, so an inline state-gas refund (e.g. an
1933 // SSTORE 0->N->0 clear, which credits the reservoir) inside one frame
1934 // must NOT carry over to a later frame's charges — the reservoir is
1935 // reset to this entry value after the frame completes.
1936 let state_gas_used_at_frame_entry = self.state_gas_used;
1937 let state_gas_reservoir_at_frame_entry = self.state_gas_reservoir;
1938 let state_gas_spill_at_frame_entry = self.state_gas_spill;
1939
1940 let (frame_success, frame_gas_used, frame_logs) = if value_transfer_reverted {
1941 self.substate.revert_backup();
1942 self.restore_cache_state()?;
1943 (false, frame.gas_limit, Vec::new())
1944 } else if bytecode.is_empty() && !is_delegation_7702 {
1945 // Default code runs only when the target has NEITHER code NOR a delegation
1946 // indicator (EIP-8141 §Execution). After eip7702_get_code,
1947 // bytecode is the delegatee's code when delegated, so a delegation to an
1948 // empty delegatee still falls into the CallFrame branch below and returns
1949 // success without executing anything — NOT into the default-code path.
1950 // current_call_frame is the OUTER frame here; its backup is the
1951 // one this branch's failure path restores, so the deferred
1952 // transfer is correctly undone on a default-code revert.
1953 do_frame_value_transfer!();
1954 use crate::opcode_handlers::frame_tx::execute_default_code;
1955 match execute_default_code(self, frame, target) {
1956 Ok((success, gas_used, logs)) => {
1957 if success {
1958 // Capture this frame's substate logs (incl. the
1959 // EIP-7708 transfer log added by
1960 // do_frame_value_transfer!) BEFORE commit_backup
1961 // merges them into the parent — mirrors the
1962 // CallFrame branch. execute_default_code returns its
1963 // own logs separately, so include both.
1964 let mut this_frame_logs = self.substate.current_logs();
1965 this_frame_logs.extend(logs);
1966 self.substate.commit_backup();
1967 (true, gas_used, this_frame_logs)
1968 } else {
1969 self.substate.revert_backup();
1970 self.restore_cache_state()?;
1971 (false, gas_used, Vec::new())
1972 }
1973 }
1974 Err(_) => {
1975 self.substate.revert_backup();
1976 self.restore_cache_state()?;
1977 (false, frame.gas_limit, Vec::new())
1978 }
1979 }
1980 } else {
1981 // Normal code execution via CallFrame. msg_value carries
1982 // `frame.value` so the contract sees the correct CALLVALUE
1983 // (EIP-8141 §Behavior), but `should_transfer_value` stays
1984 // false because the deferred `do_frame_value_transfer!()` below
1985 // (invoked after the frame swap) owns the transfer — the inner
1986 // CALL machinery must not move the funds a second time.
1987 let call_frame = CallFrame::new(
1988 caller, // msg_sender
1989 target, // to (delegator; ADDRESS/storage)
1990 code_address, // code_address (delegatee when 7702)
1991 bytecode, // bytecode (delegatee's code when 7702)
1992 frame.value, // msg_value -- CALLVALUE
1993 frame.data.clone(), // calldata
1994 is_static, // is_static
1995 frame.gas_limit, // gas_limit
1996 0, // depth
1997 false, // should_transfer_value (do_frame_value_transfer! handles it)
1998 false, // is_create
1999 0, // ret_offset
2000 0, // ret_size
2001 self.stack_pool.pop().unwrap_or_default(), // stack
2002 Memory::default(), // memory
2003 );
2004
2005 let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
2006 let saved_call_frames = mem::take(&mut self.call_frames);
2007
2008 // current_call_frame is now the INNER frame, so the deferred
2009 // transfer records into the inner backup that the revert failure
2010 // path (self.substate.revert_backup + restore_cache_state)
2011 // restores — fixing the value-leak on a reverting SENDER frame.
2012 do_frame_value_transfer!();
2013
2014 let frame_result = self.run_execution();
2015
2016 let result = match frame_result {
2017 Ok(ctx_result) => {
2018 let gas_used = ctx_result.gas_used;
2019 let success = ctx_result.is_success();
2020
2021 if success {
2022 // The inner frame is the initial call frame (call_frames
2023 // was emptied above), so `run_execution` already ran
2024 // `handle_state_backup` and committed this frame's backup,
2025 // merging its logs up into the scope measured by
2026 // `substate_logs_before`. Recover exactly this frame's logs
2027 // by slicing off everything that predated it — do NOT commit
2028 // again (a second commit would collapse an extra backup
2029 // level, breaking atomic-batch rollback) and do NOT read
2030 // `current_logs()` wholesale (it now also holds prior frames'
2031 // logs, which would duplicate them into frame_receipts[i]).
2032 let mut merged_logs = self.substate.current_logs();
2033 let this_frame_logs = merged_logs.split_off(substate_logs_before);
2034 (true, gas_used, this_frame_logs)
2035 } else {
2036 // A normal EVM revert reaches `handle_state_backup` inside
2037 // `run_execution`, which already reverted the backup and
2038 // restored the cache for this frame; repeating it here would
2039 // revert an extra level.
2040 (false, gas_used, Vec::new())
2041 }
2042 }
2043 Err(_e) => {
2044 // A `VMError` propagates out of `run_execution` before it reaches
2045 // `handle_state_backup`, so this frame's backup is still live and
2046 // must be reverted (and the cache restored) here.
2047 self.substate.revert_backup();
2048 self.restore_cache_state()?;
2049 (false, frame.gas_limit, Vec::new())
2050 }
2051 };
2052
2053 // Restore call frame state
2054 let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
2055 self.call_frames = saved_call_frames;
2056
2057 // When a frame succeeds inside an atomic batch, its state
2058 // changes must remain revertable at batch-revert time. Merge
2059 // the finished frame's backup into the outer call-frame backup
2060 // so that `restore_cache_state()` invoked by batch-revert can
2061 // undo them — and so the next clear-and-absorb folds them into
2062 // `tx_level_backup` too. Outside a batch, the finished frame's
2063 // backup never reaches the outer call frame, so absorb it
2064 // directly into `tx_level_backup` here; otherwise an invalid-tx
2065 // exit could not roll back this committed frame's state.
2066 if result.0 {
2067 if in_atomic_batch {
2068 self.merge_call_frame_backup_with_parent(
2069 &finished_frame.call_frame_backup,
2070 )?;
2071 } else {
2072 tx_level_backup.absorb(&finished_frame.call_frame_backup);
2073 }
2074 }
2075
2076 self.stack_pool.push(finished_frame.stack);
2077
2078 result
2079 };
2080
2081 // EIP-8037: a failed frame's state changes were reverted above, so it
2082 // creates no state and must contribute zero state gas. Roll the shared
2083 // `state_gas_used` back to this frame's entry value (the cache/substate
2084 // were already restored in the failure arms). Successful frames keep
2085 // their accumulated state gas.
2086 if !frame_success {
2087 self.state_gas_used = state_gas_used_at_frame_entry;
2088 }
2089 // EIP-8037: frames are gas-isolated, so the state-gas reservoir/spill
2090 // must not leak across the frame boundary. A reservoir credit from an
2091 // inline refund inside this frame (or a reverted frame's inflated
2092 // reservoir) would otherwise subsidize the next frame's state charges
2093 // (drawn before any spill to gas_remaining). Reset both to this frame's
2094 // entry value unconditionally — a successful frame already folded its
2095 // inline refund into `state_gas_used`, so the leftover reservoir credit
2096 // is spent and must be dropped.
2097 self.state_gas_reservoir = state_gas_reservoir_at_frame_entry;
2098 self.state_gas_spill = state_gas_spill_at_frame_entry;
2099
2100 total_gas_used = total_gas_used
2101 .checked_add(frame_gas_used)
2102 .ok_or(VMError::Internal(InternalError::Overflow))?;
2103 all_logs.extend(frame_logs.clone());
2104
2105 // Store frame result in context
2106 let ctx =
2107 self.frame_tx_context
2108 .as_mut()
2109 .ok_or(VMError::Internal(InternalError::Custom(
2110 "missing frame tx context".to_string(),
2111 )))?;
2112 let status_code = if frame_success {
2113 ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS
2114 } else {
2115 ethrex_common::types::FRAME_RECEIPT_STATUS_FAILURE
2116 };
2117 ctx.frame_results
2118 .push((status_code, frame_gas_used, frame_logs));
2119
2120 // Atomic batch: if a frame in the batch reverted, revert the
2121 // batch-level snapshot and skip remaining frames in the batch.
2122 if in_atomic_batch && !frame_success {
2123 self.substate.revert_backup(); // revert batch-level snapshot
2124 self.restore_cache_state()?;
2125 // EIP-7928: drop the batch's recorded changes. `restore` re-files a
2126 // freshly-written slot as a read and leaves `touched_addresses`
2127 // alone, so the accesses the batch made still appear -- only the
2128 // reverted changes go.
2129 if let Some(checkpoint) = batch_bal_checkpoint.take()
2130 && let Some(recorder) = self.db.bal_recorder.as_mut()
2131 {
2132 recorder.restore(checkpoint);
2133 }
2134 // EIP-8037: the whole batch unrolled, so none of its frames created
2135 // state — drop the state gas accumulated since batch entry.
2136 self.state_gas_used = state_gas_used_at_batch_entry;
2137
2138 // EIP-8141: frames that executed before the failure retain their
2139 // execution status and gas used; only their logs are discarded,
2140 // together with the state changes the unroll drops. `total_gas_used`
2141 // therefore stands as executed, and the failing frame keeps the gas
2142 // the single-frame path already charged it (actual `gas_used` for a
2143 // `REVERT`, the full `gas_limit` for an exceptional halt).
2144 let ctx = self.frame_tx_context.as_mut().ok_or(VMError::Internal(
2145 InternalError::Custom("missing frame tx context".to_string()),
2146 ))?;
2147 for result in ctx
2148 .frame_results
2149 .get_mut(batch_start_idx..=frame_idx)
2150 .into_iter()
2151 .flatten()
2152 {
2153 result.2 = Vec::new();
2154 }
2155 // Roll back approvals granted inside the reverted batch.
2156 ctx.restore_approvals(batch_approval_snapshot);
2157 // Remove only logs from the batch, preserving pre-batch logs
2158 all_logs.truncate(batch_logs_start);
2159
2160 // Spec: a reverted VERIFY frame invalidates the transaction even
2161 // inside an atomic batch. The batch unroll above already rolled
2162 // back state/approvals; validity is a tx-level decision. (The
2163 // failing `frame` here is the one that triggered the revert.)
2164 if frame.execution_mode() == FrameMode::Verify {
2165 tx_invalid = true;
2166 break;
2167 }
2168
2169 // Find the end of this batch (the first frame at or after the
2170 // failing one without the flag)
2171 let batch_end = find_batch_end(&frame_tx.frames, frame_idx);
2172
2173 if batch_end > frame_idx {
2174 skip_until_batch_end = Some(batch_end);
2175 } else {
2176 in_atomic_batch = false;
2177 }
2178 self.substate.clear_transient_storage();
2179 continue;
2180 }
2181
2182 // If this is the last frame of a batch (a frame without the flag), commit the batch
2183 if in_atomic_batch && !frame.is_atomic_batch() {
2184 self.substate.commit_backup(); // commit batch-level snapshot
2185 in_atomic_batch = false;
2186 }
2187
2188 // VERIFY frame enforcement: a reverted
2189 // VERIFY frame invalidates the transaction. A VERIFY frame that
2190 // succeeds WITHOUT calling APPROVE is valid (e.g. the expiry
2191 // verifier frame). A reverted VERIFY frame invalidates the tx;
2192 // batched VERIFY reverts are handled in the atomic-batch-revert
2193 // branch above (which also sets tx_invalid).
2194 if frame.execution_mode() == FrameMode::Verify && !frame_success {
2195 tx_invalid = true;
2196 break;
2197 }
2198
2199 // Clear transient storage between frames
2200 self.substate.clear_transient_storage();
2201 }
2202
2203 // Post-execution, per EIP-8141: "verify that `payer` has been set
2204 // (i.e. `payer != None`). If `payer` is set, refund any unpaid gas to
2205 // the payer. If it is not, the whole transaction is invalid."
2206 let ctx =
2207 self.frame_tx_context
2208 .as_ref()
2209 .ok_or(VMError::Internal(InternalError::Custom(
2210 "missing frame tx context".to_string(),
2211 )))?;
2212 if ctx.payer_address.is_none() {
2213 tx_invalid = true;
2214 }
2215
2216 if tx_invalid {
2217 // TX is invalid — Err must leave `db.current_accounts_state`
2218 // unchanged from before the tx (same contract as non-frame
2219 // `execute()`). Absorb the last live frame's backup (it has not
2220 // been cleared yet), then restore every absorbed frame's effects.
2221 // Substate is per-VM and discarded when this VM drops, so no
2222 // substate revert is needed.
2223 tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2224 crate::utils::restore_cache_state(self.db, tx_level_backup)?;
2225 return Err(VMError::TxValidation(
2226 crate::errors::TxValidationError::InvalidFrameTransaction,
2227 ));
2228 }
2229
2230 // Take ownership of frame context
2231 let ctx = self
2232 .frame_tx_context
2233 .take()
2234 .ok_or(VMError::Internal(InternalError::Custom(
2235 "missing frame tx context".to_string(),
2236 )))?;
2237 let payer = ctx.payer_address.unwrap_or(sender);
2238
2239 // EIP-8141 gas finalization. EIP-3529 storage refunds accumulate into a
2240 // single transaction-scoped counter across frames — `substate.refunded_gas`,
2241 // which a reverted frame or an unrolled atomic batch drops along with its
2242 // state changes — and are applied once here, capped at a fifth of the gas
2243 // used before refunds. The EIP-7623 calldata floor then applies to the frame
2244 // and signature data: the mandatory costs are always charged, and the data
2245 // cost is floored against what execution actually consumed.
2246 let mandatory_gas = frame_tx.mandatory_gas();
2247 let applied_refund = self
2248 .substate
2249 .refunded_gas
2250 .min(total_gas_used / crate::hooks::default_hook::MAX_REFUND_QUOTIENT);
2251 let data_and_execution = total_gas_used
2252 .saturating_sub(applied_refund)
2253 .saturating_sub(mandatory_gas);
2254 let total_gas_used =
2255 mandatory_gas.saturating_add(data_and_execution.max(frame_tx.calldata_floor_gas()));
2256
2257 // Gas refunds: the payer was debited the transaction's `max_cost` at
2258 // APPROVE (`max_gas` at `max_fee_per_gas`, plus the blob cost already at
2259 // the base rate, `compute_tx_max_cost`, §Gas accounting). What the payer
2260 // owes is the effective-rate cost of the gas actually used plus the same
2261 // base-rate blob burn, so the blob terms cancel and the burn is collected
2262 // exactly once and never refunded. Everything above that is returned here.
2263 // Intrinsic gas is inside `total_gas_used`, so it stays non-refundable.
2264 // When max_fee == effective_gas_price this reduces exactly to the unused
2265 // -frame-gas refund: max·T + B − e·U − B = e·(T − U).
2266 let effective_gas_price = self.env.gas_price;
2267 let charged = crate::opcode_handlers::frame_tx::compute_tx_max_cost(&ctx)
2268 .map_err(|_| VMError::Internal(InternalError::Overflow))?;
2269 let blob_burn = crate::utils::calculate_blob_gas_cost(
2270 &ctx.tx.blob_versioned_hashes,
2271 self.env.base_blob_fee_per_gas,
2272 )?;
2273 let owed = effective_gas_price
2274 .checked_mul(U256::from(total_gas_used))
2275 .and_then(|gas_owed| gas_owed.checked_add(blob_burn))
2276 .ok_or(VMError::Internal(InternalError::Overflow))?;
2277 // charged >= owed always: effective <= max_fee (by construction of the
2278 // effective price), the blob terms are identical, and total_gas_used <=
2279 // max_gas (frames are bounded by their limits, and the floor is charged
2280 // on both sides).
2281 let refund_amount = charged
2282 .checked_sub(owed)
2283 .ok_or(VMError::Internal(InternalError::Underflow))?;
2284
2285 self.increase_account_balance(payer, refund_amount)?;
2286
2287 // Pay coinbase. Mirror `pay_coinbase` on the normal-tx path so a frame
2288 // transaction has the same coinbase BlockAccessList / witness footprint:
2289 // EIP-7928 requires the coinbase to appear in the BAL for any user tx even
2290 // when the priority fee is zero, and EELS reads the coinbase account
2291 // unconditionally during fee transfer (so EIP-8025 witnesses record its
2292 // trie path even at zero fee). A frame tx is always a user tx (non-zero
2293 // effective gas price), unlike a system call.
2294 let priority_fee = effective_gas_price.saturating_sub(self.env.base_fee_per_gas);
2295 let coinbase_fee = priority_fee
2296 .checked_mul(U256::from(total_gas_used))
2297 .ok_or(VMError::Internal(InternalError::Overflow))?;
2298 if !effective_gas_price.is_zero()
2299 && let Some(recorder) = self.db.bal_recorder.as_mut()
2300 {
2301 recorder.record_touched_address(self.env.coinbase);
2302 }
2303 if coinbase_fee.is_zero() {
2304 // Zero priority fee: still read the coinbase so its witness/BAL trie
2305 // path (incl. an exclusion proof if absent) is recorded.
2306 self.db.get_account(self.env.coinbase)?;
2307 } else {
2308 self.increase_account_balance(self.env.coinbase, coinbase_fee)?;
2309 }
2310
2311 // EIP-8141: finalize self-destructs at tx end, mirroring the default
2312 // finalize hook ordering (refund -> coinbase -> delete). SELFDESTRUCT is
2313 // unrestricted during frame execution (the banned-opcode set only applies
2314 // to the mempool validation prefix), so a frame may mark same-tx-created
2315 // accounts for deletion (EIP-6780). Without this they leak into the
2316 // post-state. `iter_selfdestruct` walks the full substate chain, so a
2317 // single call here covers every committed frame. Any EIP-7708 burn logs
2318 // emitted (rare: only when a destroyed account later received ETH in the
2319 // same tx) are appended to the tx-level aggregate `all_logs`: the per-frame
2320 // consensus receipts have no slot for end-of-tx logs, but the header and
2321 // receipt blooms are derived from these aggregate logs (receipt.rs,
2322 // payload.rs), so they must be recorded there.
2323 //
2324 // KNOWN SPEC GAP (cross-client interop): these tx-end burn logs are in the
2325 // aggregate bloom but NOT in any per-frame consensus receipt, so a client
2326 // that re-derives the type-0x06 logs_bloom purely from the canonical
2327 // per-frame logs would compute a different bloom (part of the block hash).
2328 // ethrex producer and validator agree (both execute over the live
2329 // aggregate), so this is not an intra-client split; it only bites
2330 // cross-client and only for this rare destroy-after-receiving-ETH case.
2331 // EIP-7708 is silent on receipt placement and EIP-8141's frame receipt has
2332 // no tx-level logs slot, so the canonical home is genuinely undefined; do
2333 // not pin one (e.g. attribute to the last frame) unilaterally — confirm the
2334 // bloom-derivation rule against another client / the devnet first.
2335 let logs_before = self.substate.current_logs().len();
2336 crate::hooks::default_hook::delete_self_destruct_accounts(self)?;
2337 let mut logs_after = self.substate.current_logs();
2338 if logs_after.len() > logs_before {
2339 all_logs.extend(logs_after.split_off(logs_before));
2340 }
2341
2342 // Frame txs short-circuit the hook/finalize path, so the BackupHook never
2343 // runs and `db.tx_backup` stays None on the success path. A block builder
2344 // can execute a frame tx successfully and then reject it (e.g. the EIP-8037
2345 // 2D-gas overflow post-check, or an L2 invalid cross-chain message), calling
2346 // `undo_last_tx` — which needs the top-level backup to roll the committed
2347 // state back; otherwise the excluded tx's mutations leak into later txs and
2348 // the built block's state root diverges from re-execution. Populate it here
2349 // exactly as `BackupHook::finalize_execution` would: `tx_level_backup` holds
2350 // every committed frame's originals, and the outer call-frame backup now also
2351 // holds the refund/coinbase/self-destruct originals. Gated on
2352 // `preserve_top_level_backup` so it is set only when a hook reads it (L2);
2353 // on L1 the field is never consulted.
2354 if self.preserve_top_level_backup {
2355 tx_level_backup.absorb(&self.current_call_frame.call_frame_backup);
2356 self.db.tx_backup = Some(tx_level_backup);
2357 }
2358
2359 // Derive top-level status from ALL frames: the transaction succeeded
2360 // only if every executed frame succeeded; a reverted or skipped frame of
2361 // ANY mode (SENDER, DEFAULT, VERIFY) yields a failed top-level status
2362 // (analogous to status 0 in standard transactions). This MUST match the
2363 // consensus-receipt derivation in `Receipt` decoding (receipt.rs), which
2364 // re-derives `succeeded` from the per-frame statuses ALONE — the
2365 // consensus `frame_receipt` carries no frame mode, so an all-frames rule
2366 // is the only definition the encode side (here) and a wire/trie decode
2367 // can compute identically. Deriving from SENDER frames only would make a
2368 // freshly-executed receipt's `status` disagree with the same receipt
2369 // decoded from consensus bytes. (A reverted VERIFY frame already
2370 // invalidated the tx above via `tx_invalid`; this additionally covers
2371 // reverted SENDER/DEFAULT frames, which do not.)
2372 let any_frame_reverted = ctx
2373 .frame_results
2374 .iter()
2375 .any(|(status, _, _)| *status != ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS);
2376
2377 let result = if any_frame_reverted {
2378 TxResult::Revert(VMError::RevertOpcode)
2379 } else {
2380 TxResult::Success
2381 };
2382
2383 // EIP-8037: report the transaction's net state gas (same formula as the
2384 // normal-tx path in default_hook). `total_gas_used` already includes the
2385 // state gas — it spilled into each frame's gas_remaining, exactly as for any
2386 // sub-TX_MAX_GAS_LIMIT transaction whose reservoir is 0 — so reporting
2387 // `state_gas_used` here lets the block-level regular/state split
2388 // (regular = gas_used - state_gas_used) attribute it to the state dimension
2389 // instead of billing the whole amount as regular gas.
2390 let state_gas_used =
2391 u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
2392
2393 // Unused frame gas in GAS UNITS for the report — distinct from the wei
2394 // refund above (which also returns the max-vs-effective fee delta).
2395 let frame_gas_used = total_gas_used.saturating_sub(intrinsic_gas);
2396 let gas_refund = sum_frame_gas_limits.saturating_sub(frame_gas_used);
2397
2398 let report = ExecutionReport {
2399 result,
2400 gas_used: total_gas_used,
2401 gas_spent: total_gas_used,
2402 gas_refunded: gas_refund,
2403 state_gas_used,
2404 output: Bytes::new(),
2405 logs: all_logs,
2406 payer_address: ctx.payer_address,
2407 frame_results: Some(ctx.frame_results),
2408 };
2409
2410 Ok(report)
2411 }
2412
2413 /// EIP-8141 mempool entry point: set up the frame-tx context and observer,
2414 /// then simulate the validation prefix.
2415 ///
2416 /// Performs the frame-tx preamble (static constraints, nonce, fee sanity,
2417 /// `FrameTxContext` init, outer-signature validation) — the same checks
2418 /// `execute_frame_tx` runs before any frame — then activates the
2419 /// [`ValidationObserver`](crate::validation_observer::ValidationObserver) for
2420 /// `sender` with the prefix's `deploy_index`, runs the prefix via
2421 /// [`VM::simulate_validation_prefix`], and returns the raw simulation
2422 /// result. Does NOT charge or refund gas. `canonical_paymaster_pay_frame`
2423 /// is the index of a canonical paymaster's pay frame (always `None` today,
2424 /// OQ1); when set, the access-restriction skip fires for that frame.
2425 pub fn run_frame_validation_prefix(
2426 &mut self,
2427 frame_indices: &[usize],
2428 deploy_index: Option<usize>,
2429 canonical_paymaster_pay_frame: Option<usize>,
2430 ) -> Result<PrefixSimResult, VMError> {
2431 use crate::validation_observer::ValidationObserver;
2432
2433 if self.env.config.fork < Fork::Hegota {
2434 return Err(VMError::TxValidation(
2435 crate::errors::TxValidationError::FrameTxPreFork,
2436 ));
2437 }
2438
2439 let frame_tx = match &self.tx {
2440 Transaction::FrameTransaction(ft) => ft.clone(),
2441 _ => {
2442 return Err(VMError::Internal(InternalError::Custom(
2443 "run_frame_validation_prefix called on non-frame tx".to_string(),
2444 )));
2445 }
2446 };
2447
2448 let sender = frame_tx.sender;
2449
2450 if frame_tx.validate_static_constraints().is_err() {
2451 return Err(VMError::TxValidation(
2452 crate::errors::TxValidationError::InvalidFrameTransaction,
2453 ));
2454 }
2455
2456 let sender_info = self.db.get_account(sender)?.info.clone();
2457 if sender_info.nonce != frame_tx.nonce {
2458 return Err(VMError::TxValidation(
2459 crate::errors::TxValidationError::NonceMismatch {
2460 expected: sender_info.nonce,
2461 actual: frame_tx.nonce,
2462 },
2463 ));
2464 }
2465
2466 if frame_tx.max_priority_fee_per_gas > frame_tx.max_fee_per_gas {
2467 return Err(VMError::TxValidation(
2468 crate::errors::TxValidationError::PriorityGreaterThanMaxFeePerGas {
2469 priority_fee: U256::from(frame_tx.max_priority_fee_per_gas),
2470 max_fee_per_gas: U256::from(frame_tx.max_fee_per_gas),
2471 },
2472 ));
2473 }
2474
2475 if U256::from(frame_tx.max_fee_per_gas) < self.env.base_fee_per_gas {
2476 return Err(VMError::TxValidation(
2477 crate::errors::TxValidationError::InsufficientMaxFeePerGas,
2478 ));
2479 }
2480
2481 let sig_hash = frame_tx.compute_sig_hash();
2482 let max_gas = frame_tx.max_gas();
2483 self.frame_tx_context = Some(FrameTxContext {
2484 sender_approved: false,
2485 payer_address: None,
2486 frame_results: Vec::new(),
2487 current_frame_index: 0,
2488 sig_hash,
2489 tx: frame_tx.clone(),
2490 approve_called_in_current_frame: false,
2491 max_gas,
2492 blob_base_fee: self.env.base_blob_fee_per_gas,
2493 });
2494
2495 if !validate_frame_signatures(
2496 &frame_tx.signatures,
2497 sig_hash,
2498 frame_tx.sender,
2499 self.env.config.fork,
2500 self.crypto,
2501 ) {
2502 return Err(VMError::TxValidation(
2503 crate::errors::TxValidationError::InvalidFrameTransaction,
2504 ));
2505 }
2506
2507 let expiry_verifier = ethrex_common::types::frame_tx_expiry_verifier();
2508 let mut observer = ValidationObserver::new(sender, deploy_index, expiry_verifier);
2509 observer.canonical_paymaster_pay_frame = canonical_paymaster_pay_frame;
2510 self.validation_observer = observer;
2511
2512 self.simulate_validation_prefix(frame_indices)
2513 }
2514
2515 /// EIP-8141 mempool validation-prefix simulation (local peer policy).
2516 ///
2517 /// Runs ONLY the validation-prefix frames (the verify/pay/deploy frames that
2518 /// must execute before the transaction's payer is established) of a frame
2519 /// transaction, under an active [`ValidationObserver`](crate::validation_observer::ValidationObserver),
2520 /// then stops as soon as the payer has been set. Reuses the real frame
2521 /// execution primitives (`eip7702_get_code`, `execute_default_code`,
2522 /// `run_execution`, substate backups, value transfer) over the DEFAULT/VERIFY
2523 /// subset that prefixes are restricted to (Phase 1 structural rules forbid
2524 /// SENDER and atomic-batch frames in the prefix), so it dispatches real
2525 /// opcodes through the real handlers — not a separate mini-EVM.
2526 ///
2527 /// `frame_indices` are the prefix frame indices (in order), as identified by
2528 /// `FrameTransaction::validation_prefix`; expiry-verifier frames interleaved
2529 /// in the prefix are run too (they may appear between prefix frames). The
2530 /// caller must have set `frame_tx_context` and activated the observer.
2531 ///
2532 /// Returns [`PrefixSimResult`] describing the outcome. Does NOT charge fees
2533 /// or refund gas (mempool simulation only); state changes accumulate in the
2534 /// shared `db` and are discarded by the caller (a fresh simulation database).
2535 pub fn simulate_validation_prefix(
2536 &mut self,
2537 frame_indices: &[usize],
2538 ) -> Result<PrefixSimResult, VMError> {
2539 let frame_tx = match &self.tx {
2540 Transaction::FrameTransaction(ft) => ft.clone(),
2541 _ => {
2542 return Err(VMError::Internal(InternalError::Custom(
2543 "simulate_validation_prefix called on non-frame tx".to_string(),
2544 )));
2545 }
2546 };
2547
2548 let sender = frame_tx.sender;
2549 let entry_point = ethrex_common::types::frame_tx_entry_point();
2550
2551 let mut total_gas_used: u64 = 0;
2552 let mut any_revert = false;
2553 // The highest prefix-frame index we must run before stopping. We run the
2554 // prefix in source order, executing every frame from 0 up to and
2555 // including the last prefix index (covering interleaved expiry frames).
2556 let last_prefix_idx = frame_indices.iter().copied().max();
2557
2558 for (frame_idx, frame) in frame_tx.frames.iter().enumerate() {
2559 // Stop once the whole prefix has run (and the payer break below).
2560 if let Some(stop) = last_prefix_idx {
2561 if frame_idx > stop {
2562 break;
2563 }
2564 } else {
2565 break;
2566 }
2567
2568 // Each independent prefix frame starts with a clean call-frame backup
2569 // so a later frame's failure only reverts its own effects.
2570 self.current_call_frame.call_frame_backup.clear();
2571
2572 let ctx =
2573 self.frame_tx_context
2574 .as_mut()
2575 .ok_or(VMError::Internal(InternalError::Custom(
2576 "missing frame tx context".to_string(),
2577 )))?;
2578 ctx.current_frame_index = frame_idx;
2579 ctx.approve_called_in_current_frame = false;
2580
2581 let target = frame.target.unwrap_or(sender);
2582
2583 // Sync observer per-frame fields before the frame runs.
2584 self.validation_observer.current_frame_index = frame_idx;
2585 self.validation_observer.current_frame_mode = frame.mode;
2586
2587 // Prefix frames are DEFAULT (deploy) or VERIFY only; both run with
2588 // ENTRY_POINT as caller (DEFAULT not static, VERIFY static).
2589 let (caller, is_static) = match frame.execution_mode() {
2590 FrameMode::Default => (entry_point, false),
2591 FrameMode::Verify => (entry_point, true),
2592 FrameMode::Sender => {
2593 // Structural rules exclude SENDER frames from the prefix.
2594 return Err(VMError::Internal(InternalError::Custom(
2595 "SENDER frame in validation prefix".to_string(),
2596 )));
2597 }
2598 };
2599
2600 self.env.origin = caller;
2601
2602 let (is_delegation_7702, _access_cost, code_address, bytecode) =
2603 crate::utils::eip7702_get_code(
2604 self.db,
2605 &mut self.substate,
2606 target,
2607 self.env.config.fork,
2608 )?;
2609
2610 self.substate.push_backup();
2611
2612 let value_transfer_reverted = if !frame.value.is_zero() {
2613 let sender_balance = self.db.get_account(sender)?.info.balance;
2614 frame_value_exceeds_balance(sender_balance, frame.value)
2615 } else {
2616 false
2617 };
2618
2619 let (frame_success, frame_gas_used) = if value_transfer_reverted {
2620 self.substate.revert_backup();
2621 self.restore_cache_state()?;
2622 (false, frame.gas_limit)
2623 } else if bytecode.is_empty() && !is_delegation_7702 {
2624 // Default-code path (target has neither code nor a delegation).
2625 if !frame.value.is_zero() {
2626 self.transfer(sender, target, frame.value)?;
2627 }
2628 use crate::opcode_handlers::frame_tx::execute_default_code;
2629 match execute_default_code(self, frame, target) {
2630 Ok((success, gas_used, _logs)) => {
2631 if success {
2632 self.substate.commit_backup();
2633 (true, gas_used)
2634 } else {
2635 self.substate.revert_backup();
2636 self.restore_cache_state()?;
2637 (false, gas_used)
2638 }
2639 }
2640 Err(_) => {
2641 self.substate.revert_backup();
2642 self.restore_cache_state()?;
2643 (false, frame.gas_limit)
2644 }
2645 }
2646 } else {
2647 // Normal code execution via a child CallFrame.
2648 let call_frame = CallFrame::new(
2649 caller,
2650 target,
2651 code_address,
2652 bytecode,
2653 frame.value,
2654 frame.data.clone(),
2655 is_static,
2656 frame.gas_limit,
2657 0,
2658 false,
2659 false,
2660 0,
2661 0,
2662 self.stack_pool.pop().unwrap_or_default(),
2663 Memory::default(),
2664 );
2665
2666 let saved_call_frame = mem::replace(&mut self.current_call_frame, call_frame);
2667 let saved_call_frames = mem::take(&mut self.call_frames);
2668
2669 if !frame.value.is_zero() {
2670 self.transfer(sender, target, frame.value)?;
2671 }
2672
2673 let frame_result = self.run_execution();
2674
2675 let result = match frame_result {
2676 Ok(ctx_result) => {
2677 let gas_used = ctx_result.gas_used;
2678 // The inner frame is the initial call frame, so `run_execution`
2679 // already committed (success) or reverted + restored the cache
2680 // (revert) this frame's backup via `handle_state_backup`. Only a
2681 // `VMError` (the `Err` arm) leaves the backup live for us to undo.
2682 (ctx_result.is_success(), gas_used)
2683 }
2684 Err(_e) => {
2685 self.substate.revert_backup();
2686 self.restore_cache_state()?;
2687 (false, frame.gas_limit)
2688 }
2689 };
2690
2691 let finished_frame = mem::replace(&mut self.current_call_frame, saved_call_frame);
2692 self.call_frames = saved_call_frames;
2693 self.stack_pool.push(finished_frame.stack);
2694
2695 result
2696 };
2697
2698 total_gas_used = total_gas_used
2699 .checked_add(frame_gas_used)
2700 .ok_or(VMError::Internal(InternalError::Overflow))?;
2701
2702 if !frame_success {
2703 any_revert = true;
2704 }
2705
2706 // A reverted prefix frame is fatal: the transaction can never reach a
2707 // valid payer through a reverted verify/pay/deploy frame.
2708 if !frame_success {
2709 break;
2710 }
2711
2712 self.substate.clear_transient_storage();
2713
2714 // Stop as soon as the payer has been set (the prefix is complete).
2715 if self
2716 .frame_tx_context
2717 .as_ref()
2718 .and_then(|c| c.payer_address)
2719 .is_some()
2720 {
2721 break;
2722 }
2723 }
2724
2725 let ctx =
2726 self.frame_tx_context
2727 .as_ref()
2728 .ok_or(VMError::Internal(InternalError::Custom(
2729 "missing frame tx context".to_string(),
2730 )))?;
2731
2732 Ok(PrefixSimResult {
2733 any_revert,
2734 payer_address: ctx.payer_address,
2735 sender_approved: ctx.sender_approved,
2736 total_gas_used,
2737 })
2738 }
2739
2740 /// Must run after `prepare_execution` so EIP-7702 delegation is already resolved into
2741 /// `bytecode`.
2742 #[inline(always)]
2743 fn is_simple_transfer_fast_path(&self) -> bool {
2744 !self.current_call_frame.is_create
2745 && self.current_call_frame.bytecode.is_empty()
2746 // Privileged L2 txs can leave gas negative; let the slow path surface that as OOG.
2747 && self.current_call_frame.gas_remaining >= 0
2748 && self.tx.authorization_list().is_none()
2749 // Precompiles dispatch via run_execution even with empty bytecode.
2750 && !precompiles::is_precompile(
2751 &self.current_call_frame.to,
2752 self.env.config.fork,
2753 self.vm_type,
2754 )
2755 }
2756
2757 /// Main execution loop.
2758 pub fn run_execution(&mut self) -> Result<ContextResult, VMError> {
2759 // If gas is already exhausted (negative), fail immediately.
2760 // This can happen when intrinsic gas exceeds the gas limit in privileged L2 transactions.
2761 // Without this check, casting negative gas_remaining to u64 would wrap to a huge value.
2762 if self.current_call_frame.gas_remaining < 0 {
2763 return Ok(ContextResult {
2764 result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2765 gas_used: self.current_call_frame.gas_limit,
2766 gas_spent: self.current_call_frame.gas_limit,
2767 output: Bytes::new(),
2768 });
2769 }
2770
2771 // EIP-8037: the atomic prepare region rolled back (one of its charges — 7702
2772 // auth, CREATE/value NEW_ACCOUNT, recipient delegation-resolve — OOG'd).
2773 // Burn all gas and revert the tx rather than rejecting it as invalid (which
2774 // would wrongly invalidate the block). Mirrors EELS depth-0
2775 // `except ExceptionalHalt: evm.regular_gas_used += evm.gas_left; evm.gas_left = 0`
2776 // (`interpreter.py:366-374`).
2777 if self.pending_prep_oog {
2778 return Ok(ContextResult {
2779 result: TxResult::Revert(ExceptionalHalt::OutOfGas.into()),
2780 gas_used: self.current_call_frame.gas_limit,
2781 gas_spent: self.current_call_frame.gas_limit,
2782 output: Bytes::new(),
2783 });
2784 }
2785
2786 // A charged value-to-not-alive NEW_ACCOUNT means the recipient was not yet alive
2787 // at tx start and the tx transfers value. If the recipient is a precompile that
2788 // then exceptionally halts/reverts, the account is never materialized, so the
2789 // charge is rolled back in the precompile branch below (mirrors EELS
2790 // `refill_frame_state_gas`). Set in-region by `prepare_execution`.
2791 let top_frame_new_account_charged = self.value_new_account_charged;
2792
2793 #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
2794 if precompiles::is_precompile(
2795 &self.current_call_frame.to,
2796 self.env.config.fork,
2797 self.vm_type,
2798 ) {
2799 // `execute_precompile` itself never touches state gas (it only mutates
2800 // `gas_remaining`; it has no access to `state_gas_used` / `state_gas_reservoir` /
2801 // `state_gas_spill`) — the assert below guards that. The in-region EIP-2780
2802 // value-to-not-alive NEW_ACCOUNT charge (`prepare_execution`),
2803 // however, IS frame state gas, and on an exceptional halt/revert it must be
2804 // rolled back (see below). `self` is borrowed by field rather than via
2805 // `&mut self.current_call_frame` so the refund call, which needs `&mut self`,
2806 // can run after `execute_precompile`.
2807 let state_gas_used_before_precompile = self.state_gas_used;
2808 let code_address = self.current_call_frame.code_address;
2809 let precompile_gas_limit = self.current_call_frame.gas_limit;
2810 let mut gas_remaining = self.current_call_frame.gas_remaining as u64;
2811 let result = Self::execute_precompile(
2812 code_address,
2813 &self.current_call_frame.calldata,
2814 precompile_gas_limit,
2815 &mut gas_remaining,
2816 self.env.config.fork,
2817 self.db.store.precompile_cache(),
2818 self.crypto,
2819 self.stateless_validator,
2820 );
2821
2822 debug_assert_eq!(
2823 self.state_gas_used, state_gas_used_before_precompile,
2824 "precompile execution must not mutate state_gas_used"
2825 );
2826
2827 // EIP-8037 Amsterdam 2D accounting recomputes `block_gas_used` from
2828 // `raw_consumed = gas_limit - gas_remaining` inside `refund_sender`. On a
2829 // top-level precompile exceptional halt, `handle_precompile_result` already
2830 // sets `ContextResult.gas_used = gas_limit`, but `gas_remaining` retains the
2831 // untouched forwarded amount — under Amsterdam that would make the block
2832 // report only the intrinsic portion. Zero it so the block matches the
2833 // `gas_used = gas_limit` contract from `handle_precompile_result`, and roll
2834 // back the in-region value NEW_ACCOUNT charge (the recipient is never materialized
2835 // on halt) so the burned gas counts entirely as regular gas, matching EELS
2836 // `refill_frame_state_gas`. Pre-Amsterdam reads `ctx_result.gas_used` directly
2837 // and is unaffected by this path either way.
2838 if self.env.config.fork >= Fork::Amsterdam
2839 && let Ok(ctx) = &result
2840 && !ctx.is_success()
2841 {
2842 gas_remaining = 0;
2843 self.refund_new_account_state_gas(top_frame_new_account_charged)?;
2844 }
2845
2846 self.current_call_frame.gas_remaining = gas_remaining as i64;
2847
2848 return result;
2849 }
2850
2851 // Specialize the dispatch loop on whether a struct-log tracer is active.
2852 // The `!TRACED` variant compiles out every tracer branch and capture call,
2853 // leaving a minimal hot loop (the common, non-traced case).
2854 match (self.opcode_tracer.active, self.validation_observer.active) {
2855 (false, false) => self.run_dispatch::<false, false>(),
2856 (false, true) => self.run_dispatch::<false, true>(),
2857 (true, false) => self.run_dispatch::<true, false>(),
2858 (true, true) => self.run_dispatch::<true, true>(),
2859 }
2860 }
2861
2862 /// Opcode dispatch loop, monomorphized over whether a struct-log tracer is
2863 /// active. With `TRACED = false` the compiler eliminates the tracer branches
2864 /// and the cold `trace_*_step` calls entirely, so the hot loop body stays
2865 /// minimal; the traced variant keeps the cold helpers out of line.
2866 fn run_dispatch<const TRACED: bool, const VALIDATING: bool>(
2867 &mut self,
2868 ) -> Result<ContextResult, VMError> {
2869 let mut error = OnceCell::<VMError>::new();
2870
2871 #[cfg(feature = "perf_opcode_timings")]
2872 let mut timings = crate::timings::OPCODE_TIMINGS.lock().expect("poison");
2873
2874 // Copy the `&'static` table pointer once; it doesn't borrow `self`, so dispatch can still
2875 // pass `self` mutably to the handler without reloading the pointer each iteration.
2876 let opcode_table = self.opcode_table;
2877
2878 loop {
2879 // Capture pc BEFORE advance_pc() — this is the address of the current opcode.
2880 let pc_of_current_op = self.current_call_frame.pc;
2881 let opcode = self.current_call_frame.next_opcode();
2882 self.advance_pc();
2883
2884 // EIP-8141 mempool validation-trace observer (single branch on the
2885 // fast path when inactive). Enforces the banned-opcode set and the
2886 // sequential `GAS`-before-`*CALL` rule before the handler runs.
2887 if VALIDATING {
2888 self.check_validation_banned_opcode(opcode);
2889 }
2890
2891 // Struct-log pre-step capture (compiled out entirely when !TRACED).
2892 let gas_before_op = if TRACED {
2893 self.trace_pre_step(opcode, pc_of_current_op)
2894 } else {
2895 0
2896 };
2897
2898 #[cfg(feature = "perf_opcode_timings")]
2899 let opcode_time_start = std::time::Instant::now();
2900
2901 #[allow(clippy::indexing_slicing, clippy::as_conversions)]
2902 let op_result = opcode_table[opcode as usize].call(self, &mut error);
2903
2904 #[cfg(feature = "perf_opcode_timings")]
2905 {
2906 let time = opcode_time_start.elapsed();
2907 timings.update(opcode, time);
2908 }
2909
2910 // Struct-log post-step (compiled out entirely when !TRACED).
2911 if TRACED {
2912 self.trace_post_step(gas_before_op, &error);
2913 }
2914
2915 let result = match op_result {
2916 OpcodeResult::Continue => continue,
2917 OpcodeResult::Halt => match error.take() {
2918 None => self.handle_opcode_result()?,
2919 Some(error) => self.handle_opcode_error(error)?,
2920 },
2921 };
2922
2923 // Return the ExecutionReport if the executed callframe was the first one.
2924 if self.is_initial_call_frame() {
2925 // Consume the backup (move it out) unless a `BackupHook` will read it afterward
2926 // to build the tx-level undo snapshot (L2 / stateless). On L1 nothing reads it
2927 // once the cache is restored, so cloning it would be dead work.
2928 self.handle_state_backup(&result, !self.preserve_top_level_backup)?;
2929 return Ok(result);
2930 }
2931
2932 // Handle interaction between child and parent callframe.
2933 self.handle_return(&result)?;
2934 }
2935 }
2936
2937 /// EIP-8141 validation-trace banned-opcode check (mempool simulation only).
2938 ///
2939 /// Called once per dispatch-loop iteration, AFTER the opcode is fetched and
2940 /// BEFORE the handler runs, gated by `self.validation_observer.active`. Byte
2941 /// values are pinned against `opcodes.rs`.
2942 ///
2943 /// Static bans: `ORIGIN`, `GASPRICE`, `BLOCKHASH`, `COINBASE`, `TIMESTAMP`
2944 /// (except when the current frame's target is EXPIRY_VERIFIER), `NUMBER`,
2945 /// `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBHASH`, `BLOBBASEFEE`, `INVALID`,
2946 /// `SELFDESTRUCT`, `BALANCE`, `SELFBALANCE`, `TLOAD`, `TSTORE`, and `CALLCODE`
2947 /// in non-deploy prefix frames (ERC-7562 bans CALLCODE in validation;
2948 /// DELEGATECALL is allowed subject to the CALL-family trace rules in the
2949 /// handlers). `SSTORE`/`CREATE`/`CREATE2` are allowed only inside the deploy
2950 /// frame and are enforced in their handlers (state-write rules), not here.
2951 ///
2952 /// Sequential `GAS` rule: `GAS` is allowed only immediately before a
2953 /// `*CALL` (`CALL`/`CALLCODE`/`DELEGATECALL`/`STATICCALL`). We detect this by
2954 /// remembering `last_opcode`: if the previous iteration was `GAS` and this
2955 /// opcode is NOT a `*CALL`, the prior `GAS` was illegal.
2956 pub fn check_validation_banned_opcode(&mut self, opcode: u8) {
2957 use crate::validation_observer::FrameSimViolation;
2958
2959 // Opcode bytes, pinned against `opcodes.rs`. The literal values are
2960 // asserted equal to the `Opcode` enum discriminants by
2961 // `validation_observer_opcode_byte_pins` below (avoids a `const`-context
2962 // `as` cast, which the workspace clippy config denies).
2963 const ORIGIN: u8 = 0x32;
2964 const GASPRICE: u8 = 0x3A;
2965 const BLOCKHASH: u8 = 0x40;
2966 const COINBASE: u8 = 0x41;
2967 const TIMESTAMP: u8 = 0x42;
2968 const NUMBER: u8 = 0x43;
2969 const PREVRANDAO: u8 = 0x44;
2970 const GASLIMIT: u8 = 0x45;
2971 const BASEFEE: u8 = 0x48;
2972 const BLOBHASH: u8 = 0x49;
2973 const BLOBBASEFEE: u8 = 0x4A;
2974 const INVALID: u8 = 0xFE;
2975 const SELFDESTRUCT: u8 = 0xFF;
2976 const BALANCE: u8 = 0x31;
2977 const SELFBALANCE: u8 = 0x47;
2978 const TLOAD: u8 = 0x5C;
2979 const TSTORE: u8 = 0x5D;
2980 const GAS: u8 = 0x5A;
2981 const CALL: u8 = 0xF1;
2982 const CALLCODE: u8 = 0xF2;
2983 const DELEGATECALL: u8 = 0xF4;
2984 const STATICCALL: u8 = 0xFA;
2985
2986 let is_call_family = matches!(opcode, CALL | CALLCODE | DELEGATECALL | STATICCALL);
2987
2988 // Sequential GAS rule: a `GAS` on the previous iteration is only legal if
2989 // THIS opcode is a `*CALL`. Evaluate before updating `last_opcode`.
2990 if self.validation_observer.last_opcode == GAS && !is_call_family {
2991 self.validation_observer
2992 .record_violation(FrameSimViolation::BannedOpcode(GAS));
2993 }
2994
2995 // Carry `GAS` forward for the next iteration's check; reset otherwise.
2996 self.validation_observer.last_opcode = if opcode == GAS { GAS } else { 0 };
2997
2998 let banned = match opcode {
2999 ORIGIN | GASPRICE | BLOCKHASH | COINBASE | NUMBER | PREVRANDAO | GASLIMIT | BASEFEE
3000 | BLOBHASH | BLOBBASEFEE | INVALID | SELFDESTRUCT | BALANCE | SELFBALANCE | TLOAD
3001 | TSTORE => true,
3002 // TIMESTAMP is permitted only when the currently executing contract
3003 // IS the EXPIRY_VERIFIER predeploy (checked by code_address so the
3004 // rule tracks the executing contract at every call depth, not just the
3005 // top-level frame target). A nested call FROM an expiry frame INTO
3006 // another contract is correctly banned; a nested call INTO the
3007 // predeploy from any frame is correctly allowed.
3008 TIMESTAMP => {
3009 self.current_call_frame.code_address != self.validation_observer.expiry_verifier
3010 }
3011 // CALLCODE is banned in non-deploy prefix frames (ERC-7562).
3012 CALLCODE => !self.validation_observer.in_deploy_frame(),
3013 _ => false,
3014 };
3015
3016 if banned {
3017 self.validation_observer
3018 .record_violation(FrameSimViolation::BannedOpcode(opcode));
3019 }
3020 }
3021
3022 /// EIP-8141 validation-trace `SLOAD` check (mempool simulation only).
3023 ///
3024 /// `SLOAD` is allowed only when the storage owner (`address`, the executing
3025 /// frame's `to`) is the transaction sender. Records the touched slot for the
3026 /// admission-time revalidation affected-set.
3027 pub fn validation_check_sload(&mut self, address: Address, slot: H256) {
3028 use crate::validation_observer::FrameSimViolation;
3029 if self.validation_observer.in_canonical_pay_frame() {
3030 return;
3031 }
3032 if address == self.validation_observer.sender {
3033 self.validation_observer.touched_sender_slots.push(slot);
3034 } else {
3035 self.validation_observer
3036 .record_violation(FrameSimViolation::StorageReadNonSender);
3037 }
3038 }
3039
3040 /// EIP-8141 validation-trace `SSTORE` check (mempool simulation only).
3041 ///
3042 /// `SSTORE` is allowed only inside the deploy frame AND only when the storage
3043 /// owner (`address`, the executing frame's `to`) is the transaction sender.
3044 pub fn validation_check_sstore(&mut self, address: Address, slot: H256) {
3045 use crate::validation_observer::FrameSimViolation;
3046 if self.validation_observer.in_canonical_pay_frame() {
3047 return;
3048 }
3049 if self.validation_observer.in_deploy_frame() && address == self.validation_observer.sender
3050 {
3051 self.validation_observer.touched_sender_slots.push(slot);
3052 } else {
3053 self.validation_observer
3054 .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
3055 }
3056 }
3057
3058 /// EIP-8141 validation-trace state-creation check for `CREATE`/`CREATE2`
3059 /// (mempool simulation only). Contract creation is a state write permitted
3060 /// only inside the deploy frame.
3061 pub fn validation_check_create(&mut self) {
3062 use crate::validation_observer::FrameSimViolation;
3063 if self.validation_observer.in_canonical_pay_frame() {
3064 return;
3065 }
3066 if !self.validation_observer.in_deploy_frame() {
3067 self.validation_observer
3068 .record_violation(FrameSimViolation::StateWriteOutsideDeploy);
3069 }
3070 }
3071
3072 /// EIP-8141 validation-trace `CALL*`/`EXTCODE*` target check (mempool
3073 /// simulation only).
3074 ///
3075 /// The target must be an existing account or a precompile and must NOT be
3076 /// EIP-7702-delegated, except the sender running its own default code (the
3077 /// sender is exempt — its existence is a transaction precondition and it may
3078 /// have no code). `is_delegation_7702` is the flag already computed by
3079 /// `eip7702_get_code` in the CALL-family handlers, threaded in to avoid a
3080 /// second delegation resolution (and the `&mut VM` / `&mut db` borrow
3081 /// conflict a dispatch-loop stack-peek would create).
3082 pub fn validation_check_call_target(
3083 &mut self,
3084 target: Address,
3085 is_delegation_7702: bool,
3086 ) -> Result<(), VMError> {
3087 use crate::validation_observer::FrameSimViolation;
3088 if self.validation_observer.in_canonical_pay_frame() {
3089 return Ok(());
3090 }
3091 // The sender is always a legitimate target (its existence is a tx
3092 // precondition; it may legitimately have no code).
3093 if target == self.validation_observer.sender {
3094 return Ok(());
3095 }
3096 // A delegated target is disallowed in validation.
3097 if is_delegation_7702 {
3098 self.validation_observer
3099 .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
3100 return Ok(());
3101 }
3102 // Precompiles are always valid targets.
3103 if precompiles::is_precompile(&target, self.env.config.fork, self.vm_type) {
3104 return Ok(());
3105 }
3106 // Otherwise the target must be an existing (non-empty) account.
3107 if self.db.get_account(target)?.is_empty() {
3108 self.validation_observer
3109 .record_violation(FrameSimViolation::CallToNonexistentOrDelegated(target));
3110 }
3111 Ok(())
3112 }
3113
3114 /// EIP-8141 validation-trace `EXTCODE*` target check (mempool simulation
3115 /// only). Like [`VM::validation_check_call_target`], but resolves the
3116 /// EIP-7702 delegation flag itself (the EXTCODE handlers do not call
3117 /// `eip7702_get_code`). The `substate.add_accessed_address` warming the
3118 /// EXTCODE gas already performed has happened; resolving here only follows a
3119 /// delegation indicator to read its flag, mirroring the CALL-family path.
3120 pub fn validation_check_extcode_target(&mut self, target: Address) -> Result<(), VMError> {
3121 if self.validation_observer.in_canonical_pay_frame()
3122 || target == self.validation_observer.sender
3123 {
3124 return Ok(());
3125 }
3126 let (is_delegation_7702, _access_cost, _code_address, _bytecode) =
3127 crate::utils::eip7702_get_code(
3128 self.db,
3129 &mut self.substate,
3130 target,
3131 self.env.config.fork,
3132 )?;
3133 self.validation_check_call_target(target, is_delegation_7702)
3134 }
3135
3136 /// Struct-log pre-step capture, split out of the interpreter loop and kept
3137 /// cold + non-inlined so the hot dispatch loop stays small (this code is
3138 /// only reached when a struct-log tracer is active). Returns `gas_before`.
3139 #[cold]
3140 #[inline(never)]
3141 fn trace_pre_step(&mut self, opcode: u8, pc_of_current_op: usize) -> u64 {
3142 #[expect(
3143 clippy::as_conversions,
3144 reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3145 )]
3146 let gas_before = self.current_call_frame.gas_remaining.max(0) as u64;
3147 #[expect(
3148 clippy::as_conversions,
3149 reason = "call depth bounded by STACK_LIMIT=1024, fits in u32"
3150 )]
3151 let depth = (self.call_frames.len() as u32).saturating_add(1);
3152 let refund = self.substate.refunded_gas;
3153 let stack_view = self.collect_stack_for_trace();
3154 let mem_view = self.collect_memory_for_trace();
3155 // mem_size always reflects actual memory size, regardless of enable_memory.
3156 #[expect(
3157 clippy::as_conversions,
3158 reason = "memory size is bounded by gas; fits in u64"
3159 )]
3160 let mem_size_for_trace = self.current_call_frame.memory.len() as u64;
3161 let storage_kv = self.read_storage_for_trace(opcode);
3162 let return_data = if self.opcode_tracer.cfg.enable_return_data {
3163 self.current_call_frame.sub_return_data.clone()
3164 } else {
3165 Bytes::new()
3166 };
3167 #[expect(
3168 clippy::as_conversions,
3169 reason = "pc is usize, fits in u64 on supported targets"
3170 )]
3171 let pc_u64 = pc_of_current_op as u64;
3172 self.opcode_tracer.pre_step_capture(
3173 pc_u64,
3174 opcode,
3175 gas_before,
3176 depth,
3177 refund,
3178 &stack_view,
3179 &mem_view,
3180 mem_size_for_trace,
3181 &return_data,
3182 storage_kv,
3183 );
3184 gas_before
3185 }
3186
3187 /// Struct-log post-step: patch gas_cost, refund-after-op, and error into the
3188 /// buffered entry. Cold + non-inlined for the same reason as `trace_pre_step`.
3189 #[cold]
3190 #[inline(never)]
3191 fn trace_post_step(&mut self, gas_before_op: u64, error: &OnceCell<VMError>) {
3192 #[expect(
3193 clippy::as_conversions,
3194 reason = "gas_remaining is i64; clamp to 0 before converting to u64"
3195 )]
3196 let gas_after = self.current_call_frame.gas_remaining.max(0) as u64;
3197 // Prefer the explicit opcode-overhead cost written by CALL/CREATE handlers;
3198 // fall back to the gas diff for all other opcodes.
3199 let gas_cost = self
3200 .opcode_tracer
3201 .last_opcode_gas_cost
3202 .take()
3203 .unwrap_or_else(|| gas_before_op.saturating_sub(gas_after));
3204 // refund-after-op matches geth's structLogger timing: for SSTORE and
3205 // (pre-London) SELFDESTRUCT, the refund counter shown is the value
3206 // *after* the opcode's accounting applied.
3207 let refund_after = self.substate.refunded_gas;
3208 let err_str = error.get().map(|e| e.to_string());
3209 self.opcode_tracer
3210 .finalize_step(gas_cost, refund_after, err_str.as_deref());
3211 }
3212
3213 /// Executes precompile and handles the output that it returns, generating a report.
3214 #[allow(clippy::too_many_arguments)]
3215 pub fn execute_precompile(
3216 code_address: H160,
3217 calldata: &Bytes,
3218 gas_limit: u64,
3219 gas_remaining: &mut u64,
3220 fork: Fork,
3221 cache: Option<&precompiles::PrecompileCache>,
3222 crypto: &dyn Crypto,
3223 stateless_validator: Option<&dyn crate::StatelessValidator>,
3224 ) -> Result<ContextResult, VMError> {
3225 Self::handle_precompile_result(
3226 precompiles::execute_precompile(
3227 code_address,
3228 calldata,
3229 gas_remaining,
3230 fork,
3231 cache,
3232 crypto,
3233 stateless_validator,
3234 ),
3235 gas_limit,
3236 *gas_remaining,
3237 )
3238 }
3239
3240 /// True if external transaction is a contract creation
3241 pub fn is_create(&self) -> Result<bool, InternalError> {
3242 Ok(self.current_call_frame.is_create)
3243 }
3244
3245 /// Executes without making changes to the cache.
3246 pub fn stateless_execute(&mut self) -> Result<ExecutionReport, VMError> {
3247 // Add backup hook to restore state after execution. `add_hook` flips
3248 // `preserve_top_level_backup` on via `Hook::reads_top_level_backup`, so the backup is
3249 // cloned (not moved out) on the revert paths even though this VM was built with L1 `vm_type`.
3250 self.add_hook(BackupHook::default());
3251 let report = self.execute()?;
3252 // Restore cache to the state before execution.
3253 self.db.undo_last_transaction()?;
3254 Ok(report)
3255 }
3256
3257 fn prepare_execution(&mut self) -> Result<(), VMError> {
3258 // Clone each hook's `Rc` (cheap refcount bump) so the borrow on `self.hooks` is released
3259 // and `self` can be passed mutably — without `self.hooks.clone()`'s per-tx `Vec` realloc.
3260 // `self.hooks` is not mutated during the loop, so `get(i)` is always `Some` in range.
3261 for i in 0..self.hooks.len() {
3262 if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3263 hook.borrow_mut().prepare_execution(self)?;
3264 }
3265 }
3266
3267 Ok(())
3268 }
3269
3270 fn finalize_execution(
3271 &mut self,
3272 mut ctx_result: ContextResult,
3273 ) -> Result<ExecutionReport, VMError> {
3274 // EIP-8037: On top-level tx failure (REVERT, ExceptionalHalt, or OOG), the
3275 // execution portion of state gas has already been refilled into the reservoir by
3276 // the top-frame `refill_frame_state_gas` (seeded at the post-intrinsic baseline in
3277 // `add_intrinsic_gas` and fired on revert/halt in `handle_opcode_error` /
3278 // `handle_opcode_result`). The intrinsic portion stays in `state_gas_used` so block
3279 // accounting bills it. No reservoir-move is performed here. A create-tx collision
3280 // rolls its own in-region `NEW_ACCOUNT` charge (if any) back to the frame's entry
3281 // baseline inside `handle_create_transaction`'s collision branch, so there is
3282 // nothing left to refill here either (see that function).
3283 //
3284 // EIP-8037: there is no longer a separate create-failure `NEW_ACCOUNT`
3285 // refund here. The charge itself (`prepare_execution`) is now
3286 // conditioned on `get_pre_state_account(created_addr) == EMPTY_ACCOUNT`, so it
3287 // simply never fires for an already-alive target (positive balance implies
3288 // non-empty pre-state) and is rolled back by `handle_create_transaction` on
3289 // collision — matching EELS v7, which drops the created-target-alive output flag
3290 // entirely because `prepare_dispatch` never runs for a colliding create.
3291
3292 // See `prepare_execution`: per-hook `Rc::clone` avoids the `self.hooks.clone()` realloc.
3293 for i in 0..self.hooks.len() {
3294 if let Some(hook) = self.hooks.get(i).map(Rc::clone) {
3295 hook.borrow_mut()
3296 .finalize_execution(self, &mut ctx_result)?;
3297 }
3298 }
3299
3300 self.tracer.exit_context(&ctx_result, true)?;
3301
3302 // Struct-log end-of-tx capture: record final output, gas used, and revert error.
3303 // gas matches geth's `executionResult.Gas` which is post-refund (`receipt.GasUsed`).
3304 if self.opcode_tracer.active {
3305 self.opcode_tracer.output = ctx_result.output.clone();
3306 self.opcode_tracer.gas_used = ctx_result.gas_spent;
3307 self.opcode_tracer.error = match ctx_result.result {
3308 TxResult::Revert(ref err) => Some(err.to_string()),
3309 _ => None,
3310 };
3311 }
3312
3313 // Only include logs if transaction succeeded. When a transaction reverts,
3314 // no logs should be emitted (including EIP-7708 Transfer logs).
3315 let logs = if ctx_result.is_success() {
3316 self.substate.extract_logs()
3317 } else {
3318 Vec::new()
3319 };
3320
3321 // EIP-8037: `state_gas_used` is already net (signed; credits decrement it
3322 // inline), so `tx_state_gas = intrinsic_state_gas + state_gas_used` exactly
3323 // (EELS `fork.py::process_transaction`, which no longer carries a separate
3324 // tx-level refund channel). Clamp at zero — `state_gas_used` may be negative when
3325 // inline refunds exceed gross charges.
3326 let net_state_gas_used: u64 =
3327 u64::try_from(self.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
3328
3329 let report = ExecutionReport {
3330 result: ctx_result.result.clone(),
3331 gas_used: ctx_result.gas_used,
3332 gas_spent: ctx_result.gas_spent,
3333 gas_refunded: self.substate.refunded_gas,
3334 state_gas_used: net_state_gas_used,
3335 output: std::mem::take(&mut ctx_result.output),
3336 logs,
3337 payer_address: None,
3338 frame_results: None,
3339 };
3340
3341 Ok(report)
3342 }
3343
3344 // ── Struct-log helper methods ─────────────────────────────────────────────
3345
3346 /// Collects the current stack in bottom-first order for struct-log emission.
3347 ///
3348 /// LEVM stack is top-first in memory (`values[offset]` = top), so we reverse
3349 /// the active slice to produce the bottom-first wire format geth uses.
3350 /// Returns an empty `Vec` when `cfg.disable_stack` is true.
3351 pub fn collect_stack_for_trace(&self) -> Vec<U256> {
3352 use crate::constants::STACK_LIMIT;
3353 if self.opcode_tracer.cfg.disable_stack {
3354 return Vec::new();
3355 }
3356 let s = &self.current_call_frame.stack;
3357 // offset <= STACK_LIMIT by stack invariant.
3358 s.values
3359 .get(s.offset..STACK_LIMIT)
3360 .map(|slice| slice.iter().rev().copied().collect())
3361 .unwrap_or_default()
3362 }
3363
3364 /// Collects the live memory bytes for the current frame.
3365 ///
3366 /// Returns an empty `Vec` when `cfg.enable_memory` is false or memory is empty.
3367 pub fn collect_memory_for_trace(&self) -> Vec<u8> {
3368 if !self.opcode_tracer.cfg.enable_memory {
3369 return Vec::new();
3370 }
3371 self.current_call_frame.memory.live_bytes()
3372 }
3373
3374 /// Pre-reads the storage key/value for the current SLOAD or SSTORE opcode.
3375 ///
3376 /// Returns `None` when:
3377 /// - `cfg.disable_storage` is set, or
3378 /// - `opcode` is not SLOAD (0x54) or SSTORE (0x55), or
3379 /// - the stack is empty (guard against underflow before the handler runs), or
3380 /// - the storage read fails for any reason (including `AccountNotFound` —
3381 /// the trace omits the entry rather than emitting an ambiguous zero).
3382 ///
3383 /// For SLOAD: key = `stack.top`; value = the *current* stored value read from the DB.
3384 /// For SSTORE: key = `stack.top`, value = `stack[top-1]` (the new value being written).
3385 pub fn read_storage_for_trace(&mut self, opcode: u8) -> Option<(H256, H256)> {
3386 const SLOAD: u8 = 0x54;
3387 const SSTORE: u8 = 0x55;
3388
3389 if self.opcode_tracer.cfg.disable_storage {
3390 return None;
3391 }
3392 if opcode != SLOAD && opcode != SSTORE {
3393 return None;
3394 }
3395
3396 // Need at least one element on stack for SLOAD, two for SSTORE.
3397 use crate::constants::STACK_LIMIT;
3398 let offset = self.current_call_frame.stack.offset;
3399 if offset >= STACK_LIMIT {
3400 return None; // stack empty
3401 }
3402
3403 // SLOAD/SSTORE operate on the call's storage context (`to`), not the code's
3404 // address. Under DELEGATECALL/CALLCODE these differ.
3405 let addr = self.current_call_frame.to;
3406
3407 let stack_values = &self.current_call_frame.stack.values;
3408 let key_u256 = *stack_values.get(offset)?;
3409 let key = BigEndianHash::from_uint(&key_u256);
3410
3411 if opcode == SLOAD {
3412 // Omit the entry on any read failure (incl. account not yet cached);
3413 // a zero value would be indistinguishable from a legitimate never-written slot.
3414 let v = self.get_storage_value(addr, key).ok()?;
3415 let value = BigEndianHash::from_uint(&v);
3416 Some((key, value))
3417 } else {
3418 // SSTORE: need two stack elements.
3419 let next_offset = offset.checked_add(1)?;
3420 if next_offset >= STACK_LIMIT {
3421 return None;
3422 }
3423 // values[offset+1] is the new value being written (second from top = stack[top-1]).
3424 let value_u256 = *self.current_call_frame.stack.values.get(next_offset)?;
3425 let value = BigEndianHash::from_uint(&value_u256);
3426 Some((key, value))
3427 }
3428 }
3429}
3430
3431impl Substate {
3432 /// Initializes the VM substate, mainly adding addresses to the "accessed_addresses" field and the same with storage slots
3433 pub fn initialize(env: &Environment, tx: &Transaction) -> Result<Substate, VMError> {
3434 let fork = env.config.fork;
3435
3436 // Add sender and recipient to accessed accounts [https://www.evm.codes/about#access_list]
3437 // Precompiles are NO LONGER inserted here — they are warm by construction (see
3438 // `is_warm_precompile`), removing the ~20-entry floor that used to dominate this set. The
3439 // remaining working set is small (sender + coinbase + recipient + access-list/touched
3440 // addresses; real p99 ~7), so a capacity of 8 covers most txs with little waste.
3441 let mut initial_accessed_addresses =
3442 FxHashSet::with_capacity_and_hasher(8, Default::default());
3443 // Storage slots are ~98% empty (p95 0, p99 4), so `default()` (alloc-free until first
3444 // insert) beats pre-sizing, which would tax the common empty case.
3445 let mut initial_accessed_storage_slots: FxHashMap<Address, FxHashSet<H256>> =
3446 FxHashMap::default();
3447
3448 // Add Tx sender to accessed accounts
3449 initial_accessed_addresses.insert(env.origin);
3450
3451 // [EIP-3651] - Add coinbase to accessed accounts after Shanghai
3452 if fork >= Fork::Shanghai {
3453 initial_accessed_addresses.insert(env.coinbase);
3454 }
3455
3456 // Add access lists contents to accessed accounts and accessed storage slots.
3457 // Iterate by reference (`Address`/`H256` are `Copy`); the old `.clone()` deep-copied
3458 // the whole `Vec<(Address, Vec<H256>)>` per tx just to read it.
3459 for (address, keys) in tx.access_list() {
3460 initial_accessed_addresses.insert(*address);
3461 // 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
3462 let warm_slots = initial_accessed_storage_slots.entry(*address).or_default();
3463 for slot in keys {
3464 warm_slots.insert(*slot);
3465 }
3466 }
3467
3468 let substate = Substate::from_accesses(
3469 fork,
3470 initial_accessed_addresses,
3471 initial_accessed_storage_slots,
3472 );
3473
3474 Ok(substate)
3475 }
3476}
3477
3478// Test-support surface for the EIP-8037 state-gas reservoir/clamp-spill unit tests, which live
3479// in the `ethrex-test` crate (`test/tests/levm/eip8037_reservoir_tests.rs`) per the repo's
3480// test-location convention but must drive crate-private VM internals. Everything here is
3481// `#[doc(hidden)]` and exposes only what those tests touch: a fixture-free VM harness plus a
3482// handful of reservoir accessors. The harness builds the VM via struct literal to sidestep
3483// `VM::new`'s DB reads (which would pull `ethrex-storage`/`ethrex-blockchain` into levm and form
3484// a dependency cycle), keeping the two-pool arithmetic isolated.
3485#[doc(hidden)]
3486impl<'a> VM<'a> {
3487 /// Gas budget seeded into the harness top frame; large enough that spills never run it OOG.
3488 pub const STATE_GAS_HARNESS_FRAME_GAS: u64 = 1_000_000;
3489
3490 /// Builds a fixture-free VM on `fork` with a single top frame and the given starting
3491 /// `state_gas_reservoir`. `db`/`tx`/`crypto` are borrowed for the VM's lifetime but never
3492 /// read (the frame is built directly, so no account/storage/code loads occur).
3493 pub fn new_state_gas_harness(
3494 fork: Fork,
3495 db: &'a mut GeneralizedDatabase,
3496 tx: &'a Transaction,
3497 crypto: &'a dyn Crypto,
3498 state_gas_reservoir: u64,
3499 ) -> VM<'a> {
3500 let env = Environment {
3501 config: crate::environment::EVMConfig::new(
3502 fork,
3503 crate::environment::EVMConfig::canonical_values(fork),
3504 ),
3505 gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3506 block_gas_limit: Self::STATE_GAS_HARNESS_FRAME_GAS,
3507 ..Default::default()
3508 };
3509 let current_call_frame = CallFrame::new(
3510 Address::default(),
3511 Address::default(),
3512 Address::default(),
3513 Code::default(),
3514 U256::zero(),
3515 Bytes::new(),
3516 false,
3517 Self::STATE_GAS_HARNESS_FRAME_GAS,
3518 0,
3519 true,
3520 false,
3521 0,
3522 0,
3523 Stack::default(),
3524 Memory::default(),
3525 );
3526 VM {
3527 call_frames: Vec::new(),
3528 current_call_frame,
3529 env,
3530 substate: Substate::default(),
3531 db,
3532 tx,
3533 hooks: Vec::new(),
3534 storage_original_values: FxHashMap::default(),
3535 tracer: LevmCallTracer::disabled(),
3536 opcode_tracer: LevmOpcodeTracer::disabled(),
3537 debug_mode: DebugMode::disabled(),
3538 stack_pool: Vec::new(),
3539 vm_type: VMType::L1,
3540 preserve_top_level_backup: false,
3541 state_gas_used: 0,
3542 state_gas_reservoir,
3543 state_gas_reservoir_initial: state_gas_reservoir,
3544 state_gas_spill: 0,
3545 cost_per_state_byte: 0,
3546 state_gas_new_account: 0,
3547 state_gas_storage_set: 0,
3548 state_gas_auth_base: 0,
3549 intrinsic_state_gas: 0,
3550 value_new_account_charged: false,
3551 prep_baseline_state_gas: 0,
3552 prep_baseline_reservoir: 0,
3553 prep_baseline_state_gas_spill: 0,
3554 prep_region_backup_marker: PrepareRegionBackupMarker::default(),
3555 pending_prep_oog: false,
3556 opcode_table: VM::build_opcode_table(fork),
3557 crypto,
3558 stateless_validator: None,
3559 validation_observer: ValidationObserver::disabled(),
3560 frame_tx_context: None,
3561 }
3562 }
3563
3564 pub fn state_gas_reservoir(&self) -> u64 {
3565 self.state_gas_reservoir
3566 }
3567 pub fn state_gas_used(&self) -> i64 {
3568 self.state_gas_used
3569 }
3570 pub fn state_gas_spill(&self) -> u64 {
3571 self.state_gas_spill
3572 }
3573 pub fn state_gas_new_account(&self) -> u64 {
3574 self.state_gas_new_account
3575 }
3576 pub fn set_state_gas_new_account(&mut self, v: u64) {
3577 self.state_gas_new_account = v;
3578 }
3579 /// Seeds the post-intrinsic baseline (mirrors `add_intrinsic_gas`): both the VM-level
3580 /// `state_gas_used` and the top frame's entry snapshot.
3581 pub fn seed_state_gas_baseline(&mut self, used: i64) {
3582 self.state_gas_used = used;
3583 self.current_call_frame.state_gas_used_at_entry = used;
3584 }
3585 pub fn frame_state_gas_used_at_entry(&self) -> i64 {
3586 self.current_call_frame.state_gas_used_at_entry
3587 }
3588 pub fn frame_gas_remaining(&self) -> i64 {
3589 self.current_call_frame.gas_remaining
3590 }
3591 pub fn set_frame_gas_remaining(&mut self, v: i64) {
3592 self.current_call_frame.gas_remaining = v;
3593 }
3594 pub fn frame_state_gas_spilled(&self) -> u64 {
3595 self.current_call_frame.frame_state_gas_spilled
3596 }
3597}