revm_handler/
handler.rs

1use crate::EvmTr;
2use crate::{
3    execution, post_execution, pre_execution, validation, Frame, FrameInitOrResult, FrameOrResult,
4    FrameResult, ItemOrResult,
5};
6use context::result::FromStringError;
7use context::{JournalOutput, LocalContextTr, TransactionType};
8use context_interface::context::ContextError;
9use context_interface::ContextTr;
10use context_interface::{
11    result::{HaltReasonTr, InvalidHeader, InvalidTransaction, ResultAndState},
12    Cfg, Database, JournalTr, Transaction,
13};
14use interpreter::{FrameInput, Gas, InitialAndFloorGas};
15use std::{vec, vec::Vec};
16
17pub trait EvmTrError<EVM: EvmTr>:
18    From<InvalidTransaction>
19    + From<InvalidHeader>
20    + From<<<EVM::Context as ContextTr>::Db as Database>::Error>
21    + FromStringError
22{
23}
24
25impl<
26        EVM: EvmTr,
27        T: From<InvalidTransaction>
28            + From<InvalidHeader>
29            + From<<<EVM::Context as ContextTr>::Db as Database>::Error>
30            + FromStringError,
31    > EvmTrError<EVM> for T
32{
33}
34
35/// The main implementation of Ethereum Mainnet transaction execution.
36///
37/// The [`Handler::run`] method serves as the entry point for execution and provides
38/// out-of-the-box support for executing Ethereum mainnet transactions.
39///
40/// This trait allows EVM variants to customize execution logic by implementing
41/// their own method implementations.
42///
43/// The handler logic consists of four phases:
44///   * Validation - Validates tx/block/config fields and loads caller account and validates initial gas requirements and
45///     balance checks.
46///   * Pre-execution - Loads and warms accounts, deducts initial gas
47///   * Execution - Executes the main frame loop, delegating to [`Frame`] for sub-calls
48///   * Post-execution - Calculates final refunds, validates gas floor, reimburses caller,
49///     and rewards beneficiary
50///
51/// The [`Handler::catch_error`] method handles cleanup of intermediate state if an error
52/// occurs during execution.
53pub trait Handler {
54    /// The EVM type containing Context, Instruction, and Precompiles implementations.
55    type Evm: EvmTr<Context: ContextTr<Journal: JournalTr<FinalOutput = JournalOutput>>>;
56    /// The error type returned by this handler.
57    type Error: EvmTrError<Self::Evm>;
58    /// The Frame type containing data for frame execution. Supports Call, Create and EofCreate frames.
59    // TODO `FrameResult` should be a generic trait.
60    // TODO `FrameInit` should be a generic.
61    type Frame: Frame<
62        Evm = Self::Evm,
63        Error = Self::Error,
64        FrameResult = FrameResult,
65        FrameInit = FrameInput,
66    >;
67    /// The halt reason type included in the output
68    type HaltReason: HaltReasonTr;
69
70    /// The main entry point for transaction execution.
71    ///
72    /// This method calls [`Handler::run_without_catch_error`] and if it returns an error,
73    /// calls [`Handler::catch_error`] to handle the error and cleanup.
74    ///
75    /// The [`Handler::catch_error`] method ensures intermediate state is properly cleared.
76    #[inline]
77    fn run(
78        &mut self,
79        evm: &mut Self::Evm,
80    ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
81        // Run inner handler and catch all errors to handle cleanup.
82        match self.run_without_catch_error(evm) {
83            Ok(output) => Ok(output),
84            Err(e) => self.catch_error(evm, e),
85        }
86    }
87
88    /// Runs the system call.
89    ///
90    /// System call is a special transaction where caller is a [`crate::SYSTEM_ADDRESS`]
91    ///
92    /// It is used to call a system contracts and it skips all the `validation` and `pre-execution` and most of `post-execution` phases.
93    /// For example it will not deduct the caller or reward the beneficiary.
94    #[inline]
95    fn run_system_call(
96        &mut self,
97        evm: &mut Self::Evm,
98    ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
99        // dummy values that are not used.
100        let init_and_floor_gas = InitialAndFloorGas::new(0, 0);
101        // call execution and than output.
102        match self
103            .execution(evm, &init_and_floor_gas)
104            .and_then(|exec_result| self.output(evm, exec_result))
105        {
106            Ok(output) => Ok(output),
107            Err(e) => self.catch_error(evm, e),
108        }
109    }
110
111    /// Called by [`Handler::run`] to execute the core handler logic.
112    ///
113    /// Executes the four phases in sequence: [Handler::validate],
114    /// [Handler::pre_execution], [Handler::execution], [Handler::post_execution].
115    ///
116    /// Returns any errors without catching them or calling [`Handler::catch_error`].
117    #[inline]
118    fn run_without_catch_error(
119        &mut self,
120        evm: &mut Self::Evm,
121    ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
122        let init_and_floor_gas = self.validate(evm)?;
123        let eip7702_refund = self.pre_execution(evm)? as i64;
124        let exec_result = self.execution(evm, &init_and_floor_gas)?;
125        self.post_execution(evm, exec_result, init_and_floor_gas, eip7702_refund)
126    }
127
128    /// Validates the execution environment and transaction parameters.
129    ///
130    /// Calculates initial and floor gas requirements and verifies they are covered by the gas limit.
131    ///
132    /// Loads the caller account and validates transaction fields against state,
133    /// including nonce checks and balance verification for maximum gas costs.
134    #[inline]
135    fn validate(&self, evm: &mut Self::Evm) -> Result<InitialAndFloorGas, Self::Error> {
136        self.validate_env(evm)?;
137        let initial_and_floor_gas = self.validate_initial_tx_gas(evm)?;
138        self.validate_tx_against_state(evm)?;
139        Ok(initial_and_floor_gas)
140    }
141
142    /// Prepares the EVM state for execution.
143    ///
144    /// Loads the beneficiary account (EIP-3651: Warm COINBASE) and all accounts/storage from the access list (EIP-2929).
145    ///
146    /// Deducts the maximum possible fee from the caller's balance.
147    ///
148    /// For EIP-7702 transactions, applies the authorization list and delegates successful authorizations.
149    /// Returns the gas refund amount from EIP-7702. Authorizations are applied before execution begins.
150    #[inline]
151    fn pre_execution(&self, evm: &mut Self::Evm) -> Result<u64, Self::Error> {
152        self.load_accounts(evm)?;
153        self.deduct_caller(evm)?;
154        // Cache EIP-7873 EOF initcodes and calculate its hash. Does nothing if not Initcode Transaction.
155        self.apply_eip7873_eof_initcodes(evm)?;
156        let gas = self.apply_eip7702_auth_list(evm)?;
157
158        Ok(gas)
159    }
160
161    /// Creates and executes the initial frame, then processes the execution loop.
162    ///
163    /// Always calls [Handler::last_frame_result] to handle returned gas from the call.
164    #[inline]
165    fn execution(
166        &mut self,
167        evm: &mut Self::Evm,
168        init_and_floor_gas: &InitialAndFloorGas,
169    ) -> Result<FrameResult, Self::Error> {
170        let gas_limit = evm.ctx().tx().gas_limit() - init_and_floor_gas.initial_gas;
171
172        // Create first frame action
173        let first_frame_input = self.first_frame_input(evm, gas_limit)?;
174        let first_frame = self.first_frame_init(evm, first_frame_input)?;
175        let mut frame_result = match first_frame {
176            ItemOrResult::Item(frame) => self.run_exec_loop(evm, frame)?,
177            ItemOrResult::Result(result) => result,
178        };
179
180        self.last_frame_result(evm, &mut frame_result)?;
181        Ok(frame_result)
182    }
183
184    /// Handles the final steps of transaction execution.
185    ///
186    /// Calculates final refunds and validates the gas floor (EIP-7623) to ensure minimum gas is spent.
187    /// After EIP-7623, at least floor gas must be consumed.
188    ///
189    /// Reimburses unused gas to the caller and rewards the beneficiary with transaction fees.
190    /// The effective gas price determines rewards, with the base fee being burned.
191    ///
192    /// Finally, finalizes output by returning the journal state and clearing internal state
193    /// for the next execution.
194    #[inline]
195    fn post_execution(
196        &self,
197        evm: &mut Self::Evm,
198        mut exec_result: FrameResult,
199        init_and_floor_gas: InitialAndFloorGas,
200        eip7702_gas_refund: i64,
201    ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
202        // Calculate final refund and add EIP-7702 refund to gas.
203        self.refund(evm, &mut exec_result, eip7702_gas_refund);
204        // Ensure gas floor is met and minimum floor gas is spent.
205        self.eip7623_check_gas_floor(evm, &mut exec_result, init_and_floor_gas);
206        // Return unused gas to caller
207        self.reimburse_caller(evm, &mut exec_result)?;
208        // Pay transaction fees to beneficiary
209        self.reward_beneficiary(evm, &mut exec_result)?;
210        // Prepare transaction output
211        self.output(evm, exec_result)
212    }
213
214    /* VALIDATION */
215
216    /// Validates block, transaction and configuration fields.
217    ///
218    /// Performs all validation checks that can be done without loading state.
219    /// For example, verifies transaction gas limit is below block gas limit.
220    #[inline]
221    fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
222        validation::validate_env(evm.ctx())
223    }
224
225    /// Calculates initial gas costs based on transaction type and input data.
226    ///
227    /// Includes additional costs for access list and authorization list.
228    ///
229    /// Verifies the initial cost does not exceed the transaction gas limit.
230    #[inline]
231    fn validate_initial_tx_gas(&self, evm: &Self::Evm) -> Result<InitialAndFloorGas, Self::Error> {
232        let ctx = evm.ctx_ref();
233        validation::validate_initial_tx_gas(ctx.tx(), ctx.cfg().spec().into()).map_err(From::from)
234    }
235
236    /// Loads caller account to access nonce and balance.
237    ///
238    /// Calculates maximum possible transaction fee and verifies caller has sufficient balance.
239    #[inline]
240    fn validate_tx_against_state(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
241        validation::validate_tx_against_state(evm.ctx())
242    }
243
244    /* PRE EXECUTION */
245
246    /// Loads access list and beneficiary account, marking them as warm in the [`context::Journal`].
247    #[inline]
248    fn load_accounts(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
249        pre_execution::load_accounts(evm)
250    }
251
252    /// Processes the authorization list, validating authority signatures, nonces and chain IDs.
253    /// Applies valid authorizations to accounts.
254    ///
255    /// Returns the gas refund amount specified by EIP-7702.
256    #[inline]
257    fn apply_eip7702_auth_list(&self, evm: &mut Self::Evm) -> Result<u64, Self::Error> {
258        pre_execution::apply_eip7702_auth_list(evm.ctx())
259    }
260
261    /// Processes the authorization list, validating authority signatures, nonces and chain IDs.
262    /// Applies valid authorizations to accounts.
263    ///
264    /// Returns the gas refund amount specified by EIP-7702.
265    #[inline]
266    fn apply_eip7873_eof_initcodes(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
267        if evm.ctx().tx().tx_type() != TransactionType::Eip7873 {
268            return Ok(());
269        }
270        let (tx, local) = evm.ctx().tx_local();
271        local.insert_initcodes(tx.initcodes());
272        Ok(())
273    }
274
275    /// Deducts maximum possible fee and transfer value from caller's balance.
276    ///
277    /// Unused fees are returned to caller after execution completes.
278    #[inline]
279    fn deduct_caller(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
280        pre_execution::deduct_caller(evm.ctx()).map_err(From::from)
281    }
282
283    /* EXECUTION */
284
285    /// Creates initial frame input using transaction parameters, gas limit and configuration.
286    #[inline]
287    fn first_frame_input(
288        &mut self,
289        evm: &mut Self::Evm,
290        gas_limit: u64,
291    ) -> Result<FrameInput, Self::Error> {
292        let ctx: &<<Self as Handler>::Evm as EvmTr>::Context = evm.ctx_ref();
293        Ok(execution::create_init_frame(
294            ctx.tx(),
295            ctx.cfg().spec().into(),
296            gas_limit,
297        ))
298    }
299
300    /// Processes the result of the initial call and handles returned gas.
301    #[inline]
302    fn last_frame_result(
303        &self,
304        evm: &mut Self::Evm,
305        frame_result: &mut <Self::Frame as Frame>::FrameResult,
306    ) -> Result<(), Self::Error> {
307        let instruction_result = frame_result.interpreter_result().result;
308        let gas = frame_result.gas_mut();
309        let remaining = gas.remaining();
310        let refunded = gas.refunded();
311
312        // Spend the gas limit. Gas is reimbursed when the tx returns successfully.
313        *gas = Gas::new_spent(evm.ctx().tx().gas_limit());
314
315        if instruction_result.is_ok_or_revert() {
316            gas.erase_cost(remaining);
317        }
318
319        if instruction_result.is_ok() {
320            gas.record_refund(refunded);
321        }
322        Ok(())
323    }
324
325    /* FRAMES */
326
327    /// Initializes the first frame from the provided frame input.
328    #[inline]
329    fn first_frame_init(
330        &mut self,
331        evm: &mut Self::Evm,
332        frame_input: <Self::Frame as Frame>::FrameInit,
333    ) -> Result<FrameOrResult<Self::Frame>, Self::Error> {
334        Self::Frame::init_first(evm, frame_input)
335    }
336
337    /// Initializes a new frame from the provided frame input and previous frame.
338    ///
339    /// The previous frame contains shared memory that is passed to the new frame.
340    #[inline]
341    fn frame_init(
342        &mut self,
343        frame: &mut Self::Frame,
344        evm: &mut Self::Evm,
345        frame_input: <Self::Frame as Frame>::FrameInit,
346    ) -> Result<FrameOrResult<Self::Frame>, Self::Error> {
347        Frame::init(frame, evm, frame_input)
348    }
349
350    /// Executes a frame and returns either input for a new frame or the frame's result.
351    ///
352    /// When a result is returned, the frame is removed from the call stack. When frame input
353    /// is returned, a new frame is created and pushed onto the call stack.
354    #[inline]
355    fn frame_call(
356        &mut self,
357        frame: &mut Self::Frame,
358        evm: &mut Self::Evm,
359    ) -> Result<FrameInitOrResult<Self::Frame>, Self::Error> {
360        Frame::run(frame, evm)
361    }
362
363    /// Processes a frame's result by inserting it into the parent frame.
364    #[inline]
365    fn frame_return_result(
366        &mut self,
367        frame: &mut Self::Frame,
368        evm: &mut Self::Evm,
369        result: <Self::Frame as Frame>::FrameResult,
370    ) -> Result<(), Self::Error> {
371        Self::Frame::return_result(frame, evm, result)
372    }
373
374    /// Executes the main frame processing loop.
375    ///
376    /// This loop manages the frame stack, processing each frame until execution completes.
377    /// For each iteration:
378    /// 1. Calls the current frame
379    /// 2. Handles the returned frame input or result
380    /// 3. Creates new frames or propagates results as needed
381    #[inline]
382    fn run_exec_loop(
383        &mut self,
384        evm: &mut Self::Evm,
385        frame: Self::Frame,
386    ) -> Result<FrameResult, Self::Error> {
387        let mut frame_stack: Vec<Self::Frame> = vec![frame];
388        loop {
389            let frame = frame_stack.last_mut().unwrap();
390            let call_or_result = self.frame_call(frame, evm)?;
391
392            let result = match call_or_result {
393                ItemOrResult::Item(init) => {
394                    match self.frame_init(frame, evm, init)? {
395                        ItemOrResult::Item(new_frame) => {
396                            frame_stack.push(new_frame);
397                            continue;
398                        }
399                        // Do not pop the frame since no new frame was created
400                        ItemOrResult::Result(result) => result,
401                    }
402                }
403                ItemOrResult::Result(result) => {
404                    // Remove the frame that returned the result
405                    frame_stack.pop();
406                    result
407                }
408            };
409
410            let Some(frame) = frame_stack.last_mut() else {
411                return Ok(result);
412            };
413            self.frame_return_result(frame, evm, result)?;
414        }
415    }
416
417    /* POST EXECUTION */
418
419    /// Validates that the minimum gas floor requirements are satisfied.
420    ///
421    /// Ensures that at least the floor gas amount has been consumed during execution.
422    #[inline]
423    fn eip7623_check_gas_floor(
424        &self,
425        _evm: &mut Self::Evm,
426        exec_result: &mut <Self::Frame as Frame>::FrameResult,
427        init_and_floor_gas: InitialAndFloorGas,
428    ) {
429        post_execution::eip7623_check_gas_floor(exec_result.gas_mut(), init_and_floor_gas)
430    }
431
432    /// Calculates the final gas refund amount, including any EIP-7702 refunds.
433    #[inline]
434    fn refund(
435        &self,
436        evm: &mut Self::Evm,
437        exec_result: &mut <Self::Frame as Frame>::FrameResult,
438        eip7702_refund: i64,
439    ) {
440        let spec = evm.ctx().cfg().spec().into();
441        post_execution::refund(spec, exec_result.gas_mut(), eip7702_refund)
442    }
443
444    /// Returns unused gas costs to the transaction sender's account.
445    #[inline]
446    fn reimburse_caller(
447        &self,
448        evm: &mut Self::Evm,
449        exec_result: &mut <Self::Frame as Frame>::FrameResult,
450    ) -> Result<(), Self::Error> {
451        post_execution::reimburse_caller(evm.ctx(), exec_result.gas_mut()).map_err(From::from)
452    }
453
454    /// Transfers transaction fees to the block beneficiary's account.
455    #[inline]
456    fn reward_beneficiary(
457        &self,
458        evm: &mut Self::Evm,
459        exec_result: &mut <Self::Frame as Frame>::FrameResult,
460    ) -> Result<(), Self::Error> {
461        post_execution::reward_beneficiary(evm.ctx(), exec_result.gas_mut()).map_err(From::from)
462    }
463
464    /// Processes the final execution output.
465    ///
466    /// This method, retrieves the final state from the journal, converts internal results to the external output format.
467    /// Internal state is cleared and EVM is prepared for the next transaction.
468    #[inline]
469    fn output(
470        &self,
471        evm: &mut Self::Evm,
472        result: <Self::Frame as Frame>::FrameResult,
473    ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
474        match core::mem::replace(evm.ctx().error(), Ok(())) {
475            Err(ContextError::Db(e)) => return Err(e.into()),
476            Err(ContextError::Custom(e)) => return Err(Self::Error::from_string(e)),
477            Ok(_) => (),
478        }
479
480        let output = post_execution::output(evm.ctx(), result);
481
482        // Clear local context
483        evm.ctx().local().clear();
484        // Clear journal
485        evm.ctx().journal().clear();
486        Ok(output)
487    }
488
489    /// Handles cleanup when an error occurs during execution.
490    ///
491    /// Ensures the journal state is properly cleared before propagating the error.
492    /// On happy path journal is cleared in [`Handler::output`] method.
493    #[inline]
494    fn catch_error(
495        &self,
496        evm: &mut Self::Evm,
497        error: Self::Error,
498    ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
499        // clean up local context. Initcode cache needs to be discarded.
500        evm.ctx().local().clear();
501        // Clean up journal state if error occurs
502        evm.ctx().journal().clear();
503        Err(error)
504    }
505}