Skip to main content

ethrex_levm/hooks/
default_hook.rs

1use crate::{
2    account::LevmAccount,
3    constants::*,
4    errors::{ContextResult, ExceptionalHalt, InternalError, TxValidationError, VMError},
5    gas_cost::{
6        STANDARD_TOKEN_COST, WARM_ADDRESS_ACCESS_COST, cold_account_access_cost,
7        floor_tokens_in_access_list, recipient_regular_gas, total_cost_floor_per_token,
8        tx_base_cost,
9    },
10    hooks::hook::Hook,
11    utils::*,
12    vm::VM,
13};
14
15use ethrex_common::{
16    Address, H256, U256,
17    constants::EMPTY_KECCAK_HASH,
18    types::{Code, Fork},
19};
20
21pub const MAX_REFUND_QUOTIENT: u64 = 5;
22
23pub struct DefaultHook;
24
25impl Hook for DefaultHook {
26    /// ## Description
27    /// This method performs validations and returns an error if any of these fail.
28    /// It also makes pre-execution changes:
29    /// - It increases sender nonce
30    /// - It substracts up-front-cost from sender balance.
31    /// - It adds value to receiver balance.
32    /// - It calculates and adds intrinsic gas to the 'gas used' of callframe and environment.
33    ///   See 'docs' for more information about validations.
34    fn prepare_execution(&mut self, vm: &mut VM<'_>) -> Result<(), VMError> {
35        // System calls (EELS `process_unchecked_system_transaction`) have no
36        // sender semantics: no validation, no nonce bump, no fee deduction.
37        // EELS never reads the SYSTEM_ADDRESS account, so skip the whole
38        // sender path to keep the read out of execution witnesses (EIP-8025).
39        if vm.env.is_system_call {
40            // EELS `process_unchecked_system_transaction` builds the message with
41            // intrinsic_regular_gas=0 and intrinsic_state_gas=0: a system call gets
42            // the full SYS_CALL_GAS_LIMIT with no intrinsic deducted. We still call
43            // `add_intrinsic_gas` (with a zeroed intrinsic) so the Amsterdam state-gas
44            // reservoir is set up, but charge no intrinsic — otherwise the frame
45            // budget would fall below SYS_CALL_GAS_LIMIT and diverge from EELS (a
46            // system contract engineered to consume exactly SYS_CALL_GAS_LIMIT+1
47            // would then fail to run out of gas).
48            let mut intrinsic = vm.get_intrinsic_gas()?;
49            intrinsic.regular = 0;
50            intrinsic.state = 0;
51            vm.add_intrinsic_gas(&intrinsic)?;
52            transfer_value(vm)?;
53            set_bytecode_and_code_address(vm)?;
54            return Ok(());
55        }
56
57        let sender_address = vm.env.origin;
58        let sender_info = vm.db.get_account(sender_address)?.info.clone();
59
60        // Compute intrinsic gas once and reuse it for both the min-gas-limit
61        // validation and `add_intrinsic_gas` below (nothing in between mutates the
62        // calldata / access-list / auth-list it depends on).
63        let intrinsic = vm.get_intrinsic_gas()?;
64
65        if vm.env.config.fork >= Fork::Prague {
66            validate_min_gas_limit(vm, &intrinsic)?;
67            // EIP-7825 (Osaka to pre-Amsterdam): reject tx if gas_limit > POST_OSAKA_GAS_LIMIT_CAP.
68            // Amsterdam removes this restriction (EIP-8037 reservoir model).
69            if !vm.env.disable_gas_allowance_check
70                && vm.env.config.fork >= Fork::Osaka
71                && vm.env.config.fork < Fork::Amsterdam
72                && vm.tx.gas_limit() > POST_OSAKA_GAS_LIMIT_CAP
73            {
74                return Err(VMError::TxValidation(
75                    TxValidationError::TxMaxGasLimitExceeded {
76                        tx_hash: vm.tx.hash(vm.crypto),
77                        tx_gas_limit: vm.tx.gas_limit(),
78                    },
79                ));
80            }
81        }
82
83        // (1) GASLIMIT_PRICE_PRODUCT_OVERFLOW
84        let gaslimit_price_product = vm
85            .env
86            .gas_price
87            .checked_mul(vm.env.gas_limit.into())
88            .ok_or(TxValidationError::GasLimitPriceProductOverflow)?;
89
90        validate_sender_balance(vm, sender_info.balance)?;
91
92        // (2) INSUFFICIENT_MAX_FEE_PER_BLOB_GAS
93        if let Some(tx_max_fee_per_blob_gas) = vm.env.tx_max_fee_per_blob_gas {
94            validate_max_fee_per_blob_gas(vm, tx_max_fee_per_blob_gas)?;
95        }
96
97        // (3) INSUFFICIENT_ACCOUNT_FUNDS
98        deduct_caller(vm, gaslimit_price_product, sender_address)?;
99
100        // (4) INSUFFICIENT_MAX_FEE_PER_GAS
101        validate_sufficient_max_fee_per_gas(vm)?;
102
103        // (5) INITCODE_SIZE_EXCEEDED
104        if vm.is_create()? {
105            validate_init_code_size(vm)?;
106        }
107
108        // (6) INTRINSIC_GAS_TOO_LOW
109        vm.add_intrinsic_gas(&intrinsic)?;
110
111        // (7) NONCE_IS_MAX
112        vm.increment_account_nonce(sender_address)
113            .map_err(|_| TxValidationError::NonceIsMax)?;
114
115        // check for nonce mismatch
116        if !vm.env.disable_nonce_check && sender_info.nonce != vm.env.tx_nonce {
117            return Err(TxValidationError::NonceMismatch {
118                expected: sender_info.nonce,
119                actual: vm.env.tx_nonce,
120            }
121            .into());
122        }
123
124        // (8) PRIORITY_GREATER_THAN_MAX_FEE_PER_GAS
125        if let (Some(tx_max_priority_fee), Some(tx_max_fee_per_gas)) = (
126            vm.env.tx_max_priority_fee_per_gas,
127            vm.env.tx_max_fee_per_gas,
128        ) && tx_max_priority_fee > tx_max_fee_per_gas
129        {
130            return Err(TxValidationError::PriorityGreaterThanMaxFeePerGas {
131                priority_fee: tx_max_priority_fee,
132                max_fee_per_gas: tx_max_fee_per_gas,
133            }
134            .into());
135        }
136
137        // (9) SENDER_NOT_EOA
138        let code = vm.db.get_code(sender_info.code_hash)?;
139        validate_sender(sender_address, code.code())?;
140
141        // (10) GAS_ALLOWANCE_EXCEEDED
142        validate_gas_allowance(vm)?;
143
144        // Transaction is type 3 if tx_max_fee_per_blob_gas is Some
145        if vm.env.tx_max_fee_per_blob_gas.is_some() {
146            validate_4844_tx(vm)?;
147        }
148
149        // EIP-8037: enter the atomic prepare region (EELS `interpreter.py`'s depth-0
150        // `try` around `set_delegation` + `prepare_dispatch`). Taken after the sender
151        // nonce bump (7) and fee deduction (3) above so both survive a region
152        // rollback, and before the type-4 auth handling below (the first region
153        // charge). See `VM::enter_prepare_region` / `VM::fail_prepare_region`.
154        vm.enter_prepare_region();
155
156        // [EIP-7702]: https://eips.ethereum.org/EIPS/eip-7702
157        // Transaction is type 4 if authorization_list is Some
158        if vm.tx.authorization_list().is_some() {
159            validate_type_4_tx(vm)?;
160        }
161
162        // EIP-8037 (atomic prepare region): EELS `prepare_dispatch` create/value
163        // branch (interpreter.py:277-291). The CREATE / value-to-not-alive
164        // `NEW_ACCOUNT` charge is evaluated IN-REGION via `increase_state_gas`: an
165        // insufficient reservoir/gas rolls back the whole region
166        // (`vm.fail_prepare_region()`) and burns all gas, rather than rejecting the
167        // tx (which would wrongly invalidate the block). Applied AFTER EIP-7702
168        // authorizations are set (so recipient emptiness / delegation reflect the
169        // post-auth state) and BEFORE the value transfer.
170        if vm.env.config.fork >= Fork::Amsterdam && !vm.pending_prep_oog {
171            if vm.is_create()? {
172                // EELS `prepare_dispatch`: `get_pre_state_account(message.current_target)
173                // == EMPTY_ACCOUNT`. The created address cannot have been touched by
174                // this tx's fee deduction / nonce bump (those only touch the sender),
175                // and a create transaction can never carry an authorization list
176                // (`validate_type_4_tx` rejects `to == None`), so the current DB read
177                // already equals the pre-tx state for this address.
178                let created_addr = vm.current_call_frame.to;
179                // EIP-7928: record the created address in the BAL now that the prepare
180                // region has read its pre-state (EELS `prepare_dispatch`
181                // `get_pre_state_account(current_target)`), so a create that OOGs on the
182                // in-region NEW_ACCOUNT charge still lists the address — the access record
183                // survives the region rollback. Without this, a create that halts before
184                // dispatch (which is where `handle_create_transaction` records the address)
185                // would drop it and fork on the BAL hash.
186                if let Some(recorder) = vm.db.bal_recorder.as_mut() {
187                    recorder.record_touched_address(created_addr);
188                }
189                if vm.db.get_account(created_addr)?.is_empty() {
190                    let charge = vm.state_gas_new_account;
191                    if vm.increase_state_gas(charge).is_err() {
192                        vm.fail_prepare_region();
193                    }
194                }
195            } else {
196                let to = vm.current_call_frame.to;
197                let recipient = vm.db.get_account(to)?;
198                let recipient_is_empty = recipient.is_empty();
199                let recipient_code_hash = recipient.info.code_hash;
200                // EIP-7928 (tests-glamsterdam-devnet@v7.1.0): record the recipient in the
201                // BAL at its load point — mirroring EELS `prepare_dispatch`, which loads
202                // the recipient (`get_account`) at the START of dispatch, BEFORE the
203                // value NEW_ACCOUNT / delegation-access charges below. Recording here (not
204                // after the region) means a subsequent in-region OOG on those charges
205                // still lists the recipient (it was already loaded), while an earlier
206                // EIP-7702 auth halt — which skips this whole block via the
207                // `!vm.pending_prep_oog` guard above — correctly excludes it.
208                if let Some(recorder) = vm.db.bal_recorder.as_mut() {
209                    recorder.record_touched_address(to);
210                }
211                // Resolve a 7702-delegated recipient's target address (EELS
212                // `prepare_dispatch`: `get_delegated_code_address(recipient_code)`),
213                // evaluated post-auth so an auth on `tx.to` this tx is reflected.
214                let recipient_delegated_target: Option<Address> =
215                    if recipient_code_hash == *EMPTY_KECCAK_HASH {
216                        None
217                    } else {
218                        let code = vm.db.get_code(recipient_code_hash)?.code_bytes();
219                        if code_has_delegation(&code)? {
220                            Some(get_authorized_address_from_code(&code)?)
221                        } else {
222                            None
223                        }
224                    };
225
226                // If the recipient is EIP-161-empty and the tx transfers value, the
227                // value transfer will materialize a new account: charge the
228                // new-account state gas IN-REGION (EELS `prepare_dispatch` value
229                // branch: `is_account_alive`). Skipped if a 7702 auth already
230                // materialized the recipient this tx, since emptiness is evaluated
231                // post-auth. EIP-2780 (EELS PR #3048): no precompile carve-out.
232                // EIP-161/EIP-2780 define emptiness structurally, so an empty
233                // (unfunded) precompile receiving value is created like any other
234                // account and pays NEW_ACCOUNT. A pre-funded precompile is
235                // non-empty, so `recipient_is_empty` is already false and it stays
236                // exempt.
237                if recipient_is_empty && !vm.tx.value().is_zero() {
238                    let charge = vm.state_gas_new_account;
239                    if vm.increase_state_gas(charge).is_err() {
240                        vm.fail_prepare_region();
241                    } else {
242                        // Signal so a subsequent Amsterdam precompile-halt in
243                        // `run_execution` rolls this charge back (the recipient
244                        // never materializes on halt).
245                        vm.value_new_account_charged = true;
246                    }
247                }
248
249                // EIP-8037 (atomic prepare region): EELS `prepare_dispatch` delegation
250                // branch. If the recipient is 7702-delegated, charge the account access
251                // for resolving the delegation target IN-REGION via `increase_consumed_gas`
252                // (regular gas): WARM if the target is already accessed, else COLD (and
253                // mark it accessed). Charged AFTER the value NEW_ACCOUNT state charge, so
254                // an OOG here rolls back the whole region (auth + value) and burns all gas
255                // rather than rejecting the tx.
256                if !vm.pending_prep_oog
257                    && let Some(target) = recipient_delegated_target
258                {
259                    let is_warm = vm.substate.is_address_accessed(&target);
260                    let charge = if is_warm {
261                        WARM_ADDRESS_ACCESS_COST
262                    } else {
263                        cold_account_access_cost(vm.env.config.fork)
264                    };
265                    if vm.current_call_frame.increase_consumed_gas(charge).is_err() {
266                        vm.fail_prepare_region();
267                    } else if !is_warm {
268                        vm.substate.add_accessed_address(target);
269                    }
270                }
271            }
272        }
273
274        // EIP-8037: the atomic prepare region rolled back (one of its charges OOG'd)
275        // and burned all gas; `run_execution` turns `pending_prep_oog` into a full-gas
276        // revert `ContextResult` (not a tx-level `Err`, which would wrongly invalidate
277        // the block). In that case the top-frame dispatch never happens, so its
278        // recipient-touching steps (`transfer_value`, `set_bytecode_and_code_address`,
279        // which read `tx.to` via `increase_account_balance` / `eip7702_get_code`) must
280        // be skipped for EVERY tx kind, not just CREATE. EELS `prepare_dispatch` loads
281        // the recipient only at dispatch, which a prepare-region halt precedes — so a
282        // spurious recipient read here would be invisible under full-state execution but
283        // break witness sufficiency under EIP-8025 stateless validation (the recipient's
284        // trie node isn't in the witness). `undo_value_transfer` correspondingly skips
285        // the recipient debit on this path (there was no transfer to reverse), so the
286        // sender's upfront value debit is still returned with no recipient underflow.
287        if vm.pending_prep_oog {
288            return Ok(());
289        }
290
291        transfer_value(vm)?;
292
293        set_bytecode_and_code_address(vm)?;
294
295        Ok(())
296    }
297
298    /// ## Changes post execution
299    /// 1. Undo value transfer if the transaction was reverted
300    /// 2. Return unused gas + gas refunds to the sender.
301    /// 3. Pay coinbase fee
302    /// 4. Destruct addresses in selfdestruct set.
303    fn finalize_execution(
304        &mut self,
305        vm: &mut VM<'_>,
306        ctx_result: &mut ContextResult,
307    ) -> Result<(), VMError> {
308        // System calls (EELS `process_unchecked_system_transaction`) have no
309        // sender or fee semantics: there is nothing to undo, refund, or pay
310        // (the value and gas price are zero), so skip straight to the
311        // self-destruct cleanup. Callers ignore the gas accounting fields for
312        // system calls.
313        if vm.env.is_system_call {
314            delete_self_destruct_accounts(vm)?;
315            return Ok(());
316        }
317
318        if !ctx_result.is_success() {
319            undo_value_transfer(vm)?;
320        }
321
322        // EIP-8037 (Amsterdam+): CREATE-tx address collision.
323        // Per EELS process_message_call (interpreter.py:120-145), `prepare_dispatch`
324        // never runs for a colliding create (the collision check short-circuits before
325        // `process_create_message`/`process_message`), so `state_gas_used=0` and the
326        // reservoir is PRESERVED (not burned): `state_gas_left = message.state_gas_reservoir`.
327        // tx_state_gas collapses to 0, tx_regular_gas = max(intrinsic_regular +
328        // message.gas, calldata_floor). The user does NOT lose the whole gas_limit.
329        //
330        // ethrex's in-region CREATE NEW_ACCOUNT charge runs before the
331        // collision check and is rolled back to the frame's entry baseline by
332        // `handle_create_transaction` on collision (see that function), so
333        // `state_gas_used` is already net zero here.
334        if vm.env.config.fork >= Fork::Amsterdam && ctx_result.is_collision() {
335            let gas_limit = vm.env.gas_limit;
336            // state_gas_used is already net (signed, inline refunds applied); clamp at zero.
337            let state_gas: u64 =
338                u64::try_from(vm.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
339            let floor = vm.get_min_gas_used()?;
340            // Regular gas = gas_limit - state_gas_left, where state_gas_left =
341            // reservoir (PRESERVED across collision in EELS, with new_account_refund
342            // already folded in by vm.finalize_execution above). Mirrors EELS
343            // tx_gas_used_before_refund = tx.gas - gas_left(=0) - state_gas_left.
344            let regular_gas = gas_limit.saturating_sub(vm.state_gas_reservoir);
345            let effective_regular = regular_gas.max(floor);
346            ctx_result.gas_used = effective_regular
347                .checked_add(state_gas)
348                .ok_or(InternalError::Overflow)?;
349            // User pays only the effective regular (post-floor); coinbase gets the
350            // same; remainder returns to sender.
351            ctx_result.gas_spent = effective_regular;
352            pay_coinbase(vm, effective_regular)?;
353            let gas_to_return = gas_limit
354                .checked_sub(effective_regular)
355                .ok_or(InternalError::Underflow)?;
356            let wei_return_amount = vm
357                .env
358                .gas_price
359                .checked_mul(U256::from(gas_to_return))
360                .ok_or(InternalError::Overflow)?;
361            vm.increase_account_balance(vm.env.origin, wei_return_amount)?;
362            return Ok(());
363        }
364
365        // EIP-8037 (Amsterdam+): unused reservoir is always returned to sender.
366        // Per EELS, state_gas_left is preserved even on exceptional halt — only
367        // regular gas_left is burned.  The user does NOT pay for unspent reservoir.
368        if vm.env.config.fork >= Fork::Amsterdam {
369            ctx_result.gas_used = ctx_result.gas_used.saturating_sub(vm.state_gas_reservoir);
370        }
371
372        // Save pre-refund gas for EIP-7778 block accounting
373        let gas_used_pre_refund = ctx_result.gas_used;
374
375        // Note: compute_gas_refunded caps at gas_used / MAX_REFUND_QUOTIENT, where
376        // gas_used already has the reservoir subtracted (line above). This matches
377        // EELS, which applies the refund cap after reservoir removal but before the
378        // regular/state gas split.
379        let gas_refunded: u64 = compute_gas_refunded(vm, ctx_result)?;
380        let gas_spent = compute_actual_gas_used(vm, gas_refunded, gas_used_pre_refund)?;
381
382        refund_sender(vm, ctx_result, gas_refunded, gas_spent)?;
383
384        pay_coinbase(vm, gas_spent)?;
385
386        delete_self_destruct_accounts(vm)?;
387
388        Ok(())
389    }
390}
391
392pub fn undo_value_transfer(vm: &mut VM<'_>) -> Result<(), VMError> {
393    // In a create if Tx was reverted the account won't even exist by this point.
394    // On a prepare-region OOG (`pending_prep_oog`) `prepare_execution` skipped
395    // `transfer_value`, so the recipient was never credited (nor loaded) — debiting
396    // it here would both underflow and spuriously read `tx.to` out of the witness.
397    // The sender is still re-credited its upfront value debit below.
398    if !vm.is_create()? && !vm.pending_prep_oog {
399        vm.decrease_account_balance(vm.current_call_frame.to, vm.current_call_frame.msg_value)?;
400    }
401
402    vm.increase_account_balance(vm.env.origin, vm.current_call_frame.msg_value)?;
403
404    Ok(())
405}
406
407/// Refunds unused gas to the sender. The user pays `gas_spent` (post-refund);
408/// for Amsterdam+, block-level accounting is recomputed dimensionally from VM
409/// fields, not from a pre-refund total.
410pub fn refund_sender(
411    vm: &mut VM<'_>,
412    ctx_result: &mut ContextResult,
413    refunded_gas: u64,
414    gas_spent: u64,
415) -> Result<(), VMError> {
416    vm.substate.refunded_gas = refunded_gas;
417
418    // EIP-7778: Separate block vs user gas accounting for Amsterdam+
419    // Block header gas_used = max(regular_dimension, state_dimension) per EIP-7778.
420    // Receipt cumulative_gas_used = post-refund total (what user pays).
421    if vm.env.config.fork >= Fork::Amsterdam {
422        // EIP-8037: state_gas_used is already net (signed, credits applied inline);
423        // clamp at zero. There is no separate tx-level refund channel — EELS
424        // `process_transaction` sets `tx_state_gas = intrinsic_state_gas + state_gas_used`
425        // directly.
426        let state_gas: u64 =
427            u64::try_from(vm.state_gas_used.max(0)).map_err(|_| InternalError::Overflow)?;
428        // Compute raw consumption from scratch (gas_limit minus gas_remaining)
429        // to avoid interference from any reservoir-current subtraction baked
430        // into the caller's pre-refund number.
431        #[expect(clippy::as_conversions, reason = "gas_remaining is >= 0 here")]
432        let gas_remaining = vm.current_call_frame.gas_remaining.max(0) as u64;
433        let raw_consumed = vm.env.gas_limit.saturating_sub(gas_remaining);
434        // Subtract intrinsic_state (pre-consumed from gas_remaining as part of total intrinsic),
435        // the initial reservoir (pre-consumed from gas_remaining), and state-gas spills
436        // (EELS charge_state_gas spills don't count as regular_gas_used).
437        let regular_gas = raw_consumed
438            .saturating_sub(vm.intrinsic_state_gas)
439            .saturating_sub(vm.state_gas_reservoir_initial)
440            .saturating_sub(vm.state_gas_spill);
441        // EIP-8037 (glamsterdam-devnet-7 v7.2.0, EIPs#11908): the calldata floor
442        // binds the block-level regular gas dimension. Each tx contributes
443        // `max(pre_refund_gas - state_gas, calldata_floor)` to block gas, so
444        // state-gas spending cannot discount the floor. `regular_gas` here is
445        // `pre_refund_gas - state_gas`; flooring it matches EELS `tx_regular_gas`.
446        // The refund still applies only to the user payment (`gas_spent`), not
447        // block gas_used.
448        let floor = vm.get_min_gas_used()?;
449        ctx_result.gas_used = regular_gas
450            .max(floor)
451            .checked_add(state_gas)
452            .ok_or(InternalError::Overflow)?;
453        // User pays post-refund gas (with floor)
454        ctx_result.gas_spent = gas_spent;
455    } else {
456        // Pre-Amsterdam: both use post-refund value
457        ctx_result.gas_used = gas_spent;
458        ctx_result.gas_spent = gas_spent;
459    }
460
461    // Return unspent gas to the sender (based on what user pays)
462    let gas_to_return = vm
463        .env
464        .gas_limit
465        .checked_sub(gas_spent)
466        .ok_or(InternalError::Underflow)?;
467
468    let wei_return_amount = vm
469        .env
470        .gas_price
471        .checked_mul(U256::from(gas_to_return))
472        .ok_or(InternalError::Overflow)?;
473
474    vm.increase_account_balance(vm.env.origin, wei_return_amount)?;
475
476    Ok(())
477}
478
479// [EIP-3529](https://eips.ethereum.org/EIPS/eip-3529)
480pub fn compute_gas_refunded(vm: &VM<'_>, ctx_result: &ContextResult) -> Result<u64, VMError> {
481    Ok(vm
482        .substate
483        .refunded_gas
484        .min(ctx_result.gas_used / MAX_REFUND_QUOTIENT))
485}
486
487// Calculate actual gas used in the whole transaction. Since Prague there is a base minimum to be consumed.
488pub fn compute_actual_gas_used(
489    vm: &mut VM<'_>,
490    refunded_gas: u64,
491    gas_used_without_refunds: u64,
492) -> Result<u64, VMError> {
493    let exec_gas_consumed = gas_used_without_refunds
494        .checked_sub(refunded_gas)
495        .ok_or(InternalError::Underflow)?;
496
497    if vm.env.config.fork >= Fork::Prague {
498        Ok(exec_gas_consumed.max(vm.get_min_gas_used()?))
499    } else {
500        Ok(exec_gas_consumed)
501    }
502}
503
504pub fn pay_coinbase(vm: &mut VM<'_>, gas_to_pay: u64) -> Result<(), VMError> {
505    let priority_fee_per_gas = vm
506        .env
507        .gas_price
508        .checked_sub(vm.env.base_fee_per_gas)
509        .ok_or(InternalError::Underflow)?;
510
511    let coinbase_fee = U256::from(gas_to_pay)
512        .checked_mul(priority_fee_per_gas)
513        .ok_or(InternalError::Overflow)?;
514
515    // Per EIP-7928: Coinbase must appear in BAL when there's a user transaction,
516    // even if the priority fee is zero. System contract calls have gas_price = 0,
517    // so we use this to distinguish them from user transactions.
518    if !vm.env.gas_price.is_zero()
519        && let Some(recorder) = vm.db.bal_recorder.as_mut()
520    {
521        recorder.record_touched_address(vm.env.coinbase);
522    }
523
524    // Only pay coinbase if there's actually a fee to pay.
525    if !coinbase_fee.is_zero() {
526        vm.increase_account_balance(vm.env.coinbase, coinbase_fee)?;
527    } else if !vm.env.is_system_call {
528        // The spec reads the coinbase account unconditionally during user-tx
529        // fee transfer (EELS `process_transaction` calls `get_account` before
530        // deciding whether to credit), but system contract calls never touch
531        // the coinbase. Keep the read observable for zero-fee user txs
532        // (including gas-price-zero txs on zero-base-fee chains) so execution
533        // witnesses (EIP-8025) record the coinbase trie path, including its
534        // exclusion proof when it doesn't exist.
535        vm.db.get_account(vm.env.coinbase)?;
536    }
537
538    Ok(())
539}
540
541// In Cancun the only addresses destroyed are contracts created in this transaction
542pub fn delete_self_destruct_accounts(vm: &mut VM<'_>) -> Result<(), VMError> {
543    // EIP-8246 (Amsterdam+): SELFDESTRUCT no longer burns ETH.
544    // Accounts in the selfdestruct set have nonce reset to 0, code cleared, and storage cleared,
545    // but balance is preserved. If the resulting balance is zero, EIP-161 removes the account.
546    //
547    // Pre-Amsterdam (EIP-6780 / Cancun): accounts are fully wiped (LevmAccount::default()).
548    //
549    // Note: the pre-Amsterdam Amsterdam+ burn-log loop has been removed because under EIP-8246
550    // no ETH is ever burned by SELFDESTRUCT, so no Burn log is emitted at finalization.
551
552    let addresses: Vec<Address> = vm.substate.iter_selfdestruct().copied().collect();
553
554    for address in &addresses {
555        // Backup must be taken before mark_modified flips `exists` to true.
556        let account_snapshot = vm.db.get_account(*address)?;
557        vm.current_call_frame
558            .call_frame_backup
559            .backup_account_info(*address, account_snapshot)?;
560
561        if vm.env.config.fork >= Fork::Amsterdam {
562            // EIP-8246: preserve balance; clear nonce, code, and storage.
563            let account = vm.db.get_account_mut(*address)?;
564            let preserved_balance = account.info.balance;
565            account.info.nonce = 0;
566            account.info.code_hash = *EMPTY_KECCAK_HASH;
567            account.storage.clear();
568            account.has_storage = false;
569            account.info.balance = preserved_balance;
570            // Reach DestroyedModified so get_state_transitions emits removed_storage=true
571            // and correctly computes acc_info_updated (nonce/code_hash changed).
572            account.mark_destroyed();
573            account.mark_modified();
574        } else {
575            let account = vm.db.get_account_mut(*address)?;
576            *account = LevmAccount::default();
577            account.mark_destroyed();
578        }
579
580        // EIP-7928: Clean up BAL for selfdestructed account. Under EIP-8246 (Amsterdam+)
581        // the balance is preserved (no burn), so the BAL keeps its balance changes; pre-
582        // Amsterdam the account is wiped and its balance collapses to 0.
583        let preserve_balance = vm.env.config.fork >= Fork::Amsterdam;
584        if let Some(recorder) = vm.db.bal_recorder.as_mut() {
585            recorder.track_selfdestruct(*address, preserve_balance);
586        }
587    }
588
589    Ok(())
590}
591
592pub fn validate_min_gas_limit(vm: &mut VM<'_>, intrinsic: &IntrinsicGas) -> Result<(), VMError> {
593    // check for gas limit is grater or equal than the minimum required
594    let regular_gas = intrinsic.regular;
595    let state_gas = intrinsic.state;
596    let intrinsic_gas: u64 = regular_gas
597        .checked_add(state_gas)
598        .ok_or(ExceptionalHalt::OutOfGas)?;
599
600    if vm.current_call_frame.gas_limit < intrinsic_gas {
601        return Err(TxValidationError::IntrinsicGasTooLow.into());
602    }
603
604    let fork = vm.env.config.fork;
605
606    // EIP-7976 floor tokens: for the floor arm, all calldata bytes count unweighted.
607    // floor_tokens_in_calldata = (zero_bytes + nonzero_bytes) * STANDARD_TOKEN_COST
608    // Pre-Amsterdam uses the weighted EIP-7623 formula: (nonzero * 16 + zero * 4) / 4
609    let mut tokens_in_calldata: u64 = if fork >= Fork::Amsterdam {
610        // EIP-7976: floor tokens = total_bytes * STANDARD_TOKEN_COST (unweighted).
611        let total_bytes: u64 = vm
612            .current_call_frame
613            .calldata
614            .len()
615            .try_into()
616            .map_err(|_| InternalError::TypeConversion)?;
617        total_bytes
618            .checked_mul(STANDARD_TOKEN_COST)
619            .ok_or(InternalError::Overflow)?
620    } else {
621        // Pre-Amsterdam: weighted EIP-7623 token count. Reuse the calldata cost already
622        // computed in `intrinsic` (same byte string) instead of re-walking the calldata.
623        intrinsic.calldata_cost / STANDARD_TOKEN_COST
624    };
625
626    // EIP-7981 (Amsterdam+): access-list data bytes fold into the floor-token count.
627    // floor_tokens_in_access_list = access_list_bytes * STANDARD_TOKEN_COST
628    // where access_list_bytes = 20 * address_count + 32 * storage_key_count.
629    if fork >= Fork::Amsterdam {
630        let al_floor_tokens = floor_tokens_in_access_list(vm.tx.access_list());
631        tokens_in_calldata = tokens_in_calldata
632            .checked_add(al_floor_tokens)
633            .ok_or(InternalError::Overflow)?;
634    }
635
636    // floor_cost_by_tokens = base_regular_gas + total_cost_floor_per_token(fork) * tokens
637    // EIP-7976 (Amsterdam+) raises the floor multiplier from 10 to 16.
638    // The floor base is `tx_base_cost(fork)`: 21000 pre-Amsterdam, unchanged.
639    // Amsterdam+ (EIP-2780) anchors on `tx_base_cost(fork) + recipient_regular_gas(...)`
640    // (12000 base + the recipient/value regular-gas contribution), mirroring EELS
641    // `data_floor_gas_cost = total_floor_tokens * TX_DATA_TOKEN_FLOOR + base_regular_gas`.
642    let floor_base = if fork >= Fork::Amsterdam {
643        tx_base_cost(fork)
644            .checked_add(recipient_regular_gas(
645                &vm.tx.to(),
646                vm.tx.value(),
647                vm.env.origin,
648                fork,
649            ))
650            .ok_or(InternalError::Overflow)?
651    } else {
652        tx_base_cost(fork)
653    };
654
655    let floor_cost_by_tokens = tokens_in_calldata
656        .checked_mul(total_cost_floor_per_token(fork))
657        .ok_or(InternalError::Overflow)?
658        .checked_add(floor_base)
659        .ok_or(InternalError::Overflow)?;
660
661    // EIP-8037 (Amsterdam+): Regular gas is capped at TX_MAX_GAS_LIMIT — reject if
662    // intrinsic regular gas or calldata floor exceeds the cap (no amount of gas_limit
663    // can make the TX valid since excess gas_limit becomes state gas reservoir).
664    // Must be checked before the floor check so the correct error is returned.
665    // NOTE: We use IntrinsicGasTooLow (not TxMaxGasLimitExceeded) intentionally —
666    // this matches the EELS exception mapping for this specific case.
667    if vm.env.config.fork >= Fork::Amsterdam
668        && regular_gas.max(floor_cost_by_tokens) > TX_MAX_GAS_LIMIT_AMSTERDAM
669    {
670        return Err(TxValidationError::IntrinsicGasTooLow.into());
671    }
672
673    if vm.current_call_frame.gas_limit < floor_cost_by_tokens {
674        return Err(TxValidationError::IntrinsicGasBelowFloorGasCost.into());
675    }
676
677    Ok(())
678}
679
680pub fn validate_max_fee_per_blob_gas(
681    vm: &mut VM<'_>,
682    tx_max_fee_per_blob_gas: U256,
683) -> Result<(), VMError> {
684    let base_fee_per_blob_gas = vm.env.base_blob_fee_per_gas;
685    if tx_max_fee_per_blob_gas < base_fee_per_blob_gas {
686        return Err(TxValidationError::InsufficientMaxFeePerBlobGas {
687            base_fee_per_blob_gas,
688            tx_max_fee_per_blob_gas,
689        }
690        .into());
691    }
692
693    Ok(())
694}
695
696pub fn validate_init_code_size(vm: &mut VM<'_>) -> Result<(), VMError> {
697    // [EIP-3860] - INITCODE_SIZE_EXCEEDED
698    // [EIP-7954] - Amsterdam increases the limit
699    let code_size = vm.current_call_frame.calldata.len();
700    let max_size = if vm.env.config.fork >= Fork::Amsterdam {
701        AMSTERDAM_INIT_CODE_MAX_SIZE
702    } else {
703        INIT_CODE_MAX_SIZE
704    };
705    if code_size > max_size && vm.env.config.fork >= Fork::Shanghai {
706        return Err(TxValidationError::InitcodeSizeExceeded {
707            max_size,
708            actual_size: code_size,
709        }
710        .into());
711    }
712    Ok(())
713}
714
715pub fn validate_sufficient_max_fee_per_gas(vm: &mut VM<'_>) -> Result<(), TxValidationError> {
716    if vm.env.tx_max_fee_per_gas.unwrap_or(vm.env.gas_price) < vm.env.base_fee_per_gas {
717        return Err(TxValidationError::InsufficientMaxFeePerGas);
718    }
719    Ok(())
720}
721
722pub fn validate_4844_tx(vm: &mut VM<'_>) -> Result<(), VMError> {
723    // (11) TYPE_3_TX_PRE_FORK
724    if vm.env.config.fork < Fork::Cancun {
725        return Err(TxValidationError::Type3TxPreFork.into());
726    }
727
728    let blob_hashes = &vm.env.tx_blob_hashes;
729
730    // (12) TYPE_3_TX_ZERO_BLOBS
731    if blob_hashes.is_empty() {
732        return Err(TxValidationError::Type3TxZeroBlobs.into());
733    }
734
735    // (13) TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH
736    for blob_hash in blob_hashes {
737        let blob_hash = blob_hash.as_bytes();
738        if blob_hash
739            .first()
740            .is_some_and(|first_byte| !VALID_BLOB_PREFIXES.contains(first_byte))
741        {
742            return Err(TxValidationError::Type3TxInvalidBlobVersionedHash.into());
743        }
744    }
745
746    // (14) TYPE_3_TX_BLOB_COUNT_EXCEEDED
747    let max_blob_count = vm
748        .env
749        .config
750        .blob_schedule
751        .max
752        .try_into()
753        .map_err(|_| InternalError::TypeConversion)?;
754    let blob_count = blob_hashes.len();
755    if blob_count > max_blob_count {
756        return Err(TxValidationError::Type3TxBlobCountExceeded {
757            max_blob_count,
758            actual_blob_count: blob_count,
759        }
760        .into());
761    }
762    if vm.env.config.fork >= Fork::Osaka && blob_count > MAX_BLOB_COUNT_TX {
763        return Err(TxValidationError::Type3TxBlobCountExceeded {
764            max_blob_count: MAX_BLOB_COUNT_TX,
765            actual_blob_count: blob_count,
766        }
767        .into());
768    }
769
770    // (15) TYPE_3_TX_CONTRACT_CREATION
771    // NOTE: This will never happen, since the EIP-4844 tx (type 3) does not have a TxKind field
772    // only supports an Address which must be non-empty.
773    // If a type 3 tx has the field `to` as null (signaling create), it will raise an exception on RLP decoding,
774    // it won't reach this point.
775    // For more information, please check the following thread:
776    // - https://github.com/lambdaclass/ethrex/pull/2425/files/819825516dc633275df56b2886b921061c4d7681#r2035611105
777    if vm.is_create()? {
778        return Err(TxValidationError::Type3TxContractCreation.into());
779    }
780
781    Ok(())
782}
783
784pub fn validate_type_4_tx(vm: &mut VM<'_>) -> Result<(), VMError> {
785    let Some(auth_list) = vm.tx.authorization_list() else {
786        // vm.authorization_list should be Some at this point.
787        return Err(InternalError::Custom("Auth list not found".to_string()).into());
788    };
789
790    // (16) TYPE_4_TX_PRE_FORK
791    if vm.env.config.fork < Fork::Prague {
792        return Err(TxValidationError::Type4TxPreFork.into());
793    }
794
795    // (17) TYPE_4_TX_CONTRACT_CREATION
796    // From the EIP docs: a null destination is not valid.
797    // NOTE: This will never happen, since the EIP-7702 tx (type 4) does not have a TxKind field
798    // only supports an Address which must be non-empty.
799    // If a type 4 tx has the field `to` as null (signaling create), it will raise an exception on RLP decoding,
800    // it won't reach this point.
801    // For more information, please check the following thread:
802    // - https://github.com/lambdaclass/ethrex/pull/2425/files/819825516dc633275df56b2886b921061c4d7681#r2035611105
803    if vm.is_create()? {
804        return Err(TxValidationError::Type4TxContractCreation.into());
805    }
806
807    // (18) TYPE_4_TX_LIST_EMPTY
808    // From the EIP docs: The transaction is considered invalid if the length of authorization_list is zero.
809    if auth_list.is_empty() {
810        return Err(TxValidationError::Type4TxAuthorizationListIsEmpty.into());
811    }
812
813    vm.eip7702_set_access_code()
814}
815
816pub fn validate_sender(sender_address: Address, code: &[u8]) -> Result<(), VMError> {
817    if !code.is_empty() && !code_has_delegation(code)? {
818        return Err(TxValidationError::SenderNotEOA(sender_address).into());
819    }
820    Ok(())
821}
822
823pub fn validate_gas_allowance(vm: &mut VM<'_>) -> Result<(), TxValidationError> {
824    // System contract calls (EIP-2935, EIP-4788, EIP-7002, EIP-7251) bypass the
825    // block-level gas-allowance check — their 30M gas budget is a protocol rule
826    // independent of `block_gas_limit`.
827    if vm.env.is_system_call || vm.env.disable_gas_allowance_check {
828        return Ok(());
829    }
830    if vm.env.gas_limit > vm.env.block_gas_limit {
831        return Err(TxValidationError::GasAllowanceExceeded {
832            block_gas_limit: vm.env.block_gas_limit,
833            tx_gas_limit: vm.env.gas_limit,
834        });
835    }
836    Ok(())
837}
838
839pub fn validate_sender_balance(vm: &mut VM<'_>, sender_balance: U256) -> Result<(), VMError> {
840    if vm.env.disable_balance_check {
841        return Ok(());
842    }
843
844    // Up front cost is the maximum amount of wei that a user is willing to pay for. Gaslimit * gasprice + value + blob_gas_cost
845    let value = vm.current_call_frame.msg_value;
846
847    // blob gas cost = max fee per blob gas * blob gas used
848    // https://eips.ethereum.org/EIPS/eip-4844
849    let max_blob_gas_cost =
850        get_max_blob_gas_price(&vm.env.tx_blob_hashes, vm.env.tx_max_fee_per_blob_gas)?;
851
852    // For the transaction to be valid the sender account has to have a balance >= gas_price * gas_limit + value if tx is type 0 and 1
853    // balance >= max_fee_per_gas * gas_limit + value + blob_gas_cost if tx is type 2 or 3
854    let gas_fee_for_valid_tx = vm
855        .env
856        .tx_max_fee_per_gas
857        .unwrap_or(vm.env.gas_price)
858        .checked_mul(vm.env.gas_limit.into())
859        .ok_or(TxValidationError::GasLimitPriceProductOverflow)?;
860
861    let balance_for_valid_tx = gas_fee_for_valid_tx
862        .checked_add(value)
863        .ok_or(TxValidationError::InsufficientAccountFunds)?
864        .checked_add(max_blob_gas_cost)
865        .ok_or(TxValidationError::InsufficientAccountFunds)?;
866
867    if sender_balance < balance_for_valid_tx {
868        return Err(TxValidationError::InsufficientAccountFunds.into());
869    }
870
871    Ok(())
872}
873
874pub fn deduct_caller(
875    vm: &mut VM<'_>,
876    gas_limit_price_product: U256,
877    sender_address: Address,
878) -> Result<(), VMError> {
879    if vm.env.disable_balance_check {
880        return Ok(());
881    }
882
883    // Up front cost is the maximum amount of wei that a user is willing to pay for. Gaslimit * gasprice + value + blob_gas_cost
884    let value = vm.current_call_frame.msg_value;
885
886    let blob_gas_cost =
887        calculate_blob_gas_cost(&vm.env.tx_blob_hashes, vm.env.base_blob_fee_per_gas)?;
888
889    // The real cost to deduct is calculated as effective_gas_price * gas_limit + value + blob_gas_cost
890    let up_front_cost = gas_limit_price_product
891        .checked_add(value)
892        .ok_or(TxValidationError::InsufficientAccountFunds)?
893        .checked_add(blob_gas_cost)
894        .ok_or(TxValidationError::InsufficientAccountFunds)?;
895    // There is no error specified for overflow in up_front_cost
896    // in ef_tests. We went for "InsufficientAccountFunds" simply
897    // because if the upfront cost is bigger than U256, then,
898    // technically, the sender will not be able to pay it.
899
900    vm.decrease_account_balance(sender_address, up_front_cost)
901        .map_err(|_| TxValidationError::InsufficientAccountFunds)?;
902
903    Ok(())
904}
905
906/// Transfer msg_value to transaction recipient
907pub fn transfer_value(vm: &mut VM<'_>) -> Result<(), VMError> {
908    if !vm.is_create()? {
909        let value = vm.current_call_frame.msg_value;
910        let to = vm.current_call_frame.to;
911
912        vm.increase_account_balance(to, value)?;
913
914        // EIP-7708: Emit transfer log for nonzero-value transactions to DIFFERENT accounts
915        // Self-transfers (origin == to) should NOT emit a log per the EIP spec
916        let from = vm.env.origin;
917        if vm.env.config.fork >= Fork::Amsterdam && !value.is_zero() && from != to {
918            let log = create_eth_transfer_log(from, to, value);
919            vm.substate.add_log(log);
920        }
921    }
922    Ok(())
923}
924
925/// Sets bytecode and code_address to CallFrame
926pub fn set_bytecode_and_code_address(vm: &mut VM<'_>) -> Result<(), VMError> {
927    // Get bytecode and code_address for assigning those values to the callframe.
928    let (bytecode, code_address) = if vm.is_create()? {
929        // Here bytecode is the calldata and the code_address is just the created contract address.
930        let calldata = std::mem::take(&mut vm.current_call_frame.calldata);
931        (
932            // SAFETY: we don't need the hash for the initcode
933            Code::from_bytecode_unchecked(calldata, H256::zero()),
934            vm.current_call_frame.to,
935        )
936    } else {
937        // Here bytecode and code_address could be either from the account or from the delegated account.
938        let to = vm.current_call_frame.to;
939
940        // Record tx.to as touched in BAL (the target of message call transaction).
941        // EIP-7928 (tests-glamsterdam-devnet@v7.1.0): skipped when the atomic prepare
942        // region rolled back (`pending_prep_oog`). EELS v7.1.0 stopped loading the
943        // recipient at inclusion (`prepare_message`) and now loads it only in the
944        // top-frame `prepare_dispatch`, which an EIP-7702 auth halt precedes — so a
945        // tx that OOGs during authorization processing must not touch the recipient.
946        if !vm.pending_prep_oog
947            && let Some(recorder) = vm.db.bal_recorder.as_mut()
948        {
949            recorder.record_touched_address(to);
950        }
951
952        let (is_delegation, _eip7702_gas_consumed, code_address, bytecode) =
953            eip7702_get_code(vm.db, &mut vm.substate, to, vm.env.config.fork)?;
954
955        // If EIP-7702 delegation, also record the delegation target (code source) in BAL.
956        // Skipped when the atomic prepare region rolled back (`pending_prep_oog`): EELS
957        // `prepare_dispatch` resolves and reads the delegated address (`get_account`,
958        // which feeds `account_reads`) only AFTER its warm/cold access charge succeeds.
959        // When that charge OOGs — or an earlier in-region charge (auth / value
960        // NEW_ACCOUNT) OOGs before the delegation is reached — EELS never records the
961        // target, so neither may ethrex, or the BAL would carry a spurious touch.
962        if is_delegation
963            && !vm.pending_prep_oog
964            && let Some(recorder) = vm.db.bal_recorder.as_mut()
965        {
966            recorder.record_touched_address(code_address);
967        }
968
969        (bytecode, code_address)
970    };
971
972    // Assign code and code_address to callframe
973    vm.current_call_frame.code_address = code_address;
974    vm.current_call_frame.set_code(bytecode)?;
975
976    Ok(())
977}