Skip to main content

revm_interpreter/instructions/contract/
call_helpers.rs

1use crate::{
2    interpreter::Interpreter,
3    interpreter_types::{InterpreterTypes as ITy, MemoryTr, RuntimeFlag, StackTr},
4    InstructionContext as Ictx, InstructionResult,
5};
6use context_interface::{cfg::GasParams, host::LoadError, Host};
7use core::{cmp::min, ops::Range};
8use primitives::{
9    hardfork::SpecId::{self, *},
10    Address, B256, U256,
11};
12use state::Bytecode;
13
14/// Gets memory input and output ranges for call instructions.
15#[inline]
16pub fn get_memory_input_and_out_ranges(
17    interpreter: &mut Interpreter<impl ITy>,
18    gas_params: &GasParams,
19) -> Result<(Range<usize>, Range<usize>), InstructionResult> {
20    popn!([in_offset, in_len, out_offset, out_len], interpreter);
21
22    let mut in_range = resize_memory(interpreter, gas_params, in_offset, in_len)?;
23
24    if !in_range.is_empty() {
25        let offset = interpreter.memory.local_memory_offset();
26        in_range = in_range.start.saturating_add(offset)..in_range.end.saturating_add(offset);
27    }
28
29    let ret_range = resize_memory(interpreter, gas_params, out_offset, out_len)?;
30    Ok((in_range, ret_range))
31}
32
33/// Resize memory and return range of memory.
34/// If `len` is 0 dont touch memory and return `usize::MAX` as offset and 0 as length.
35#[inline]
36pub fn resize_memory(
37    interpreter: &mut Interpreter<impl ITy>,
38    gas_params: &GasParams,
39    offset: U256,
40    len: U256,
41) -> Result<Range<usize>, InstructionResult> {
42    let len = as_usize_or_fail!(interpreter, len);
43    let offset = if len != 0 {
44        let offset = as_usize_or_fail!(interpreter, offset);
45        interpreter.resize_memory(gas_params, offset, len)?;
46        offset
47    } else {
48        usize::MAX // unrealistic value so we are sure it is not used
49    };
50    Ok(offset..offset + len)
51}
52
53/// Calculates gas cost and limit for call instructions.
54#[inline(never)]
55pub fn load_acc_and_calc_gas<H: Host + ?Sized>(
56    context: &mut Ictx<'_, H, impl ITy>,
57    to: Address,
58    transfers_value: bool,
59    create_empty_account: bool,
60    stack_gas_limit: u64,
61) -> Result<(u64, Bytecode, B256), InstructionResult> {
62    // Transfer value cost
63    if transfers_value {
64        gas!(
65            context.interpreter,
66            context.host.gas_params().transfer_value_cost()
67        );
68    }
69
70    // load account delegated and deduct dynamic gas.
71    let (gas, state_gas_cost, bytecode, code_hash) =
72        load_account_delegated_handle_error(context, to, transfers_value, create_empty_account)?;
73    let interpreter = &mut context.interpreter;
74
75    // deduct dynamic gas.
76    gas!(interpreter, gas);
77
78    // deduct state gas (EIP-8037) if any.
79    state_gas!(interpreter, state_gas_cost);
80
81    let interpreter = &mut context.interpreter;
82    let host = &mut context.host;
83
84    // EIP-150: Gas cost changes for IO-heavy operations
85    let mut gas_limit = if interpreter.runtime_flag.spec_id().is_enabled_in(TANGERINE) {
86        // On mainnet this will take return 63/64 of gas_limit.
87        let reduced_gas_limit = host
88            .gas_params()
89            .call_stipend_reduction(interpreter.gas.remaining());
90        min(reduced_gas_limit, stack_gas_limit)
91    } else {
92        stack_gas_limit
93    };
94    gas!(interpreter, gas_limit);
95
96    // Add call stipend if there is value to be transferred.
97    if transfers_value {
98        gas_limit = gas_limit.saturating_add(host.gas_params().call_stipend());
99    }
100
101    Ok((gas_limit, bytecode, code_hash))
102}
103
104/// Loads accounts and its delegate account.
105///
106/// Returns `(regular_gas_cost, state_gas_cost, bytecode, code_hash)`.
107#[inline]
108pub fn load_account_delegated_handle_error<H: Host + ?Sized>(
109    context: &mut Ictx<'_, H, impl ITy>,
110    to: Address,
111    transfers_value: bool,
112    create_empty_account: bool,
113) -> Result<(u64, u64, Bytecode, B256), InstructionResult> {
114    // move this to static gas.
115    let remaining_gas = context.interpreter.gas.remaining();
116    Ok(load_account_delegated(
117        context.host,
118        context.interpreter.runtime_flag.spec_id(),
119        remaining_gas,
120        to,
121        transfers_value,
122        create_empty_account,
123    )?)
124}
125
126/// Loads accounts and its delegate account.
127///
128/// Assumption is that warm gas is already deducted.
129///
130/// Returns `(regular_gas_cost, state_gas_cost, bytecode, code_hash)`.
131/// `state_gas_cost` is non-zero only when creating a new empty account (EIP-8037).
132#[inline]
133pub fn load_account_delegated<H: Host + ?Sized>(
134    host: &mut H,
135    spec: SpecId,
136    remaining_gas: u64,
137    address: Address,
138    transfers_value: bool,
139    create_empty_account: bool,
140) -> Result<(u64, u64, Bytecode, B256), LoadError> {
141    let mut cost = 0;
142    let mut state_gas_cost = 0;
143    let is_berlin = spec.is_enabled_in(SpecId::BERLIN);
144    let is_spurious_dragon = spec.is_enabled_in(SpecId::SPURIOUS_DRAGON);
145
146    let additional_cold_cost = host.gas_params().cold_account_additional_cost();
147    let warm_storage_read_cost = host.gas_params().warm_storage_read_cost();
148
149    let skip_cold_load = is_berlin && remaining_gas < additional_cold_cost;
150    let account = host.load_account_info_skip_cold_load(address, true, skip_cold_load)?;
151    if is_berlin && account.is_cold {
152        cost += additional_cold_cost;
153    }
154    let mut bytecode = account.code.clone().unwrap_or_default();
155    let mut code_hash = account.code_hash();
156    // New account cost, as account is empty there is no delegated account and we can return early.
157    if create_empty_account && account.is_empty {
158        cost += host
159            .gas_params()
160            .new_account_cost(is_spurious_dragon, transfers_value);
161        if host.is_amsterdam_eip8037_enabled() && transfers_value {
162            state_gas_cost += host.gas_params().new_account_state_gas();
163        }
164        return Ok((cost, state_gas_cost, bytecode, code_hash));
165    }
166
167    // load delegate code if account is EIP-7702
168    if let Some(address) = account.code.as_ref().and_then(Bytecode::eip7702_address) {
169        // EIP-7702 is enabled after berlin hardfork.
170        cost += warm_storage_read_cost;
171        if cost > remaining_gas {
172            return Err(LoadError::ColdLoadSkipped);
173        }
174
175        // skip cold load if there is enough gas to cover the cost.
176        let skip_cold_load = remaining_gas < cost + additional_cold_cost;
177        let delegate_account =
178            host.load_account_info_skip_cold_load(address, true, skip_cold_load)?;
179
180        if delegate_account.is_cold {
181            cost += additional_cold_cost;
182        }
183        bytecode = delegate_account.code.clone().unwrap_or_default();
184        code_hash = delegate_account.code_hash();
185    }
186
187    Ok((cost, state_gas_cost, bytecode, code_hash))
188}