ethrex-levm 17.0.0

Native EVM implementation for the ethrex Ethereum execution client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! # Control flow and memory operations
//!
//! Includes the following opcodes:
//!   - `POP`
//!   - `GAS`
//!   - `PC`
//!   - `MLOAD`
//!   - `MSTORE`
//!   - `MSTORE8`
//!   - `MCOPY`
//!   - `MSIZE`
//!   - `TLOAD`
//!   - `TSTORE`
//!   - `SLOAD`
//!   - `SSTORE`
//!   - `JUMPDEST`
//!   - `JUMP`
//!   - `JUMPI`

use crate::{
    constants::WORD_SIZE_IN_BYTES_USIZE,
    errors::{ExceptionalHalt, InternalError, OpcodeResult, VMError},
    gas_cost::{self, SSTORE_STIPEND},
    memory::calculate_memory_size,
    opcode_handlers::OpcodeHandler,
    opcodes::Opcode,
    utils::{size_offset_to_usize, u256_to_usize},
    vm::VM,
};
use ethrex_common::{H256, U256, types::Fork};
use std::{mem, slice};

/// Implementation for the `POP` opcode.
pub struct OpPopHandler;
impl OpcodeHandler for OpPopHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame.increase_consumed_gas(gas_cost::POP)?;

        vm.current_call_frame.stack.pop1()?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `GAS` opcode.
pub struct OpGasHandler;
impl OpcodeHandler for OpGasHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame.increase_consumed_gas(gas_cost::GAS)?;

        vm.current_call_frame
            .stack
            .push(vm.current_call_frame.gas_remaining.into())?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `PC` opcode.
pub struct OpPcHandler;
impl OpcodeHandler for OpPcHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame.increase_consumed_gas(gas_cost::PC)?;

        // Note: Since the PC has been preincremented, subtracting 1 from it to get the operation's
        //   offset will never cause an underflow condition.
        vm.current_call_frame
            .stack
            .push(vm.current_call_frame.pc.wrapping_sub(1).into())?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `MLOAD` opcode.
pub struct OpMLoadHandler;
impl OpcodeHandler for OpMLoadHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        // Stack-neutral: replace the top (the offset) with the loaded word in place.
        let offset = u256_to_usize(*vm.current_call_frame.stack.top_mut()?)?;
        vm.current_call_frame
            .increase_consumed_gas(gas_cost::mload(
                calculate_memory_size(offset, WORD_SIZE_IN_BYTES_USIZE)?,
                vm.current_call_frame.memory.len(),
            )?)?;

        let word = vm.current_call_frame.memory.load_word(offset)?;
        *vm.current_call_frame.stack.top_mut()? = word;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `MSTORE` opcode.
pub struct OpMStoreHandler;
impl OpcodeHandler for OpMStoreHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        let [offset, value] = *vm.current_call_frame.stack.pop()?;

        // Handle debug text printing for solidity contracts that enable it.
        if vm.debug_mode.enabled && vm.debug_mode.handle_debug(offset, value)? {
            return Ok(OpcodeResult::Continue);
        }

        let offset = u256_to_usize(offset)?;
        vm.current_call_frame
            .increase_consumed_gas(gas_cost::mstore(
                calculate_memory_size(offset, WORD_SIZE_IN_BYTES_USIZE)?,
                vm.current_call_frame.memory.len(),
            )?)?;

        vm.current_call_frame.memory.store_word(offset, value)?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `MSTORE8` opcode.
pub struct OpMStore8Handler;
impl OpcodeHandler for OpMStore8Handler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        let [offset, value] = *vm.current_call_frame.stack.pop()?;
        let offset = u256_to_usize(offset)?;
        let value = value.byte(0);

        vm.current_call_frame
            .increase_consumed_gas(gas_cost::mstore8(
                calculate_memory_size(offset, size_of::<u8>())?,
                vm.current_call_frame.memory.len(),
            )?)?;

        vm.current_call_frame
            .memory
            .store_data(offset, slice::from_ref(&value))?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `MCOPY` opcode.
pub struct OpMCopyHandler;
impl OpcodeHandler for OpMCopyHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        let [dst_offset, src_offset, len] = *vm.current_call_frame.stack.pop()?;
        let (len, dst_offset) = size_offset_to_usize(len, dst_offset)?;
        let src_offset = u256_to_usize(src_offset).unwrap_or(usize::MAX);

        vm.current_call_frame
            .increase_consumed_gas(gas_cost::mcopy(
                calculate_memory_size(src_offset.max(dst_offset), len)?,
                vm.current_call_frame.memory.len(),
                len,
            )?)?;

        vm.current_call_frame
            .memory
            .copy_within(src_offset, dst_offset, len)?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `MSIZE` opcode.
pub struct OpMSizeHandler;
impl OpcodeHandler for OpMSizeHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame
            .increase_consumed_gas(gas_cost::MSIZE)?;

        vm.current_call_frame
            .stack
            .push(vm.current_call_frame.memory.len().into())?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `TLOAD` opcode.
pub struct OpTLoadHandler;
impl OpcodeHandler for OpTLoadHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame
            .increase_consumed_gas(gas_cost::TLOAD)?;

        let key = vm.current_call_frame.stack.pop1()?;
        vm.current_call_frame
            .stack
            .push(vm.substate.get_transient(&vm.current_call_frame.to, &key))?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `TSTORE` opcode.
pub struct OpTStoreHandler;
impl OpcodeHandler for OpTStoreHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        if vm.current_call_frame.is_static {
            return Err(ExceptionalHalt::OpcodeNotAllowedInStaticContext.into());
        }

        vm.current_call_frame
            .increase_consumed_gas(gas_cost::TSTORE)?;

        let [key, value] = *vm.current_call_frame.stack.pop()?;
        vm.substate
            .set_transient(&vm.current_call_frame.to, &key, value);

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `SLOAD` opcode.
pub struct OpSLoadHandler;
impl OpcodeHandler for OpSLoadHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        let storage_slot_key = vm.current_call_frame.stack.pop1()?;
        let address = vm.current_call_frame.to;
        let key = {
            #[expect(unsafe_code)]
            unsafe {
                let mut hash = mem::transmute::<U256, H256>(storage_slot_key);
                hash.0.reverse();
                hash
            }
        };

        vm.current_call_frame
            .increase_consumed_gas(gas_cost::sload(
                vm.substate.add_accessed_slot(address, key),
            )?)?;

        // Record to BAL AFTER gas check passes per EIP-7928
        vm.record_storage_slot_to_bal(address, storage_slot_key);

        let value = vm.get_storage_value(address, key)?;
        vm.current_call_frame.stack.push(value)?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `SSTORE` opcode.
pub struct OpSStoreHandler;
impl OpcodeHandler for OpSStoreHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        if vm.current_call_frame.is_static {
            return Err(ExceptionalHalt::OpcodeNotAllowedInStaticContext.into());
        }

        // EIP-2200
        if vm.current_call_frame.gas_remaining <= SSTORE_STIPEND {
            return Err(ExceptionalHalt::OutOfGas.into());
        }

        let [storage_slot_key, value] = *vm.current_call_frame.stack.pop()?;
        let to = vm.current_call_frame.to;
        #[expect(unsafe_code)]
        let key = unsafe {
            let mut hash = mem::transmute::<U256, H256>(storage_slot_key);
            hash.0.reverse();
            hash
        };

        let (current_value, original_value, storage_slot_was_cold) =
            vm.access_storage_slot_for_sstore(to, key)?;

        // Record storage read to BAL AFTER SSTORE_STIPEND check passes, BEFORE main gas check.
        // Per EIP-7928: if SSTORE passes the stipend check but fails the main gas charge,
        // the slot MUST appear as a read because the implicit SLOAD has already happened.
        vm.record_storage_slot_to_bal(to, storage_slot_key);

        let fork = vm.env.config.fork;

        // EIP-8037 (Amsterdam+): check if state gas is needed for new storage slot (0 -> nonzero),
        // but charge it AFTER regular gas per EELS ordering (ethereum/EIPs#11421).
        // Regular gas OOG must not consume state gas that would inflate the parent's reservoir.
        let needs_state_gas = fork >= Fork::Amsterdam
            && value != current_value
            && current_value == original_value
            && original_value.is_zero()
            && !value.is_zero();

        vm.current_call_frame
            .increase_consumed_gas(gas_cost::sstore(
                original_value,
                current_value,
                value,
                storage_slot_was_cold,
                fork,
            )?)?;

        if needs_state_gas {
            vm.increase_state_gas(vm.state_gas_storage_set)?;
        }
        // EIP-8037 (Amsterdam+) 0→N→0: the slot was created in this tx (original == 0),
        // dirtied to N (current_value != 0), and now being reset to 0 (value == original == 0).
        // The creation state gas is refunded via clamp-and-spill, not the regular refund counter.
        let is_zero_to_n_to_zero_amsterdam = fork >= Fork::Amsterdam
            && value != current_value
            && current_value != original_value
            && value == original_value
            && original_value.is_zero();

        if value != current_value {
            // EIP-2929
            const REMOVE_SLOT_COST: i64 = 4800;
            const RESTORE_EMPTY_SLOT_COST: i64 = 19900;
            const RESTORE_SLOT_COST: i64 = 2800;

            // The operations on `delta` cannot overflow.
            let mut delta = 0i64;
            #[expect(
                clippy::arithmetic_side_effects,
                reason = "delta additions are bounded by known constants"
            )]
            if current_value == original_value {
                if !original_value.is_zero() && value.is_zero() {
                    delta += REMOVE_SLOT_COST;
                }
            } else {
                if !original_value.is_zero() {
                    if current_value.is_zero() {
                        delta -= REMOVE_SLOT_COST;
                    } else if value.is_zero() {
                        delta += REMOVE_SLOT_COST;
                    }
                }

                if value == original_value {
                    if original_value.is_zero() {
                        // EIP-8037 (Amsterdam+): restore_empty_slot_cost changes from 19900 to 2800
                        // because the SSTORE creation cost changed from 20000 to 2900.
                        // The state gas portion is refunded via the reservoir (clamp-and-spill),
                        // NOT through the regular refund counter.
                        if fork >= Fork::Amsterdam {
                            delta += RESTORE_SLOT_COST; // 2800 instead of 19900
                        } else {
                            delta += RESTORE_EMPTY_SLOT_COST;
                        }
                    } else {
                        delta += RESTORE_SLOT_COST;
                    }
                }
            }

            // Update refunded gas after checking for overflow or underflow.
            match vm.substate.refunded_gas.checked_add_signed(delta) {
                Some(refunded_gas) => vm.substate.refunded_gas = refunded_gas,
                None if delta < 0 => return Err(InternalError::Underflow.into()),
                None => return Err(InternalError::Overflow.into()),
            }
        }

        // EIP-8037: credit the state gas refund via clamp-and-spill (after regular gas processing).
        if is_zero_to_n_to_zero_amsterdam {
            vm.credit_state_gas_refund(vm.state_gas_storage_set)?;
        }

        if value != current_value {
            vm.update_account_storage(to, key, storage_slot_key, value, current_value)?;
        }

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `JUMPDEST` opcode.
pub struct OpJumpDestHandler;
impl OpcodeHandler for OpJumpDestHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame
            .increase_consumed_gas(gas_cost::JUMPDEST)?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `JUMP` opcode.
pub struct OpJumpHandler;
impl OpcodeHandler for OpJumpHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame
            .increase_consumed_gas(gas_cost::JUMP)?;

        let target = vm.current_call_frame.stack.pop1()?;
        jump(vm, target.try_into().unwrap_or(usize::MAX), gas_cost::JUMP)?;

        Ok(OpcodeResult::Continue)
    }
}

/// Implementation for the `JUMPI` opcode.
pub struct OpJumpIHandler;
impl OpcodeHandler for OpJumpIHandler {
    #[inline(always)]
    fn eval(vm: &mut VM<'_>) -> Result<OpcodeResult, VMError> {
        vm.current_call_frame
            .increase_consumed_gas(gas_cost::JUMPI)?;

        let [target, condition] = *vm.current_call_frame.stack.pop()?;
        if !condition.is_zero() {
            jump(vm, target.try_into().unwrap_or(usize::MAX), gas_cost::JUMPI)?;
        }

        Ok(OpcodeResult::Continue)
    }
}

/// Validate and take a jump. Fuses the destination JUMPDEST (advances PC past
/// it and charges its 1 gas inline) to save a dispatch cycle on the hot path.
///
/// When the tracer is active we keep the fusion for performance and *synthesize*
/// a JUMPDEST entry in the trace log: `parent_gas_cost` is recorded as the
/// override for the parent JUMP/JUMPI step (so its `gasCost` doesn't absorb the
/// JUMPDEST charge), and the JUMPDEST step is pushed directly via
/// `synthesize_step` after the gas is charged.
fn jump(vm: &mut VM<'_>, target: usize, parent_gas_cost: u64) -> Result<(), VMError> {
    // Check target address validity.
    //   - Target bytecode has to be a JUMPDEST.
    //   - Target address must not be blacklisted (aka. the JUMPDEST must not be part of a literal).
    #[expect(clippy::as_conversions, reason = "safe")]
    if vm
        .current_call_frame
        .bytecode
        .dispatch_buf()
        .get(target)
        .is_some_and(|&value| {
            value == Opcode::JUMPDEST as u8
                && vm
                    .current_call_frame
                    .bytecode
                    .jump_targets
                    .binary_search(&(target as u32))
                    .is_ok()
        })
    {
        if vm.opcode_tracer.active {
            // Override the parent JUMP/JUMPI's gasCost so the dispatch loop
            // doesn't roll the upcoming JUMPDEST charge into it.
            vm.opcode_tracer.last_opcode_gas_cost = Some(parent_gas_cost);

            // Capture the synthetic JUMPDEST step's state BEFORE charging its gas.
            let synth = build_jumpdest_step(vm, target);

            // Fuse: charge JUMPDEST + advance PC past it.
            vm.current_call_frame.pc = target.wrapping_add(1);
            vm.current_call_frame
                .increase_consumed_gas(gas_cost::JUMPDEST)?;

            vm.opcode_tracer.synthesize_step(synth);
        } else {
            // Hot path: fuse JUMP/JUMPI + JUMPDEST without any trace bookkeeping.
            vm.current_call_frame.pc = target.wrapping_add(1);
            vm.current_call_frame
                .increase_consumed_gas(gas_cost::JUMPDEST)?;
        }
        Ok(())
    } else {
        // Target address is invalid.
        Err(ExceptionalHalt::InvalidJump.into())
    }
}

/// Builds a synthetic JUMPDEST trace entry. Captures gas/stack/memory/return-data
/// state at the moment of the call (i.e. *before* the JUMPDEST gas has been
/// charged) and hands them to the shared [`opcode_tracer::build_step`] so the
/// cfg-driven conditionals (disable_stack, enable_memory, enable_return_data)
/// live in exactly one place.
#[expect(
    clippy::as_conversions,
    reason = "pc/depth/mem_size bounded; fit in target types"
)]
fn build_jumpdest_step(vm: &VM<'_>, target: usize) -> ethrex_common::tracing::OpcodeStep {
    use crate::opcode_tracer::build_step;
    use bytes::Bytes;

    let cfg = &vm.opcode_tracer.cfg;
    let gas = vm.current_call_frame.gas_remaining.max(0) as u64;
    let depth = (vm.call_frames.len() as u32).saturating_add(1);
    let refund = vm.substate.refunded_gas;
    let mem_size = vm.current_call_frame.memory.len() as u64;

    let stack_view = if cfg.disable_stack {
        Vec::new()
    } else {
        vm.collect_stack_for_trace()
    };
    let mem_view = if cfg.enable_memory {
        vm.collect_memory_for_trace()
    } else {
        Vec::new()
    };
    let return_data = if cfg.enable_return_data {
        vm.current_call_frame.sub_return_data.clone()
    } else {
        Bytes::new()
    };

    build_step(
        cfg,
        target as u64,
        Opcode::JUMPDEST as u8,
        gas,
        gas_cost::JUMPDEST,
        depth,
        refund,
        &stack_view,
        &mem_view,
        mem_size,
        &return_data,
        None,
    )
}