revm_handler/
frame.rs

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