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