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