Skip to main content

revm_handler/
pre_execution.rs

1//! Handles related to the main function of the EVM.
2//!
3//! They handle initial setup of the EVM, call loop and the final return of the EVM
4
5use crate::{EvmTr, PrecompileProvider};
6use bytecode::Bytecode;
7use context_interface::{
8    journaled_state::{account::JournaledAccountTr, JournalTr},
9    result::InvalidTransaction,
10    transaction::{AccessListItemTr, AuthorizationTr, Transaction, TransactionType},
11    Block, Cfg, ContextTr, Database,
12};
13use core::cmp::Ordering;
14use interpreter::InitialAndFloorGas;
15use primitives::{hardfork::SpecId, AddressMap, HashSet, StorageKey, U256};
16use state::AccountInfo;
17
18/// Loads and warms accounts for execution, including precompiles and access list.
19pub fn load_accounts<
20    EVM: EvmTr<Precompiles: PrecompileProvider<EVM::Context>>,
21    ERROR: From<<<EVM::Context as ContextTr>::Db as Database>::Error>,
22>(
23    evm: &mut EVM,
24) -> Result<(), ERROR> {
25    let (context, precompiles) = evm.ctx_precompiles();
26
27    let gen_spec = context.cfg().spec();
28    let spec = gen_spec.clone().into();
29    // sets eth spec id in journal
30    context.journal_mut().set_spec_id(spec);
31    let precompiles_changed = precompiles.set_spec(gen_spec);
32    let empty_warmed_precompiles = context.journal_mut().precompile_addresses().is_empty();
33
34    if precompiles_changed || empty_warmed_precompiles {
35        // load new precompile addresses into journal.
36        // When precompiles addresses are changed we reset the warmed hashmap to those new addresses.
37        context
38            .journal_mut()
39            .warm_precompiles(precompiles.warm_addresses().collect());
40    }
41
42    // Load coinbase
43    // EIP-3651: Warm COINBASE. Starts the `COINBASE` address warm
44    if spec.is_enabled_in(SpecId::SHANGHAI) {
45        let coinbase = context.block().beneficiary();
46        context.journal_mut().warm_coinbase_account(coinbase);
47    }
48
49    // Load access list
50    let (tx, journal) = context.tx_journal_mut();
51    // legacy is only tx type that does not have access list.
52    if tx.tx_type() != TransactionType::Legacy {
53        if let Some(access_list) = tx.access_list() {
54            let mut map: AddressMap<HashSet<StorageKey>> = AddressMap::default();
55            for item in access_list {
56                map.entry(*item.address())
57                    .or_default()
58                    .extend(item.storage_slots().map(|key| U256::from_be_bytes(key.0)));
59            }
60            journal.warm_access_list(map);
61        }
62    }
63
64    Ok(())
65}
66
67/// Validates caller account nonce and code according to EIP-3607.
68#[inline]
69pub fn validate_account_nonce_and_code_with_components(
70    caller_info: &AccountInfo,
71    tx: impl Transaction,
72    cfg: impl Cfg,
73) -> Result<(), InvalidTransaction> {
74    validate_account_nonce_and_code(
75        caller_info,
76        tx.nonce(),
77        cfg.is_eip3607_disabled(),
78        cfg.is_nonce_check_disabled(),
79    )
80}
81
82/// Validates caller account nonce and code according to EIP-3607.
83#[inline]
84pub fn validate_account_nonce_and_code(
85    caller_info: &AccountInfo,
86    tx_nonce: u64,
87    is_eip3607_disabled: bool,
88    is_nonce_check_disabled: bool,
89) -> Result<(), InvalidTransaction> {
90    // EIP-3607: Reject transactions from senders with deployed code
91    // This EIP is introduced after london but there was no collision in past
92    // so we can leave it enabled always
93    if !is_eip3607_disabled {
94        let bytecode = match caller_info.code.as_ref() {
95            Some(code) => code,
96            None => &Bytecode::default(),
97        };
98        // Allow EOAs whose code is a valid delegation designation,
99        // i.e. 0xef0100 || address, to continue to originate transactions.
100        if !bytecode.is_empty() && !bytecode.is_eip7702() {
101            return Err(InvalidTransaction::RejectCallerWithCode);
102        }
103    }
104
105    // Check that the transaction's nonce is correct
106    if !is_nonce_check_disabled {
107        let tx = tx_nonce;
108        let state = caller_info.nonce;
109        match tx.cmp(&state) {
110            Ordering::Greater => {
111                return Err(InvalidTransaction::NonceTooHigh { tx, state });
112            }
113            Ordering::Less => {
114                return Err(InvalidTransaction::NonceTooLow { tx, state });
115            }
116            _ => {}
117        }
118    }
119    Ok(())
120}
121
122/// Check maximum possible fee and deduct the effective fee.
123///
124/// Returns new balance.
125#[inline]
126pub fn calculate_caller_fee(
127    balance: U256,
128    tx: impl Transaction,
129    block: impl Block,
130    cfg: impl Cfg,
131) -> Result<U256, InvalidTransaction> {
132    // If fee charge is disabled, return the balance as-is without deducting fees.
133    // This is useful for `eth_call` and similar simulation scenarios.
134    if cfg.is_fee_charge_disabled() {
135        return Ok(balance);
136    }
137
138    let basefee = block.basefee() as u128;
139    let blob_price = block.blob_gasprice().unwrap_or_default();
140    let is_balance_check_disabled = cfg.is_balance_check_disabled();
141
142    if !is_balance_check_disabled {
143        tx.ensure_enough_balance(balance)?;
144    }
145
146    let effective_balance_spending = tx
147        .effective_balance_spending(basefee, blob_price)
148        .expect("effective balance is always smaller than max balance so it can't overflow");
149
150    let gas_balance_spending = effective_balance_spending - tx.value();
151
152    // new balance
153    let mut new_balance = balance.saturating_sub(gas_balance_spending);
154
155    if is_balance_check_disabled {
156        // Make sure the caller's balance is at least the value of the transaction.
157        new_balance = new_balance.max(tx.value());
158    }
159
160    Ok(new_balance)
161}
162
163/// Validates caller state and deducts transaction costs from the caller's balance.
164#[inline]
165pub fn validate_against_state_and_deduct_caller<
166    CTX: ContextTr,
167    ERROR: From<InvalidTransaction> + From<<CTX::Db as Database>::Error>,
168>(
169    context: &mut CTX,
170) -> Result<(), ERROR> {
171    let (block, tx, cfg, journal, _, _) = context.all_mut();
172
173    // Load caller's account.
174    let mut caller = journal.load_account_with_code_mut(tx.caller())?.data;
175
176    validate_account_nonce_and_code_with_components(&caller.account().info, tx, cfg)?;
177
178    let new_balance = calculate_caller_fee(*caller.balance(), tx, block, cfg)?;
179
180    caller.set_balance(new_balance);
181    if tx.kind().is_call() {
182        caller.bump_nonce();
183    }
184    Ok(())
185}
186
187/// Apply EIP-7702 auth list and return number gas refund on already created accounts.
188///
189/// Note that this function will do nothing if the transaction type is not EIP-7702.
190/// If you need to apply auth list for other transaction types, use [`apply_auth_list`] function.
191///
192/// Internally uses [`apply_auth_list`] function.
193#[inline]
194pub fn apply_eip7702_auth_list<
195    CTX: ContextTr,
196    ERROR: From<InvalidTransaction> + From<<CTX::Db as Database>::Error>,
197>(
198    context: &mut CTX,
199    init_and_floor_gas: &mut InitialAndFloorGas,
200) -> Result<u64, ERROR> {
201    let chain_id = context.cfg().chain_id();
202    let refund_per_auth = context.cfg().gas_params().tx_eip7702_auth_refund();
203    let (tx, journal) = context.tx_journal_mut();
204
205    // Return if not EIP-7702 transaction.
206    if tx.tx_type() != TransactionType::Eip7702 {
207        return Ok(0);
208    }
209    let eip7702_refund =
210        apply_auth_list::<_, ERROR>(chain_id, refund_per_auth, tx.authorization_list(), journal)?;
211
212    // EIP-8037: Split auth list refund into state gas and regular gas portions.
213    // The state gas portion is added to the reservoir after initial_state_gas deduction,
214    // matching the Python spec where set_delegation adds state refund directly to
215    // state_gas_reservoir. This ensures refunded state gas stays as reservoir gas
216    // (not regular gas), so it's not consumed on frame halt.
217    // The regular gas portion goes through the normal refund mechanism.
218    let (eip7702_state_refund, eip7702_regular_refund_raw) = context
219        .cfg()
220        .gas_params()
221        .split_eip7702_refund(eip7702_refund);
222    if eip7702_state_refund > 0 {
223        init_and_floor_gas.eip7702_reservoir_refund = eip7702_state_refund;
224    }
225
226    Ok(eip7702_regular_refund_raw)
227}
228
229/// Apply EIP-7702 style auth list and return number gas refund on already created accounts.
230///
231/// It is more granular function from [`apply_eip7702_auth_list`] function as it takes only the list, journal and chain id.
232///
233/// The `refund_per_auth` parameter specifies the gas refund per existing account authorization.
234/// By default this is `PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` (25000 - 12500 = 12500),
235/// but can be configured via [`GasParams::tx_eip7702_auth_refund`](context_interface::cfg::gas_params::GasParams::tx_eip7702_auth_refund).
236#[inline]
237pub fn apply_auth_list<
238    JOURNAL: JournalTr,
239    ERROR: From<InvalidTransaction> + From<<JOURNAL::Database as Database>::Error>,
240>(
241    chain_id: u64,
242    refund_per_auth: u64,
243    auth_list: impl Iterator<Item = impl AuthorizationTr>,
244    journal: &mut JOURNAL,
245) -> Result<u64, ERROR> {
246    let mut refunded_accounts = 0;
247    for authorization in auth_list {
248        // 1. Verify the chain id is either 0 or the chain's current ID.
249        let auth_chain_id = authorization.chain_id();
250        if !auth_chain_id.is_zero() && auth_chain_id != U256::from(chain_id) {
251            continue;
252        }
253
254        // 2. Verify the `nonce` is less than `2**64 - 1`.
255        if authorization.nonce() == u64::MAX {
256            continue;
257        }
258
259        // recover authority and authorized addresses.
260        // 3. `authority = ecrecover(keccak(MAGIC || rlp([chain_id, address, nonce])), y_parity, r, s]`
261        let Some(authority) = authorization.authority() else {
262            continue;
263        };
264
265        // warm authority account and check nonce.
266        // 4. Add `authority` to `accessed_addresses` (as defined in [EIP-2929](./eip-2929.md).)
267        let mut authority_acc = journal.load_account_with_code_mut(authority)?;
268        let authority_acc_info = &authority_acc.account().info;
269
270        // 5. Verify the code of `authority` is either empty or already delegated.
271        if let Some(bytecode) = &authority_acc_info.code {
272            // if it is not empty and it is not eip7702
273            if !bytecode.is_empty() && !bytecode.is_eip7702() {
274                continue;
275            }
276        }
277
278        // 6. Verify the nonce of `authority` is equal to `nonce`. In case `authority` does not exist in the trie, verify that `nonce` is equal to `0`.
279        if authorization.nonce() != authority_acc_info.nonce {
280            continue;
281        }
282
283        // 7. Add `PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` gas to the global refund counter if `authority` exists in the trie.
284        if !(authority_acc_info.is_empty()
285            && authority_acc
286                .account()
287                .is_loaded_as_not_existing_not_touched())
288        {
289            refunded_accounts += 1;
290        }
291
292        // 8. Set the code of `authority` to be `0xef0100 || address`. This is a delegation designation.
293        //  * As a special case, if `address` is `0x0000000000000000000000000000000000000000` do not write the designation.
294        //    Clear the accounts code and reset the account's code hash to the empty hash `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`.
295        // 9. Increase the nonce of `authority` by one.
296        authority_acc.delegate(authorization.address());
297    }
298
299    let refunded_gas = refunded_accounts * refund_per_auth;
300
301    Ok(refunded_gas)
302}