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::{take_error, 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, GasTracker, 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 Address, Bytes, U256,
26};
27use state::Bytecode;
28use std::{borrow::ToOwned, boxed::Box, vec::Vec};
29
30#[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 pub data: FrameData,
43 pub input: FrameInput,
45 pub depth: usize,
47 pub checkpoint: JournalCheckpoint,
49 pub interpreter: Interpreter<IW>,
51 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 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 pub const fn is_finished(&self) -> bool {
88 self.is_finished
89 }
90
91 pub const fn set_finished(&mut self, finished: bool) {
93 self.is_finished = finished;
94 }
95}
96
97pub type ContextTrDbError<CTX> = <<CTX as ContextTr>::Db as Database>::Error;
99
100impl EthFrame<EthInterpreter> {
101 #[expect(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 reservoir_remaining_gas: u64,
116 checkpoint: JournalCheckpoint,
117 ) {
118 let Self {
119 data: data_ref,
120 input: input_ref,
121 depth: depth_ref,
122 interpreter,
123 checkpoint: checkpoint_ref,
124 is_finished: is_finished_ref,
125 } = self;
126 *data_ref = data;
127 *input_ref = input;
128 *depth_ref = depth;
129 *is_finished_ref = false;
130 interpreter.clear(
131 memory,
132 bytecode,
133 inputs,
134 is_static,
135 spec_id,
136 gas_limit,
137 reservoir_remaining_gas,
138 );
139 *checkpoint_ref = checkpoint;
140 }
141
142 #[inline]
144 pub fn make_call_frame<
145 CTX: ContextTr,
146 PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
147 ERROR: From<ContextTrDbError<CTX>> + FromStringError,
148 >(
149 mut this: OutFrame<'_, Self>,
150 ctx: &mut CTX,
151 precompiles: &mut PRECOMPILES,
152 depth: usize,
153 memory: SharedMemory,
154 inputs: Box<CallInputs>,
155 ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> {
156 let reservoir_remaining_gas = inputs.reservoir;
157 let charged_new_account_state_gas = inputs.charged_new_account_state_gas;
158 let gas =
159 Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, reservoir_remaining_gas);
160
161 let return_result = |instruction_result: InstructionResult| {
162 Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome {
163 result: InterpreterResult {
164 result: instruction_result,
165 gas,
166 output: Bytes::new(),
167 },
168 memory_offset: inputs.return_memory_offset.clone(),
169 was_precompile_called: false,
170 precompile_call_logs: Vec::new(),
171 charged_new_account_state_gas,
172 })))
173 };
174
175 if depth > CALL_STACK_LIMIT as usize {
177 return return_result(InstructionResult::CallTooDeep);
178 }
179
180 let checkpoint = ctx.journal_mut().checkpoint();
182
183 if let CallValue::Transfer(value) = inputs.value {
185 if let Some(i) =
188 ctx.journal_mut()
189 .transfer_loaded(inputs.caller, inputs.target_address, value)
190 {
191 ctx.journal_mut().checkpoint_revert(checkpoint);
192 return return_result(i.into());
193 }
194 }
195
196 let interpreter_input = InputsImpl {
197 target_address: inputs.target_address,
198 caller_address: inputs.caller,
199 bytecode_address: Some(inputs.bytecode_address),
200 input: inputs.input.clone(),
201 call_value: inputs.value.get(),
202 };
203 let is_static = inputs.is_static;
204 let gas_limit = inputs.gas_limit;
205
206 if let Some(result) = precompiles.run(ctx, &inputs).map_err(ERROR::from_string)? {
207 let mut logs = Vec::new();
208 if result.result.is_ok() {
209 ctx.journal_mut().checkpoint_commit();
212 } else {
213 logs = ctx.journal_mut().logs()[checkpoint.log_i..].to_vec();
216 ctx.journal_mut().checkpoint_revert(checkpoint);
217 }
218 return Ok(ItemOrResult::Result(FrameResult::Call(CallOutcome {
219 result,
220 memory_offset: inputs.return_memory_offset.clone(),
221 was_precompile_called: true,
222 precompile_call_logs: logs,
223 charged_new_account_state_gas,
224 })));
225 }
226
227 let (bytecode_hash, bytecode) = inputs.known_bytecode.clone();
229
230 if bytecode.is_empty() {
232 ctx.journal_mut().checkpoint_commit();
233 return return_result(InstructionResult::Stop);
234 }
235
236 this.get(EthFrame::invalid).clear(
238 FrameData::Call(CallFrame {
239 return_memory_range: inputs.return_memory_offset.clone(),
240 }),
241 FrameInput::Call(inputs),
242 depth,
243 memory,
244 ExtBytecode::new_with_hash(bytecode, bytecode_hash),
245 interpreter_input,
246 is_static,
247 ctx.cfg().spec().into(),
248 gas_limit,
249 reservoir_remaining_gas,
250 checkpoint,
251 );
252
253 Ok(ItemOrResult::Item(this.consume()))
254 }
255
256 #[inline]
258 pub fn make_create_frame<
259 CTX: ContextTr,
260 ERROR: From<ContextTrDbError<CTX>> + FromStringError,
261 >(
262 mut this: OutFrame<'_, Self>,
263 context: &mut CTX,
264 depth: usize,
265 memory: SharedMemory,
266 inputs: Box<CreateInputs>,
267 ) -> Result<ItemOrResult<FrameToken, FrameResult>, ERROR> {
268 let reservoir_remaining_gas = inputs.reservoir();
269 let spec = context.cfg().spec().into();
270 let charged_create_state_gas = inputs.charged_create_state_gas();
275 let return_error = |e| {
276 Ok(ItemOrResult::Result(FrameResult::Create(CreateOutcome {
277 result: InterpreterResult {
278 result: e,
279 gas: Gas::new_with_regular_gas_and_reservoir(
280 inputs.gas_limit(),
281 reservoir_remaining_gas,
282 ),
283 output: Bytes::new(),
284 },
285 address: None,
286 charged_create_state_gas,
287 })))
288 };
289
290 if depth > CALL_STACK_LIMIT as usize {
292 return return_error(InstructionResult::CallTooDeep);
293 }
294
295 let journal = context.journal_mut();
297 let mut caller_info = journal.load_account_mut(inputs.caller())?;
298
299 if *caller_info.balance() < inputs.value() {
302 return return_error(InstructionResult::OutOfFunds);
303 }
304
305 let old_nonce = caller_info.nonce();
307 if !caller_info.bump_nonce() {
308 return return_error(InstructionResult::Return);
309 };
310
311 let created_address = inputs.created_address(old_nonce);
314 let init_code_hash = matches!(inputs.scheme(), CreateScheme::Create2 { .. })
315 .then(|| inputs.init_code_hash());
316
317 drop(caller_info); journal.load_account(created_address)?;
321
322 let checkpoint = match context.journal_mut().create_account_checkpoint(
324 inputs.caller(),
325 created_address,
326 inputs.value(),
327 spec,
328 ) {
329 Ok(checkpoint) => checkpoint,
330 Err(e) => return return_error(e.into()),
331 };
332
333 let bytecode = ExtBytecode::new_with_optional_hash(
334 Bytecode::new_legacy(inputs.init_code().clone()),
335 init_code_hash,
336 );
337
338 let interpreter_input = InputsImpl {
339 target_address: created_address,
340 caller_address: inputs.caller(),
341 bytecode_address: None,
342 input: CallInput::Bytes(Bytes::new()),
343 call_value: inputs.value(),
344 };
345 let gas_limit = inputs.gas_limit();
346
347 this.get(EthFrame::invalid).clear(
348 FrameData::Create(CreateFrame { created_address }),
349 FrameInput::Create(inputs),
350 depth,
351 memory,
352 bytecode,
353 interpreter_input,
354 false,
355 spec,
356 gas_limit,
357 reservoir_remaining_gas,
358 checkpoint,
359 );
360
361 Ok(ItemOrResult::Item(this.consume()))
362 }
363
364 pub fn init_with_context<
366 CTX: ContextTr,
367 PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
368 >(
369 this: OutFrame<'_, Self>,
370 ctx: &mut CTX,
371 precompiles: &mut PRECOMPILES,
372 frame_init: FrameInit,
373 ) -> Result<
374 ItemOrResult<FrameToken, FrameResult>,
375 ContextError<<<CTX as ContextTr>::Db as Database>::Error>,
376 > {
377 let FrameInit {
379 depth,
380 memory,
381 frame_input,
382 } = frame_init;
383
384 match frame_input {
385 FrameInput::Call(inputs) => {
386 Self::make_call_frame(this, ctx, precompiles, depth, memory, inputs)
387 }
388 FrameInput::Create(inputs) => Self::make_create_frame(this, ctx, depth, memory, inputs),
389 FrameInput::Empty => unreachable!(),
390 }
391 }
392}
393
394impl EthFrame<EthInterpreter> {
395 pub fn process_next_action<
397 CTX: ContextTr,
398 ERROR: From<ContextTrDbError<CTX>> + FromStringError,
399 >(
400 &mut self,
401 context: &mut CTX,
402 next_action: InterpreterAction,
403 ) -> Result<FrameInitOrResult<Self>, ERROR> {
404 let mut interpreter_result = match next_action {
407 InterpreterAction::NewFrame(frame_input) => {
408 let depth = self.depth + 1;
409 return Ok(ItemOrResult::Item(FrameInit {
410 frame_input,
411 depth,
412 memory: self.interpreter.memory.new_child_context(),
413 }));
414 }
415 InterpreterAction::Return(result) => result,
416 };
417
418 let result = match &self.data {
420 FrameData::Call(frame) => {
421 if interpreter_result.result.is_ok() {
424 context.journal_mut().checkpoint_commit();
425 } else {
426 context.journal_mut().checkpoint_revert(self.checkpoint);
427 }
428 let charged_new_account_state_gas = match &self.input {
432 FrameInput::Call(inputs) => inputs.charged_new_account_state_gas,
433 _ => false,
434 };
435 let mut outcome =
436 CallOutcome::new(interpreter_result, frame.return_memory_range.clone());
437 outcome.charged_new_account_state_gas = charged_new_account_state_gas;
438 ItemOrResult::Result(FrameResult::Call(outcome))
439 }
440 FrameData::Create(frame) => {
441 return_create(
442 context,
443 self.checkpoint,
444 &mut interpreter_result,
445 frame.created_address,
446 );
447
448 let mut create_outcome =
449 CreateOutcome::new(interpreter_result, Some(frame.created_address));
450 create_outcome.charged_create_state_gas = match &self.input {
451 FrameInput::Create(inputs) => inputs.charged_create_state_gas(),
452 _ => false,
453 };
454 ItemOrResult::Result(FrameResult::Create(create_outcome))
455 }
456 };
457
458 Ok(result)
459 }
460
461 pub fn return_result<CTX: ContextTr, ERROR: From<ContextTrDbError<CTX>> + FromStringError>(
463 &mut self,
464 ctx: &mut CTX,
465 result: FrameResult,
466 ) -> Result<(), ERROR> {
467 self.interpreter.memory.free_child_context();
468 take_error::<ERROR, _>(ctx.error())?;
469
470 let refund_state_gas = result.refundable_state_gas(ctx.cfg().gas_params());
477
478 match result {
480 FrameResult::Call(outcome) => {
481 let mut out_gas = outcome.gas();
482 let ins_result = *outcome.instruction_result();
483 let returned_len = outcome.result.output.len();
484
485 let interpreter = &mut self.interpreter;
486 let mem_length = outcome.memory_length();
487 let mem_start = outcome.memory_start();
488 interpreter.return_data.set_buffer(outcome.result.output);
489
490 let target_len = min(mem_length, returned_len);
491
492 if ins_result == InstructionResult::FatalExternalError {
493 panic!("Fatal external error in insert_call_outcome");
494 }
495
496 let item = if ins_result.is_ok() {
497 U256::from(1)
498 } else {
499 U256::ZERO
500 };
501 let _ = interpreter.stack.push(item);
503
504 if ins_result.is_ok_or_revert() {
506 interpreter
507 .memory
508 .set(mem_start, &interpreter.return_data.buffer()[..target_len]);
509 }
510
511 handle_reservoir_remaining_gas(
515 ins_result,
516 interpreter.gas.tracker_mut(),
517 out_gas.tracker_mut(),
518 );
519 }
520 FrameResult::Create(outcome) => {
521 let instruction_result = *outcome.instruction_result();
522 let interpreter = &mut self.interpreter;
523
524 if instruction_result == InstructionResult::Revert {
525 interpreter
527 .return_data
528 .set_buffer(outcome.output().to_owned());
529 } else {
530 interpreter.return_data.clear();
532 };
533
534 assert_ne!(
535 instruction_result,
536 InstructionResult::FatalExternalError,
537 "Fatal external error in insert_eofcreate_outcome"
538 );
539
540 let mut create_gas = *outcome.gas();
541
542 handle_reservoir_remaining_gas(
546 instruction_result,
547 interpreter.gas.tracker_mut(),
548 create_gas.tracker_mut(),
549 );
550
551 let stack_item = if instruction_result.is_ok() {
552 outcome.address.unwrap_or_default().into_word().into()
553 } else {
554 U256::ZERO
555 };
556
557 let _ = interpreter.stack.push(stack_item);
559 }
560 }
561
562 if let Some(charge) = refund_state_gas {
565 self.interpreter.gas.refill_reservoir(charge);
566 }
567
568 Ok(())
569 }
570}
571
572#[inline]
592pub const fn handle_reservoir_remaining_gas(
593 instruction_result: InstructionResult,
594 parent_gas: &mut GasTracker,
595 child_gas: &mut GasTracker,
596) {
597 if !instruction_result.is_ok() {
599 child_gas.rollback_state_gas();
600 child_gas.set_refunded(0);
601 }
602 if instruction_result.is_halt() {
603 child_gas.spend_all();
607 }
608
609 if instruction_result.is_ok_or_revert() {
611 parent_gas.erase_cost(child_gas.remaining());
612 }
613 parent_gas.set_reservoir(child_gas.reservoir());
614 if instruction_result.is_ok() {
615 parent_gas.set_state_gas_spent(
621 parent_gas
622 .state_gas_spent()
623 .saturating_add(child_gas.state_gas_spent()),
624 );
625 parent_gas.add_state_gas_spilled(child_gas.state_gas_spilled());
626 parent_gas.record_refund(child_gas.refunded());
627 }
628}
629
630pub fn return_create<CTX: ContextTr>(
638 context: &mut CTX,
639 checkpoint: JournalCheckpoint,
640 interpreter_result: &mut InterpreterResult,
641 address: Address,
642) {
643 let (_, _, cfg, journal, _, _) = context.all_mut();
644
645 let max_code_size = cfg.max_code_size();
646 let is_eip3541_disabled = cfg.is_eip3541_disabled();
647 let spec_id = cfg.spec().into();
648 let is_amsterdam_eip8037 = cfg.is_amsterdam_eip8037_enabled();
649 let gas_params = cfg.gas_params();
650
651 if !interpreter_result.result.is_ok() {
653 journal.checkpoint_revert(checkpoint);
654 return;
655 }
656
657 if spec_id.is_enabled_in(SPURIOUS_DRAGON) && interpreter_result.output.len() > max_code_size {
662 journal.checkpoint_revert(checkpoint);
663 interpreter_result.result = InstructionResult::CreateContractSizeLimit;
664 return;
665 }
666
667 if !is_eip3541_disabled
672 && spec_id.is_enabled_in(LONDON)
673 && interpreter_result.output.first() == Some(&0xEF)
674 {
675 journal.checkpoint_revert(checkpoint);
676 interpreter_result.result = InstructionResult::CreateContractStartingWithEF;
677 return;
678 }
679
680 let gas_for_code = gas_params.code_deposit_cost(interpreter_result.output.len());
682 if !interpreter_result.gas.record_regular_cost(gas_for_code) {
683 if spec_id.is_enabled_in(HOMESTEAD) {
688 journal.checkpoint_revert(checkpoint);
689 interpreter_result.result = InstructionResult::OutOfGas;
690 return;
691 } else {
692 interpreter_result.output = Bytes::new();
693 }
694 }
695
696 if is_amsterdam_eip8037 {
703 let hash_cost = gas_params.keccak256_cost(interpreter_result.output.len());
704 if !interpreter_result.gas.record_regular_cost(hash_cost) {
705 journal.checkpoint_revert(checkpoint);
706 interpreter_result.result = InstructionResult::OutOfGas;
707 return;
708 }
709 let state_gas_for_code = gas_params.code_deposit_state_gas(interpreter_result.output.len());
715 if state_gas_for_code > 0 && !interpreter_result.gas.record_state_cost(state_gas_for_code) {
716 journal.checkpoint_revert(checkpoint);
717 interpreter_result.result = InstructionResult::OutOfGas;
718 return;
719 }
720 }
721
722 journal.checkpoint_commit();
724
725 let bytecode = Bytecode::new_legacy(interpreter_result.output.clone());
727
728 journal.set_code(address, bytecode);
730
731 interpreter_result.result = InstructionResult::Return;
732}