Skip to main content

ethrex_levm/
execution_handlers.rs

1use crate::{
2    constants::*,
3    errors::{ContextResult, ExceptionalHalt, InternalError, TxResult, VMError},
4    gas_cost::{CODE_DEPOSIT_COST, CODE_DEPOSIT_REGULAR_COST_PER_WORD},
5    vm::VM,
6};
7
8use bytes::Bytes;
9use ethrex_common::types::{Code, Fork};
10
11impl<'a> VM<'a> {
12    pub fn handle_precompile_result(
13        precompile_result: Result<Bytes, VMError>,
14        gas_limit: u64,
15        gas_remaining: u64,
16    ) -> Result<ContextResult, VMError> {
17        match precompile_result {
18            Ok(output) => {
19                let gas_used = gas_limit
20                    .checked_sub(gas_remaining)
21                    .ok_or(InternalError::Underflow)?;
22                Ok(ContextResult {
23                    result: TxResult::Success,
24                    gas_used,
25                    gas_spent: gas_used, // Will be updated in finalize_execution
26                    output,
27                })
28            }
29            Err(error) => {
30                if error.should_propagate() {
31                    return Err(error);
32                }
33
34                Ok(ContextResult {
35                    result: TxResult::Revert(error),
36                    gas_used: gas_limit,
37                    gas_spent: gas_limit, // Will be updated in finalize_execution
38                    output: Bytes::new(),
39                })
40            }
41        }
42    }
43
44    #[cold] // used in the hot path loop, called only really once.
45    pub fn handle_opcode_result(&mut self) -> Result<ContextResult, VMError> {
46        // On successful create check output validity
47        if self.is_create()? {
48            let validate_create = self.validate_contract_creation();
49
50            if let Err(error) = validate_create {
51                if error.should_propagate() {
52                    return Err(error);
53                }
54
55                // EIP-8037 (Amsterdam+): roll back this frame's state gas in LIFO order
56                // BEFORE zeroing gas. Mirrors EELS `process_create_message`'s
57                // `refill_frame_state_gas` on the code-deposit ExceptionalHalt path.
58                // Must run before the `&mut self.current_call_frame` borrow below.
59                if self.env.config.fork >= Fork::Amsterdam {
60                    let entry = self.current_call_frame.state_gas_used_at_entry;
61                    self.refill_frame_state_gas(entry)?;
62                }
63
64                // Consume all gas because error was exceptional.
65                let callframe = &mut self.current_call_frame;
66                callframe.gas_remaining = 0;
67
68                #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
69                let gas_used = callframe
70                    .gas_limit
71                    .checked_sub(callframe.gas_remaining as u64)
72                    .ok_or(InternalError::Underflow)?;
73                return Ok(ContextResult {
74                    result: TxResult::Revert(error),
75                    gas_used,
76                    gas_spent: gas_used, // Will be updated in finalize_execution
77                    output: Bytes::new(),
78                });
79            }
80
81            // Set bytecode to the newly created contract.
82            let contract_address = self.current_call_frame.to;
83            let code = self.current_call_frame.output.clone();
84            self.update_account_bytecode(contract_address, Code::from_bytecode(code, self.crypto))?;
85        }
86
87        #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
88        let gas_used = {
89            let callframe = &mut self.current_call_frame;
90            callframe
91                .gas_limit
92                .checked_sub(callframe.gas_remaining as u64)
93                .ok_or(InternalError::Underflow)?
94        };
95        Ok(ContextResult {
96            result: TxResult::Success,
97            gas_used,
98            gas_spent: gas_used, // Will be updated in finalize_execution
99            output: std::mem::take(&mut self.current_call_frame.output),
100        })
101    }
102
103    #[cold] // used in the hot path loop, called only really once.
104    pub fn handle_opcode_error(&mut self, error: VMError) -> Result<ContextResult, VMError> {
105        if error.should_propagate() {
106            return Err(error);
107        }
108
109        // EIP-8037 (Amsterdam+): roll back this frame's state gas in LIFO order BEFORE
110        // zeroing gas on exceptional halt. Covers both revert and exceptional-halt paths
111        // (mirrors EELS `process_message`'s `refill_frame_state_gas` on Revert/ExceptionalHalt).
112        // Must run before the `&mut self.current_call_frame` borrow below since refill needs `&mut self`.
113        if self.env.config.fork >= Fork::Amsterdam {
114            let entry = self.current_call_frame.state_gas_used_at_entry;
115            self.refill_frame_state_gas(entry)?;
116        }
117
118        let callframe = &mut self.current_call_frame;
119
120        // Unless error is caused by Revert Opcode, consume all gas left.
121        if !error.is_revert_opcode() {
122            callframe.gas_remaining = 0;
123        }
124
125        #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
126        let gas_used = callframe
127            .gas_limit
128            .checked_sub(callframe.gas_remaining as u64)
129            .ok_or(InternalError::Underflow)?;
130        Ok(ContextResult {
131            result: TxResult::Revert(error),
132            gas_used,
133            gas_spent: gas_used, // Will be updated in finalize_execution
134            output: std::mem::take(&mut callframe.output),
135        })
136    }
137
138    /// Handles external create transaction.
139    pub fn handle_create_transaction(&mut self) -> Result<Option<ContextResult>, VMError> {
140        let new_contract_address = self.current_call_frame.to;
141
142        // EIP-7928: Record contract address in BAL before collision check.
143        // Per EELS reference, the address is tracked even when the create collides.
144        if let Some(recorder) = self.db.bal_recorder.as_mut() {
145            recorder.record_touched_address(new_contract_address);
146        }
147
148        let new_account = self.get_account_mut(new_contract_address)?;
149
150        if new_account.create_would_collide() {
151            // EIP-8037: `prepare_execution`'s in-region CREATE `NEW_ACCOUNT` charge
152            // runs before this collision check and fires whenever the
153            // target's pre-state was EMPTY_ACCOUNT — which can be true even for a
154            // colliding target in the EELS-documented "highly unlikely" case of a
155            // zero-nonce/zero-code/zero-balance address that nonetheless has storage
156            // (`create_would_collide` also considers storage; `is_empty()` doesn't).
157            //
158            // Known near-unreachable divergence (code review, accepted): if the
159            // reservoir/gas cannot cover that in-region NEW_ACCOUNT charge for such a
160            // storage-only colliding target, ethrex takes the region-OOG path (burns all
161            // gas) whereas EELS — which checks `account_deployable()` before
162            // `prepare_dispatch` — never charges and preserves the reservoir. This
163            // requires deriving a CREATE address that already holds storage with zero
164            // nonce/code/balance AND under-funding it, which is not reachable via real
165            // CREATE/CREATE2 address derivation; documented rather than guarded.
166            //
167            // Roll that charge back to the frame's entry baseline: EELS never runs
168            // `prepare_dispatch` for a colliding create (`process_message_call`
169            // short-circuits on `account_deployable() == False` before calling
170            // `process_create_message`), so a collision must leave `state_gas_used`
171            // (and any state-gas spill) net zero. No opcodes have run yet, so
172            // `frame_used = state_gas_used - entry` is exactly this charge, if any.
173            if self.env.config.fork >= Fork::Amsterdam {
174                let entry = self.current_call_frame.state_gas_used_at_entry;
175                self.refill_frame_state_gas(entry)?;
176            }
177
178            // Per EIP-684: a tx-level CREATE collision burns the
179            // full forwarded execution gas as `regular_gas_used`. Zero `gas_remaining`
180            // so `raw_consumed = gas_limit` for the downstream regular-gas formula in
181            // `default_hook::refund_sender`; otherwise the post-intrinsic leftover
182            // leaks back to the sender and never reaches the regular dimension.
183            self.current_call_frame.gas_remaining = 0;
184            return Ok(Some(ContextResult {
185                result: TxResult::Revert(ExceptionalHalt::AddressAlreadyOccupied.into()),
186                gas_used: self.env.gas_limit,
187                gas_spent: self.env.gas_limit, // Will be updated in finalize_execution
188                output: Bytes::new(),
189            }));
190        }
191
192        let value = self.current_call_frame.msg_value;
193        self.increase_account_balance(new_contract_address, value)?;
194
195        // EIP-7708 / traceTransfers: emit transfer log for nonzero-value contract
196        // creation transactions. Origin is sender, new_contract_address is the recipient.
197        self.add_eth_transfer_logs(self.env.origin, new_contract_address, value);
198
199        self.increment_account_nonce(new_contract_address)?;
200
201        Ok(None)
202    }
203
204    /// Validates that the contract creation was successful, otherwise it returns an ExceptionalHalt.
205    fn validate_contract_creation(&mut self) -> Result<(), VMError> {
206        let fork = self.env.config.fork;
207        let code = &self.current_call_frame.output;
208
209        let code_length: u64 = code
210            .len()
211            .try_into()
212            .map_err(|_| InternalError::TypeConversion)?;
213
214        // 1. If the first byte of code is 0xEF
215        if code.first().is_some_and(|v| v == &EOF_PREFIX) {
216            return Err(ExceptionalHalt::InvalidContractPrefix.into());
217        }
218
219        // EIP-8037 (Amsterdam+): Per EELS process_create_message (bal@v5.4.0):
220        // 1. Size check first (reject oversized before any gas charges)
221        // 2. Keccak hash cost (regular gas)
222        // 3. State gas for code deposit
223        if fork >= Fork::Amsterdam {
224            // Size check BEFORE gas charges
225            if code_length > AMSTERDAM_MAX_CODE_SIZE {
226                return Err(ExceptionalHalt::ContractOutputTooBig.into());
227            }
228
229            let words = code_length.div_ceil(32);
230            let regular = words
231                .checked_mul(CODE_DEPOSIT_REGULAR_COST_PER_WORD)
232                .ok_or(InternalError::Overflow)?;
233            let state = code_length
234                .checked_mul(self.cost_per_state_byte)
235                .ok_or(InternalError::Overflow)?;
236
237            // Regular gas (keccak hash cost) before state gas
238            self.current_call_frame.increase_consumed_gas(regular)?;
239            if state > 0 {
240                self.increase_state_gas(state)?;
241            }
242        } else {
243            // Pre-Amsterdam: size check first, then regular gas charge
244            if code_length > MAX_CODE_SIZE {
245                return Err(ExceptionalHalt::ContractOutputTooBig.into());
246            }
247            let regular = code_length
248                .checked_mul(CODE_DEPOSIT_COST)
249                .ok_or(InternalError::Overflow)?;
250            self.current_call_frame.increase_consumed_gas(regular)?;
251        }
252
253        Ok(())
254    }
255}