Skip to main content

ethrex_common/types/
account.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use bytes::{BufMut, Bytes, BytesMut};
5use ethereum_types::{H256, U256};
6use ethrex_crypto::{Crypto, NativeCrypto};
7use ethrex_trie::Trie;
8use rustc_hash::FxHashMap;
9use serde::{Deserialize, Serialize};
10
11use ethrex_rlp::{
12    decode::RLPDecode,
13    encode::RLPEncode,
14    error::RLPDecodeError,
15    structs::{Decoder, Encoder},
16};
17
18use super::GenesisAccount;
19use crate::constants::{EMPTY_KECCAK_HASH, EMPTY_TRIE_HASH};
20
21std::thread_local! {
22    /// Shared empty jumpdest bitmap. `Code::default()` and any bytecode without a
23    /// `JUMPDEST` clone this (a refcount bump) instead of allocating a fresh empty
24    /// `Arc` header each time. This matters because the per-tx `Code::default()`
25    /// placeholder and every EOA / empty-code load would otherwise each allocate.
26    /// One per thread: with a single process-wide `Arc`, threads executing
27    /// transactions in parallel all bump the same reference count and contend on it.
28    static EMPTY_JUMPDESTS: Arc<[u8]> = Arc::from(Vec::new());
29}
30
31fn empty_jumpdests() -> Arc<[u8]> {
32    EMPTY_JUMPDESTS.with(Arc::clone)
33}
34
35/// The allocations an initcode [`Code`] is built in: its bytecode buffer and its
36/// jump-destination bitmap. A finished initcode hands them back through
37/// [`Code::into_initcode_buffer`], so the VM can keep them for the next CREATE instead of
38/// allocating new ones each time, which a zkVM guest's bump allocator never reclaims.
39#[derive(Debug, Default)]
40pub struct InitcodeBuffer {
41    bytecode: BytesMut,
42    jumpdests: Option<Arc<[u8]>>,
43}
44
45impl InitcodeBuffer {
46    /// Replaces the contents with `initcode`, with room for the padding
47    /// [`Code::from_initcode_buffer`] appends, so that appending it does not reallocate.
48    pub fn set(&mut self, initcode: &[u8]) {
49        let needed = initcode.len().saturating_add(BYTECODE_PADDING);
50        let capacity = self.bytecode.capacity();
51        if capacity < needed {
52            // A new buffer rather than this one grown, which would copy what it held. At
53            // least twice as large, so initcode that grows a little each CREATE allocates a
54            // few times rather than every time.
55            self.bytecode = BytesMut::with_capacity(needed.max(capacity.saturating_mul(2)));
56        } else {
57            self.bytecode.clear();
58        }
59        self.bytecode.extend_from_slice(initcode);
60    }
61
62    /// Empties the buffer, keeping its allocations.
63    pub fn clear(&mut self) {
64        self.bytecode.clear();
65    }
66
67    /// The initcode the buffer was last [set](InitcodeBuffer::set) to.
68    pub fn initcode(&self) -> &[u8] {
69        &self.bytecode
70    }
71
72    /// How many bytes of initcode and padding the buffer holds without reallocating.
73    pub fn capacity(&self) -> usize {
74        self.bytecode.capacity()
75    }
76
77    /// Whether the buffer holds any allocation worth keeping.
78    pub fn is_allocated(&self) -> bool {
79        self.bytecode.capacity() > 0 || self.jumpdests.is_some()
80    }
81}
82
83/// A zeroed jump-destination bitmap of `len` bytes, in one allocation: one built in a `Vec`
84/// is copied into a second allocation to become an `Arc`.
85fn zeroed_bitmap(len: usize) -> Arc<[u8]> {
86    std::iter::repeat_n(0, len).collect()
87}
88
89/// A zeroed jump-destination bitmap at least `len` bytes long: `scratch`, whole, when it is
90/// long enough and nothing else references it, which holds for the ones
91/// [`Code::into_initcode_buffer`] hands back, and a new one otherwise. A new one replacing a
92/// `scratch` too short is at least twice as long, as [`InitcodeBuffer::set`] does.
93fn zeroed_bitmap_in(scratch: Option<Arc<[u8]>>, len: usize) -> Arc<[u8]> {
94    let outgrown = match scratch {
95        Some(mut bitmap) if bitmap.len() >= len => {
96            if let Some(bits) = Arc::get_mut(&mut bitmap) {
97                // All of it, not just the first `len` bytes. JUMP trusts the bitmap alone, so
98                // a bit left past the end of the code would make a jump there valid; and the
99                // per-opcode scan only writes the bytes that hold a jump destination.
100                bits.fill(0);
101                return bitmap;
102            }
103            0
104        }
105        Some(bitmap) => bitmap.len(),
106        None => 0,
107    };
108    zeroed_bitmap(len.max(outgrown.saturating_mul(2)))
109}
110
111/// Sets the bit of every `JUMPDEST` in `code` that is not a `PUSH` immediate in `bitmap`,
112/// which is zeroed and `ceil(code.len() / 8)` bytes long. Returns whether it set any.
113/// See [`Code::compute_jumpdests`] for why the scan depends on the target.
114fn mark_jumpdests(code: &[u8], bitmap: &mut [u8]) -> bool {
115    #[cfg(any(
116        target_arch = "aarch64",
117        all(target_arch = "x86_64", target_feature = "ssse3")
118    ))]
119    let any = by_block::jumpdests(code, bitmap);
120    #[cfg(not(any(
121        target_arch = "aarch64",
122        all(target_arch = "x86_64", target_feature = "ssse3")
123    )))]
124    let any = jumpdests_by_opcode(code, bitmap);
125    any
126}
127
128/// Trailing STOP bytes appended to every bytecode so the dispatch loop can read
129/// the next opcode without a bounds check. 33 is the widest single-opcode advance
130/// (PUSH32: 1 opcode byte + 32 immediate bytes), so `pc` can never step past the
131/// padding regardless of which opcode sits at the last real byte.
132pub const BYTECODE_PADDING: usize = 33;
133
134#[derive(Clone, Debug, PartialEq, Eq, Hash)]
135pub struct Code {
136    // hash is only used for bytecodes stored in the DB, either for reading it from the DB
137    // or with the CODEHASH opcode, which needs an account address as argument and
138    // thus only accessed persisted bytecodes.
139    // We use a bogus H256::zero() value for initcodes as there is no way for the VM or
140    // endpoints to access that hash, saving one expensive Keccak hash.
141    pub hash: H256,
142    /// bytecode padded with 33 zeroes (STOP opcodes, due to PUSH32) to avoid checks on the hot path.
143    bytecode: Bytes,
144    /// The real bytecode length, needed for some opcodes, `bytecode` is padded with 33 STOPs to avoid checked adds on hot loop.
145    bytecode_len: usize,
146    /// One bit per bytecode byte, set when that offset holds a `JUMPDEST` that is not
147    /// part of a `PUSH` immediate. Costs `ceil(len / 8)` bytes regardless of how dense
148    /// the jump destinations are, and validating a jump is a bit test rather than a
149    /// search.
150    ///
151    /// Bytecode with no jump destination stores a zero-length bitmap (`EMPTY_JUMPDESTS`)
152    /// rather than an all-zero one, so this is not always `ceil(len / 8)` bytes long;
153    /// [`Code::is_valid_jumpdest`] reads a missing byte as "no jump destination". Initcode
154    /// built by [`Code::from_initcode_buffer`] is the exception: it keeps the bitmap it was
155    /// built in, which can be all zero, or longer than `ceil(len / 8)` and zero past it.
156    //
157    // `Arc<[u8]>` so cloning `Code` (hot: every message-call resolves and clones
158    // the callee's code) is a refcount bump instead of deep-copying the bitmap.
159    // Serializes via serde's `rc` feature (enabled workspace-wide).
160    jumpdests: Arc<[u8]>,
161}
162
163impl Code {
164    // SAFETY: hash will be stored as-is, so it either needs to match
165    // the real code hash (i.e. it was precomputed and we're reusing)
166    // or never be read (e.g. for initcode).
167    //
168    // `code` is the logical, unpadded bytecode; `BYTECODE_PADDING` STOP bytes are
169    // appended internally by `from_parts_unchecked`.
170    pub fn from_bytecode_unchecked(code: Bytes, hash: H256) -> Self {
171        let jumpdests = Self::compute_jumpdests(&code);
172        Self::from_parts_unchecked(hash, &code, jumpdests)
173    }
174
175    /// `code` is the logical, unpadded bytecode; `BYTECODE_PADDING` STOP bytes are
176    /// appended internally by `from_parts_unchecked`.
177    pub fn from_bytecode(code: Bytes, crypto: &dyn Crypto) -> Self {
178        let jumpdests = Self::compute_jumpdests(&code);
179        let hash = H256(crypto.keccak256(code.as_ref()));
180        Self::from_parts_unchecked(hash, &code, jumpdests)
181    }
182
183    /// Builds a `Code` from precomputed parts. The caller must guarantee `hash`
184    /// and `jumpdests` correspond to `code`; neither is recomputed or validated.
185    ///
186    /// `code` is the logical, unpadded bytecode: this function appends
187    /// `BYTECODE_PADDING` STOP bytes and records the original length in
188    /// `bytecode_len`. Never pass a pre-padded buffer, or the logical length and
189    /// every `JUMPDEST`/`PUSH` offset derived from it would be wrong.
190    pub fn from_parts_unchecked(hash: H256, code: &[u8], jumpdests: Arc<[u8]>) -> Self {
191        let bytecode_len = code.len();
192        let mut padded_code = Vec::with_capacity(bytecode_len + BYTECODE_PADDING);
193        padded_code.extend_from_slice(code);
194        padded_code.extend_from_slice(&[0u8; BYTECODE_PADDING]);
195        Self {
196            hash,
197            bytecode: Bytes::from_owner(padded_code),
198            bytecode_len,
199            jumpdests,
200        }
201    }
202
203    /// Builds initcode from the initcode `buffer` was [set](InitcodeBuffer::set) to, in the
204    /// buffer's allocations: the padding is appended in place and the buffer becomes the
205    /// bytecode, and the jump-destination bitmap reuses the buffer's when that is the right
206    /// size. [`Code::into_initcode_buffer`] hands them back for the next initcode. The hash is
207    /// the same placeholder any initcode gets.
208    ///
209    /// Unlike other code, initcode keeps the bitmap it was built in, so it can be handed back
210    /// with the bytecode: even when it marks nothing, instead of the shared empty one, and
211    /// even when it is longer than the code needs, zeroed past its end.
212    pub fn from_initcode_buffer(buffer: InitcodeBuffer) -> Self {
213        let InitcodeBuffer {
214            mut bytecode,
215            jumpdests,
216        } = buffer;
217        let bytecode_len = bytecode.len();
218        let bitmap_len = bytecode_len.div_ceil(8);
219        let mut jumpdests = zeroed_bitmap_in(jumpdests, bitmap_len);
220        // The bitmap can be longer than this code needs; the scan writes its first
221        // `bitmap_len` bytes, and the rest stay zero.
222        mark_jumpdests(&bytecode, &mut Arc::make_mut(&mut jumpdests)[..bitmap_len]);
223        bytecode.extend_from_slice(&[0u8; BYTECODE_PADDING]);
224        Self {
225            hash: H256::zero(),
226            bytecode: bytecode.freeze(),
227            bytecode_len,
228            jumpdests,
229        }
230    }
231
232    /// Hands back the allocations of initcode built by [`Code::from_initcode_buffer`], each
233    /// only when nothing else references it. The bytecode buffer comes back empty, so handing
234    /// back any other `Code`'s is harmless too: no stale bytecode can be built from again.
235    pub fn into_initcode_buffer(self) -> InitcodeBuffer {
236        let mut bytecode = self.bytecode.try_into_mut().unwrap_or_default();
237        bytecode.clear();
238        let mut jumpdests = self.jumpdests;
239        let unique = Arc::get_mut(&mut jumpdests).is_some();
240        InitcodeBuffer {
241            bytecode,
242            jumpdests: unique.then_some(jumpdests),
243        }
244    }
245
246    /// Builds the [`Code::jumpdests`] bitmap: the bit of every `JUMPDEST` that is not a
247    /// `PUSH` immediate.
248    ///
249    /// On aarch64, and on x86_64 with SSSE3, this runs without a data-dependent branch
250    /// (see `by_block`), because a scan that branches on each opcode stalls on every
251    /// misprediction, and random bytecode mispredicts on most bytes. execution-specs#3631
252    /// builds such initcode on purpose. Other targets are mostly the zkVM guests, which
253    /// have no branch predictor and would only pay for the extra instructions, so they
254    /// keep the plain scan (`jumpdests_by_opcode`).
255    pub fn compute_jumpdests(code: &[u8]) -> Arc<[u8]> {
256        // Even an empty `Arc` allocates its reference counts.
257        if code.is_empty() {
258            return empty_jumpdests();
259        }
260        let mut bitmap = zeroed_bitmap(code.len().div_ceil(8));
261        let any = mark_jumpdests(code, Arc::make_mut(&mut bitmap));
262        // Share the single empty bitmap for jumpless bytecode (very common: EOAs,
263        // tiny contracts) so we don't keep an all-zero map; `is_valid_jumpdest`
264        // reads a missing byte as "no jump destination".
265        if any { bitmap } else { empty_jumpdests() }
266    }
267
268    /// Whether `offset` is a valid jump destination, i.e. it holds a `JUMPDEST` that is
269    /// not part of a `PUSH` immediate. Offsets past the bytecode are not valid.
270    #[inline]
271    pub fn is_valid_jumpdest(&self, offset: usize) -> bool {
272        self.jumpdests
273            .get(offset / 8)
274            .is_some_and(|byte| byte & (1 << (offset % 8)) != 0)
275    }
276
277    /// The raw [`Code::jumpdests`] bitmap, for persisting it alongside the bytecode.
278    #[inline]
279    pub fn jumpdests(&self) -> &[u8] {
280        &self.jumpdests
281    }
282
283    #[inline]
284    pub fn code(&self) -> &[u8] {
285        self.bytecode.get(..self.bytecode_len).unwrap_or_default()
286    }
287
288    #[inline]
289    pub fn code_bytes(&self) -> Bytes {
290        self.bytecode.slice(..self.bytecode_len)
291    }
292
293    #[inline]
294    pub fn len(&self) -> usize {
295        self.bytecode_len
296    }
297
298    #[inline]
299    pub fn is_empty(&self) -> bool {
300        self.bytecode_len == 0
301    }
302
303    /// Returns the padded bytecode buffer (real code + [`BYTECODE_PADDING`] trailing
304    /// STOPs) used by the opcode dispatch loop to read opcodes without bounds checks.
305    /// Use [`Code::code`] for the real, unpadded bytecode.
306    #[inline]
307    pub fn dispatch_buf(&self) -> &[u8] {
308        &self.bytecode
309    }
310
311    /// Estimates the size of the Code struct in bytes
312    /// (including stack size and heap allocation).
313    ///
314    /// Note: an estimate. It ignores allocator overhead and the `Arc`/`Bytes` control
315    /// blocks, so it slightly under-counts, and a shared allocation is attributed in
316    /// full to every entry holding it.
317    ///
318    /// # Returns
319    ///
320    /// usize - Estimated size in bytes
321    pub fn size(&self) -> usize {
322        let hash_size = size_of::<H256>();
323        let bytes_size = size_of::<Bytes>() + self.bytecode.len();
324        let bitmap_size = size_of::<Arc<[u8]>>() + self.jumpdests.len();
325        hash_size + bytes_size + bitmap_size
326    }
327}
328
329// Opcodes the jump destination analysis needs. The vm module defines them too, but
330// depending on it here would be circular.
331const OP_JUMPDEST: u8 = 0x5B;
332const OP_PUSH1: u8 = 0x60;
333const OP_PUSH32: u8 = 0x7F;
334
335/// Fills `bitmap` for `code` one opcode at a time and returns whether any bit is set.
336///
337/// The bits of a byte are accumulated in a register and written once the scan leaves
338/// that byte, which the monotonic `i` makes safe. Reading the bitmap back inside the
339/// loop instead would turn each `JUMPDEST` into a read-modify-write, and indexing it
340/// would put a bounds-check panic path in the loop body, which inhibits optimization
341/// of every iteration rather than only the ones that find a destination.
342#[cfg_attr(
343    any(
344        target_arch = "aarch64",
345        all(target_arch = "x86_64", target_feature = "ssse3")
346    ),
347    allow(dead_code)
348)]
349fn jumpdests_by_opcode(code: &[u8], bitmap: &mut [u8]) -> bool {
350    let mut any = false;
351    let mut current_byte = usize::MAX;
352    let mut bits = 0u8;
353    let mut i = 0;
354    while i < code.len() {
355        match code[i] {
356            OP_JUMPDEST => {
357                if i / 8 != current_byte {
358                    if let Some(byte) = bitmap.get_mut(current_byte) {
359                        *byte = bits;
360                    }
361                    current_byte = i / 8;
362                    bits = 0;
363                }
364                bits |= 1 << (i % 8);
365                any = true;
366            }
367            // PUSH1..PUSH32 are followed by 1..32 immediate bytes.
368            c @ OP_PUSH1..=OP_PUSH32 => i += usize::from(c - OP_PUSH1) + 1,
369            _ => (),
370        }
371        i += 1;
372    }
373    if let Some(byte) = bitmap.get_mut(current_byte) {
374        *byte = bits;
375    }
376    any
377}
378
379/// The jump destination analysis without a data-dependent branch, 64 bytes at a time.
380///
381/// Whether a byte is an opcode depends on every `PUSH` before it, so the natural scan
382/// branches on each opcode, and on random bytecode that branch mispredicts on most bytes.
383/// Here the work per block is the same whatever its bytes are:
384///
385/// 1. In each 16-byte group, the walks from all 16 bytes, each as if its byte were an
386///    opcode, advance at once until they leave the group (see [`group_walks`]).
387/// 2. The real walk enters the block where the previous block's walk left it. Where it
388///    leaves a group is where it enters the next one, so four dependent loads pick the
389///    walk of each group, and give where the walk enters the next block.
390#[cfg(any(
391    target_arch = "aarch64",
392    all(target_arch = "x86_64", target_feature = "ssse3")
393))]
394mod by_block {
395    use super::{OP_JUMPDEST, OP_PUSH1};
396    use lanes::Lanes;
397
398    /// Bytes per block, one `u64` of bitmap.
399    const BLOCK: usize = 64;
400    /// Bytes per group, one SIMD register.
401    const GROUP: usize = 16;
402
403    /// Fills `bitmap` for `code` and returns whether any bit is set.
404    pub(super) fn jumpdests(code: &[u8], bitmap: &mut [u8]) -> bool {
405        let mut walks = Walks::new();
406        let (blocks, tail) = code.as_chunks::<BLOCK>();
407        let mut carry = 0;
408        let mut any = 0;
409        // A full block fills exactly one 8-byte word of the bitmap.
410        for (block, word) in blocks.iter().zip(bitmap.as_chunks_mut::<8>().0) {
411            let valid = block_jumpdests(block, &mut carry, &mut walks);
412            *word = valid.to_le_bytes();
413            any |= valid;
414        }
415        if !tail.is_empty() {
416            // Zeros are STOPs, which are neither destinations nor PUSHes.
417            let mut padded = [0; BLOCK];
418            padded[..tail.len()].copy_from_slice(tail);
419            let valid = block_jumpdests(&padded, &mut carry, &mut walks);
420            let rest = &mut bitmap[blocks.len() * 8..];
421            rest.copy_from_slice(&valid.to_le_bytes()[..rest.len()]);
422            any |= valid;
423        }
424        any != 0
425    }
426
427    /// The walks of one block's bytes (see [`group_walks`]), by position in the block:
428    /// where each leaves its group, and which bytes of the group it lands on, the lower
429    /// 8 in `low_stops` and the upper 8 in `high_stops`.
430    ///
431    /// Positions from 64 on stand for the next block: they lead to themselves and land on
432    /// nothing, so a walk that has left the block stays where it is.
433    struct Walks {
434        exits: [u8; 2 * BLOCK],
435        low_stops: [u8; 2 * BLOCK],
436        high_stops: [u8; 2 * BLOCK],
437    }
438
439    impl Walks {
440        fn new() -> Self {
441            Self {
442                exits: core::array::from_fn(|i| i as u8),
443                low_stops: [0; 2 * BLOCK],
444                high_stops: [0; 2 * BLOCK],
445            }
446        }
447    }
448
449    /// The valid jump destinations of one block, bit `i` for byte `i`.
450    ///
451    /// `carry` is how many leading bytes of the block are immediates of a `PUSH` in the
452    /// previous block, and is updated for the next one.
453    #[inline(always)]
454    fn block_jumpdests(block: &[u8; BLOCK], carry: &mut usize, walks: &mut Walks) -> u64 {
455        let groups = block.as_chunks::<GROUP>().0;
456        let groups: [Lanes; BLOCK / GROUP] = core::array::from_fn(|g| Lanes::load(&groups[g]));
457        let jumpdests = Lanes::bits(groups.map(|bytes| bytes.eq(Lanes::splat(OP_JUMPDEST))));
458        for (g, bytes) in groups.into_iter().enumerate() {
459            let (exits, low_stops, high_stops) = group_walks(bytes);
460            // From here on, positions are relative to the block instead of the group.
461            let exits = exits.add(Lanes::splat((g * GROUP) as u8));
462            exits.store(&mut walks.exits.as_chunks_mut::<GROUP>().0[g]);
463            low_stops.store(&mut walks.low_stops.as_chunks_mut::<GROUP>().0[g]);
464            high_stops.store(&mut walks.high_stops.as_chunks_mut::<GROUP>().0[g]);
465        }
466        let mut at = *carry;
467        let mut opcodes = 0;
468        for _ in 0..BLOCK / GROUP {
469            // At most 96, 32 immediates past the block; the modulo drops the bounds checks.
470            let i = at % (2 * BLOCK);
471            let stops = u64::from(walks.low_stops[i]) | (u64::from(walks.high_stops[i]) << 8);
472            // Past the block there are no stops, so the shift only matters inside it.
473            let group_start = i & (BLOCK - GROUP);
474            opcodes |= stops << group_start;
475            at = usize::from(walks.exits[i]);
476        }
477        // Each load moves the walk past at least one more group, so it is now past the
478        // block, by as many bytes as the next block starts with immediates.
479        *carry = at - BLOCK;
480        jumpdests & opcodes
481    }
482
483    /// For each byte of a 16-byte group, the walk that starts if that byte is an opcode,
484    /// up to where it leaves the group: the position it leaves to, relative to the group
485    /// (16 to 48), and the bytes it lands on, bits 0 to 7 in the first mask and bits 8 to
486    /// 15 in the second.
487    ///
488    /// All 16 walks advance together by pointer doubling: each round, a walk that is still
489    /// in the group takes as many steps again by continuing with the walk of the byte it
490    /// is at, which a table lookup of every lane (TBL on aarch64, PSHUFB on x86_64) reads.
491    /// A step moves at least one byte, so four rounds (16 steps) take every walk out of
492    /// the group.
493    #[inline(always)]
494    fn group_walks(bytes: Lanes) -> (Lanes, Lanes, Lanes) {
495        const POSITIONS_PLUS_ONE: [u8; GROUP] =
496            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
497        const LOW_POSITION_BITS: [u8; GROUP] =
498            [1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0];
499        const HIGH_POSITION_BITS: [u8; GROUP] =
500            [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 8, 16, 32, 64, 128];
501        // PUSH1..PUSH32 are exactly the bytes 0b011x_xxxx, with `byte - PUSH1 + 1`
502        // immediates.
503        let is_push = bytes.and(Lanes::splat(0xE0)).eq(Lanes::splat(OP_PUSH1));
504        let immediates = is_push.and(bytes.sub(Lanes::splat(OP_PUSH1 - 1)));
505        // One step, past the opcode and its immediates.
506        let mut exits = Lanes::load(&POSITIONS_PLUS_ONE).add(immediates);
507        let mut low_stops = Lanes::load(&LOW_POSITION_BITS);
508        let mut high_stops = Lanes::load(&HIGH_POSITION_BITS);
509        // The lookups read zero for a walk that has left the group, so its stops stay as
510        // they are, and `max` keeps its exit, while a walk still inside moves ahead.
511        // Stops in the lower 8 bytes are a walk's first 8 at most, so the last round can
512        // skip them.
513        for round in 0..4 {
514            if round < 3 {
515                low_stops = low_stops.or(low_stops.lookup(exits));
516            }
517            high_stops = high_stops.or(high_stops.lookup(exits));
518            exits = exits.max(exits.lookup(exits));
519        }
520        (exits, low_stops, high_stops)
521    }
522
523    #[cfg(target_arch = "aarch64")]
524    mod lanes {
525        use core::arch::aarch64::*;
526
527        /// 16 bytes in a NEON register.
528        #[derive(Clone, Copy)]
529        pub(super) struct Lanes(uint8x16_t);
530
531        // SAFETY (every `unsafe` below): NEON is part of the aarch64 baseline, and the
532        // loads and stores go through a reference to exactly 16 bytes, with no alignment
533        // requirement.
534        impl Lanes {
535            #[inline(always)]
536            pub(super) fn load(bytes: &[u8; 16]) -> Self {
537                unsafe { Self(vld1q_u8(bytes.as_ptr())) }
538            }
539
540            #[inline(always)]
541            pub(super) fn store(self, out: &mut [u8; 16]) {
542                unsafe { vst1q_u8(out.as_mut_ptr(), self.0) }
543            }
544
545            #[inline(always)]
546            pub(super) fn splat(byte: u8) -> Self {
547                unsafe { Self(vdupq_n_u8(byte)) }
548            }
549
550            #[inline(always)]
551            pub(super) fn and(self, other: Self) -> Self {
552                unsafe { Self(vandq_u8(self.0, other.0)) }
553            }
554
555            #[inline(always)]
556            pub(super) fn or(self, other: Self) -> Self {
557                unsafe { Self(vorrq_u8(self.0, other.0)) }
558            }
559
560            #[inline(always)]
561            pub(super) fn add(self, other: Self) -> Self {
562                unsafe { Self(vaddq_u8(self.0, other.0)) }
563            }
564
565            #[inline(always)]
566            pub(super) fn sub(self, other: Self) -> Self {
567                unsafe { Self(vsubq_u8(self.0, other.0)) }
568            }
569
570            /// All ones in the lanes that are equal, zero in the others.
571            #[inline(always)]
572            pub(super) fn eq(self, other: Self) -> Self {
573                unsafe { Self(vceqq_u8(self.0, other.0)) }
574            }
575
576            #[inline(always)]
577            pub(super) fn max(self, other: Self) -> Self {
578                unsafe { Self(vmaxq_u8(self.0, other.0)) }
579            }
580
581            /// Lane `i` of `self` for each lane `i` of `indices` below 16, zero for the rest.
582            #[inline(always)]
583            pub(super) fn lookup(self, indices: Self) -> Self {
584                unsafe { Self(vqtbl1q_u8(self.0, indices.0)) }
585            }
586
587            /// The top bit of every lane of four registers of all-ones or zero lanes.
588            ///
589            /// NEON has no instruction that gathers one bit per byte, so each lane keeps
590            /// the bit of its position within 8 bytes, and three rounds of pairwise adds
591            /// pack them into one `u64`.
592            #[inline(always)]
593            pub(super) fn bits(masks: [Self; 4]) -> u64 {
594                unsafe {
595                    let position_bits = vreinterpretq_u8_u64(vdupq_n_u64(0x8040_2010_0804_0201));
596                    let [a, b, c, d] = masks.map(|m| vandq_u8(m.0, position_bits));
597                    let quarters = vpaddq_u8(vpaddq_u8(a, b), vpaddq_u8(c, d));
598                    vgetq_lane_u64::<0>(vreinterpretq_u64_u8(vpaddq_u8(quarters, quarters)))
599                }
600            }
601        }
602    }
603
604    #[cfg(target_arch = "x86_64")]
605    mod lanes {
606        use core::arch::x86_64::*;
607
608        /// 16 bytes in an SSE register.
609        #[derive(Clone, Copy)]
610        pub(super) struct Lanes(__m128i);
611
612        // SAFETY (every `unsafe` below): SSE2 is part of the x86_64 baseline, SSSE3 is
613        // enabled for this build (see the `cfg` on `by_block`), and the loads and stores
614        // go through a reference to exactly 16 bytes, with no alignment requirement.
615        impl Lanes {
616            #[inline(always)]
617            pub(super) fn load(bytes: &[u8; 16]) -> Self {
618                unsafe { Self(_mm_loadu_si128(bytes.as_ptr().cast())) }
619            }
620
621            #[inline(always)]
622            pub(super) fn store(self, out: &mut [u8; 16]) {
623                unsafe { _mm_storeu_si128(out.as_mut_ptr().cast(), self.0) }
624            }
625
626            #[inline(always)]
627            pub(super) fn splat(byte: u8) -> Self {
628                unsafe { Self(_mm_set1_epi8(byte as i8)) }
629            }
630
631            #[inline(always)]
632            pub(super) fn and(self, other: Self) -> Self {
633                unsafe { Self(_mm_and_si128(self.0, other.0)) }
634            }
635
636            #[inline(always)]
637            pub(super) fn or(self, other: Self) -> Self {
638                unsafe { Self(_mm_or_si128(self.0, other.0)) }
639            }
640
641            #[inline(always)]
642            pub(super) fn add(self, other: Self) -> Self {
643                unsafe { Self(_mm_add_epi8(self.0, other.0)) }
644            }
645
646            #[inline(always)]
647            pub(super) fn sub(self, other: Self) -> Self {
648                unsafe { Self(_mm_sub_epi8(self.0, other.0)) }
649            }
650
651            /// All ones in the lanes that are equal, zero in the others.
652            #[inline(always)]
653            pub(super) fn eq(self, other: Self) -> Self {
654                unsafe { Self(_mm_cmpeq_epi8(self.0, other.0)) }
655            }
656
657            #[inline(always)]
658            pub(super) fn max(self, other: Self) -> Self {
659                unsafe { Self(_mm_max_epu8(self.0, other.0)) }
660            }
661
662            /// Lane `i` of `self` for each lane `i` of `indices` below 16, zero for the rest
663            /// up to 143.
664            #[inline(always)]
665            pub(super) fn lookup(self, indices: Self) -> Self {
666                // PSHUFB zeroes the lanes whose index has its top bit set and otherwise
667                // uses the index's low 4 bits. Adding 0x70 sets the top bit of 16..=143
668                // and keeps the low 4 bits of 0..=15.
669                unsafe {
670                    let indices = _mm_add_epi8(indices.0, _mm_set1_epi8(0x70));
671                    Self(_mm_shuffle_epi8(self.0, indices))
672                }
673            }
674
675            /// The top bit of every lane of four registers of all-ones or zero lanes.
676            #[inline(always)]
677            pub(super) fn bits(masks: [Self; 4]) -> u64 {
678                masks.iter().enumerate().fold(0, |bits, (i, m)| {
679                    let lanes = unsafe { _mm_movemask_epi8(m.0) } as u16;
680                    bits | (u64::from(lanes) << (16 * i))
681                })
682            }
683        }
684    }
685}
686
687/// Serde shadow for [`Code`]. Stores the *logical* (unpadded) bytecode so the
688/// padding is never part of the serialized form. Deserialization re-pads through
689/// [`Code::from_parts_unchecked`], which keeps the dispatch-loop invariant (every
690/// `Code` is padded with [`BYTECODE_PADDING`] trailing STOPs) sound regardless of
691/// where the bytes came from. Deserializing the padded buffer directly would
692/// otherwise let unpadded input through and cause OOB reads during execution.
693/// The jump destinations are deliberately absent: they are a pure function of the
694/// bytecode, so carrying them would put a derived value in the wire format of everything
695/// that embeds a `Code` (notably `AccountUpdate`, which the L2 rollup store persists with
696/// bincode) and couple that format to how they happen to be represented.
697/// Wire form of [`Code`]. Jump destinations are recomputed from `code` on
698/// deserialize, never read from here — but the `jump_targets` field is kept so
699/// the layout stays byte-identical to the pre-bitmap `Code` serialization.
700/// `Code` is embedded in `AccountUpdate`, which is persisted with bincode (a
701/// non-self-describing, positional codec) in the L2 rollup store; dropping the
702/// field would shift every following field and make existing rows undecodable.
703/// It is always serialized empty and ignored on read.
704#[derive(Serialize, Deserialize)]
705struct CodeSerde {
706    hash: H256,
707    code: Bytes,
708    jump_targets: Arc<[u32]>,
709}
710
711impl Serialize for Code {
712    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
713        CodeSerde {
714            hash: self.hash,
715            code: self.code_bytes(),
716            jump_targets: Arc::from([]),
717        }
718        .serialize(serializer)
719    }
720}
721
722impl<'de> Deserialize<'de> for Code {
723    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
724        // `jump_targets` is read only to consume its bytes (layout compatibility);
725        // the bitmap is always recomputed from `code`.
726        let CodeSerde {
727            hash,
728            code,
729            jump_targets: _,
730        } = CodeSerde::deserialize(deserializer)?;
731        Ok(Self::from_parts_unchecked(
732            hash,
733            &code,
734            Self::compute_jumpdests(&code),
735        ))
736    }
737}
738
739#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
740pub struct CodeMetadata {
741    pub length: u64,
742}
743
744#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
745pub struct Account {
746    pub info: AccountInfo,
747    pub code: Code,
748    pub storage: FxHashMap<H256, U256>,
749}
750
751#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq, Hash)]
752pub struct AccountInfo {
753    pub code_hash: H256,
754    pub balance: U256,
755    pub nonce: u64,
756}
757
758#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
759pub struct AccountState {
760    pub nonce: u64,
761    pub balance: U256,
762    pub storage_root: H256,
763    pub code_hash: H256,
764}
765
766/// A slim codec for an [`AccountState`].
767///
768/// The slim codec will optimize both the [storage root](AccountState::storage_root) and the
769/// [code hash](AccountState::code_hash)'s encoding so that it does not take space when empty.
770///
771/// The correct way to use it is to wrap the [`AccountState`] and encode it using this codec, and
772/// not to store the codec as a field in a struct.
773#[derive(Clone, Copy, Debug, Default, PartialEq)]
774pub struct AccountStateSlimCodec(pub AccountState);
775
776impl Default for AccountInfo {
777    fn default() -> Self {
778        Self {
779            code_hash: *EMPTY_KECCAK_HASH,
780            balance: Default::default(),
781            nonce: Default::default(),
782        }
783    }
784}
785
786impl Default for AccountState {
787    fn default() -> Self {
788        Self {
789            nonce: Default::default(),
790            balance: Default::default(),
791            storage_root: *EMPTY_TRIE_HASH,
792            code_hash: *EMPTY_KECCAK_HASH,
793        }
794    }
795}
796
797impl Default for Code {
798    fn default() -> Self {
799        Self {
800            bytecode: Bytes::from_static(&[0u8; BYTECODE_PADDING]),
801            bytecode_len: 0,
802            hash: *EMPTY_KECCAK_HASH,
803            jumpdests: empty_jumpdests(),
804        }
805    }
806}
807
808impl From<GenesisAccount> for Account {
809    fn from(genesis: GenesisAccount) -> Self {
810        let code = Code::from_bytecode(genesis.code, &NativeCrypto);
811        Self {
812            info: AccountInfo {
813                code_hash: code.hash,
814                balance: genesis.balance,
815                nonce: genesis.nonce,
816            },
817            code,
818            storage: genesis
819                .storage
820                .iter()
821                .map(|(k, v)| (H256(k.to_big_endian()), *v))
822                .collect(),
823        }
824    }
825}
826
827pub fn code_hash(code: &Bytes, crypto: &dyn Crypto) -> H256 {
828    H256(crypto.keccak256(code.as_ref()))
829}
830
831/// EIP-7702 delegation designation: an EOA whose code is `0xef0100 || address`.
832/// See <https://eips.ethereum.org/EIPS/eip-7702>.
833pub const EIP7702_DELEGATION_PREFIX: [u8; 3] = [0xef, 0x01, 0x00];
834/// Total byte length of an EIP-7702 delegation designation: 3-byte prefix
835/// plus the 20-byte target address.
836pub const EIP7702_DELEGATED_CODE_LEN: usize = 23;
837
838/// Returns true iff `code` is a valid EIP-7702 delegation designation
839/// (exactly 23 bytes, prefixed with `0xef0100`).
840pub fn is_eip7702_delegation(code: &[u8]) -> bool {
841    code.len() == EIP7702_DELEGATED_CODE_LEN && code.starts_with(&EIP7702_DELEGATION_PREFIX)
842}
843
844impl RLPEncode for AccountInfo {
845    fn encode(&self, buf: &mut dyn bytes::BufMut) {
846        Encoder::new(buf)
847            .encode_field(&self.code_hash)
848            .encode_field(&self.balance)
849            .encode_field(&self.nonce)
850            .finish();
851    }
852}
853
854impl RLPDecode for AccountInfo {
855    fn decode_unfinished(rlp: &[u8]) -> Result<(AccountInfo, &[u8]), RLPDecodeError> {
856        let decoder = Decoder::new(rlp)?;
857        let (code_hash, decoder) = decoder.decode_field("code_hash")?;
858        let (balance, decoder) = decoder.decode_field("balance")?;
859        let (nonce, decoder) = decoder.decode_field("nonce")?;
860        let account_info = AccountInfo {
861            code_hash,
862            balance,
863            nonce,
864        };
865        Ok((account_info, decoder.finish()?))
866    }
867}
868
869impl RLPEncode for AccountState {
870    fn encode(&self, buf: &mut dyn bytes::BufMut) {
871        Encoder::new(buf)
872            .encode_field(&self.nonce)
873            .encode_field(&self.balance)
874            .encode_field(&self.storage_root)
875            .encode_field(&self.code_hash)
876            .finish();
877    }
878}
879
880impl RLPDecode for AccountState {
881    fn decode_unfinished(rlp: &[u8]) -> Result<(AccountState, &[u8]), RLPDecodeError> {
882        let decoder = Decoder::new(rlp)?;
883        let (nonce, decoder) = decoder.decode_field("nonce")?;
884        let (balance, decoder) = decoder.decode_field("balance")?;
885        let (storage_root, decoder) = decoder.decode_field("storage_root")?;
886        let (code_hash, decoder) = decoder.decode_field("code_hash")?;
887        let state = AccountState {
888            nonce,
889            balance,
890            storage_root,
891            code_hash,
892        };
893        Ok((state, decoder.finish()?))
894    }
895}
896
897impl RLPEncode for AccountStateSlimCodec {
898    fn encode(&self, buf: &mut dyn BufMut) {
899        struct StorageRootCodec<'a>(&'a H256);
900        impl RLPEncode for StorageRootCodec<'_> {
901            fn encode(&self, buf: &mut dyn BufMut) {
902                let data = if *self.0 != *EMPTY_TRIE_HASH {
903                    self.0.as_bytes()
904                } else {
905                    &[]
906                };
907
908                data.encode(buf);
909            }
910        }
911
912        struct CodeHashCodec<'a>(&'a H256);
913        impl RLPEncode for CodeHashCodec<'_> {
914            fn encode(&self, buf: &mut dyn BufMut) {
915                let data = if *self.0 != *EMPTY_KECCAK_HASH {
916                    self.0.as_bytes()
917                } else {
918                    &[]
919                };
920
921                data.encode(buf);
922            }
923        }
924
925        Encoder::new(buf)
926            .encode_field(&self.0.nonce)
927            .encode_field(&self.0.balance)
928            .encode_field(&StorageRootCodec(&self.0.storage_root))
929            .encode_field(&CodeHashCodec(&self.0.code_hash))
930            .finish();
931    }
932}
933
934impl RLPDecode for AccountStateSlimCodec {
935    fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
936        struct StorageRootCodec(H256);
937        impl RLPDecode for StorageRootCodec {
938            fn decode_unfinished(mut rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
939                let value = match rlp.split_off_first() {
940                    Some(0x80) => *EMPTY_TRIE_HASH,
941                    Some(0xA0) => {
942                        let data;
943                        (data, rlp) = rlp
944                            .split_first_chunk::<32>()
945                            .ok_or(RLPDecodeError::InvalidLength)?;
946                        H256(*data)
947                    }
948                    _ => return Err(RLPDecodeError::InvalidLength),
949                };
950
951                Ok((Self(value), rlp))
952            }
953        }
954
955        struct CodeHashCodec(H256);
956        impl RLPDecode for CodeHashCodec {
957            fn decode_unfinished(mut rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
958                let value = match rlp.split_off_first() {
959                    Some(0x80) => *EMPTY_KECCAK_HASH,
960                    Some(0xA0) => {
961                        let data;
962                        (data, rlp) = rlp
963                            .split_first_chunk::<32>()
964                            .ok_or(RLPDecodeError::InvalidLength)?;
965                        H256(*data)
966                    }
967                    _ => return Err(RLPDecodeError::InvalidLength),
968                };
969
970                Ok((Self(value), rlp))
971            }
972        }
973
974        let decoder = Decoder::new(rlp)?;
975        let (nonce, decoder) = decoder.decode_field("nonce")?;
976        let (balance, decoder) = decoder.decode_field("balance")?;
977        let (StorageRootCodec(storage_root), decoder) = decoder.decode_field("storage_root")?;
978        let (CodeHashCodec(code_hash), decoder) = decoder.decode_field("code_hash")?;
979
980        Ok((
981            Self(AccountState {
982                nonce,
983                balance,
984                storage_root,
985                code_hash,
986            }),
987            decoder.finish()?,
988        ))
989    }
990}
991
992pub fn compute_storage_root(storage: &BTreeMap<U256, U256>, crypto: &dyn Crypto) -> H256 {
993    let iter = storage.iter().filter_map(|(k, v)| {
994        (!v.is_zero()).then_some((
995            crypto.keccak256(&k.to_big_endian()).to_vec(),
996            v.encode_to_vec(),
997        ))
998    });
999    Trie::compute_hash_from_unsorted_iter(iter, crypto)
1000}
1001
1002impl From<&GenesisAccount> for AccountState {
1003    fn from(value: &GenesisAccount) -> Self {
1004        AccountState {
1005            nonce: value.nonce,
1006            balance: value.balance,
1007            storage_root: compute_storage_root(&value.storage, &NativeCrypto),
1008            code_hash: code_hash(&value.code, &NativeCrypto),
1009        }
1010    }
1011}
1012
1013impl Account {
1014    pub fn new(balance: U256, code: Code, nonce: u64, storage: FxHashMap<H256, U256>) -> Self {
1015        Self {
1016            info: AccountInfo {
1017                balance,
1018                code_hash: code.hash,
1019                nonce,
1020            },
1021            code,
1022            storage,
1023        }
1024    }
1025}
1026
1027impl AccountInfo {
1028    pub fn is_empty(&self) -> bool {
1029        self.balance.is_zero() && self.nonce == 0 && self.code_hash == *EMPTY_KECCAK_HASH
1030    }
1031}
1032
1033#[cfg(test)]
1034mod test {
1035    use std::str::FromStr;
1036
1037    use super::*;
1038
1039    // Pre-bitmap on-wire layout of `Code`: `{hash, code, jump_targets}`. `AccountUpdate`
1040    // embeds `Code` and is persisted with bincode (positional) in the L2 rollup store,
1041    // so a row written before the bitmap change carries a non-empty `jump_targets`.
1042    #[derive(serde::Serialize)]
1043    struct OldCodeSerde {
1044        hash: H256,
1045        code: Bytes,
1046        jump_targets: Vec<u32>,
1047    }
1048
1049    // `Code` is never persisted alone — it sits inside `AccountUpdate`, which has fields
1050    // AFTER `code`. These wrappers mirror that: a field following the code. A standalone
1051    // `Code` would tolerate trailing bytes, hiding the bug; only an embedded field
1052    // exposes the positional shift.
1053    #[derive(serde::Serialize)]
1054    struct OldWrap {
1055        code: OldCodeSerde,
1056        tail: u64,
1057    }
1058    #[derive(serde::Deserialize)]
1059    struct NewWrap {
1060        code: Code,
1061        tail: u64,
1062    }
1063
1064    // A row serialized under the old three-field layout must still decode with the field
1065    // following `code` intact: the current `Code` deserializer reads and discards
1066    // `jump_targets`, keeping the layout aligned. Without the retained field, bincode
1067    // reads `tail` from the `jump_targets` bytes and every following field is corrupt —
1068    // exactly the `store_account_updates_by_block_number` break.
1069    #[test]
1070    fn embedded_code_decodes_an_old_layout_bincode_row() {
1071        // PUSH1 0x00 JUMPDEST STOP — offset 2 is a real JUMPDEST, offset 1 a PUSH immediate.
1072        let bytecode = Bytes::from(vec![0x60, 0x00, 0x5b, 0x00]);
1073        let hash = H256::from_low_u64_be(0xabc);
1074        const SENTINEL: u64 = 0x0123_4567_89ab_cdef;
1075        let old = OldWrap {
1076            code: OldCodeSerde {
1077                hash,
1078                code: bytecode.clone(),
1079                jump_targets: vec![2], // non-empty, as an old row would hold
1080            },
1081            tail: SENTINEL,
1082        };
1083        let bytes = bincode::serialize(&old).expect("serialize old layout");
1084
1085        let decoded: NewWrap = bincode::deserialize(&bytes).expect("decode old row under new Code");
1086        assert_eq!(decoded.code.hash, hash);
1087        assert_eq!(decoded.code.code_bytes(), bytecode);
1088        // The field after `code` must survive — this is what breaks if the layout shifts.
1089        assert_eq!(
1090            decoded.tail, SENTINEL,
1091            "field after Code corrupted by layout shift"
1092        );
1093        // Jump destinations recomputed from code, not read from the row.
1094        assert!(decoded.code.is_valid_jumpdest(2));
1095        assert!(!decoded.code.is_valid_jumpdest(1));
1096    }
1097
1098    #[test]
1099    fn test_code_hash() {
1100        let empty_code = Bytes::new();
1101        let hash = code_hash(&empty_code, &NativeCrypto);
1102        assert_eq!(
1103            hash,
1104            H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
1105                .unwrap()
1106        )
1107    }
1108
1109    #[test]
1110    fn test_is_eip7702_delegation_valid() {
1111        // 0xef0100 || 20-byte address
1112        let mut code = Vec::with_capacity(23);
1113        code.extend_from_slice(&EIP7702_DELEGATION_PREFIX);
1114        code.extend_from_slice(&[0x42; 20]);
1115        assert!(is_eip7702_delegation(&code));
1116    }
1117
1118    #[test]
1119    fn test_is_eip7702_delegation_rejects_empty() {
1120        assert!(!is_eip7702_delegation(&[]));
1121    }
1122
1123    #[test]
1124    fn test_is_eip7702_delegation_rejects_short() {
1125        // Prefix only, no address.
1126        assert!(!is_eip7702_delegation(&EIP7702_DELEGATION_PREFIX));
1127    }
1128
1129    #[test]
1130    fn test_is_eip7702_delegation_rejects_long() {
1131        // Correct prefix but 24 bytes total.
1132        let mut code = Vec::with_capacity(24);
1133        code.extend_from_slice(&EIP7702_DELEGATION_PREFIX);
1134        code.extend_from_slice(&[0x42; 21]);
1135        assert!(!is_eip7702_delegation(&code));
1136    }
1137
1138    #[test]
1139    fn test_is_eip7702_delegation_rejects_wrong_prefix() {
1140        // Right length, wrong magic.
1141        let mut code = Vec::with_capacity(23);
1142        code.extend_from_slice(&[0xef, 0x01, 0x01]); // off by one in the last prefix byte
1143        code.extend_from_slice(&[0x42; 20]);
1144        assert!(!is_eip7702_delegation(&code));
1145    }
1146
1147    #[test]
1148    fn test_is_eip7702_delegation_rejects_arbitrary_contract_code() {
1149        // Real contract code starting with anything else.
1150        let code = vec![0x60, 0x60, 0x60, 0x40, 0x52 /* ... */];
1151        assert!(!is_eip7702_delegation(&code));
1152    }
1153
1154    // On these targets `compute_jumpdests` runs `by_block`, so the scan it replaces only
1155    // runs here, as the reference: both must give the same bitmap.
1156    #[cfg(any(
1157        target_arch = "aarch64",
1158        all(target_arch = "x86_64", target_feature = "ssse3")
1159    ))]
1160    mod by_block_against_the_scan {
1161        use super::*;
1162
1163        fn assert_same_jumpdests(code: &[u8]) {
1164            let mut want = vec![0; code.len().div_ceil(8)];
1165            let mut got = want.clone();
1166            let want_any = jumpdests_by_opcode(code, &mut want);
1167            let got_any = by_block::jumpdests(code, &mut got);
1168            assert_eq!((got_any, got), (want_any, want), "code {code:02x?}");
1169        }
1170
1171        /// One or two bytes at every offset of codes whose lengths straddle the 16-byte
1172        /// groups and 64-byte blocks, so every PUSH below crosses each boundary, and is cut
1173        /// short by the end of the code.
1174        #[test]
1175        fn matches_around_group_and_block_boundaries() {
1176            // STOP, JUMPDEST, the shortest PUSHes, the ones that fill a group with their
1177            // immediates or come a byte short or over, and the longest ones.
1178            const BYTES: [u8; 9] = [
1179                0x00,
1180                OP_JUMPDEST,
1181                OP_PUSH1,
1182                OP_PUSH1 + 1,
1183                OP_PUSH1 + 14,
1184                OP_PUSH1 + 15,
1185                OP_PUSH1 + 16,
1186                OP_PUSH32 - 1,
1187                OP_PUSH32,
1188            ];
1189            let lengths = [
1190                1, 15, 16, 17, 31, 32, 33, 63, 64, 65, 96, 127, 128, 129, 193,
1191            ];
1192            // A JUMPDEST filler exposes any immediate taken for an opcode or the other way
1193            // round. A PUSH1 filler makes where each block's walk starts depend on every
1194            // byte before it.
1195            for filler in [OP_JUMPDEST, OP_PUSH1] {
1196                for len in lengths {
1197                    for at in 0..len {
1198                        for first in BYTES {
1199                            for second in [None].into_iter().chain(BYTES.map(Some)) {
1200                                let mut code = vec![filler; len];
1201                                code[at] = first;
1202                                if let (Some(second), Some(byte)) = (second, code.get_mut(at + 1)) {
1203                                    *byte = second;
1204                                }
1205                                assert_same_jumpdests(&code);
1206                            }
1207                        }
1208                    }
1209                }
1210            }
1211        }
1212
1213        /// Random code up to 4 KiB long, over byte mixes that make the scan's branches
1214        /// unpredictable.
1215        #[test]
1216        fn matches_on_random_code() {
1217            // xorshift64, so every run checks the same inputs.
1218            let mut state = 0x9E37_79B9_7F4A_7C15_u64;
1219            let mut next = move || {
1220                state ^= state << 13;
1221                state ^= state >> 7;
1222                state ^= state << 17;
1223                state
1224            };
1225            let jumpdest_and_pushes: Vec<u8> = std::iter::once(OP_JUMPDEST)
1226                .chain(OP_PUSH1..=OP_PUSH32)
1227                .collect();
1228            let all_bytes: Vec<u8> = (0..=u8::MAX).collect();
1229            let mixes: [&[u8]; 4] = [
1230                &[0x00, OP_JUMPDEST, OP_PUSH1],
1231                &[OP_JUMPDEST, OP_PUSH1, OP_PUSH1 + 1],
1232                &jumpdest_and_pushes,
1233                &all_bytes,
1234            ];
1235            for mix in mixes {
1236                for _ in 0..200 {
1237                    let len = (next() % 4096) as usize;
1238                    let code: Vec<u8> = (0..len)
1239                        .map(|_| mix[(next() % mix.len() as u64) as usize])
1240                        .collect();
1241                    assert_same_jumpdests(&code);
1242                }
1243            }
1244        }
1245    }
1246
1247    #[test]
1248    fn a_reused_jump_destination_bitmap_keeps_nothing_of_the_initcode_before() {
1249        // Initcode of the same length, so the second reuses the first one's bitmap: a
1250        // JUMPDEST at offset 8, in the bitmap's second byte, then one only at offset 0, in
1251        // its first. The per-opcode scan the zkVM guests use writes only the first byte, so a
1252        // bitmap reused without zeroing keeps offset 8 valid there. The block scan on this
1253        // host rewrites every byte; the tests below catch a missing zeroing here too.
1254        let mut first_initcode = [0u8; 16];
1255        first_initcode[8] = 0x5b;
1256        let mut second_initcode = [0u8; 16];
1257        second_initcode[0] = 0x5b;
1258        let mut buffer = InitcodeBuffer::default();
1259        buffer.set(&first_initcode);
1260        let first = Code::from_initcode_buffer(buffer);
1261
1262        let mut buffer = first.into_initcode_buffer();
1263        buffer.set(&second_initcode);
1264        let second = Code::from_initcode_buffer(buffer);
1265
1266        assert!(second.is_valid_jumpdest(0));
1267        assert!(!second.is_valid_jumpdest(8));
1268    }
1269
1270    #[test]
1271    fn shorter_initcode_has_no_jump_destination_past_its_end_in_a_reused_bitmap() {
1272        // A JUMPDEST at every offset of the first initcode fills its 8-byte bitmap. The
1273        // second, two bytes long, reuses that bitmap but needs only its first byte, and
1274        // JUMP trusts the bitmap alone: a bit left past the end of the code would make a
1275        // jump there valid.
1276        let mut buffer = InitcodeBuffer::default();
1277        buffer.set(&[0x5b; 64]);
1278        let first = Code::from_initcode_buffer(buffer);
1279
1280        let mut buffer = first.into_initcode_buffer();
1281        buffer.set(&[0x00, 0x5b]); // STOP, JUMPDEST
1282        let second = Code::from_initcode_buffer(buffer);
1283
1284        assert!(second.is_valid_jumpdest(1));
1285        assert!(
1286            (0..64)
1287                .filter(|&offset| offset != 1)
1288                .all(|offset| !second.is_valid_jumpdest(offset))
1289        );
1290    }
1291
1292    #[test]
1293    fn a_longer_bitmap_is_reused_whole_and_zeroed() {
1294        let scratch: Arc<[u8]> = Arc::from(vec![0xff; 8]);
1295
1296        let bitmap = zeroed_bitmap_in(Some(scratch), 4);
1297
1298        // Kept at its length rather than replaced by a 4-byte one, and zeroed past the 4
1299        // bytes the code needs too.
1300        assert_eq!(&*bitmap, &[0; 8]);
1301    }
1302
1303    #[test]
1304    fn a_buffer_outgrown_by_initcode_at_least_doubles() {
1305        let mut buffer = InitcodeBuffer::default();
1306        buffer.set(&[0; 1000]);
1307
1308        buffer.set(&[0; 1001]);
1309
1310        // Replaced by one exactly the new size, initcode growing a byte each CREATE would
1311        // allocate a new buffer every time.
1312        assert!(buffer.capacity() >= 2 * (1000 + BYTECODE_PADDING));
1313    }
1314
1315    #[test]
1316    fn an_outgrown_bitmap_at_least_doubles() {
1317        let scratch: Arc<[u8]> = Arc::from(vec![0; 4]);
1318
1319        let bitmap = zeroed_bitmap_in(Some(scratch), 5);
1320
1321        assert!(bitmap.len() >= 8);
1322        assert!(bitmap.iter().all(|&byte| byte == 0));
1323    }
1324
1325    #[test]
1326    fn a_handed_back_initcode_buffer_holds_no_bytecode() {
1327        // A buffer is meant to be set before code is built from it again. Built from as it
1328        // comes back, it must give empty code, not the previous bytecode and its padding.
1329        let mut buffer = InitcodeBuffer::default();
1330        buffer.set(&[0x60, 0x01]); // PUSH1 1
1331        let code = Code::from_initcode_buffer(buffer);
1332
1333        let rebuilt = Code::from_initcode_buffer(code.into_initcode_buffer());
1334
1335        assert!(rebuilt.is_empty());
1336    }
1337}