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
use std::{cell::RefCell, rc::Rc};

use crate::{
    constants::{MEMORY_EXPANSION_QUOTIENT, WORD_SIZE_IN_BYTES_U64, WORD_SIZE_IN_BYTES_USIZE},
    errors::{ExceptionalHalt, InternalError, VMError},
};
use ExceptionalHalt::OutOfBounds;
use bytes::Bytes;
use ethrex_common::{
    U256,
    utils::{u256_from_big_endian_const, u256_to_big_endian},
};

/// A cheaply clonable callframe-shared memory buffer.
///
/// When a new callframe is created a RC clone of this memory is made, with the current base offset at the length of the buffer at that time.
#[derive(Debug, Clone)]
pub struct Memory {
    pub buffer: Rc<RefCell<Vec<u8>>>,
    pub len: usize,
    current_base: usize,
}

impl Memory {
    #[inline]
    pub fn new() -> Self {
        Self {
            buffer: Rc::new(RefCell::new(Vec::new())),
            len: 0,
            current_base: 0,
        }
    }

    /// Resets this memory so its buffer can be reused from a pool by the next transaction:
    /// drops all contents (length → 0, capacity retained) and rebases to 0.
    ///
    /// Truncating the buffer to length 0 is REQUIRED for correctness, not just hygiene:
    /// [`Memory::resize`] only zero-fills bytes grown *past* `buffer.len()`, so handing a
    /// non-empty buffer to the next tx would expose stale data from the previous one (a
    /// consensus bug). Capacity is kept so the grown allocation is reused.
    #[inline]
    pub fn reset_for_reuse(&mut self) {
        self.buffer.borrow_mut().clear();
        self.len = 0;
        self.current_base = 0;
    }

    /// Gets the Memory for the next children callframe.
    #[inline]
    pub fn next_memory(&self) -> Memory {
        let mut mem = self.clone();
        mem.current_base = mem.buffer.borrow().len();
        mem.len = 0;
        mem
    }

    /// Cleans the memory from base onwards, this must be used in callframes when handling returns.
    ///
    /// On the callframe that is about to be dropped.
    #[inline]
    pub fn clean_from_base(&self) {
        #[expect(unsafe_code)]
        unsafe {
            self.buffer
                .borrow_mut()
                .get_unchecked_mut(self.current_base..(self.current_base.wrapping_add(self.len)))
                .fill(0);
        }
    }

    /// Truncates the memory back to base. This is crucial for constrained
    /// memory in zkVMs. The memory is not freed, but rather shrunk in `len`,
    /// so that the already allocated `capacity` is reused.
    #[cfg(target_arch = "riscv64")]
    #[inline]
    pub fn truncate_to_base(&self) {
        self.buffer.borrow_mut().truncate(self.current_base);
    }

    /// Returns the len of the current memory, from the current base.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a copy of the live byte slice for this frame (from `current_base` to
    /// `current_base + len`).  Used by the struct-log tracer for memory capture.
    pub fn live_bytes(&self) -> Vec<u8> {
        if self.len == 0 {
            return Vec::new();
        }
        let buf = self.buffer.borrow();
        let end = self.current_base.saturating_add(self.len);
        buf.get(self.current_base..end)
            .map(<[u8]>::to_vec)
            .unwrap_or_default()
    }

    /// Resizes the from the current base to fit the memory specified at new_memory_size.
    ///
    /// Note: new_memory_size is increased to the next 32 byte multiple.
    #[inline(always)]
    pub fn resize(&mut self, new_memory_size: usize) -> Result<(), VMError> {
        if new_memory_size == 0 {
            return Ok(());
        }

        let new_memory_size = new_memory_size
            .checked_next_multiple_of(WORD_SIZE_IN_BYTES_USIZE)
            .ok_or(OutOfBounds)?;

        let current_len = self.len();

        if new_memory_size <= current_len {
            return Ok(());
        }

        self.len = new_memory_size;

        let mut buffer = self.buffer.borrow_mut();

        #[allow(clippy::arithmetic_side_effects)]
        let real_new_memory_size = new_memory_size + self.current_base;

        if real_new_memory_size > buffer.len() {
            // when resizing, avoid really small resizes.
            let new_size = real_new_memory_size.next_multiple_of(64);
            buffer.resize(new_size, 0);
        }

        Ok(())
    }

    /// Load `size` bytes from the given offset. Returning a Bytes.
    #[inline]
    pub fn load_range(&mut self, offset: usize, size: usize) -> Result<Bytes, VMError> {
        if size == 0 {
            return Ok(Bytes::new());
        }

        let new_size = offset.checked_add(size).ok_or(OutOfBounds)?;
        self.resize(new_size)?;

        let true_offset = offset.wrapping_add(self.current_base);

        let buf = self.buffer.borrow();

        // SAFETY: resize already makes sure bounds are correct.
        #[allow(unsafe_code)]
        unsafe {
            Ok(Bytes::copy_from_slice(buf.get_unchecked(
                true_offset..(true_offset.wrapping_add(size)),
            )))
        }
    }

    /// Borrow `size` bytes from the given offset and pass them to `f`, without
    /// allocating a `Bytes` copy of the range.
    ///
    /// `load_range` reads through `self.buffer.borrow()`, whose `Ref` guard cannot
    /// outlive this call — so a `-> &[u8]` accessor can't be written. Callers that
    /// only need to read the range (e.g. hashing) take the borrow via this closure
    /// instead. Semantics match `load_range` exactly, including zero-padding reads
    /// past the current length (handled by `resize`).
    #[inline]
    pub fn with_range<R>(
        &mut self,
        offset: usize,
        size: usize,
        f: impl FnOnce(&[u8]) -> R,
    ) -> Result<R, VMError> {
        if size == 0 {
            return Ok(f(&[]));
        }

        let new_size = offset.checked_add(size).ok_or(OutOfBounds)?;
        self.resize(new_size)?;

        let true_offset = offset.wrapping_add(self.current_base);

        let buf = self.buffer.borrow();

        // SAFETY: resize already makes sure bounds are correct.
        #[allow(unsafe_code)]
        let range = unsafe { buf.get_unchecked(true_offset..(true_offset.wrapping_add(size))) };
        Ok(f(range))
    }

    /// Load N bytes from the given offset.
    #[inline(always)]
    pub fn load_range_const<const N: usize>(&mut self, offset: usize) -> Result<[u8; N], VMError> {
        let new_size = offset.checked_add(N).ok_or(OutOfBounds)?;
        self.resize(new_size)?;

        let true_offset = offset.checked_add(self.current_base).ok_or(OutOfBounds)?;

        let buf = self.buffer.borrow();
        // SAFETY: resize already makes sure bounds are correct.
        #[allow(unsafe_code)]
        unsafe {
            Ok(*buf
                .get_unchecked(true_offset..(true_offset.wrapping_add(N)))
                .as_ptr()
                .cast::<[u8; N]>())
        }
    }

    /// Load a word from at the given offset.
    #[inline(always)]
    pub fn load_word(&mut self, offset: usize) -> Result<U256, VMError> {
        let value: [u8; 32] = self.load_range_const(offset)?;
        Ok(u256_from_big_endian_const(value))
    }

    /// Stores the given data and data size at the given offset.
    ///
    /// Internal use.
    #[inline(always)]
    fn store(&self, data: &[u8], at_offset: usize, data_size: usize) -> Result<(), VMError> {
        if data_size == 0 {
            return Ok(());
        }

        let real_offset = self.current_base.wrapping_add(at_offset);

        let mut buffer = self.buffer.borrow_mut();

        let real_data_size = data_size.min(data.len());

        // SAFETY: Used internally, resize always called before this function.
        #[allow(clippy::indexing_slicing, clippy::arithmetic_side_effects)]
        #[allow(unsafe_code)]
        unsafe {
            std::ptr::copy_nonoverlapping(
                data.get_unchecked(..real_data_size).as_ptr(),
                buffer
                    .get_unchecked_mut(real_offset..(real_offset + real_data_size))
                    .as_mut_ptr(),
                real_data_size,
            );
        }

        Ok(())
    }

    /// Stores the given data at the given offset.
    #[inline(always)]
    pub fn store_data(&mut self, offset: usize, data: &[u8]) -> Result<(), VMError> {
        if data.is_empty() {
            return Ok(());
        }
        let new_size = offset.checked_add(data.len()).ok_or(OutOfBounds)?;
        self.resize(new_size)?;
        self.store(data, offset, data.len())
    }

    /// Stores data and zero-pads up to total_size at the given offset.
    #[inline(always)]
    pub fn store_data_zero_padded(
        &mut self,
        offset: usize,
        data: &[u8],
        total_size: usize,
    ) -> Result<(), VMError> {
        if total_size == 0 {
            return Ok(());
        }

        let new_size = offset.checked_add(total_size).ok_or(OutOfBounds)?;
        self.resize(new_size)?;

        let copy_size = data.len().min(total_size);
        if copy_size > 0 {
            self.store(data, offset, copy_size)?;
        }

        #[allow(clippy::arithmetic_side_effects)]
        if copy_size < total_size {
            // SAFETY: copy_size < total_size and offset + total_size didn't overflow (checked above),
            // so offset + copy_size cannot overflow.
            let zero_offset = offset.wrapping_add(copy_size);
            let zero_size = total_size - copy_size;
            let real_offset = self.current_base.wrapping_add(zero_offset);
            let mut buffer = self.buffer.borrow_mut();

            // resize ensures bounds are correct
            #[expect(unsafe_code)]
            unsafe {
                buffer
                    .get_unchecked_mut(real_offset..real_offset.wrapping_add(zero_size))
                    .fill(0);
            }
        }

        Ok(())
    }

    /// Stores a word at the given offset, resizing memory if needed.
    #[inline(always)]
    pub fn store_word(&mut self, offset: usize, word: U256) -> Result<(), VMError> {
        let new_size: usize = offset
            .checked_add(WORD_SIZE_IN_BYTES_USIZE)
            .ok_or(OutOfBounds)?;

        self.resize(new_size)?;
        self.store(&u256_to_big_endian(word), offset, WORD_SIZE_IN_BYTES_USIZE)?;
        Ok(())
    }

    /// Copies memory within 2 offsets. Like a memmove.
    ///
    /// Resizes if needed, because one can copy from "expanded memory", which is initialized with zeroes.
    pub fn copy_within(
        &mut self,
        from_offset: usize,
        to_offset: usize,
        size: usize,
    ) -> Result<(), VMError> {
        if size == 0 {
            return Ok(());
        }

        self.resize(
            to_offset
                .max(from_offset)
                .checked_add(size)
                .ok_or(InternalError::Overflow)?,
        )?;

        let true_from_offset = from_offset
            .checked_add(self.current_base)
            .ok_or(OutOfBounds)?;

        let true_to_offset = to_offset
            .checked_add(self.current_base)
            .ok_or(OutOfBounds)?;
        let mut buffer = self.buffer.borrow_mut();

        buffer.copy_within(
            true_from_offset
                ..(true_from_offset
                    .checked_add(size)
                    .ok_or(InternalError::Overflow)?),
            true_to_offset,
        );

        Ok(())
    }

    #[inline(always)]
    pub fn store_zeros(&mut self, offset: usize, size: usize) -> Result<(), VMError> {
        if size == 0 {
            return Ok(());
        }

        let new_size = offset.checked_add(size).ok_or(OutOfBounds)?;
        self.resize(new_size)?;

        let real_offset = self.current_base.wrapping_add(offset);
        let mut buffer = self.buffer.borrow_mut();

        // resize ensures bounds are correct
        #[expect(unsafe_code)]
        unsafe {
            buffer
                .get_unchecked_mut(real_offset..(real_offset.wrapping_add(size)))
                .fill(0);
        }

        Ok(())
    }
}

impl Default for Memory {
    fn default() -> Self {
        Self::new()
    }
}

/// When a memory expansion is triggered, only the additional bytes of memory
/// must be paid for.
#[inline]
pub fn expansion_cost(new_memory_size: usize, current_memory_size: usize) -> Result<u64, VMError> {
    let cost = if new_memory_size <= current_memory_size {
        0
    } else {
        // We already know new_memory_size > current_memory_size,
        // and cost(x) > cost(y) where x > y, so cost should not underflow.
        cost(new_memory_size)?.wrapping_sub(cost(current_memory_size)?)
    };
    Ok(cost)
}

/// The total cost for a given memory size.
/// Gas cost should always be computed in u64
#[inline]
fn cost(memory_size: usize) -> Result<u64, VMError> {
    let memory_size = u64::try_from(memory_size).map_err(|_| InternalError::TypeConversion)?;

    // memory size measured in 32 byte words
    let words = memory_size.div_ceil(WORD_SIZE_IN_BYTES_U64);

    // Cost(words) ≈ floor(words^2 / q) + 3 * words
    // For this to overflow memory size in words should be 2^32, which is impossible.
    #[expect(clippy::arithmetic_side_effects)]
    let gas_cost = words * words / MEMORY_EXPANSION_QUOTIENT + 3 * words;

    Ok(gas_cost)
}

#[inline]
pub fn calculate_memory_size(offset: usize, size: usize) -> Result<usize, VMError> {
    if size == 0 {
        return Ok(0);
    }

    offset
        .checked_add(size)
        .and_then(|sum| sum.checked_next_multiple_of(WORD_SIZE_IN_BYTES_USIZE))
        .ok_or(OutOfBounds.into())
}