Skip to main content

revm_interpreter/instructions/contract/
call_helpers.rs

1use crate::{
2    interpreter::Interpreter,
3    interpreter_types::{InterpreterTypes, MemoryTr, RuntimeFlag, StackTr},
4    InstructionContext,
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 InterpreterTypes>,
18    gas_params: &GasParams,
19) -> Option<(Range<usize>, Range<usize>)> {
20    popn!([in_offset, in_len, out_offset, out_len], interpreter, None);
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    Some((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 InterpreterTypes>,
38    gas_params: &GasParams,
39    offset: U256,
40    len: U256,
41) -> Option<Range<usize>> {
42    let len = as_usize_or_fail_ret!(interpreter, len, None);
43    let offset = if len != 0 {
44        let offset = as_usize_or_fail_ret!(interpreter, offset, None);
45        resize_memory!(interpreter, gas_params, offset, len, None);
46        offset
47    } else {
48        usize::MAX //unrealistic value so we are sure it is not used
49    };
50    Some(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 InstructionContext<'_, H, impl InterpreterTypes>,
57    to: Address,
58    transfers_value: bool,
59    create_empty_account: bool,
60    stack_gas_limit: u64,
61) -> Option<(u64, Bytecode, B256)> {
62    // Transfer value cost
63    if transfers_value {
64        gas!(
65            context.interpreter,
66            context.host.gas_params().transfer_value_cost(),
67            None
68        );
69    }
70
71    // load account delegated and deduct dynamic gas.
72    let (gas, state_gas_cost, bytecode, code_hash) =
73        load_account_delegated_handle_error(context, to, transfers_value, create_empty_account)?;
74    let interpreter = &mut context.interpreter;
75
76    // deduct dynamic gas.
77    gas!(interpreter, gas, None);
78
79    // deduct state gas (EIP-8037) if any.
80    state_gas!(interpreter, state_gas_cost, None);
81
82    let interpreter = &mut context.interpreter;
83    let host = &mut context.host;
84
85    // EIP-150: Gas cost changes for IO-heavy operations
86    let mut gas_limit = if interpreter.runtime_flag.spec_id().is_enabled_in(TANGERINE) {
87        // On mainnet this will take return 63/64 of gas_limit.
88        let reduced_gas_limit = host
89            .gas_params()
90            .call_stipend_reduction(interpreter.gas.remaining());
91        min(reduced_gas_limit, stack_gas_limit)
92    } else {
93        stack_gas_limit
94    };
95    gas!(interpreter, gas_limit, None);
96
97    // Add call stipend if there is value to be transferred.
98    if transfers_value {
99        gas_limit = gas_limit.saturating_add(host.gas_params().call_stipend());
100    }
101
102    Some((gas_limit, bytecode, code_hash))
103}
104
105/// Loads accounts and its delegate account.
106///
107/// Returns `(regular_gas_cost, state_gas_cost, bytecode, code_hash)`.
108#[inline]
109pub fn load_account_delegated_handle_error<H: Host + ?Sized>(
110    context: &mut InstructionContext<'_, H, impl InterpreterTypes>,
111    to: Address,
112    transfers_value: bool,
113    create_empty_account: bool,
114) -> Option<(u64, u64, Bytecode, B256)> {
115    // move this to static gas.
116    let remaining_gas = context.interpreter.gas.remaining();
117    match load_account_delegated(
118        context.host,
119        context.interpreter.runtime_flag.spec_id(),
120        remaining_gas,
121        to,
122        transfers_value,
123        create_empty_account,
124    ) {
125        Ok(out) => return Some(out),
126        Err(LoadError::ColdLoadSkipped) => {
127            context.interpreter.halt_oog();
128        }
129        Err(LoadError::DBError) => {
130            context.interpreter.halt_fatal();
131        }
132    }
133    None
134}
135
136/// Loads accounts and its delegate account.
137///
138/// Assumption is that warm gas is already deducted.
139///
140/// Returns `(regular_gas_cost, state_gas_cost, bytecode, code_hash)`.
141/// `state_gas_cost` is non-zero only when creating a new empty account (EIP-8037).
142#[inline]
143pub fn load_account_delegated<H: Host + ?Sized>(
144    host: &mut H,
145    spec: SpecId,
146    remaining_gas: u64,
147    address: Address,
148    transfers_value: bool,
149    create_empty_account: bool,
150) -> Result<(u64, u64, Bytecode, B256), LoadError> {
151    let mut cost = 0;
152    let mut state_gas_cost = 0;
153    let is_berlin = spec.is_enabled_in(SpecId::BERLIN);
154    let is_spurious_dragon = spec.is_enabled_in(SpecId::SPURIOUS_DRAGON);
155
156    let additional_cold_cost = host.gas_params().cold_account_additional_cost();
157    let warm_storage_read_cost = host.gas_params().warm_storage_read_cost();
158
159    let skip_cold_load = is_berlin && remaining_gas < additional_cold_cost;
160    let account = host.load_account_info_skip_cold_load(address, true, skip_cold_load)?;
161    if is_berlin && account.is_cold {
162        cost += additional_cold_cost;
163    }
164    let mut bytecode = account.code.clone().unwrap_or_default();
165    let mut code_hash = account.code_hash();
166    // New account cost, as account is empty there is no delegated account and we can return early.
167    if create_empty_account && account.is_empty {
168        cost += host
169            .gas_params()
170            .new_account_cost(is_spurious_dragon, transfers_value);
171        if host.is_amsterdam_eip8037_enabled() && transfers_value {
172            state_gas_cost += host.gas_params().new_account_state_gas();
173        }
174        return Ok((cost, state_gas_cost, bytecode, code_hash));
175    }
176
177    // load delegate code if account is EIP-7702
178    if let Some(address) = account.code.as_ref().and_then(Bytecode::eip7702_address) {
179        // EIP-7702 is enabled after berlin hardfork.
180        cost += warm_storage_read_cost;
181        if cost > remaining_gas {
182            return Err(LoadError::ColdLoadSkipped);
183        }
184
185        // skip cold load if there is enough gas to cover the cost.
186        let skip_cold_load = remaining_gas < cost + additional_cold_cost;
187        let delegate_account =
188            host.load_account_info_skip_cold_load(address, true, skip_cold_load)?;
189
190        if delegate_account.is_cold {
191            cost += additional_cold_cost;
192        }
193        bytecode = delegate_account.code.clone().unwrap_or_default();
194        code_hash = delegate_account.code_hash();
195    }
196
197    Ok((cost, state_gas_cost, bytecode, code_hash))
198}