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;
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 let gas = self.apply_eip7702_auth_list(evm)?;
155 Ok(gas)
156 }
157
158 /// Creates and executes the initial frame, then processes the execution loop.
159 ///
160 /// Always calls [Handler::last_frame_result] to handle returned gas from the call.
161 #[inline]
162 fn execution(
163 &mut self,
164 evm: &mut Self::Evm,
165 init_and_floor_gas: &InitialAndFloorGas,
166 ) -> Result<FrameResult, Self::Error> {
167 let gas_limit = evm.ctx().tx().gas_limit() - init_and_floor_gas.initial_gas;
168
169 // Create first frame action
170 let first_frame_input = self.first_frame_input(evm, gas_limit)?;
171 let first_frame = self.first_frame_init(evm, first_frame_input)?;
172 let mut frame_result = match first_frame {
173 ItemOrResult::Item(frame) => self.run_exec_loop(evm, frame)?,
174 ItemOrResult::Result(result) => result,
175 };
176
177 self.last_frame_result(evm, &mut frame_result)?;
178 Ok(frame_result)
179 }
180
181 /// Handles the final steps of transaction execution.
182 ///
183 /// Calculates final refunds and validates the gas floor (EIP-7623) to ensure minimum gas is spent.
184 /// After EIP-7623, at least floor gas must be consumed.
185 ///
186 /// Reimburses unused gas to the caller and rewards the beneficiary with transaction fees.
187 /// The effective gas price determines rewards, with the base fee being burned.
188 ///
189 /// Finally, finalizes output by returning the journal state and clearing internal state
190 /// for the next execution.
191 #[inline]
192 fn post_execution(
193 &self,
194 evm: &mut Self::Evm,
195 mut exec_result: FrameResult,
196 init_and_floor_gas: InitialAndFloorGas,
197 eip7702_gas_refund: i64,
198 ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
199 // Calculate final refund and add EIP-7702 refund to gas.
200 self.refund(evm, &mut exec_result, eip7702_gas_refund);
201 // Ensure gas floor is met and minimum floor gas is spent.
202 self.eip7623_check_gas_floor(evm, &mut exec_result, init_and_floor_gas);
203 // Return unused gas to caller
204 self.reimburse_caller(evm, &mut exec_result)?;
205 // Pay transaction fees to beneficiary
206 self.reward_beneficiary(evm, &mut exec_result)?;
207 // Prepare transaction output
208 self.output(evm, exec_result)
209 }
210
211 /* VALIDATION */
212
213 /// Validates block, transaction and configuration fields.
214 ///
215 /// Performs all validation checks that can be done without loading state.
216 /// For example, verifies transaction gas limit is below block gas limit.
217 #[inline]
218 fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
219 validation::validate_env(evm.ctx())
220 }
221
222 /// Calculates initial gas costs based on transaction type and input data.
223 ///
224 /// Includes additional costs for access list and authorization list.
225 ///
226 /// Verifies the initial cost does not exceed the transaction gas limit.
227 #[inline]
228 fn validate_initial_tx_gas(&self, evm: &Self::Evm) -> Result<InitialAndFloorGas, Self::Error> {
229 let ctx = evm.ctx_ref();
230 validation::validate_initial_tx_gas(ctx.tx(), ctx.cfg().spec().into()).map_err(From::from)
231 }
232
233 /// Loads caller account to access nonce and balance.
234 ///
235 /// Calculates maximum possible transaction fee and verifies caller has sufficient balance.
236 #[inline]
237 fn validate_tx_against_state(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
238 validation::validate_tx_against_state(evm.ctx())
239 }
240
241 /* PRE EXECUTION */
242
243 /// Loads access list and beneficiary account, marking them as warm in the [`context::Journal`].
244 #[inline]
245 fn load_accounts(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
246 pre_execution::load_accounts(evm)
247 }
248
249 /// Processes the authorization list, validating authority signatures, nonces and chain IDs.
250 /// Applies valid authorizations to accounts.
251 ///
252 /// Returns the gas refund amount specified by EIP-7702.
253 #[inline]
254 fn apply_eip7702_auth_list(&self, evm: &mut Self::Evm) -> Result<u64, Self::Error> {
255 pre_execution::apply_eip7702_auth_list(evm.ctx())
256 }
257
258 /// Deducts maximum possible fee and transfer value from caller's balance.
259 ///
260 /// Unused fees are returned to caller after execution completes.
261 #[inline]
262 fn deduct_caller(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> {
263 pre_execution::deduct_caller(evm.ctx()).map_err(From::from)
264 }
265
266 /* EXECUTION */
267
268 /// Creates initial frame input using transaction parameters, gas limit and configuration.
269 #[inline]
270 fn first_frame_input(
271 &mut self,
272 evm: &mut Self::Evm,
273 gas_limit: u64,
274 ) -> Result<FrameInput, Self::Error> {
275 let ctx: &<<Self as Handler>::Evm as EvmTr>::Context = evm.ctx_ref();
276 Ok(execution::create_init_frame(
277 ctx.tx(),
278 ctx.cfg().spec().into(),
279 gas_limit,
280 ))
281 }
282
283 /// Processes the result of the initial call and handles returned gas.
284 #[inline]
285 fn last_frame_result(
286 &self,
287 evm: &mut Self::Evm,
288 frame_result: &mut <Self::Frame as Frame>::FrameResult,
289 ) -> Result<(), Self::Error> {
290 let instruction_result = frame_result.interpreter_result().result;
291 let gas = frame_result.gas_mut();
292 let remaining = gas.remaining();
293 let refunded = gas.refunded();
294
295 // Spend the gas limit. Gas is reimbursed when the tx returns successfully.
296 *gas = Gas::new_spent(evm.ctx().tx().gas_limit());
297
298 if instruction_result.is_ok_or_revert() {
299 gas.erase_cost(remaining);
300 }
301
302 if instruction_result.is_ok() {
303 gas.record_refund(refunded);
304 }
305 Ok(())
306 }
307
308 /* FRAMES */
309
310 /// Initializes the first frame from the provided frame input.
311 #[inline]
312 fn first_frame_init(
313 &mut self,
314 evm: &mut Self::Evm,
315 frame_input: <Self::Frame as Frame>::FrameInit,
316 ) -> Result<FrameOrResult<Self::Frame>, Self::Error> {
317 Self::Frame::init_first(evm, frame_input)
318 }
319
320 /// Initializes a new frame from the provided frame input and previous frame.
321 ///
322 /// The previous frame contains shared memory that is passed to the new frame.
323 #[inline]
324 fn frame_init(
325 &mut self,
326 frame: &Self::Frame,
327 evm: &mut Self::Evm,
328 frame_input: <Self::Frame as Frame>::FrameInit,
329 ) -> Result<FrameOrResult<Self::Frame>, Self::Error> {
330 Frame::init(frame, evm, frame_input)
331 }
332
333 /// Executes a frame and returns either input for a new frame or the frame's result.
334 ///
335 /// When a result is returned, the frame is removed from the call stack. When frame input
336 /// is returned, a new frame is created and pushed onto the call stack.
337 #[inline]
338 fn frame_call(
339 &mut self,
340 frame: &mut Self::Frame,
341 evm: &mut Self::Evm,
342 ) -> Result<FrameInitOrResult<Self::Frame>, Self::Error> {
343 Frame::run(frame, evm)
344 }
345
346 /// Processes a frame's result by inserting it into the parent frame.
347 #[inline]
348 fn frame_return_result(
349 &mut self,
350 frame: &mut Self::Frame,
351 evm: &mut Self::Evm,
352 result: <Self::Frame as Frame>::FrameResult,
353 ) -> Result<(), Self::Error> {
354 Self::Frame::return_result(frame, evm, result)
355 }
356
357 /// Executes the main frame processing loop.
358 ///
359 /// This loop manages the frame stack, processing each frame until execution completes.
360 /// For each iteration:
361 /// 1. Calls the current frame
362 /// 2. Handles the returned frame input or result
363 /// 3. Creates new frames or propagates results as needed
364 #[inline]
365 fn run_exec_loop(
366 &mut self,
367 evm: &mut Self::Evm,
368 frame: Self::Frame,
369 ) -> Result<FrameResult, Self::Error> {
370 let mut frame_stack: Vec<Self::Frame> = vec![frame];
371 loop {
372 let frame = frame_stack.last_mut().unwrap();
373 let call_or_result = self.frame_call(frame, evm)?;
374
375 let result = match call_or_result {
376 ItemOrResult::Item(init) => {
377 match self.frame_init(frame, evm, init)? {
378 ItemOrResult::Item(new_frame) => {
379 frame_stack.push(new_frame);
380 continue;
381 }
382 // Do not pop the frame since no new frame was created
383 ItemOrResult::Result(result) => result,
384 }
385 }
386 ItemOrResult::Result(result) => {
387 // Remove the frame that returned the result
388 frame_stack.pop();
389 result
390 }
391 };
392
393 let Some(frame) = frame_stack.last_mut() else {
394 return Ok(result);
395 };
396 self.frame_return_result(frame, evm, result)?;
397 }
398 }
399
400 /* POST EXECUTION */
401
402 /// Validates that the minimum gas floor requirements are satisfied.
403 ///
404 /// Ensures that at least the floor gas amount has been consumed during execution.
405 #[inline]
406 fn eip7623_check_gas_floor(
407 &self,
408 _evm: &mut Self::Evm,
409 exec_result: &mut <Self::Frame as Frame>::FrameResult,
410 init_and_floor_gas: InitialAndFloorGas,
411 ) {
412 post_execution::eip7623_check_gas_floor(exec_result.gas_mut(), init_and_floor_gas)
413 }
414
415 /// Calculates the final gas refund amount, including any EIP-7702 refunds.
416 #[inline]
417 fn refund(
418 &self,
419 evm: &mut Self::Evm,
420 exec_result: &mut <Self::Frame as Frame>::FrameResult,
421 eip7702_refund: i64,
422 ) {
423 let spec = evm.ctx().cfg().spec().into();
424 post_execution::refund(spec, exec_result.gas_mut(), eip7702_refund)
425 }
426
427 /// Returns unused gas costs to the transaction sender's account.
428 #[inline]
429 fn reimburse_caller(
430 &self,
431 evm: &mut Self::Evm,
432 exec_result: &mut <Self::Frame as Frame>::FrameResult,
433 ) -> Result<(), Self::Error> {
434 post_execution::reimburse_caller(evm.ctx(), exec_result.gas_mut()).map_err(From::from)
435 }
436
437 /// Transfers transaction fees to the block beneficiary's account.
438 #[inline]
439 fn reward_beneficiary(
440 &self,
441 evm: &mut Self::Evm,
442 exec_result: &mut <Self::Frame as Frame>::FrameResult,
443 ) -> Result<(), Self::Error> {
444 post_execution::reward_beneficiary(evm.ctx(), exec_result.gas_mut()).map_err(From::from)
445 }
446
447 /// Processes the final execution output.
448 ///
449 /// This method, retrieves the final state from the journal, converts internal results to the external output format.
450 /// Internal state is cleared and EVM is prepared for the next transaction.
451 #[inline]
452 fn output(
453 &self,
454 evm: &mut Self::Evm,
455 result: <Self::Frame as Frame>::FrameResult,
456 ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
457 match core::mem::replace(evm.ctx().error(), Ok(())) {
458 Err(ContextError::Db(e)) => return Err(e.into()),
459 Err(ContextError::Custom(e)) => return Err(Self::Error::from_string(e)),
460 Ok(_) => (),
461 }
462
463 let output = post_execution::output(evm.ctx(), result);
464
465 // Clear journal
466 evm.ctx().journal().clear();
467 Ok(output)
468 }
469
470 /// Handles cleanup when an error occurs during execution.
471 ///
472 /// Ensures the journal state is properly cleared before propagating the error.
473 /// On happy path journal is cleared in [`Handler::output`] method.
474 #[inline]
475 fn catch_error(
476 &self,
477 evm: &mut Self::Evm,
478 error: Self::Error,
479 ) -> Result<ResultAndState<Self::HaltReason>, Self::Error> {
480 // Clean up journal state if error occurs
481 evm.ctx().journal().clear();
482 Err(error)
483 }
484}