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        let bytecode = inputs.bytecode.clone();
205        let bytecode_hash = inputs.bytecode_hash;
206
207        // Returns success if bytecode is empty.
208        if bytecode.is_empty() {
209            ctx.journal_mut().checkpoint_commit();
210            return return_result(InstructionResult::Stop);
211        }
212
213        // Create interpreter and executes call and push new CallStackFrame.
214        this.get(EthFrame::invalid).clear(
215            FrameData::Call(CallFrame {
216                return_memory_range: inputs.return_memory_offset.clone(),
217            }),
218            FrameInput::Call(inputs),
219            depth,
220            memory,
221            ExtBytecode::new_with_hash(bytecode, bytecode_hash),
222            interpreter_input,
223            is_static,
224            ctx.cfg().spec().into(),
225            gas_limit,
226            checkpoint,
227        );
228        Ok(ItemOrResult::Item(this.consume()))
229    }
230
231    /// Make create frame.
232    #[inline]
233    pub fn make_create_frame<
234        CTX: ContextTr,
235        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
236    >(
237        mut this: OutFrame<'_, Self>,
238        context: &mut CTX,
239        depth: usize,
240        memory: SharedMemory,
241        inputs: Box<CreateInputs>,
242    ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> {
243        let spec = context.cfg().spec().into();
244        let return_error = |e| {
245            Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome {
246                result: InterpreterResult {
247                    result: e,
248                    gas: Gas::new(inputs.gas_limit),
249                    output: Bytes::new(),
250                },
251                address: None,
252            })))
253        };
254
255        // Check depth
256        if depth > CALL_STACK_LIMIT as usize {
257            return return_error(InstructionResult::CallTooDeep);
258        }
259
260        // Fetch balance of caller.
261        let caller_info = &mut context.journal_mut().load_account(inputs.caller)?.data.info;
262
263        // Check if caller has enough balance to send to the created contract.
264        if caller_info.balance < inputs.value {
265            return return_error(InstructionResult::OutOfFunds);
266        }
267
268        // Increase nonce of caller and check if it overflows
269        let old_nonce = caller_info.nonce;
270        let Some(new_nonce) = old_nonce.checked_add(1) else {
271            return return_error(InstructionResult::Return);
272        };
273        caller_info.nonce = new_nonce;
274        context
275            .journal_mut()
276            .nonce_bump_journal_entry(inputs.caller);
277
278        // Create address
279        let mut init_code_hash = None;
280        let created_address = match inputs.scheme {
281            CreateScheme::Create => inputs.caller.create(old_nonce),
282            CreateScheme::Create2 { salt } => {
283                let init_code_hash = *init_code_hash.insert(keccak256(&inputs.init_code));
284                inputs.caller.create2(salt.to_be_bytes(), init_code_hash)
285            }
286            CreateScheme::Custom { address } => address,
287        };
288
289        // warm load account.
290        context.journal_mut().load_account(created_address)?;
291
292        // Create account, transfer funds and make the journal checkpoint.
293        let checkpoint = match context.journal_mut().create_account_checkpoint(
294            inputs.caller,
295            created_address,
296            inputs.value,
297            spec,
298        ) {
299            Ok(checkpoint) => checkpoint,
300            Err(e) => return return_error(e.into()),
301        };
302
303        let bytecode = ExtBytecode::new_with_optional_hash(
304            Bytecode::new_legacy(inputs.init_code.clone()),
305            init_code_hash,
306        );
307
308        let interpreter_input = InputsImpl {
309            target_address: created_address,
310            caller_address: inputs.caller,
311            bytecode_address: None,
312            input: CallInput::Bytes(Bytes::new()),
313            call_value: inputs.value,
314        };
315        let gas_limit = inputs.gas_limit;
316
317        this.get(EthFrame::invalid).clear(
318            FrameData::Create(CreateFrame { created_address }),
319            FrameInput::Create(inputs),
320            depth,
321            memory,
322            bytecode,
323            interpreter_input,
324            false,
325            spec,
326            gas_limit,
327            checkpoint,
328        );
329        Ok(ItemOrResult::Item(this.consume()))
330    }
331
332    /// Initializes a frame with the given context and precompiles.
333    pub fn init_with_context<
334        CTX: ContextTr,
335        PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
336    >(
337        this: OutFrame<'_, Self>,
338        ctx: &mut CTX,
339        precompiles: &mut PRECOMPILES,
340        frame_init: FrameInit,
341    ) -> Result<
342        ItemOrResult<FrameToken, FrameResult>,
343        ContextError<<<CTX as ContextTr>::Db as Database>::Error>,
344    > {
345        // TODO cleanup inner make functions
346        let FrameInit {
347            depth,
348            memory,
349            frame_input,
350        } = frame_init;
351
352        match frame_input {
353            FrameInput::Call(inputs) => {
354                Self::make_call_frame(this, ctx, precompiles, depth, memory, inputs)
355            }
356            FrameInput::Create(inputs) => Self::make_create_frame(this, ctx, depth, memory, inputs),
357            FrameInput::Empty => unreachable!(),
358        }
359    }
360}
361
362impl EthFrame<EthInterpreter> {
363    /// Processes the next interpreter action, either creating a new frame or returning a result.
364    pub fn process_next_action<
365        CTX: ContextTr,
366        ERROR: From<ContextTrDbError<CTX>> + FromStringError,
367    >(
368        &mut self,
369        context: &mut CTX,
370        next_action: InterpreterAction,
371    ) -> Result<FrameInitOrResult<Self>, ERROR> {
372        let spec = context.cfg().spec().into();
373
374        // Run interpreter
375
376        let mut interpreter_result = match next_action {
377            InterpreterAction::NewFrame(frame_input) => {
378                let depth = self.depth + 1;
379                return Ok(ItemOrResult::Item(FrameInit {
380                    frame_input,
381                    depth,
382                    memory: self.interpreter.memory.new_child_context(),
383                }));
384            }
385            InterpreterAction::Return(result) => result,
386        };
387
388        // Handle return from frame
389        let result = match &self.data {
390            FrameData::Call(frame) => {
391                // return_call
392                // Revert changes or not.
393                if interpreter_result.result.is_ok() {
394                    context.journal_mut().checkpoint_commit();
395                } else {
396                    context.journal_mut().checkpoint_revert(self.checkpoint);
397                }
398                ItemOrResult::Result(FrameResult::Call(CallOutcome::new(
399                    interpreter_result,
400                    frame.return_memory_range.clone(),
401                )))
402            }
403            FrameData::Create(frame) => {
404                let max_code_size = context.cfg().max_code_size();
405                let is_eip3541_disabled = context.cfg().is_eip3541_disabled();
406                return_create(
407                    context.journal_mut(),
408                    self.checkpoint,
409                    &mut interpreter_result,
410                    frame.created_address,
411                    max_code_size,
412                    is_eip3541_disabled,
413                    spec,
414                );
415
416                ItemOrResult::Result(FrameResult::Create(CreateOutcome::new(
417                    interpreter_result,
418                    Some(frame.created_address),
419                )))
420            }
421        };
422
423        Ok(result)
424    }
425
426    /// Processes a frame result and updates the interpreter state accordingly.
427    pub fn return_result<CTX: ContextTr, ERROR: From<ContextTrDbError<CTX>> + FromStringError>(
428        &mut self,
429        ctx: &mut CTX,
430        result: FrameResult,
431    ) -> Result<(), ERROR> {
432        self.interpreter.memory.free_child_context();
433        match core::mem::replace(ctx.error(), Ok(())) {
434            Err(ContextError::Db(e)) => return Err(e.into()),
435            Err(ContextError::Custom(e)) => return Err(ERROR::from_string(e)),
436            Ok(_) => (),
437        }
438
439        // Insert result to the top frame.
440        match result {
441            FrameResult::Call(outcome) => {
442                let out_gas = outcome.gas();
443                let ins_result = *outcome.instruction_result();
444                let returned_len = outcome.result.output.len();
445
446                let interpreter = &mut self.interpreter;
447                let mem_length = outcome.memory_length();
448                let mem_start = outcome.memory_start();
449                interpreter.return_data.set_buffer(outcome.result.output);
450
451                let target_len = min(mem_length, returned_len);
452
453                if ins_result == InstructionResult::FatalExternalError {
454                    panic!("Fatal external error in insert_call_outcome");
455                }
456
457                let item = if ins_result.is_ok() {
458                    U256::from(1)
459                } else {
460                    U256::ZERO
461                };
462                // Safe to push without stack limit check
463                let _ = interpreter.stack.push(item);
464
465                // Return unspend gas.
466                if ins_result.is_ok_or_revert() {
467                    interpreter.gas.erase_cost(out_gas.remaining());
468                    interpreter
469                        .memory
470                        .set(mem_start, &interpreter.return_data.buffer()[..target_len]);
471                }
472
473                if ins_result.is_ok() {
474                    interpreter.gas.record_refund(out_gas.refunded());
475                }
476            }
477            FrameResult::Create(outcome) => {
478                let instruction_result = *outcome.instruction_result();
479                let interpreter = &mut self.interpreter;
480
481                if instruction_result == InstructionResult::Revert {
482                    // Save data to return data buffer if the create reverted
483                    interpreter
484                        .return_data
485                        .set_buffer(outcome.output().to_owned());
486                } else {
487                    // Otherwise clear it. Note that RETURN opcode should abort.
488                    interpreter.return_data.clear();
489                };
490
491                assert_ne!(
492                    instruction_result,
493                    InstructionResult::FatalExternalError,
494                    "Fatal external error in insert_eofcreate_outcome"
495                );
496
497                let this_gas = &mut interpreter.gas;
498                if instruction_result.is_ok_or_revert() {
499                    this_gas.erase_cost(outcome.gas().remaining());
500                }
501
502                let stack_item = if instruction_result.is_ok() {
503                    this_gas.record_refund(outcome.gas().refunded());
504                    outcome.address.unwrap_or_default().into_word().into()
505                } else {
506                    U256::ZERO
507                };
508
509                // Safe to push without stack limit check
510                let _ = interpreter.stack.push(stack_item);
511            }
512        }
513
514        Ok(())
515    }
516}
517
518/// Handles the result of a CREATE operation, including validation and state updates.
519pub fn return_create<JOURNAL: JournalTr>(
520    journal: &mut JOURNAL,
521    checkpoint: JournalCheckpoint,
522    interpreter_result: &mut InterpreterResult,
523    address: Address,
524    max_code_size: usize,
525    is_eip3541_disabled: bool,
526    spec_id: SpecId,
527) {
528    // If return is not ok revert and return.
529    if !interpreter_result.result.is_ok() {
530        journal.checkpoint_revert(checkpoint);
531        return;
532    }
533    // Host error if present on execution
534    // If ok, check contract creation limit and calculate gas deduction on output len.
535    //
536    // EIP-3541: Reject new contract code starting with the 0xEF byte
537    if !is_eip3541_disabled
538        && spec_id.is_enabled_in(LONDON)
539        && interpreter_result.output.first() == Some(&0xEF)
540    {
541        journal.checkpoint_revert(checkpoint);
542        interpreter_result.result = InstructionResult::CreateContractStartingWithEF;
543        return;
544    }
545
546    // EIP-170: Contract code size limit to 0x6000 (~25kb)
547    // EIP-7907 increased this limit to 0xc000 (~49kb).
548    if spec_id.is_enabled_in(SPURIOUS_DRAGON) && interpreter_result.output.len() > max_code_size {
549        journal.checkpoint_revert(checkpoint);
550        interpreter_result.result = InstructionResult::CreateContractSizeLimit;
551        return;
552    }
553    let gas_for_code = interpreter_result.output.len() as u64 * gas::CODEDEPOSIT;
554    if !interpreter_result.gas.record_cost(gas_for_code) {
555        // Record code deposit gas cost and check if we are out of gas.
556        // EIP-2 point 3: If contract creation does not have enough gas to pay for the
557        // final gas fee for adding the contract code to the state, the contract
558        // creation fails (i.e. goes out-of-gas) rather than leaving an empty contract.
559        if spec_id.is_enabled_in(HOMESTEAD) {
560            journal.checkpoint_revert(checkpoint);
561            interpreter_result.result = InstructionResult::OutOfGas;
562            return;
563        } else {
564            interpreter_result.output = Bytes::new();
565        }
566    }
567    // If we have enough gas we can commit changes.
568    journal.checkpoint_commit();
569
570    // Do analysis of bytecode straight away.
571    let bytecode = Bytecode::new_legacy(interpreter_result.output.clone());
572
573    // Set code
574    journal.set_code(address, bytecode);
575
576    interpreter_result.result = InstructionResult::Return;
577}