revm_handler/
frame.rs

1use crate::{
2    evm::FrameTr, item_or_result::FrameInitOrResult, precompile_provider::PrecompileProvider,
3    CallFrame, CreateFrame, FrameData, FrameResult, ItemOrResult,
4};
5use context::result::FromStringError;
6use context_interface::{
7    context::ContextError,
8    journaled_state::{account::JournaledAccountTr, JournalCheckpoint, JournalTr},
9    local::{FrameToken, OutFrame},
10    Cfg, ContextTr, Database,
11};
12use core::cmp::min;
13use derive_where::derive_where;
14use interpreter::{
15    interpreter::{EthInterpreter, ExtBytecode},
16    interpreter_action::FrameInit,
17    interpreter_types::ReturnData,
18    CallInput, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, CreateScheme,
19    FrameInput, Gas, InputsImpl, InstructionResult, Interpreter, InterpreterAction,
20    InterpreterResult, InterpreterTypes, SharedMemory,
21};
22use primitives::{
23    constants::CALL_STACK_LIMIT,
24    hardfork::SpecId::{self, HOMESTEAD, LONDON, SPURIOUS_DRAGON},
25    keccak256, Address, Bytes, U256,
26};
27use state::Bytecode;
28use std::{borrow::ToOwned, boxed::Box, vec::Vec};
29
30/// Frame implementation for Ethereum.
31#[derive_where(Clone, Debug; IW,
32    <IW as InterpreterTypes>::Stack,
33    <IW as InterpreterTypes>::Memory,
34    <IW as InterpreterTypes>::Bytecode,
35    <IW as InterpreterTypes>::ReturnData,
36    <IW as InterpreterTypes>::Input,
37    <IW as InterpreterTypes>::RuntimeFlag,
38    <IW as InterpreterTypes>::Extend,
39)]
40pub struct EthFrame<IW: InterpreterTypes = EthInterpreter> {
41    /// Frame-specific data (Call, Create, or EOFCreate).
42    pub data: FrameData,
43    /// Input data for the frame.
44    pub input: FrameInput,
45    /// Current call depth in the execution stack.
46    pub depth: usize,
47    /// Journal checkpoint for state reversion.
48    pub checkpoint: JournalCheckpoint,
49    /// Interpreter instance for executing bytecode.
50    pub interpreter: Interpreter<IW>,
51    /// Whether the frame has been finished its execution.
52    /// Frame is considered finished if it has been called and returned a result.
53    pub is_finished: bool,
54}
55
56impl<IT: InterpreterTypes> FrameTr for EthFrame<IT> {
57    type FrameResult = FrameResult;
58    type FrameInit = FrameInit;
59}
60
61impl Default for EthFrame<EthInterpreter> {
62    fn default() -> Self {
63        Self::do_default(Interpreter::default())
64    }
65}
66
67impl EthFrame<EthInterpreter> {
68    /// Creates an new invalid [`EthFrame`].
69    pub fn invalid() -> Self {
70        Self::do_default(Interpreter::invalid())
71    }
72
73    fn do_default(interpreter: Interpreter<EthInterpreter>) -> Self {
74        Self {
75            data: FrameData::Call(CallFrame {
76                return_memory_range: 0..0,
77            }),
78            input: FrameInput::Empty,
79            depth: 0,
80            checkpoint: JournalCheckpoint::default(),
81            interpreter,
82            is_finished: false,
83        }
84    }
85
86    /// Returns true if the frame has finished execution.
87    pub fn is_finished(&self) -> bool {
88        self.is_finished
89    }
90
91    /// Sets the finished state of the frame.
92    pub fn set_finished(&mut self, finished: bool) {
93        self.is_finished = finished;
94    }
95}
96
97/// Type alias for database errors from a context.
98pub type ContextTrDbError<CTX> = <<CTX as ContextTr>::Db as Database>::Error;
99
100impl EthFrame<EthInterpreter> {
101    /// Clear and initialize a frame.
102    #[allow(clippy::too_many_arguments)]
103    #[inline(always)]
104    pub fn clear(
105        &mut self,
106        data: FrameData,
107        input: FrameInput,
108        depth: usize,
109        memory: SharedMemory,
110        bytecode: ExtBytecode,
111        inputs: InputsImpl,
112        is_static: bool,
113        spec_id: SpecId,
114        gas_limit: u64,
115        checkpoint: JournalCheckpoint,
116    ) {
117        let Self {
118            data: data_ref,
119            input: input_ref,
120            depth: depth_ref,
121            interpreter,
122            checkpoint: checkpoint_ref,
123            is_finished: is_finished_ref,
124        } = self;
125        *data_ref = data;
126        *input_ref = input;
127        *depth_ref = depth;
128        *is_finished_ref = false;
129        interpreter.clear(memory, bytecode, inputs, is_static, spec_id, gas_limit);
130        *checkpoint_ref = checkpoint;
131    }
132
133    /// Make call frame
134    #[inline]
135    pub fn make_call_frame<
136        CTX: ContextTr,
137        PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
138        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
139    >(
140        mut this: OutFrame<'_, Self>,
141        ctx: &mut CTX,
142        precompiles: &mut PRECOMPILES,
143        depth: usize,
144        memory: SharedMemory,
145        inputs: Box<CallInputs>,
146    ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> {
147        let gas = Gas::new(inputs.gas_limit);
148        let return_result = |instruction_result: InstructionResult| {
149            Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome {
150                result: InterpreterResult {
151                    result: instruction_result,
152                    gas,
153                    output: Bytes::new(),
154                },
155                memory_offset: inputs.return_memory_offset.clone(),
156                was_precompile_called: false,
157                precompile_call_logs: Vec::new(),
158            })))
159        };
160
161        // Check depth
162        if depth > CALL_STACK_LIMIT as usize {
163            return return_result(InstructionResult::CallTooDeep);
164        }
165
166        // Create subroutine checkpoint
167        let checkpoint = ctx.journal_mut().checkpoint();
168
169        // Touch address. For "EIP-158 State Clear", this will erase empty accounts.
170        if let CallValue::Transfer(value) = inputs.value {
171            // Transfer value from caller to called account
172            // Target will get touched even if balance transferred is zero.
173            if let Some(i) =
174                ctx.journal_mut()
175                    .transfer_loaded(inputs.caller, inputs.target_address, value)
176            {
177                ctx.journal_mut().checkpoint_revert(checkpoint);
178                return return_result(i.into());
179            }
180        }
181
182        let interpreter_input = InputsImpl {
183            target_address: inputs.target_address,
184            caller_address: inputs.caller,
185            bytecode_address: Some(inputs.bytecode_address),
186            input: inputs.input.clone(),
187            call_value: inputs.value.get(),
188        };
189        let is_static = inputs.is_static;
190        let gas_limit = inputs.gas_limit;
191
192        if let Some(result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? {
193            let mut logs = Vec::new();
194            if result.result.is_ok() {
195                ctx.journal_mut().checkpoint_commit();
196            } else {
197                // clone logs that precompile created, only possible with custom precompiles.
198                // checkpoint.log_i will be always correct.
199                logs = ctx.journal_mut().logs()[checkpoint.log_i..].to_vec();
200                ctx.journal_mut().checkpoint_revert(checkpoint);
201            }
202            return Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome {
203                result,
204                memory_offset: inputs.return_memory_offset.clone(),
205                was_precompile_called: true,
206                precompile_call_logs: logs,
207            })));
208        }
209
210        // Get bytecode and hash - either from known_bytecode or load from account
211        let (bytecode, bytecode_hash) = if let Some((hash, code)) = inputs.known_bytecode.clone() {
212            // Use provided bytecode and hash
213            (code, hash)
214        } else {
215            // Load account and get its bytecode
216            let account = ctx
217                .journal_mut()
218                .load_account_with_code(inputs.bytecode_address)?;
219            (
220                account.info.code.clone().unwrap_or_default(),
221                account.info.code_hash,
222            )
223        };
224
225        // Returns success if bytecode is empty.
226        if bytecode.is_empty() {
227            ctx.journal_mut().checkpoint_commit();
228            return return_result(InstructionResult::Stop);
229        }
230
231        // Create interpreter and executes call and push new CallStackFrame.
232        this.get(EthFrame::invalid).clear(
233            FrameData::Call(CallFrame {
234                return_memory_range: inputs.return_memory_offset.clone(),
235            }),
236            FrameInput::Call(inputs),
237            depth,
238            memory,
239            ExtBytecode::new_with_hash(bytecode, bytecode_hash),
240            interpreter_input,
241            is_static,
242            ctx.cfg().spec().into(),
243            gas_limit,
244            checkpoint,
245        );
246        Ok(ItemOrResult::Item(this.consume()))
247    }
248
249    /// Make create frame.
250    #[inline]
251    pub fn make_create_frame<
252        CTX: ContextTr,
253        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
254    >(
255        mut this: OutFrame<'_, Self>,
256        context: &mut CTX,
257        depth: usize,
258        memory: SharedMemory,
259        inputs: Box<CreateInputs>,
260    ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> {
261        let spec = context.cfg().spec().into();
262        let return_error = |e| {
263            Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome {
264                result: InterpreterResult {
265                    result: e,
266                    gas: Gas::new(inputs.gas_limit()),
267                    output: Bytes::new(),
268                },
269                address: None,
270            })))
271        };
272
273        // Check depth
274        if depth > CALL_STACK_LIMIT as usize {
275            return return_error(InstructionResult::CallTooDeep);
276        }
277
278        // Fetch balance of caller.
279        let journal = context.journal_mut();
280        let mut caller_info = journal.load_account_mut(inputs.caller())?;
281
282        // Check if caller has enough balance to send to the created contract.
283        // decrement of balance is done in the create_account_checkpoint.
284        if *caller_info.balance() < inputs.value() {
285            return return_error(InstructionResult::OutOfFunds);
286        }
287
288        // Increase nonce of caller and check if it overflows
289        let old_nonce = caller_info.nonce();
290        if !caller_info.bump_nonce() {
291            return return_error(InstructionResult::Return);
292        };
293
294        // Create address
295        let mut init_code_hash = None;
296        let created_address = match inputs.scheme() {
297            CreateScheme::Create => inputs.caller().create(old_nonce),
298            CreateScheme::Create2 { salt } => {
299                let init_code_hash = *init_code_hash.insert(keccak256(inputs.init_code()));
300                inputs.caller().create2(salt.to_be_bytes(), init_code_hash)
301            }
302            CreateScheme::Custom { address } => address,
303        };
304
305        drop(caller_info); // Drop caller info to avoid borrow checker issues.
306
307        // warm load account.
308        journal.load_account(created_address)?;
309
310        // Create account, transfer funds and make the journal checkpoint.
311        let checkpoint = match context.journal_mut().create_account_checkpoint(
312            inputs.caller(),
313            created_address,
314            inputs.value(),
315            spec,
316        ) {
317            Ok(checkpoint) => checkpoint,
318            Err(e) => return return_error(e.into()),
319        };
320
321        let bytecode = ExtBytecode::new_with_optional_hash(
322            Bytecode::new_legacy(inputs.init_code().clone()),
323            init_code_hash,
324        );
325
326        let interpreter_input = InputsImpl {
327            target_address: created_address,
328            caller_address: inputs.caller(),
329            bytecode_address: None,
330            input: CallInput::Bytes(Bytes::new()),
331            call_value: inputs.value(),
332        };
333        let gas_limit = inputs.gas_limit();
334
335        this.get(EthFrame::invalid).clear(
336            FrameData::Create(CreateFrame { created_address }),
337            FrameInput::Create(inputs),
338            depth,
339            memory,
340            bytecode,
341            interpreter_input,
342            false,
343            spec,
344            gas_limit,
345            checkpoint,
346        );
347        Ok(ItemOrResult::Item(this.consume()))
348    }
349
350    /// Initializes a frame with the given context and precompiles.
351    pub fn init_with_context<
352        CTX: ContextTr,
353        PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
354    >(
355        this: OutFrame<'_, Self>,
356        ctx: &mut CTX,
357        precompiles: &mut PRECOMPILES,
358        frame_init: FrameInit,
359    ) -> Result<
360        ItemOrResult<FrameToken, FrameResult>,
361        ContextError<<<CTX as ContextTr>::Db as Database>::Error>,
362    > {
363        // TODO cleanup inner make functions
364        let FrameInit {
365            depth,
366            memory,
367            frame_input,
368        } = frame_init;
369
370        match frame_input {
371            FrameInput::Call(inputs) => {
372                Self::make_call_frame(this, ctx, precompiles, depth, memory, inputs)
373            }
374            FrameInput::Create(inputs) => Self::make_create_frame(this, ctx, depth, memory, inputs),
375            FrameInput::Empty => unreachable!(),
376        }
377    }
378}
379
380impl EthFrame<EthInterpreter> {
381    /// Processes the next interpreter action, either creating a new frame or returning a result.
382    pub fn process_next_action<
383        CTX: ContextTr,
384        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
385    >(
386        &mut self,
387        context: &mut CTX,
388        next_action: InterpreterAction,
389    ) -> Result<FrameInitOrResult<Self>, ERROR> {
390        // Run interpreter
391
392        let mut interpreter_result = match next_action {
393            InterpreterAction::NewFrame(frame_input) => {
394                let depth = self.depth + 1;
395                return Ok(ItemOrResult::Item(FrameInit {
396                    frame_input,
397                    depth,
398                    memory: self.interpreter.memory.new_child_context(),
399                }));
400            }
401            InterpreterAction::Return(result) => result,
402        };
403
404        // Handle return from frame
405        let result = match &self.data {
406            FrameData::Call(frame) => {
407                // return_call
408                // Revert changes or not.
409                if interpreter_result.result.is_ok() {
410                    context.journal_mut().checkpoint_commit();
411                } else {
412                    context.journal_mut().checkpoint_revert(self.checkpoint);
413                }
414                ItemOrResult::Result(FrameResult::Call(CallOutcome::new(
415                    interpreter_result,
416                    frame.return_memory_range.clone(),
417                )))
418            }
419            FrameData::Create(frame) => {
420                let (cfg, journal) = context.cfg_journal_mut();
421                return_create(
422                    journal,
423                    cfg,
424                    self.checkpoint,
425                    &mut interpreter_result,
426                    frame.created_address,
427                );
428
429                ItemOrResult::Result(FrameResult::Create(CreateOutcome::new(
430                    interpreter_result,
431                    Some(frame.created_address),
432                )))
433            }
434        };
435
436        Ok(result)
437    }
438
439    /// Processes a frame result and updates the interpreter state accordingly.
440    pub fn return_result<CTX: ContextTr, ERROR: From<ContextTrDbError<CTX>> + FromStringError>(
441        &mut self,
442        ctx: &mut CTX,
443        result: FrameResult,
444    ) -> Result<(), ERROR> {
445        self.interpreter.memory.free_child_context();
446        match core::mem::replace(ctx.error(), Ok(())) {
447            Err(ContextError::Db(e)) => return Err(e.into()),
448            Err(ContextError::Custom(e)) => return Err(ERROR::from_string(e)),
449            Ok(_) => (),
450        }
451
452        // Insert result to the top frame.
453        match result {
454            FrameResult::Call(outcome) => {
455                let out_gas = outcome.gas();
456                let ins_result = *outcome.instruction_result();
457                let returned_len = outcome.result.output.len();
458
459                let interpreter = &mut self.interpreter;
460                let mem_length = outcome.memory_length();
461                let mem_start = outcome.memory_start();
462                interpreter.return_data.set_buffer(outcome.result.output);
463
464                let target_len = min(mem_length, returned_len);
465
466                if ins_result == InstructionResult::FatalExternalError {
467                    panic!("Fatal external error in insert_call_outcome");
468                }
469
470                let item = if ins_result.is_ok() {
471                    U256::from(1)
472                } else {
473                    U256::ZERO
474                };
475                // Safe to push without stack limit check
476                let _ = interpreter.stack.push(item);
477
478                // Return unspend gas.
479                if ins_result.is_ok_or_revert() {
480                    interpreter.gas.erase_cost(out_gas.remaining());
481                    interpreter
482                        .memory
483                        .set(mem_start, &interpreter.return_data.buffer()[..target_len]);
484                }
485
486                if ins_result.is_ok() {
487                    interpreter.gas.record_refund(out_gas.refunded());
488                }
489            }
490            FrameResult::Create(outcome) => {
491                let instruction_result = *outcome.instruction_result();
492                let interpreter = &mut self.interpreter;
493
494                if instruction_result == InstructionResult::Revert {
495                    // Save data to return data buffer if the create reverted
496                    interpreter
497                        .return_data
498                        .set_buffer(outcome.output().to_owned());
499                } else {
500                    // Otherwise clear it. Note that RETURN opcode should abort.
501                    interpreter.return_data.clear();
502                };
503
504                assert_ne!(
505                    instruction_result,
506                    InstructionResult::FatalExternalError,
507                    "Fatal external error in insert_eofcreate_outcome"
508                );
509
510                let this_gas = &mut interpreter.gas;
511                if instruction_result.is_ok_or_revert() {
512                    this_gas.erase_cost(outcome.gas().remaining());
513                }
514
515                let stack_item = if instruction_result.is_ok() {
516                    this_gas.record_refund(outcome.gas().refunded());
517                    outcome.address.unwrap_or_default().into_word().into()
518                } else {
519                    U256::ZERO
520                };
521
522                // Safe to push without stack limit check
523                let _ = interpreter.stack.push(stack_item);
524            }
525        }
526
527        Ok(())
528    }
529}
530
531/// Handles the result of a CREATE operation, including validation and state updates.
532pub fn return_create<JOURNAL: JournalTr, CFG: Cfg>(
533    journal: &mut JOURNAL,
534    cfg: CFG,
535    checkpoint: JournalCheckpoint,
536    interpreter_result: &mut InterpreterResult,
537    address: Address,
538) {
539    let max_code_size = cfg.max_code_size();
540    let is_eip3541_disabled = cfg.is_eip3541_disabled();
541    let spec_id = cfg.spec().into();
542
543    // If return is not ok revert and return.
544    if !interpreter_result.result.is_ok() {
545        journal.checkpoint_revert(checkpoint);
546        return;
547    }
548    // Host error if present on execution
549    // If ok, check contract creation limit and calculate gas deduction on output len.
550    //
551    // EIP-3541: Reject new contract code starting with the 0xEF byte
552    if !is_eip3541_disabled
553        && spec_id.is_enabled_in(LONDON)
554        && interpreter_result.output.first() == Some(&0xEF)
555    {
556        journal.checkpoint_revert(checkpoint);
557        interpreter_result.result = InstructionResult::CreateContractStartingWithEF;
558        return;
559    }
560
561    // EIP-170: Contract code size limit to 0x6000 (~25kb)
562    // EIP-7907 increased this limit to 0xc000 (~49kb).
563    if spec_id.is_enabled_in(SPURIOUS_DRAGON) && interpreter_result.output.len() > max_code_size {
564        journal.checkpoint_revert(checkpoint);
565        interpreter_result.result = InstructionResult::CreateContractSizeLimit;
566        return;
567    }
568    let gas_for_code = cfg
569        .gas_params()
570        .code_deposit_cost(interpreter_result.output.len());
571    if !interpreter_result.gas.record_cost(gas_for_code) {
572        // Record code deposit gas cost and check if we are out of gas.
573        // EIP-2 point 3: If contract creation does not have enough gas to pay for the
574        // final gas fee for adding the contract code to the state, the contract
575        // creation fails (i.e. goes out-of-gas) rather than leaving an empty contract.
576        if spec_id.is_enabled_in(HOMESTEAD) {
577            journal.checkpoint_revert(checkpoint);
578            interpreter_result.result = InstructionResult::OutOfGas;
579            return;
580        } else {
581            interpreter_result.output = Bytes::new();
582        }
583    }
584    // If we have enough gas we can commit changes.
585    journal.checkpoint_commit();
586
587    // Do analysis of bytecode straight away.
588    let bytecode = Bytecode::new_legacy(interpreter_result.output.clone());
589
590    // Set code
591    journal.set_code(address, bytecode);
592
593    interpreter_result.result = InstructionResult::Return;
594}