Skip to main content

reth_trie_common/
hashed_state.rs

1use crate::{
2    bundle_state::BundleAccount,
3    prefix_set::{PrefixSetMut, TriePrefixSetsMut},
4    utils::{extend_sorted_vec, kway_merge_disjoint_sorted, kway_merge_sorted},
5    KeyHasher, MultiProofTargets, Nibbles,
6};
7use alloc::{borrow::Cow, vec::Vec};
8use alloy_primitives::{
9    keccak256,
10    map::{hash_map, B256Map, HashMap, HashSet},
11    Address, B256, U256,
12};
13use itertools::Itertools;
14use reth_primitives_traits::Account;
15
16#[cfg(feature = "rayon")]
17use reth_concurrency::sync::rayon::prelude::{
18    FromParallelIterator, IntoParallelIterator, ParallelIterator,
19};
20
21/// In-memory hashed state that stores account and storage changes with keccak256-hashed keys in
22/// hash maps.
23#[derive(PartialEq, Eq, Clone, Default, Debug)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25pub struct HashedPostState {
26    /// Mapping of hashed address to account info, `None` if destroyed.
27    pub accounts: B256Map<Option<Account>>,
28    /// Mapping of hashed address to hashed storage.
29    pub storages: B256Map<HashedStorage>,
30}
31
32impl HashedPostState {
33    /// Create new instance of [`HashedPostState`].
34    pub fn with_capacity(capacity: usize) -> Self {
35        Self {
36            accounts: B256Map::with_capacity_and_hasher(capacity, Default::default()),
37            storages: B256Map::with_capacity_and_hasher(capacity, Default::default()),
38        }
39    }
40
41    /// Initialize [`HashedPostState`] from bundle state.
42    /// Hashes all changed accounts and storage entries that are currently stored in the bundle
43    /// state.
44    #[inline]
45    pub fn from_bundle_state<'a, KH: KeyHasher>(
46        state: impl IntoIterator<Item = (&'a Address, &'a BundleAccount)>,
47    ) -> Self {
48        state
49            .into_iter()
50            .map(|(address, account)| {
51                let hashed_address = KH::hash_key(address);
52                let hashed_account = account.info.as_ref().map(Into::into);
53                let hashed_storage = HashedStorage::from_iter(
54                    account
55                        .storage
56                        .iter()
57                        .map(|(slot, value)| (keccak256(B256::from(*slot)), value.present_value)),
58                );
59
60                (
61                    hashed_address,
62                    hashed_account,
63                    (!hashed_storage.is_empty()).then_some(hashed_storage),
64                )
65            })
66            .collect()
67    }
68
69    /// Construct [`HashedPostState`] from a single [`HashedStorage`].
70    pub fn from_hashed_storage(hashed_address: B256, storage: HashedStorage) -> Self {
71        Self {
72            accounts: HashMap::default(),
73            storages: HashMap::from_iter([(hashed_address, storage)]),
74        }
75    }
76
77    /// Set account entries on hashed state.
78    pub fn with_accounts(
79        mut self,
80        accounts: impl IntoIterator<Item = (B256, Option<Account>)>,
81    ) -> Self {
82        self.accounts = HashMap::from_iter(accounts);
83        self
84    }
85
86    /// Set storage entries on hashed state.
87    pub fn with_storages(
88        mut self,
89        storages: impl IntoIterator<Item = (B256, HashedStorage)>,
90    ) -> Self {
91        self.storages = HashMap::from_iter(storages);
92        self
93    }
94
95    /// Returns `true` if the hashed state is empty.
96    pub fn is_empty(&self) -> bool {
97        self.accounts.is_empty() && self.storages.is_empty()
98    }
99
100    /// Construct [`TriePrefixSetsMut`] from hashed post state.
101    /// The prefix sets contain the hashed account and storage keys that have been changed in the
102    /// post state.
103    pub fn construct_prefix_sets(&self) -> TriePrefixSetsMut {
104        // Populate account prefix set.
105        let mut account_prefix_set = PrefixSetMut::with_capacity(self.accounts.len());
106        let mut destroyed_accounts = HashSet::default();
107        for (hashed_address, account) in &self.accounts {
108            account_prefix_set.insert(Nibbles::unpack(hashed_address));
109
110            if account.is_none() {
111                destroyed_accounts.insert(*hashed_address);
112            }
113        }
114
115        // Populate storage prefix sets.
116        let mut storage_prefix_sets =
117            HashMap::with_capacity_and_hasher(self.storages.len(), Default::default());
118        for (hashed_address, hashed_storage) in &self.storages {
119            account_prefix_set.insert(Nibbles::unpack(hashed_address));
120            storage_prefix_sets.insert(*hashed_address, hashed_storage.construct_prefix_set());
121        }
122
123        TriePrefixSetsMut { account_prefix_set, storage_prefix_sets, destroyed_accounts }
124    }
125
126    /// Create multiproof targets for this state.
127    pub fn multi_proof_targets(&self) -> MultiProofTargets {
128        // Pre-allocate minimum capacity for the targets.
129        let mut targets = MultiProofTargets::with_capacity(self.accounts.len());
130        for hashed_address in self.accounts.keys() {
131            targets.insert(*hashed_address, Default::default());
132        }
133        for (hashed_address, storage) in &self.storages {
134            targets.entry(*hashed_address).or_default().extend(storage.storage.keys().copied());
135        }
136        targets
137    }
138
139    /// Create multiproof targets difference for this state,
140    /// i.e., the targets that are in targets create from `self` but not in `excluded`.
141    ///
142    /// This method is preferred to first calling `Self::multi_proof_targets` and the calling
143    /// `MultiProofTargets::retain_difference`, because it does not over allocate the targets map.
144    pub fn multi_proof_targets_difference(
145        &self,
146        excluded: &MultiProofTargets,
147    ) -> MultiProofTargets {
148        let mut targets = MultiProofTargets::default();
149        for hashed_address in self.accounts.keys() {
150            if !excluded.contains_key(hashed_address) {
151                targets.insert(*hashed_address, Default::default());
152            }
153        }
154        for (hashed_address, storage) in &self.storages {
155            let maybe_excluded_storage = excluded.get(hashed_address);
156            let mut hashed_slots_targets = storage
157                .storage
158                .keys()
159                .filter(|slot| !maybe_excluded_storage.is_some_and(|f| f.contains(*slot)))
160                .peekable();
161            if hashed_slots_targets.peek().is_some() {
162                targets.entry(*hashed_address).or_default().extend(hashed_slots_targets);
163            }
164        }
165        targets
166    }
167
168    /// Returns an iterator that yields chunks of the specified size.
169    ///
170    /// See [`ChunkedHashedPostState`] for more information.
171    ///
172    /// # Panics
173    ///
174    /// Panics if the chunk size is zero.
175    pub fn chunks(self, size: usize) -> ChunkedHashedPostState {
176        ChunkedHashedPostState::new(self, size)
177    }
178
179    /// Returns the number of items that will be considered during chunking in `[Self::chunks]`.
180    pub fn chunking_length(&self) -> usize {
181        self.accounts.len() +
182            self.storages.values().map(|storage| storage.storage.len()).sum::<usize>()
183    }
184
185    /// Extend this hashed post state with contents of another.
186    /// Entries in the second hashed post state take precedence.
187    pub fn extend(&mut self, other: Self) {
188        self.extend_inner(Cow::Owned(other));
189    }
190
191    /// Extend this hashed post state with contents of another.
192    /// Entries in the second hashed post state take precedence.
193    ///
194    /// Slightly less efficient than [`Self::extend`], but preferred to `extend(other.clone())`.
195    pub fn extend_ref(&mut self, other: &Self) {
196        self.extend_inner(Cow::Borrowed(other));
197    }
198
199    #[allow(clippy::clone_on_copy)]
200    fn extend_inner(&mut self, other: Cow<'_, Self>) {
201        self.accounts.extend(other.accounts.iter().map(|(&k, v)| (k, v.clone())));
202
203        self.storages.reserve(other.storages.len());
204        match other {
205            Cow::Borrowed(other) => {
206                self.extend_storages(other.storages.iter().map(|(k, v)| (*k, Cow::Borrowed(v))))
207            }
208            Cow::Owned(other) => {
209                self.extend_storages(other.storages.into_iter().map(|(k, v)| (k, Cow::Owned(v))))
210            }
211        }
212    }
213
214    fn extend_storages<'a>(
215        &mut self,
216        storages: impl IntoIterator<Item = (B256, Cow<'a, HashedStorage>)>,
217    ) {
218        for (hashed_address, storage) in storages {
219            match self.storages.entry(hashed_address) {
220                hash_map::Entry::Vacant(entry) => {
221                    entry.insert(storage.into_owned());
222                }
223                hash_map::Entry::Occupied(mut entry) => {
224                    entry.get_mut().extend(&storage);
225                }
226            }
227        }
228    }
229
230    /// Extend this hashed post state with sorted data, converting directly into the unsorted
231    /// `HashMap` representation. This is more efficient than first converting to `HashedPostState`
232    /// and then extending, as it avoids creating intermediate `HashMap` allocations.
233    #[allow(clippy::clone_on_copy)]
234    pub fn extend_from_sorted(&mut self, sorted: &HashedPostStateSorted) {
235        // Reserve capacity for accounts
236        self.accounts.reserve(sorted.accounts.len());
237
238        // Insert accounts (Some = updated, None = destroyed)
239        for (address, account) in &sorted.accounts {
240            self.accounts.insert(*address, account.clone());
241        }
242
243        // Reserve capacity for storages
244        self.storages.reserve(sorted.storages.len());
245
246        // Extend storages
247        for (hashed_address, sorted_storage) in &sorted.storages {
248            match self.storages.entry(*hashed_address) {
249                hash_map::Entry::Vacant(entry) => {
250                    let mut new_storage = HashedStorage::default();
251                    new_storage.extend_from_sorted(sorted_storage);
252                    entry.insert(new_storage);
253                }
254                hash_map::Entry::Occupied(mut entry) => {
255                    entry.get_mut().extend_from_sorted(sorted_storage);
256                }
257            }
258        }
259    }
260
261    /// Converts hashed post state into [`HashedPostStateSorted`].
262    pub fn into_sorted(self) -> HashedPostStateSorted {
263        let mut accounts: Vec<_> = self.accounts.into_iter().collect();
264        accounts.sort_unstable_by_key(|(address, _)| *address);
265
266        let storages = self
267            .storages
268            .into_iter()
269            .map(|(hashed_address, storage)| (hashed_address, storage.into_sorted()))
270            .collect();
271
272        HashedPostStateSorted { accounts, storages }
273    }
274
275    /// Creates a sorted copy without consuming self.
276    /// More efficient than `.clone().into_sorted()` as it avoids cloning `HashMap` metadata.
277    #[allow(clippy::clone_on_copy)]
278    pub fn clone_into_sorted(&self) -> HashedPostStateSorted {
279        let mut accounts: Vec<_> = self.accounts.iter().map(|(&k, v)| (k, v.clone())).collect();
280        accounts.sort_unstable_by_key(|(address, _)| *address);
281
282        let storages = self
283            .storages
284            .iter()
285            .map(|(&hashed_address, storage)| (hashed_address, storage.clone_into_sorted()))
286            .collect();
287
288        HashedPostStateSorted { accounts, storages }
289    }
290
291    /// Clears the account and storage maps of this `HashedPostState`.
292    pub fn clear(&mut self) {
293        self.accounts.clear();
294        self.storages.clear();
295    }
296}
297
298impl FromIterator<(B256, Option<Account>, Option<HashedStorage>)> for HashedPostState {
299    /// Constructs a [`HashedPostState`] from an iterator of tuples containing:
300    /// - Hashed address (B256)
301    /// - Optional account info (`None` indicates destroyed account)
302    /// - Optional hashed storage
303    ///
304    /// # Important
305    ///
306    /// - The iterator **assumes unique hashed addresses** (B256). If duplicate addresses are
307    ///   present, later entries will overwrite earlier ones for accounts, and storage will be
308    ///   merged.
309    /// - The [`HashedStorage`] **must not be empty** (as determined by
310    ///   [`HashedStorage::is_empty`]). Empty storage should be represented as `None` rather than
311    ///   `Some(empty_storage)`. This ensures the storage map only contains meaningful entries.
312    ///
313    /// Use `(!storage.is_empty()).then_some(storage)` to convert empty storage to `None`.
314    fn from_iter<T: IntoIterator<Item = (B256, Option<Account>, Option<HashedStorage>)>>(
315        iter: T,
316    ) -> Self {
317        let iter = iter.into_iter();
318        let (lower, _) = iter.size_hint();
319        let mut hashed_state = Self::with_capacity(lower);
320
321        for (hashed_address, info, hashed_storage) in iter {
322            hashed_state.accounts.insert(hashed_address, info);
323            if let Some(storage) = hashed_storage {
324                hashed_state.storages.insert(hashed_address, storage);
325            }
326        }
327
328        hashed_state
329    }
330}
331
332#[cfg(feature = "rayon")]
333impl FromParallelIterator<(B256, Option<Account>, Option<HashedStorage>)> for HashedPostState {
334    /// Parallel version of [`FromIterator`] for constructing [`HashedPostState`] from a parallel
335    /// iterator.
336    ///
337    /// See [`FromIterator::from_iter`] for details on the expected input format.
338    ///
339    /// # Important
340    ///
341    /// - The iterator **assumes unique hashed addresses** (B256). If duplicate addresses are
342    ///   present, later entries will overwrite earlier ones for accounts, and storage will be
343    ///   merged.
344    /// - The [`HashedStorage`] **must not be empty**. Empty storage should be `None`.
345    fn from_par_iter<I>(par_iter: I) -> Self
346    where
347        I: IntoParallelIterator<Item = (B256, Option<Account>, Option<HashedStorage>)>,
348    {
349        let vec: Vec<_> = par_iter.into_par_iter().collect();
350        vec.into_iter().collect()
351    }
352}
353
354/// Representation of in-memory hashed storage.
355#[derive(PartialEq, Eq, Clone, Debug, Default)]
356#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
357pub struct HashedStorage {
358    /// Mapping of hashed storage slot to storage value.
359    pub storage: B256Map<U256>,
360}
361
362impl HashedStorage {
363    /// Check if self is empty.
364    pub fn is_empty(&self) -> bool {
365        self.storage.is_empty()
366    }
367
368    /// Create new hashed storage from iterator.
369    #[expect(clippy::should_implement_trait)]
370    pub fn from_iter(iter: impl IntoIterator<Item = (B256, U256)>) -> Self {
371        Self { storage: HashMap::from_iter(iter) }
372    }
373
374    /// Create new hashed storage from plain storage.
375    pub fn from_plain_storage<'a>(storage: impl IntoIterator<Item = (&'a U256, &'a U256)>) -> Self {
376        Self::from_iter(
377            storage.into_iter().map(|(key, value)| (keccak256(B256::from(*key)), *value)),
378        )
379    }
380
381    /// Construct [`PrefixSetMut`] from hashed storage.
382    pub fn construct_prefix_set(&self) -> PrefixSetMut {
383        let mut prefix_set = PrefixSetMut::with_capacity(self.storage.len());
384        for hashed_slot in self.storage.keys() {
385            prefix_set.insert(Nibbles::unpack(hashed_slot));
386        }
387        prefix_set
388    }
389
390    /// Extend hashed storage with contents of other.
391    /// The entries in second hashed storage take precedence.
392    pub fn extend(&mut self, other: &Self) {
393        self.storage.extend(other.storage.iter().map(|(&k, &v)| (k, v)));
394    }
395
396    /// Extend hashed storage with sorted data, converting directly into the unsorted `HashMap`
397    /// representation. This is more efficient than first converting to `HashedStorage` and
398    /// then extending, as it avoids creating intermediate `HashMap` allocations.
399    pub fn extend_from_sorted(&mut self, sorted: &HashedStorageSorted) {
400        // Reserve capacity for all slots
401        self.storage.reserve(sorted.storage_slots.len());
402
403        // Insert all storage slots
404        for (slot, value) in &sorted.storage_slots {
405            self.storage.insert(*slot, *value);
406        }
407    }
408
409    /// Converts hashed storage into [`HashedStorageSorted`].
410    pub fn into_sorted(self) -> HashedStorageSorted {
411        let mut storage_slots: Vec<_> = self.storage.into_iter().collect();
412        storage_slots.sort_unstable_by_key(|(key, _)| *key);
413
414        HashedStorageSorted { storage_slots }
415    }
416
417    /// Creates a sorted copy without consuming self.
418    /// More efficient than `.clone().into_sorted()` as it avoids cloning `HashMap` metadata.
419    pub fn clone_into_sorted(&self) -> HashedStorageSorted {
420        let mut storage_slots: Vec<_> = self.storage.iter().map(|(&k, &v)| (k, v)).collect();
421        storage_slots.sort_unstable_by_key(|(key, _)| *key);
422
423        HashedStorageSorted { storage_slots }
424    }
425}
426
427/// Sorted hashed post state optimized for iterating during state trie calculation.
428#[derive(PartialEq, Eq, Clone, Default, Debug)]
429#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
430pub struct HashedPostStateSorted {
431    /// Sorted collection of account updates. `None` indicates a destroyed account.
432    pub accounts: Vec<(B256, Option<Account>)>,
433    /// Map of hashed addresses to their sorted storage updates.
434    pub storages: B256Map<HashedStorageSorted>,
435}
436
437impl HashedPostStateSorted {
438    /// Create new instance of [`HashedPostStateSorted`]
439    pub const fn new(
440        accounts: Vec<(B256, Option<Account>)>,
441        storages: B256Map<HashedStorageSorted>,
442    ) -> Self {
443        Self { accounts, storages }
444    }
445
446    /// Returns reference to hashed accounts.
447    pub const fn accounts(&self) -> &Vec<(B256, Option<Account>)> {
448        &self.accounts
449    }
450
451    /// Returns reference to hashed account storages.
452    pub const fn account_storages(&self) -> &B256Map<HashedStorageSorted> {
453        &self.storages
454    }
455
456    /// Returns `true` if there are no account or storage updates.
457    pub fn is_empty(&self) -> bool {
458        self.accounts.is_empty() && self.storages.is_empty()
459    }
460
461    /// Returns the total number of updates including all accounts and storage updates.
462    pub fn total_len(&self) -> usize {
463        self.accounts.len() + self.storages.values().map(|s| s.len()).sum::<usize>()
464    }
465
466    /// Construct [`TriePrefixSetsMut`] from hashed post state.
467    ///
468    /// The prefix sets contain the hashed account and storage keys that have been changed in the
469    /// post state.
470    pub fn construct_prefix_sets(&self) -> TriePrefixSetsMut {
471        let mut account_prefix_set = PrefixSetMut::with_capacity(self.accounts.len());
472        let mut destroyed_accounts = HashSet::default();
473        for (hashed_address, account) in &self.accounts {
474            account_prefix_set.insert(Nibbles::unpack(hashed_address));
475            if account.is_none() {
476                destroyed_accounts.insert(*hashed_address);
477            }
478        }
479
480        let mut storage_prefix_sets =
481            B256Map::with_capacity_and_hasher(self.storages.len(), Default::default());
482        for (hashed_address, hashed_storage) in &self.storages {
483            // Ensure account trie covers storage overlays even if account map is empty.
484            account_prefix_set.insert(Nibbles::unpack(hashed_address));
485            let mut prefix_set = PrefixSetMut::with_capacity(hashed_storage.storage_slots.len());
486            prefix_set.extend_keys(
487                hashed_storage
488                    .storage_slots
489                    .iter()
490                    .map(|(hashed_slot, _)| Nibbles::unpack(hashed_slot)),
491            );
492
493            storage_prefix_sets.insert(*hashed_address, prefix_set);
494        }
495
496        TriePrefixSetsMut { account_prefix_set, storage_prefix_sets, destroyed_accounts }
497    }
498
499    /// Extends this state with contents of another sorted state.
500    /// Entries in `other` take precedence for duplicate keys.
501    ///
502    /// Sorts the accounts after extending. Sorts the storage after extending, for each account.
503    pub fn extend_ref_and_sort(&mut self, other: &Self) {
504        // Extend accounts
505        extend_sorted_vec(&mut self.accounts, &other.accounts);
506
507        // Extend storages
508        for (hashed_address, other_storage) in &other.storages {
509            self.storages
510                .entry(*hashed_address)
511                .and_modify(|existing| existing.extend_ref(other_storage))
512                .or_insert_with(|| other_storage.clone());
513        }
514    }
515
516    /// Batch-merge sorted hashed post states. Iterator yields **newest to oldest**.
517    ///
518    /// For small batches, uses `extend_ref_and_sort` loop.
519    /// For large batches, uses k-way merge for O(n log k) complexity.
520    pub fn merge_batch<T: AsRef<Self> + From<Self>>(iter: impl IntoIterator<Item = T>) -> T {
521        let items: alloc::vec::Vec<_> = iter.into_iter().collect();
522        match items.len() {
523            0 => Self::default().into(),
524            1 => items.into_iter().next().expect("len == 1"),
525            _ => Self::merge_slice(&items).into(),
526        }
527    }
528
529    /// Batch-merge sorted hashed post states from a slice. Slice is **newest to oldest**.
530    ///
531    /// This variant takes a slice reference directly, avoiding iterator collection overhead.
532    /// For small batches, uses `extend_ref_and_sort` loop.
533    /// For large batches, uses k-way merge for O(n log k) complexity.
534    pub fn merge_slice<T: AsRef<Self>>(items: &[T]) -> Self {
535        const THRESHOLD: usize = 30;
536
537        let k = items.len();
538
539        if k == 0 {
540            return Self::default();
541        }
542        if k == 1 {
543            return items[0].as_ref().clone();
544        }
545
546        if k < THRESHOLD {
547            // Small k: extend loop, oldest-to-newest so newer overrides older.
548            let mut iter = items.iter().rev();
549            let mut acc = iter.next().expect("k > 0").as_ref().clone();
550            for next in iter {
551                acc.extend_ref_and_sort(next.as_ref());
552            }
553            return acc;
554        }
555
556        // Large k: k-way merge.
557        let accounts = kway_merge_sorted(items.iter().map(|i| i.as_ref().accounts.as_slice()));
558
559        struct StorageAcc<'a> {
560            slices: Vec<&'a [(B256, U256)]>,
561        }
562
563        let mut acc: B256Map<StorageAcc<'_>> = B256Map::default();
564
565        for item in items {
566            for (addr, storage) in &item.as_ref().storages {
567                let entry = acc.entry(*addr).or_insert_with(|| StorageAcc { slices: Vec::new() });
568                entry.slices.push(storage.storage_slots.as_slice());
569            }
570        }
571
572        let storages = acc
573            .into_iter()
574            .map(|(addr, entry)| {
575                let storage_slots = kway_merge_sorted(entry.slices);
576                (addr, HashedStorageSorted { storage_slots })
577            })
578            .collect();
579
580        Self { accounts, storages }
581    }
582
583    /// Merges the batch and removes overlapping keys whose mask values all differ from the merged
584    /// batch value.
585    ///
586    /// Account keys are masked at the top level, while storage entries are masked at the slot
587    /// level. For duplicate keys in the batch, later items take precedence over earlier ones. An
588    /// overlapping entry is retained if any mask value is equal to the merged batch value. The
589    /// order of the mask does not matter. An empty mask merges the batch without filtering.
590    pub fn disjointed_merge_batch<'a>(batch: &[&'a Self], mask: &[&'a Self]) -> Self {
591        let account_count = batch.iter().map(|item| item.accounts.len()).sum();
592        let mut accounts = Vec::with_capacity(account_count);
593        accounts.extend(kway_merge_disjoint_sorted(
594            batch.iter().rev().map(|item| item.accounts.as_slice()),
595            mask.iter().map(|item| item.accounts.as_slice()),
596        ));
597
598        struct StorageAcc<'a> {
599            slot_count: usize,
600            slices: Vec<&'a [(B256, U256)]>,
601        }
602
603        #[derive(Default)]
604        struct StorageMaskAcc<'a> {
605            slices: Vec<&'a [(B256, U256)]>,
606        }
607
608        let mut storages = B256Map::with_capacity_and_hasher(
609            batch.iter().map(|item| item.storages.len()).sum(),
610            Default::default(),
611        );
612
613        for item in batch.iter().rev() {
614            for (hashed_address, storage) in &item.storages {
615                let entry = storages
616                    .entry(*hashed_address)
617                    .or_insert_with(|| StorageAcc { slot_count: 0, slices: Vec::new() });
618                entry.slices.push(storage.storage_slots.as_slice());
619                entry.slot_count += storage.storage_slots.len();
620            }
621        }
622
623        let mut storage_masks: B256Map<StorageMaskAcc<'a>> = B256Map::with_capacity_and_hasher(
624            mask.iter().map(|item| item.storages.len()).sum(),
625            Default::default(),
626        );
627        for item in mask {
628            for (hashed_address, storage) in &item.storages {
629                let entry = storage_masks.entry(*hashed_address).or_default();
630                entry.slices.push(storage.storage_slots.as_slice());
631            }
632        }
633
634        let storages = storages
635            .into_iter()
636            .filter_map(|(hashed_address, entry)| {
637                let slot_count = entry.slot_count;
638                let storage_slots = match storage_masks.get(&hashed_address) {
639                    Some(mask_entry) => {
640                        let mut storage_slots = Vec::with_capacity(slot_count);
641                        storage_slots.extend(kway_merge_disjoint_sorted(
642                            entry.slices,
643                            mask_entry.slices.iter().copied(),
644                        ));
645                        storage_slots
646                    }
647                    None => kway_merge_sorted(entry.slices),
648                };
649
650                (!storage_slots.is_empty() || mask.is_empty())
651                    .then_some((hashed_address, HashedStorageSorted { storage_slots }))
652            })
653            .collect();
654
655        Self { accounts, storages }
656    }
657
658    /// Clears all accounts and storage data.
659    pub fn clear(&mut self) {
660        self.accounts.clear();
661        self.storages.clear();
662    }
663}
664
665impl AsRef<Self> for HashedPostStateSorted {
666    fn as_ref(&self) -> &Self {
667        self
668    }
669}
670
671/// Sorted hashed storage optimized for iterating during state trie calculation.
672#[derive(Clone, Eq, PartialEq, Debug, Default)]
673#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
674pub struct HashedStorageSorted {
675    /// Sorted collection of updated storage slots. [`U256::ZERO`] indicates a deleted value.
676    pub storage_slots: Vec<(B256, U256)>,
677}
678
679impl HashedStorageSorted {
680    /// Returns reference to updated storage slots.
681    pub fn storage_slots_ref(&self) -> &[(B256, U256)] {
682        &self.storage_slots
683    }
684
685    /// Returns the total number of storage slot updates.
686    pub const fn len(&self) -> usize {
687        self.storage_slots.len()
688    }
689
690    /// Returns `true` if there are no storage slot updates.
691    pub const fn is_empty(&self) -> bool {
692        self.storage_slots.is_empty()
693    }
694
695    /// Extends the storage slots updates with another set of sorted updates.
696    pub fn extend_ref(&mut self, other: &Self) {
697        extend_sorted_vec(&mut self.storage_slots, &other.storage_slots);
698    }
699
700    /// Batch-merge sorted hashed storage. Iterator yields **newest to oldest**.
701    pub fn merge_batch<'a>(updates: impl IntoIterator<Item = &'a Self>) -> Self {
702        let updates: Vec<_> = updates.into_iter().collect();
703        Self {
704            storage_slots: kway_merge_sorted(updates.iter().map(|u| u.storage_slots.as_slice())),
705        }
706    }
707}
708
709impl From<HashedStorageSorted> for HashedStorage {
710    fn from(sorted: HashedStorageSorted) -> Self {
711        let mut storage = B256Map::default();
712
713        // Add all storage slots (including zero-valued ones which indicate deletion)
714        for (slot, value) in sorted.storage_slots {
715            storage.insert(slot, value);
716        }
717
718        Self { storage }
719    }
720}
721
722impl From<HashedPostStateSorted> for HashedPostState {
723    fn from(sorted: HashedPostStateSorted) -> Self {
724        let mut accounts =
725            B256Map::with_capacity_and_hasher(sorted.accounts.len(), Default::default());
726
727        // Add all accounts (Some for updated, None for destroyed)
728        for (address, account) in sorted.accounts {
729            accounts.insert(address, account);
730        }
731
732        // Convert storages
733        let storages = sorted
734            .storages
735            .into_iter()
736            .map(|(address, storage)| (address, storage.into()))
737            .collect();
738
739        Self { accounts, storages }
740    }
741}
742
743/// An iterator that yields chunks of the state updates of at most `size` account and storage
744/// targets.
745///
746/// Storage updates for each account are yielded before its account update.
747#[derive(Debug)]
748pub struct ChunkedHashedPostState {
749    flattened: alloc::vec::IntoIter<(B256, FlattenedHashedPostStateItem)>,
750    size: usize,
751}
752
753/// Order discriminant for sorting flattened state items.
754/// Ordering: `StorageUpdate` (by slot) < `Account`
755#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
756enum FlattenedStateOrder {
757    StorageUpdate(B256),
758    Account,
759}
760
761#[derive(Debug)]
762enum FlattenedHashedPostStateItem {
763    Account(Option<Account>),
764    StorageUpdate { slot: B256, value: U256 },
765}
766
767impl FlattenedHashedPostStateItem {
768    const fn order(&self) -> FlattenedStateOrder {
769        match self {
770            Self::StorageUpdate { slot, .. } => FlattenedStateOrder::StorageUpdate(*slot),
771            Self::Account(_) => FlattenedStateOrder::Account,
772        }
773    }
774}
775
776impl ChunkedHashedPostState {
777    fn new(hashed_post_state: HashedPostState, size: usize) -> Self {
778        assert!(size > 0, "chunk size must be non-zero");
779        let flattened = hashed_post_state
780            .storages
781            .into_iter()
782            .flat_map(|(address, storage)| {
783                storage.storage.into_iter().map(move |(slot, value)| {
784                    (address, FlattenedHashedPostStateItem::StorageUpdate { slot, value })
785                })
786            })
787            .chain(hashed_post_state.accounts.into_iter().map(|(address, account)| {
788                (address, FlattenedHashedPostStateItem::Account(account))
789            }))
790            // Sort by address, then by item order to ensure correct application sequence:
791            // 1. Storage updates (sorted by slot for determinism)
792            // 2. Account updates (can be applied last)
793            .sorted_unstable_by_key(|(address, item)| (*address, item.order()));
794
795        Self { flattened, size }
796    }
797}
798
799impl Iterator for ChunkedHashedPostState {
800    type Item = HashedPostState;
801
802    fn next(&mut self) -> Option<Self::Item> {
803        let mut chunk = HashedPostState::default();
804
805        let mut current_size = 0;
806        while current_size < self.size {
807            let Some((address, item)) = self.flattened.next() else { break };
808
809            match item {
810                FlattenedHashedPostStateItem::Account(account) => {
811                    chunk.accounts.insert(address, account);
812                }
813                FlattenedHashedPostStateItem::StorageUpdate { slot, value } => {
814                    chunk.storages.entry(address).or_default().storage.insert(slot, value);
815                }
816            }
817
818            current_size += 1;
819        }
820
821        if chunk.is_empty() {
822            None
823        } else {
824            Some(chunk)
825        }
826    }
827}
828
829#[cfg(test)]
830mod tests {
831    use super::*;
832    use crate::{
833        bundle_state::{AccountStatus, StorageSlot, StorageWithOriginalValues},
834        KeccakKeyHasher,
835    };
836    use alloy_primitives::Bytes;
837    use evm2::{bytecode::Bytecode, evm::AccountInfo};
838
839    fn bundle_hashed_storage(account: &BundleAccount) -> Option<HashedStorage> {
840        let address = Address::ZERO;
841        let mut state =
842            HashedPostState::from_bundle_state::<KeccakKeyHasher>([(&address, account)]);
843        state.storages.remove(&keccak256(address))
844    }
845
846    fn changed_storage(original: U256, present: U256) -> StorageWithOriginalValues {
847        core::iter::once((U256::ONE, StorageSlot::new_changed(original, present))).collect()
848    }
849
850    #[test]
851    fn test_hashed_post_state_from_bundle_state() {
852        // Prepare a random Ethereum address as a key for the account.
853        let address = Address::random();
854
855        // Create a mock account info object.
856        let account_info = AccountInfo {
857            balance: U256::from(123),
858            nonce: 42,
859            code_hash: B256::random(),
860            code: Some(Bytecode::new_raw(Bytes::from(vec![1, 2]))),
861            ..Default::default()
862        };
863
864        let mut storage = StorageWithOriginalValues::default();
865        storage
866            .insert(U256::ONE, StorageSlot { present_value: U256::from(4), ..Default::default() });
867
868        // Create a `BundleAccount` struct to represent the account and its storage.
869        let account = BundleAccount {
870            status: AccountStatus::Changed,
871            info: Some(account_info.clone()),
872            storage,
873            original_info: None,
874        };
875
876        // Create a vector of tuples representing the bundle state.
877        let state = vec![(&address, &account)];
878
879        // Convert the bundle state into a hashed post state.
880        let hashed_state = HashedPostState::from_bundle_state::<KeccakKeyHasher>(state);
881
882        // Validate the hashed post state.
883        assert_eq!(hashed_state.accounts.len(), 1);
884        assert_eq!(hashed_state.storages.len(), 1);
885
886        // Validate the account info.
887        assert_eq!(
888            *hashed_state.accounts.get(&keccak256(address)).unwrap(),
889            Some(Account::from(&account_info))
890        );
891    }
892
893    #[test]
894    fn destroyed_prefunded_account_without_storage_emits_no_storage() {
895        let original_info = AccountInfo { balance: U256::ONE, ..Default::default() };
896        let account = BundleAccount::new(
897            Some(original_info),
898            None,
899            StorageWithOriginalValues::default(),
900            AccountStatus::Destroyed,
901        );
902
903        assert!(bundle_hashed_storage(&account).is_none());
904    }
905
906    #[test]
907    fn destroyed_accounts_emit_zero_storage_changes() {
908        let existing_contract =
909            AccountInfo { code_hash: B256::repeat_byte(0x01), ..Default::default() };
910        let legacy_empty_account = AccountInfo::default();
911        let prefunded_account = AccountInfo { balance: U256::ONE, ..Default::default() };
912
913        for original_info in
914            [Some(existing_contract), Some(legacy_empty_account), Some(prefunded_account), None]
915        {
916            let account = BundleAccount::new(
917                original_info,
918                None,
919                changed_storage(U256::from(2), U256::ZERO),
920                AccountStatus::Destroyed,
921            );
922
923            let storage = bundle_hashed_storage(&account).unwrap();
924            let hashed_slot = keccak256(B256::with_last_byte(1));
925            assert_eq!(storage.storage[&hashed_slot], U256::ZERO);
926        }
927    }
928
929    #[test]
930    fn destroyed_recreated_accounts_preserve_storage() {
931        let value = U256::from(2);
932        let new_account = BundleAccount::new(
933            None,
934            Some(AccountInfo::default()),
935            changed_storage(U256::ZERO, value),
936            AccountStatus::DestroyedChanged,
937        );
938        let original_info =
939            AccountInfo { code_hash: B256::repeat_byte(0x01), ..Default::default() };
940        let existing_account = BundleAccount::new(
941            Some(original_info),
942            Some(AccountInfo::default()),
943            changed_storage(U256::ZERO, value),
944            AccountStatus::DestroyedChanged,
945        );
946
947        let new_storage = bundle_hashed_storage(&new_account).unwrap();
948        let existing_storage = bundle_hashed_storage(&existing_account).unwrap();
949        let hashed_slot = keccak256(B256::with_last_byte(1));
950        assert_eq!(new_storage.storage[&hashed_slot], value);
951        assert_eq!(existing_storage.storage[&hashed_slot], value);
952    }
953
954    #[test]
955    fn test_hashed_post_state_with_accounts() {
956        // Prepare random addresses and mock account info.
957        let address_1 = Address::random();
958        let address_2 = Address::random();
959
960        let account_info_1 = AccountInfo {
961            balance: U256::from(1000),
962            nonce: 1,
963            code_hash: B256::random(),
964            code: None,
965            ..Default::default()
966        };
967
968        // Create hashed accounts with addresses.
969        let account_1 = (keccak256(address_1), Some(Account::from(&account_info_1)));
970        let account_2 = (keccak256(address_2), None);
971
972        // Add accounts to the hashed post state.
973        let hashed_state = HashedPostState::default().with_accounts(vec![account_1, account_2]);
974
975        // Validate the hashed post state.
976        assert_eq!(hashed_state.accounts.len(), 2);
977        assert!(hashed_state.accounts.contains_key(&keccak256(address_1)));
978        assert!(hashed_state.accounts.contains_key(&keccak256(address_2)));
979    }
980
981    #[test]
982    fn test_hashed_post_state_with_storages() {
983        // Prepare random addresses and mock storage entries.
984        let address_1 = Address::random();
985        let address_2 = Address::random();
986
987        let storage_1 = (keccak256(address_1), HashedStorage::default());
988        let storage_2 = (keccak256(address_2), HashedStorage::default());
989
990        // Add storages to the hashed post state.
991        let hashed_state = HashedPostState::default().with_storages(vec![storage_1, storage_2]);
992
993        // Validate the hashed post state.
994        assert_eq!(hashed_state.storages.len(), 2);
995        assert!(hashed_state.storages.contains_key(&keccak256(address_1)));
996        assert!(hashed_state.storages.contains_key(&keccak256(address_2)));
997    }
998
999    #[test]
1000    fn test_hashed_post_state_is_empty() {
1001        // Create an empty hashed post state and validate it's empty.
1002        let empty_state = HashedPostState::default();
1003        assert!(empty_state.is_empty());
1004
1005        // Add an account and validate the state is no longer empty.
1006        let non_empty_state = HashedPostState::default()
1007            .with_accounts(vec![(keccak256(Address::random()), Some(Account::default()))]);
1008        assert!(!non_empty_state.is_empty());
1009    }
1010
1011    fn create_state_for_multi_proof_targets() -> HashedPostState {
1012        let mut state = HashedPostState::default();
1013
1014        let addr1 = B256::random();
1015        let addr2 = B256::random();
1016        state.accounts.insert(addr1, Some(Default::default()));
1017        state.accounts.insert(addr2, Some(Default::default()));
1018
1019        let mut storage = HashedStorage::default();
1020        let slot1 = B256::random();
1021        let slot2 = B256::random();
1022        storage.storage.insert(slot1, U256::ZERO);
1023        storage.storage.insert(slot2, U256::ONE);
1024        state.storages.insert(addr1, storage);
1025
1026        state
1027    }
1028
1029    #[test]
1030    fn test_multi_proof_targets_difference_empty_state() {
1031        let state = HashedPostState::default();
1032        let excluded = MultiProofTargets::default();
1033
1034        let targets = state.multi_proof_targets_difference(&excluded);
1035        assert!(targets.is_empty());
1036    }
1037
1038    #[test]
1039    fn test_multi_proof_targets_difference_new_account_targets() {
1040        let state = create_state_for_multi_proof_targets();
1041        let excluded = MultiProofTargets::default();
1042
1043        // should return all accounts as targets since excluded is empty
1044        let targets = state.multi_proof_targets_difference(&excluded);
1045        assert_eq!(targets.len(), state.accounts.len());
1046        for addr in state.accounts.keys() {
1047            assert!(targets.contains_key(addr));
1048        }
1049    }
1050
1051    #[test]
1052    fn test_multi_proof_targets_difference_new_storage_targets() {
1053        let state = create_state_for_multi_proof_targets();
1054        let excluded = MultiProofTargets::default();
1055
1056        let targets = state.multi_proof_targets_difference(&excluded);
1057
1058        // verify storage slots are included for accounts with storage
1059        for (addr, storage) in &state.storages {
1060            assert!(targets.contains_key(addr));
1061            let target_slots = &targets[addr];
1062            assert_eq!(target_slots.len(), storage.storage.len());
1063            for slot in storage.storage.keys() {
1064                assert!(target_slots.contains(slot));
1065            }
1066        }
1067    }
1068
1069    #[test]
1070    fn test_multi_proof_targets_difference_filter_excluded_accounts() {
1071        let state = create_state_for_multi_proof_targets();
1072        let mut excluded = MultiProofTargets::default();
1073
1074        // select an account that has no storage updates
1075        let excluded_addr = state
1076            .accounts
1077            .keys()
1078            .find(|&&addr| !state.storages.contains_key(&addr))
1079            .expect("Should have an account without storage");
1080
1081        // mark the account as excluded
1082        excluded.insert(*excluded_addr, HashSet::default());
1083
1084        let targets = state.multi_proof_targets_difference(&excluded);
1085
1086        // should not include the already excluded account since it has no storage updates
1087        assert!(!targets.contains_key(excluded_addr));
1088        // other accounts should still be included
1089        assert_eq!(targets.len(), state.accounts.len() - 1);
1090    }
1091
1092    #[test]
1093    fn test_multi_proof_targets_difference_filter_excluded_storage() {
1094        let state = create_state_for_multi_proof_targets();
1095        let mut excluded = MultiProofTargets::default();
1096
1097        // mark one storage slot as excluded
1098        let (addr, storage) = state.storages.iter().next().unwrap();
1099        let mut excluded_slots = HashSet::default();
1100        let excluded_slot = *storage.storage.keys().next().unwrap();
1101        excluded_slots.insert(excluded_slot);
1102        excluded.insert(*addr, excluded_slots);
1103
1104        let targets = state.multi_proof_targets_difference(&excluded);
1105
1106        // should not include the excluded storage slot
1107        let target_slots = &targets[addr];
1108        assert!(!target_slots.contains(&excluded_slot));
1109        assert_eq!(target_slots.len(), storage.storage.len() - 1);
1110    }
1111
1112    #[test]
1113    fn test_multi_proof_targets_difference_mixed_excluded_state() {
1114        let mut state = HashedPostState::default();
1115        let mut excluded = MultiProofTargets::default();
1116
1117        let addr1 = B256::random();
1118        let addr2 = B256::random();
1119        let slot1 = B256::random();
1120        let slot2 = B256::random();
1121
1122        state.accounts.insert(addr1, Some(Default::default()));
1123        state.accounts.insert(addr2, Some(Default::default()));
1124
1125        let mut storage = HashedStorage::default();
1126        storage.storage.insert(slot1, U256::ZERO);
1127        storage.storage.insert(slot2, U256::ONE);
1128        state.storages.insert(addr1, storage);
1129
1130        let mut excluded_slots = HashSet::default();
1131        excluded_slots.insert(slot1);
1132        excluded.insert(addr1, excluded_slots);
1133
1134        let targets = state.multi_proof_targets_difference(&excluded);
1135
1136        assert!(targets.contains_key(&addr2));
1137        assert!(!targets[&addr1].contains(&slot1));
1138        assert!(targets[&addr1].contains(&slot2));
1139    }
1140
1141    #[test]
1142    fn test_multi_proof_targets_difference_unmodified_account_with_storage() {
1143        let mut state = HashedPostState::default();
1144        let excluded = MultiProofTargets::default();
1145
1146        let addr = B256::random();
1147        let slot1 = B256::random();
1148        let slot2 = B256::random();
1149
1150        // don't add the account to state.accounts (simulating unmodified account)
1151        // but add storage updates for this account
1152        let mut storage = HashedStorage::default();
1153        storage.storage.insert(slot1, U256::ONE);
1154        storage.storage.insert(slot2, U256::from(2));
1155        state.storages.insert(addr, storage);
1156
1157        assert!(!state.accounts.contains_key(&addr));
1158        assert!(!excluded.contains_key(&addr));
1159
1160        let targets = state.multi_proof_targets_difference(&excluded);
1161
1162        // verify that we still get the storage slots for the unmodified account
1163        assert!(targets.contains_key(&addr));
1164
1165        let target_slots = &targets[&addr];
1166        assert_eq!(target_slots.len(), 2);
1167        assert!(target_slots.contains(&slot1));
1168        assert!(target_slots.contains(&slot2));
1169    }
1170
1171    #[test]
1172    fn test_hashed_post_state_sorted_extend_ref() {
1173        // Test extending accounts
1174        let mut state1 = HashedPostStateSorted {
1175            accounts: vec![
1176                (B256::repeat_byte(1), Some(Account::default())),
1177                (B256::repeat_byte(3), Some(Account::default())),
1178                (B256::repeat_byte(5), None),
1179            ],
1180            storages: B256Map::default(),
1181        };
1182
1183        let state2 = HashedPostStateSorted {
1184            accounts: vec![
1185                (B256::repeat_byte(2), Some(Account::default())),
1186                (B256::repeat_byte(3), Some(Account { nonce: 1, ..Default::default() })), /* Override */
1187                (B256::repeat_byte(4), Some(Account::default())),
1188                (B256::repeat_byte(6), None),
1189            ],
1190            storages: B256Map::default(),
1191        };
1192
1193        state1.extend_ref_and_sort(&state2);
1194
1195        // Check accounts are merged and sorted
1196        assert_eq!(state1.accounts.len(), 6);
1197        assert_eq!(state1.accounts[0].0, B256::repeat_byte(1));
1198        assert_eq!(state1.accounts[1].0, B256::repeat_byte(2));
1199        assert_eq!(state1.accounts[2].0, B256::repeat_byte(3));
1200        assert_eq!(state1.accounts[2].1.as_ref().unwrap().nonce, 1); // Should have state2's value
1201        assert_eq!(state1.accounts[3].0, B256::repeat_byte(4));
1202        assert_eq!(state1.accounts[4].0, B256::repeat_byte(5));
1203        assert_eq!(state1.accounts[4].1, None);
1204        assert_eq!(state1.accounts[5].0, B256::repeat_byte(6));
1205        assert_eq!(state1.accounts[5].1, None);
1206    }
1207
1208    #[test]
1209    fn test_hashed_storage_sorted_extend_ref() {
1210        // Test normal extension
1211        let mut storage1 = HashedStorageSorted {
1212            storage_slots: vec![
1213                (B256::repeat_byte(1), U256::from(10)),
1214                (B256::repeat_byte(3), U256::from(30)),
1215                (B256::repeat_byte(5), U256::ZERO),
1216            ],
1217        };
1218
1219        let storage2 = HashedStorageSorted {
1220            storage_slots: vec![
1221                (B256::repeat_byte(2), U256::from(20)),
1222                (B256::repeat_byte(3), U256::from(300)), // Override
1223                (B256::repeat_byte(4), U256::from(40)),
1224                (B256::repeat_byte(6), U256::ZERO),
1225            ],
1226        };
1227
1228        storage1.extend_ref(&storage2);
1229
1230        assert_eq!(storage1.storage_slots.len(), 6);
1231        assert_eq!(storage1.storage_slots[0].0, B256::repeat_byte(1));
1232        assert_eq!(storage1.storage_slots[0].1, U256::from(10));
1233        assert_eq!(storage1.storage_slots[1].0, B256::repeat_byte(2));
1234        assert_eq!(storage1.storage_slots[1].1, U256::from(20));
1235        assert_eq!(storage1.storage_slots[2].0, B256::repeat_byte(3));
1236        assert_eq!(storage1.storage_slots[2].1, U256::from(300)); // Should have storage2's value
1237        assert_eq!(storage1.storage_slots[3].0, B256::repeat_byte(4));
1238        assert_eq!(storage1.storage_slots[3].1, U256::from(40));
1239        assert_eq!(storage1.storage_slots[4].0, B256::repeat_byte(5));
1240        assert_eq!(storage1.storage_slots[4].1, U256::ZERO);
1241        assert_eq!(storage1.storage_slots[5].0, B256::repeat_byte(6));
1242        assert_eq!(storage1.storage_slots[5].1, U256::ZERO);
1243    }
1244
1245    /// Test extending with sorted accounts merges correctly into `HashMap`
1246    #[test]
1247    fn test_hashed_post_state_extend_from_sorted_with_accounts() {
1248        let addr1 = B256::random();
1249        let addr2 = B256::random();
1250
1251        let mut state = HashedPostState::default();
1252        state.accounts.insert(addr1, Some(Default::default()));
1253
1254        let mut sorted_state = HashedPostStateSorted::default();
1255        sorted_state.accounts.push((addr2, Some(Default::default())));
1256
1257        state.extend_from_sorted(&sorted_state);
1258
1259        assert_eq!(state.accounts.len(), 2);
1260        assert!(state.accounts.contains_key(&addr1));
1261        assert!(state.accounts.contains_key(&addr2));
1262    }
1263
1264    /// Test destroyed accounts (None values) are inserted correctly
1265    #[test]
1266    fn test_hashed_post_state_extend_from_sorted_with_destroyed_accounts() {
1267        let addr1 = B256::random();
1268
1269        let mut state = HashedPostState::default();
1270
1271        let mut sorted_state = HashedPostStateSorted::default();
1272        sorted_state.accounts.push((addr1, None));
1273
1274        state.extend_from_sorted(&sorted_state);
1275
1276        assert!(state.accounts.contains_key(&addr1));
1277        assert_eq!(state.accounts.get(&addr1), Some(&None));
1278    }
1279
1280    #[test]
1281    fn test_hashed_post_state_sorted_disjointed_merge_batch() {
1282        fn account(nonce: u64) -> Account {
1283            Account { nonce, ..Default::default() }
1284        }
1285
1286        let kept_account = B256::with_last_byte(1);
1287        let removed_account = B256::with_last_byte(2);
1288        let kept_storage = B256::with_last_byte(3);
1289        let slot1 = B256::with_last_byte(11);
1290        let slot2 = B256::with_last_byte(12);
1291
1292        let older = HashedPostStateSorted::new(
1293            vec![(kept_account, Some(account(1))), (removed_account, Some(account(10)))],
1294            B256Map::from_iter([(
1295                kept_storage,
1296                HashedStorageSorted { storage_slots: vec![(slot1, U256::ONE)] },
1297            )]),
1298        );
1299
1300        let newer = HashedPostStateSorted::new(
1301            vec![(kept_account, Some(account(2)))],
1302            B256Map::from_iter([(
1303                kept_storage,
1304                HashedStorageSorted {
1305                    storage_slots: vec![(slot1, U256::from(3)), (slot2, U256::from(4))],
1306                },
1307            )]),
1308        );
1309
1310        let remove_a = HashedPostStateSorted::new(
1311            vec![(removed_account, None)],
1312            B256Map::from_iter([(
1313                kept_storage,
1314                HashedStorageSorted { storage_slots: vec![(slot2, U256::ZERO)] },
1315            )]),
1316        );
1317
1318        let remove_b = HashedPostStateSorted::new(
1319            vec![(B256::with_last_byte(255), Some(account(99)))],
1320            B256Map::default(),
1321        );
1322
1323        let result = HashedPostStateSorted::disjointed_merge_batch(
1324            &[&older, &newer],
1325            &[&remove_b, &remove_a],
1326        );
1327
1328        assert_eq!(result.accounts, vec![(kept_account, Some(account(2)))]);
1329        assert_eq!(result.storages.len(), 1);
1330        assert_eq!(
1331            result.storages.get(&kept_storage),
1332            Some(&HashedStorageSorted { storage_slots: vec![(slot1, U256::from(3))] })
1333        );
1334    }
1335
1336    #[test]
1337    fn test_hashed_post_state_sorted_disjointed_merge_batch_empty_mask_merges_batch() {
1338        let address = B256::with_last_byte(1);
1339        let storage = B256::with_last_byte(2);
1340        let slot = B256::with_last_byte(3);
1341        let empty_storage = B256::with_last_byte(4);
1342        let older = HashedPostStateSorted::new(
1343            vec![(address, Some(Account { nonce: 1, ..Default::default() }))],
1344            B256Map::from_iter([
1345                (storage, HashedStorageSorted { storage_slots: vec![(slot, U256::ONE)] }),
1346                (empty_storage, HashedStorageSorted::default()),
1347            ]),
1348        );
1349        let newer = HashedPostStateSorted::new(
1350            vec![(address, Some(Account { nonce: 2, ..Default::default() }))],
1351            B256Map::from_iter([(
1352                storage,
1353                HashedStorageSorted { storage_slots: vec![(slot, U256::from(2))] },
1354            )]),
1355        );
1356        let expected = HashedPostStateSorted::merge_batch(vec![newer.clone(), older.clone()]);
1357
1358        let result = HashedPostStateSorted::disjointed_merge_batch(&[&older, &newer], &[]);
1359
1360        assert_eq!(result, expected);
1361    }
1362
1363    #[test]
1364    fn test_hashed_post_state_sorted_disjointed_merge_batch_removes_overlapping_batch_key() {
1365        fn account(nonce: u64) -> Account {
1366            Account { nonce, ..Default::default() }
1367        }
1368
1369        let overlapping_account = B256::with_last_byte(21);
1370
1371        let older = HashedPostStateSorted::new(
1372            vec![(overlapping_account, Some(account(1)))],
1373            B256Map::default(),
1374        );
1375
1376        let newer = HashedPostStateSorted::new(
1377            vec![(overlapping_account, Some(account(2)))],
1378            B256Map::default(),
1379        );
1380
1381        let remove =
1382            HashedPostStateSorted::new(vec![(overlapping_account, None)], B256Map::default());
1383
1384        let result = HashedPostStateSorted::disjointed_merge_batch(&[&older, &newer], &[&remove]);
1385
1386        assert!(result.accounts.is_empty());
1387    }
1388
1389    #[test]
1390    fn test_hashed_post_state_sorted_disjointed_merge_batch_keeps_equal_overlaps() {
1391        fn account(nonce: u64) -> Account {
1392            Account { nonce, ..Default::default() }
1393        }
1394
1395        let address = B256::with_last_byte(21);
1396        let deleted_address = B256::with_last_byte(24);
1397        let storage = B256::with_last_byte(22);
1398        let deleted_storage = B256::with_last_byte(25);
1399        let slot = B256::with_last_byte(23);
1400        let deleted_slot = B256::with_last_byte(26);
1401        let batch = HashedPostStateSorted::new(
1402            vec![(address, Some(account(1))), (deleted_address, None)],
1403            B256Map::from_iter([
1404                (storage, HashedStorageSorted { storage_slots: vec![(slot, U256::ONE)] }),
1405                (
1406                    deleted_storage,
1407                    HashedStorageSorted { storage_slots: vec![(deleted_slot, U256::ZERO)] },
1408                ),
1409            ]),
1410        );
1411        let different_mask = HashedPostStateSorted::new(
1412            vec![(address, Some(account(2))), (deleted_address, Some(account(3)))],
1413            B256Map::from_iter([
1414                (storage, HashedStorageSorted { storage_slots: vec![(slot, U256::from(2))] }),
1415                (
1416                    deleted_storage,
1417                    HashedStorageSorted { storage_slots: vec![(deleted_slot, U256::from(3))] },
1418                ),
1419            ]),
1420        );
1421        let equal_mask = batch.clone();
1422
1423        let result = HashedPostStateSorted::disjointed_merge_batch(
1424            &[&batch],
1425            &[&different_mask, &equal_mask],
1426        );
1427        let reversed = HashedPostStateSorted::disjointed_merge_batch(
1428            &[&batch],
1429            &[&equal_mask, &different_mask],
1430        );
1431
1432        assert_eq!(result, batch);
1433        assert_eq!(reversed, result);
1434    }
1435
1436    #[test]
1437    fn test_hashed_post_state_sorted_disjointed_merge_batch_ignores_empty_storage_mask() {
1438        let storage = B256::with_last_byte(31);
1439        let slot = B256::with_last_byte(32);
1440
1441        let batch = HashedPostStateSorted::new(
1442            vec![],
1443            B256Map::from_iter([(
1444                storage,
1445                HashedStorageSorted { storage_slots: vec![(slot, U256::ONE)] },
1446            )]),
1447        );
1448        let mask = HashedPostStateSorted::new(
1449            vec![],
1450            B256Map::from_iter([(storage, HashedStorageSorted { storage_slots: vec![] })]),
1451        );
1452
1453        let result = HashedPostStateSorted::disjointed_merge_batch(&[&batch], &[&mask]);
1454
1455        assert_eq!(
1456            result.storages.get(&storage),
1457            Some(&HashedStorageSorted { storage_slots: vec![(slot, U256::ONE)] })
1458        );
1459    }
1460
1461    /// Test storage merges both zero and non-zero valued slots
1462    #[test]
1463    fn test_hashed_storage_extend_from_sorted() {
1464        let slot1 = B256::random();
1465        let slot2 = B256::random();
1466        let slot3 = B256::random();
1467
1468        let mut storage = HashedStorage::from_iter([(slot1, U256::from(100))]);
1469
1470        let sorted = HashedStorageSorted {
1471            storage_slots: vec![(slot2, U256::from(200)), (slot3, U256::ZERO)],
1472        };
1473
1474        storage.extend_from_sorted(&sorted);
1475        assert_eq!(storage.storage.len(), 3);
1476        assert_eq!(storage.storage.get(&slot1), Some(&U256::from(100)));
1477        assert_eq!(storage.storage.get(&slot2), Some(&U256::from(200)));
1478        assert_eq!(storage.storage.get(&slot3), Some(&U256::ZERO));
1479    }
1480
1481    #[test]
1482    fn test_hashed_post_state_chunking_length() {
1483        let addr1 = B256::repeat_byte(1);
1484        let addr2 = B256::repeat_byte(2);
1485        let addr3 = B256::repeat_byte(3);
1486        let addr4 = B256::repeat_byte(4);
1487        let slot1 = B256::repeat_byte(1);
1488        let slot2 = B256::repeat_byte(2);
1489        let slot3 = B256::repeat_byte(3);
1490
1491        let state = HashedPostState {
1492            accounts: B256Map::from_iter([(addr1, None), (addr2, None), (addr4, None)]),
1493            storages: B256Map::from_iter([
1494                (
1495                    addr1,
1496                    HashedStorage {
1497                        storage: B256Map::from_iter([
1498                            (slot1, U256::ZERO),
1499                            (slot2, U256::ZERO),
1500                            (slot3, U256::ZERO),
1501                        ]),
1502                    },
1503                ),
1504                (
1505                    addr2,
1506                    HashedStorage {
1507                        storage: B256Map::from_iter([
1508                            (slot1, U256::ZERO),
1509                            (slot2, U256::ZERO),
1510                            (slot3, U256::ZERO),
1511                        ]),
1512                    },
1513                ),
1514                (
1515                    addr3,
1516                    HashedStorage {
1517                        storage: B256Map::from_iter([
1518                            (slot1, U256::ZERO),
1519                            (slot2, U256::ZERO),
1520                            (slot3, U256::ZERO),
1521                        ]),
1522                    },
1523                ),
1524            ]),
1525        };
1526
1527        let chunking_length = state.chunking_length();
1528        for size in 1..=state.clone().chunks(1).count() {
1529            let chunk_count = state.clone().chunks(size).count();
1530            let expected_count = chunking_length.div_ceil(size);
1531            assert_eq!(
1532                chunk_count, expected_count,
1533                "chunking_length: {}, size: {}",
1534                chunking_length, size
1535            );
1536        }
1537    }
1538
1539    #[test]
1540    fn test_clone_into_sorted_equivalence() {
1541        let addr1 = B256::repeat_byte(1);
1542        let addr2 = B256::repeat_byte(2);
1543        let addr3 = B256::repeat_byte(3);
1544        let slot1 = B256::repeat_byte(1);
1545        let slot2 = B256::repeat_byte(2);
1546        let slot3 = B256::repeat_byte(3);
1547
1548        let state = HashedPostState {
1549            accounts: B256Map::from_iter([
1550                (addr1, Some(Account { nonce: 1, balance: U256::from(100), ..Default::default() })),
1551                (addr2, None),
1552                (addr3, Some(Account::default())),
1553            ]),
1554            storages: B256Map::from_iter([
1555                (
1556                    addr1,
1557                    HashedStorage {
1558                        storage: B256Map::from_iter([
1559                            (slot1, U256::from(10)),
1560                            (slot2, U256::from(20)),
1561                        ]),
1562                    },
1563                ),
1564                (addr2, HashedStorage { storage: B256Map::from_iter([(slot3, U256::ZERO)]) }),
1565            ]),
1566        };
1567
1568        // clone_into_sorted should produce the same result as clone().into_sorted()
1569        let sorted_via_clone = state.clone().into_sorted();
1570        let sorted_via_clone_into = state.clone_into_sorted();
1571
1572        assert_eq!(sorted_via_clone, sorted_via_clone_into);
1573
1574        // Verify the original state is not consumed
1575        assert_eq!(state.accounts.len(), 3);
1576        assert_eq!(state.storages.len(), 2);
1577    }
1578
1579    #[test]
1580    fn test_hashed_storage_clone_into_sorted_equivalence() {
1581        let slot1 = B256::repeat_byte(1);
1582        let slot2 = B256::repeat_byte(2);
1583        let slot3 = B256::repeat_byte(3);
1584
1585        let storage = HashedStorage {
1586            storage: B256Map::from_iter([
1587                (slot1, U256::from(100)),
1588                (slot2, U256::ZERO),
1589                (slot3, U256::from(300)),
1590            ]),
1591        };
1592
1593        // clone_into_sorted should produce the same result as clone().into_sorted()
1594        let sorted_via_clone = storage.clone().into_sorted();
1595        let sorted_via_clone_into = storage.clone_into_sorted();
1596
1597        assert_eq!(sorted_via_clone, sorted_via_clone_into);
1598
1599        // Verify the original storage is not consumed
1600        assert_eq!(storage.storage.len(), 3);
1601    }
1602}
1603
1604/// Bincode-compatible hashed state type serde implementations.
1605#[cfg(feature = "serde-bincode-compat")]
1606pub mod serde_bincode_compat {
1607    use super::Account;
1608    use alloc::{borrow::Cow, vec::Vec};
1609    use alloy_primitives::{map::B256Map, B256, U256};
1610    use core::fmt;
1611    use serde::{
1612        de::{Error as _, SeqAccess, Visitor},
1613        Deserialize, Deserializer, Serialize, Serializer,
1614    };
1615    use serde_with::{DeserializeAs, SerializeAs};
1616
1617    /// Bincode-compatible [`super::HashedPostState`] serde implementation.
1618    ///
1619    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
1620    /// ```rust
1621    /// use reth_trie_common::{serde_bincode_compat, HashedPostState};
1622    /// use serde::{Deserialize, Serialize};
1623    /// use serde_with::serde_as;
1624    ///
1625    /// #[serde_as]
1626    /// #[derive(Serialize, Deserialize)]
1627    /// struct Data {
1628    ///     #[serde_as(as = "serde_bincode_compat::hashed_state::HashedPostState")]
1629    ///     hashed_state: HashedPostState,
1630    /// }
1631    /// ```
1632    #[derive(Debug, Serialize, Deserialize)]
1633    pub struct HashedPostState<'a> {
1634        accounts: Cow<'a, B256Map<Option<Account>>>,
1635        storages: B256Map<HashedStorage<'a>>,
1636    }
1637
1638    impl<'a> From<&'a super::HashedPostState> for HashedPostState<'a> {
1639        fn from(value: &'a super::HashedPostState) -> Self {
1640            Self {
1641                accounts: Cow::Borrowed(&value.accounts),
1642                storages: value.storages.iter().map(|(k, v)| (*k, v.into())).collect(),
1643            }
1644        }
1645    }
1646
1647    impl<'a> From<HashedPostState<'a>> for super::HashedPostState {
1648        fn from(value: HashedPostState<'a>) -> Self {
1649            Self {
1650                accounts: value.accounts.into_owned(),
1651                storages: value.storages.into_iter().map(|(k, v)| (k, v.into())).collect(),
1652            }
1653        }
1654    }
1655
1656    impl SerializeAs<super::HashedPostState> for HashedPostState<'_> {
1657        fn serialize_as<S>(
1658            source: &super::HashedPostState,
1659            serializer: S,
1660        ) -> Result<S::Ok, S::Error>
1661        where
1662            S: Serializer,
1663        {
1664            HashedPostState::from(source).serialize(serializer)
1665        }
1666    }
1667
1668    impl<'de> DeserializeAs<'de, super::HashedPostState> for HashedPostState<'de> {
1669        fn deserialize_as<D>(deserializer: D) -> Result<super::HashedPostState, D::Error>
1670        where
1671            D: Deserializer<'de>,
1672        {
1673            HashedPostState::deserialize(deserializer).map(Into::into)
1674        }
1675    }
1676
1677    /// Bincode-compatible [`super::HashedStorage`] serde implementation.
1678    ///
1679    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
1680    /// ```rust
1681    /// use reth_trie_common::{serde_bincode_compat, HashedStorage};
1682    /// use serde::{Deserialize, Serialize};
1683    /// use serde_with::serde_as;
1684    ///
1685    /// #[serde_as]
1686    /// #[derive(Serialize, Deserialize)]
1687    /// struct Data {
1688    ///     #[serde_as(as = "serde_bincode_compat::hashed_state::HashedStorage")]
1689    ///     hashed_storage: HashedStorage,
1690    /// }
1691    /// ```
1692    #[derive(Debug, Serialize, Deserialize)]
1693    pub struct HashedStorage<'a> {
1694        storage: Cow<'a, B256Map<U256>>,
1695    }
1696
1697    impl<'a> From<&'a super::HashedStorage> for HashedStorage<'a> {
1698        fn from(value: &'a super::HashedStorage) -> Self {
1699            Self { storage: Cow::Borrowed(&value.storage) }
1700        }
1701    }
1702
1703    impl<'a> From<HashedStorage<'a>> for super::HashedStorage {
1704        fn from(value: HashedStorage<'a>) -> Self {
1705            Self { storage: value.storage.into_owned() }
1706        }
1707    }
1708
1709    impl SerializeAs<super::HashedStorage> for HashedStorage<'_> {
1710        fn serialize_as<S>(source: &super::HashedStorage, serializer: S) -> Result<S::Ok, S::Error>
1711        where
1712            S: Serializer,
1713        {
1714            HashedStorage::from(source).serialize(serializer)
1715        }
1716    }
1717
1718    impl<'de> DeserializeAs<'de, super::HashedStorage> for HashedStorage<'de> {
1719        fn deserialize_as<D>(deserializer: D) -> Result<super::HashedStorage, D::Error>
1720        where
1721            D: Deserializer<'de>,
1722        {
1723            HashedStorage::deserialize(deserializer).map(Into::into)
1724        }
1725    }
1726
1727    /// Bincode-compatible [`super::HashedPostStateSorted`] serde implementation.
1728    ///
1729    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
1730    /// ```rust
1731    /// use reth_trie_common::{serde_bincode_compat, HashedPostStateSorted};
1732    /// use serde::{Deserialize, Serialize};
1733    /// use serde_with::serde_as;
1734    ///
1735    /// #[serde_as]
1736    /// #[derive(Serialize, Deserialize)]
1737    /// struct Data {
1738    ///     #[serde_as(as = "serde_bincode_compat::hashed_state::HashedPostStateSorted")]
1739    ///     hashed_state: HashedPostStateSorted,
1740    /// }
1741    /// ```
1742    #[derive(Debug, Serialize, Deserialize)]
1743    pub struct HashedPostStateSorted<'a> {
1744        accounts: Cow<'a, [(B256, Option<Account>)]>,
1745        storages: B256Map<HashedStorageSorted<'a>>,
1746    }
1747
1748    impl<'a> From<&'a super::HashedPostStateSorted> for HashedPostStateSorted<'a> {
1749        fn from(value: &'a super::HashedPostStateSorted) -> Self {
1750            Self {
1751                accounts: Cow::Borrowed(&value.accounts),
1752                storages: value.storages.iter().map(|(k, v)| (*k, v.into())).collect(),
1753            }
1754        }
1755    }
1756
1757    impl<'a> From<HashedPostStateSorted<'a>> for super::HashedPostStateSorted {
1758        fn from(value: HashedPostStateSorted<'a>) -> Self {
1759            Self {
1760                accounts: value.accounts.into_owned(),
1761                storages: value.storages.into_iter().map(|(k, v)| (k, v.into())).collect(),
1762            }
1763        }
1764    }
1765
1766    impl SerializeAs<super::HashedPostStateSorted> for HashedPostStateSorted<'_> {
1767        fn serialize_as<S>(
1768            source: &super::HashedPostStateSorted,
1769            serializer: S,
1770        ) -> Result<S::Ok, S::Error>
1771        where
1772            S: Serializer,
1773        {
1774            HashedPostStateSorted::from(source).serialize(serializer)
1775        }
1776    }
1777
1778    impl<'de> DeserializeAs<'de, super::HashedPostStateSorted> for HashedPostStateSorted<'de> {
1779        fn deserialize_as<D>(deserializer: D) -> Result<super::HashedPostStateSorted, D::Error>
1780        where
1781            D: Deserializer<'de>,
1782        {
1783            HashedPostStateSorted::deserialize(deserializer).map(Into::into)
1784        }
1785    }
1786
1787    /// Bincode-compatible [`super::HashedStorageSorted`] serde implementation.
1788    ///
1789    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
1790    /// ```rust
1791    /// use reth_trie_common::{serde_bincode_compat, HashedStorageSorted};
1792    /// use serde::{Deserialize, Serialize};
1793    /// use serde_with::serde_as;
1794    ///
1795    /// #[serde_as]
1796    /// #[derive(Serialize, Deserialize)]
1797    /// struct Data {
1798    ///     #[serde_as(as = "serde_bincode_compat::hashed_state::HashedStorageSorted")]
1799    ///     hashed_storage: HashedStorageSorted,
1800    /// }
1801    /// ```
1802    #[derive(Debug, Serialize)]
1803    pub struct HashedStorageSorted<'a> {
1804        storage_slots: Cow<'a, [(B256, U256)]>,
1805    }
1806
1807    impl<'de, 'a> Deserialize<'de> for HashedStorageSorted<'a> {
1808        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1809        where
1810            D: Deserializer<'de>,
1811        {
1812            struct HashedStorageSortedVisitor;
1813
1814            impl<'de> Visitor<'de> for HashedStorageSortedVisitor {
1815                type Value = Vec<(B256, U256)>;
1816
1817                fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1818                    formatter.write_str("hashed storage with an optional legacy wipe marker")
1819                }
1820
1821                fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1822                where
1823                    A: SeqAccess<'de>,
1824                {
1825                    let len = seq.size_hint().unwrap_or_default();
1826                    if !matches!(len, 1 | 2) {
1827                        return Err(A::Error::invalid_length(len, &self))
1828                    }
1829
1830                    let storage_slots =
1831                        seq.next_element()?.ok_or_else(|| A::Error::invalid_length(0, &self))?;
1832                    if len == 2 {
1833                        let _: bool = seq
1834                            .next_element()?
1835                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
1836                    }
1837
1838                    Ok(storage_slots)
1839                }
1840            }
1841
1842            // Bincode uses the supplied tuple length for the current format, while MessagePack
1843            // exposes the encoded sequence length so legacy ExEx WAL entries can still be read.
1844            deserializer
1845                .deserialize_tuple(1, HashedStorageSortedVisitor)
1846                .map(|storage_slots| Self { storage_slots: Cow::Owned(storage_slots) })
1847        }
1848    }
1849
1850    impl<'a> From<&'a super::HashedStorageSorted> for HashedStorageSorted<'a> {
1851        fn from(value: &'a super::HashedStorageSorted) -> Self {
1852            Self { storage_slots: Cow::Borrowed(&value.storage_slots) }
1853        }
1854    }
1855
1856    impl<'a> From<HashedStorageSorted<'a>> for super::HashedStorageSorted {
1857        fn from(value: HashedStorageSorted<'a>) -> Self {
1858            Self { storage_slots: value.storage_slots.into_owned() }
1859        }
1860    }
1861
1862    impl SerializeAs<super::HashedStorageSorted> for HashedStorageSorted<'_> {
1863        fn serialize_as<S>(
1864            source: &super::HashedStorageSorted,
1865            serializer: S,
1866        ) -> Result<S::Ok, S::Error>
1867        where
1868            S: Serializer,
1869        {
1870            HashedStorageSorted::from(source).serialize(serializer)
1871        }
1872    }
1873
1874    impl<'de> DeserializeAs<'de, super::HashedStorageSorted> for HashedStorageSorted<'de> {
1875        fn deserialize_as<D>(deserializer: D) -> Result<super::HashedStorageSorted, D::Error>
1876        where
1877            D: Deserializer<'de>,
1878        {
1879            HashedStorageSorted::deserialize(deserializer).map(Into::into)
1880        }
1881    }
1882
1883    #[cfg(test)]
1884    mod tests {
1885        use crate::{
1886            hashed_state::{
1887                HashedPostState, HashedPostStateSorted, HashedStorage, HashedStorageSorted,
1888            },
1889            serde_bincode_compat,
1890        };
1891        use alloy_primitives::{B256, U256};
1892        use reth_primitives_traits::Account;
1893        use serde::{Deserialize, Serialize};
1894        use serde_with::serde_as;
1895
1896        #[test]
1897        fn test_hashed_post_state_bincode_roundtrip() {
1898            // Bincode cannot delimit an account whose extension is skipped during serialization.
1899            if Account::EXTENSIONS_ENABLED {
1900                return;
1901            }
1902
1903            #[serde_as]
1904            #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
1905            struct Data {
1906                #[serde_as(as = "serde_bincode_compat::hashed_state::HashedPostState")]
1907                hashed_state: HashedPostState,
1908            }
1909
1910            let mut data = Data { hashed_state: HashedPostState::default() };
1911            let encoded = bincode::serialize(&data).unwrap();
1912            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1913            assert_eq!(decoded, data);
1914
1915            data.hashed_state.accounts.insert(B256::random(), Some(Account::default()));
1916            let encoded = bincode::serialize(&data).unwrap();
1917            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1918            assert_eq!(decoded, data);
1919
1920            data.hashed_state.storages.insert(B256::random(), HashedStorage::default());
1921            let encoded = bincode::serialize(&data).unwrap();
1922            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1923            assert_eq!(decoded, data);
1924        }
1925
1926        #[test]
1927        fn test_hashed_storage_bincode_roundtrip() {
1928            #[serde_as]
1929            #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
1930            struct Data {
1931                #[serde_as(as = "serde_bincode_compat::hashed_state::HashedStorage")]
1932                hashed_storage: HashedStorage,
1933            }
1934
1935            let mut data = Data { hashed_storage: HashedStorage::default() };
1936            let encoded = bincode::serialize(&data).unwrap();
1937            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1938            assert_eq!(decoded, data);
1939
1940            data.hashed_storage.storage.insert(B256::random(), U256::ONE);
1941            let encoded = bincode::serialize(&data).unwrap();
1942            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1943            assert_eq!(decoded, data);
1944        }
1945
1946        #[test]
1947        fn test_hashed_post_state_sorted_bincode_roundtrip() {
1948            // Bincode cannot delimit an account whose extension is skipped during serialization.
1949            if Account::EXTENSIONS_ENABLED {
1950                return;
1951            }
1952
1953            #[serde_as]
1954            #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
1955            struct Data {
1956                #[serde_as(as = "serde_bincode_compat::hashed_state::HashedPostStateSorted")]
1957                hashed_state: HashedPostStateSorted,
1958            }
1959
1960            let mut data = Data { hashed_state: HashedPostStateSorted::default() };
1961            let encoded = bincode::serialize(&data).unwrap();
1962            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1963            assert_eq!(decoded, data);
1964
1965            data.hashed_state.accounts.push((B256::random(), Some(Account::default())));
1966            data.hashed_state
1967                .accounts
1968                .push((B256::random(), Some(Account { nonce: 1, ..Default::default() })));
1969            let encoded = bincode::serialize(&data).unwrap();
1970            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1971            assert_eq!(decoded, data);
1972
1973            data.hashed_state.storages.insert(
1974                B256::random(),
1975                HashedStorageSorted { storage_slots: vec![(B256::repeat_byte(1), U256::from(10))] },
1976            );
1977            let encoded = bincode::serialize(&data).unwrap();
1978            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1979            assert_eq!(decoded, data);
1980        }
1981
1982        #[test]
1983        fn test_hashed_storage_sorted_bincode_roundtrip() {
1984            #[serde_as]
1985            #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
1986            struct Data {
1987                #[serde_as(as = "serde_bincode_compat::hashed_state::HashedStorageSorted")]
1988                hashed_storage: HashedStorageSorted,
1989            }
1990
1991            let mut data =
1992                Data { hashed_storage: HashedStorageSorted { storage_slots: Vec::new() } };
1993            let encoded = bincode::serialize(&data).unwrap();
1994            let decoded: Data = bincode::deserialize(&encoded).unwrap();
1995            assert_eq!(decoded, data);
1996
1997            data.hashed_storage.storage_slots.push((B256::random(), U256::ONE));
1998            let encoded = bincode::serialize(&data).unwrap();
1999            let decoded: Data = bincode::deserialize(&encoded).unwrap();
2000            assert_eq!(decoded, data);
2001        }
2002    }
2003}