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 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#[derive(Debug, Default)]
40pub struct InitcodeBuffer {
41 bytecode: BytesMut,
42 jumpdests: Option<Arc<[u8]>>,
43}
44
45impl InitcodeBuffer {
46 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 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 pub fn clear(&mut self) {
64 self.bytecode.clear();
65 }
66
67 pub fn initcode(&self) -> &[u8] {
69 &self.bytecode
70 }
71
72 pub fn capacity(&self) -> usize {
74 self.bytecode.capacity()
75 }
76
77 pub fn is_allocated(&self) -> bool {
79 self.bytecode.capacity() > 0 || self.jumpdests.is_some()
80 }
81}
82
83fn zeroed_bitmap(len: usize) -> Arc<[u8]> {
86 std::iter::repeat_n(0, len).collect()
87}
88
89fn 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 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
111fn 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
128pub const BYTECODE_PADDING: usize = 33;
133
134#[derive(Clone, Debug, PartialEq, Eq, Hash)]
135pub struct Code {
136 pub hash: H256,
142 bytecode: Bytes,
144 bytecode_len: usize,
146 jumpdests: Arc<[u8]>,
161}
162
163impl Code {
164 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 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 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 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 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 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 pub fn compute_jumpdests(code: &[u8]) -> Arc<[u8]> {
256 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 if any { bitmap } else { empty_jumpdests() }
266 }
267
268 #[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 #[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 #[inline]
307 pub fn dispatch_buf(&self) -> &[u8] {
308 &self.bytecode
309 }
310
311 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
329const OP_JUMPDEST: u8 = 0x5B;
332const OP_PUSH1: u8 = 0x60;
333const OP_PUSH32: u8 = 0x7F;
334
335#[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 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#[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 const BLOCK: usize = 64;
400 const GROUP: usize = 16;
402
403 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 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 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 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 #[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 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 let i = at % (2 * BLOCK);
471 let stops = u64::from(walks.low_stops[i]) | (u64::from(walks.high_stops[i]) << 8);
472 let group_start = i & (BLOCK - GROUP);
474 opcodes |= stops << group_start;
475 at = usize::from(walks.exits[i]);
476 }
477 *carry = at - BLOCK;
480 jumpdests & opcodes
481 }
482
483 #[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 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 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 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 #[derive(Clone, Copy)]
529 pub(super) struct Lanes(uint8x16_t);
530
531 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 #[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 #[inline(always)]
583 pub(super) fn lookup(self, indices: Self) -> Self {
584 unsafe { Self(vqtbl1q_u8(self.0, indices.0)) }
585 }
586
587 #[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 #[derive(Clone, Copy)]
610 pub(super) struct Lanes(__m128i);
611
612 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 #[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 #[inline(always)]
665 pub(super) fn lookup(self, indices: Self) -> Self {
666 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 #[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#[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 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#[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
831pub const EIP7702_DELEGATION_PREFIX: [u8; 3] = [0xef, 0x01, 0x00];
834pub const EIP7702_DELEGATED_CODE_LEN: usize = 23;
837
838pub 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 #[derive(serde::Serialize)]
1043 struct OldCodeSerde {
1044 hash: H256,
1045 code: Bytes,
1046 jump_targets: Vec<u32>,
1047 }
1048
1049 #[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 #[test]
1070 fn embedded_code_decodes_an_old_layout_bincode_row() {
1071 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], },
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 assert_eq!(
1090 decoded.tail, SENTINEL,
1091 "field after Code corrupted by layout shift"
1092 );
1093 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 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 assert!(!is_eip7702_delegation(&EIP7702_DELEGATION_PREFIX));
1127 }
1128
1129 #[test]
1130 fn test_is_eip7702_delegation_rejects_long() {
1131 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 let mut code = Vec::with_capacity(23);
1142 code.extend_from_slice(&[0xef, 0x01, 0x01]); 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 let code = vec![0x60, 0x60, 0x60, 0x40, 0x52 ];
1151 assert!(!is_eip7702_delegation(&code));
1152 }
1153
1154 #[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 #[test]
1175 fn matches_around_group_and_block_boundaries() {
1176 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 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 #[test]
1216 fn matches_on_random_code() {
1217 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 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 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]); 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 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 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 let mut buffer = InitcodeBuffer::default();
1330 buffer.set(&[0x60, 0x01]); 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}