Skip to main content

reth_trie_db/
state.rs

1use crate::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory};
2use alloy_primitives::{keccak256, map::B256Map, Address, BlockNumber, B256};
3use reth_db_api::{
4    models::{AccountBeforeTx, BlockNumberAddress},
5    transaction::DbTx,
6};
7use reth_execution_errors::StateRootError;
8use reth_storage_api::{ChangeSetReader, DBProvider, StorageChangeSetReader, StorageSettingsCache};
9use reth_storage_errors::provider::ProviderError;
10use reth_trie::{
11    hashed_cursor::HashedPostStateCursorFactory, trie_cursor::InMemoryTrieCursorFactory,
12    updates::TrieUpdates, HashedPostStateSorted, HashedStorageSorted, StateRoot, TrieInputSorted,
13};
14use std::{collections::HashSet, ops::RangeInclusive};
15use tracing::{debug, instrument};
16
17/// Extends [`StateRoot`] with operations specific for working with a database transaction.
18pub trait DatabaseStateRoot<'a, TX>: Sized {
19    /// Create a new [`StateRoot`] instance.
20    fn from_tx(tx: &'a TX) -> Self;
21
22    /// Given a block number range, identifies all the accounts and storage keys that
23    /// have changed.
24    ///
25    /// # Returns
26    ///
27    /// An instance of state root calculator with account and storage prefixes loaded.
28    fn incremental_root_calculator(
29        provider: &'a (impl ChangeSetReader
30                 + StorageChangeSetReader
31                 + StorageSettingsCache
32                 + DBProvider<Tx = TX>),
33        range: RangeInclusive<BlockNumber>,
34    ) -> Result<Self, StateRootError>;
35
36    /// Computes the state root of the trie with the changed account and storage prefixes and
37    /// existing trie nodes collecting updates in the process.
38    ///
39    /// Ignores the threshold.
40    ///
41    /// # Returns
42    ///
43    /// The updated state root and the trie updates.
44    fn incremental_root_with_updates(
45        provider: &'a (impl ChangeSetReader
46                 + StorageChangeSetReader
47                 + StorageSettingsCache
48                 + DBProvider<Tx = TX>),
49        range: RangeInclusive<BlockNumber>,
50    ) -> Result<(B256, TrieUpdates), StateRootError>;
51
52    /// Calculate the state root for this [`HashedPostStateSorted`].
53    /// Internally, this method retrieves prefixsets and uses them
54    /// to calculate incremental state root.
55    ///
56    /// # Example
57    ///
58    /// ```
59    /// use alloy_primitives::U256;
60    /// use reth_db::test_utils::create_test_rw_db;
61    /// use reth_db_api::database::Database;
62    /// use reth_primitives_traits::Account;
63    /// use reth_trie::{updates::TrieUpdates, HashedPostState, StateRoot};
64    /// use reth_trie_db::{DatabaseStateRoot, LegacyKeyAdapter};
65    ///
66    /// # reth_concurrency::sync::Runtime::new().run(|| {
67    /// // Initialize the database
68    /// let db = create_test_rw_db();
69    ///
70    /// // Initialize hashed post state
71    /// let mut hashed_state = HashedPostState::default();
72    /// hashed_state.accounts.insert(
73    ///     [0x11; 32].into(),
74    ///     Some(Account { nonce: 1, balance: U256::from(10), ..Default::default() }),
75    /// );
76    ///
77    /// // Calculate the state root
78    /// let tx = db.tx().expect("failed to create transaction");
79    /// let state_root = <StateRoot<
80    ///     reth_trie_db::DatabaseTrieCursorFactory<_, LegacyKeyAdapter>,
81    ///     reth_trie_db::DatabaseHashedCursorFactory<_>,
82    /// > as DatabaseStateRoot<_>>::overlay_root(&tx, &hashed_state.into_sorted());
83    /// # });
84    /// ```
85    ///
86    /// # Returns
87    ///
88    /// The state root for this [`HashedPostStateSorted`].
89    fn overlay_root(tx: &'a TX, post_state: &HashedPostStateSorted)
90        -> Result<B256, StateRootError>;
91
92    /// Calculates the state root for this [`HashedPostStateSorted`] and returns it alongside trie
93    /// updates. See [`Self::overlay_root`] for more info.
94    fn overlay_root_with_updates(
95        tx: &'a TX,
96        post_state: &HashedPostStateSorted,
97    ) -> Result<(B256, TrieUpdates), StateRootError>;
98
99    /// Calculates the state root for provided [`HashedPostStateSorted`] using cached intermediate
100    /// nodes.
101    fn overlay_root_from_nodes(tx: &'a TX, input: TrieInputSorted) -> Result<B256, StateRootError>;
102
103    /// Calculates the state root and trie updates for provided [`HashedPostStateSorted`] using
104    /// cached intermediate nodes.
105    fn overlay_root_from_nodes_with_updates(
106        tx: &'a TX,
107        input: TrieInputSorted,
108    ) -> Result<(B256, TrieUpdates), StateRootError>;
109}
110
111/// Extends [`HashedPostStateSorted`] with operations specific for working with a database
112/// transaction.
113pub trait DatabaseHashedPostState: Sized {
114    /// Initializes [`HashedPostStateSorted`] from reverts. Iterates over state reverts in the
115    /// specified range and aggregates them into sorted hashed state.
116    fn from_reverts(
117        provider: &(impl ChangeSetReader + StorageChangeSetReader),
118        range: RangeInclusive<BlockNumber>,
119    ) -> Result<HashedPostStateSorted, ProviderError>;
120}
121
122impl<'a, TX: DbTx, A: crate::TrieTableAdapter> DatabaseStateRoot<'a, TX>
123    for StateRoot<DatabaseTrieCursorFactory<&'a TX, A>, DatabaseHashedCursorFactory<&'a TX>>
124{
125    fn from_tx(tx: &'a TX) -> Self {
126        Self::new(DatabaseTrieCursorFactory::new(tx), DatabaseHashedCursorFactory::new(tx))
127    }
128
129    fn incremental_root_calculator(
130        provider: &'a (impl ChangeSetReader
131                 + StorageChangeSetReader
132                 + StorageSettingsCache
133                 + DBProvider<Tx = TX>),
134        range: RangeInclusive<BlockNumber>,
135    ) -> Result<Self, StateRootError> {
136        let loaded_prefix_sets =
137            crate::prefix_set::load_prefix_sets_with_provider(provider, range)?;
138        Ok(Self::from_tx(provider.tx_ref()).with_prefix_sets(loaded_prefix_sets))
139    }
140
141    fn incremental_root_with_updates(
142        provider: &'a (impl ChangeSetReader
143                 + StorageChangeSetReader
144                 + StorageSettingsCache
145                 + DBProvider<Tx = TX>),
146        range: RangeInclusive<BlockNumber>,
147    ) -> Result<(B256, TrieUpdates), StateRootError> {
148        debug!(target: "trie::loader", ?range, "incremental state root");
149        Self::incremental_root_calculator(provider, range)?.root_with_updates()
150    }
151
152    fn overlay_root(
153        tx: &'a TX,
154        post_state: &HashedPostStateSorted,
155    ) -> Result<B256, StateRootError> {
156        let prefix_sets = post_state.construct_prefix_sets().freeze();
157        StateRoot::new(
158            DatabaseTrieCursorFactory::<_, A>::new(tx),
159            HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), post_state),
160        )
161        .with_prefix_sets(prefix_sets)
162        .root()
163    }
164
165    fn overlay_root_with_updates(
166        tx: &'a TX,
167        post_state: &HashedPostStateSorted,
168    ) -> Result<(B256, TrieUpdates), StateRootError> {
169        let prefix_sets = post_state.construct_prefix_sets().freeze();
170        StateRoot::new(
171            DatabaseTrieCursorFactory::<_, A>::new(tx),
172            HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), post_state),
173        )
174        .with_prefix_sets(prefix_sets)
175        .root_with_updates()
176    }
177
178    fn overlay_root_from_nodes(tx: &'a TX, input: TrieInputSorted) -> Result<B256, StateRootError> {
179        StateRoot::new(
180            InMemoryTrieCursorFactory::new(
181                DatabaseTrieCursorFactory::<_, A>::new(tx),
182                input.nodes.as_ref(),
183            ),
184            HashedPostStateCursorFactory::new(
185                DatabaseHashedCursorFactory::new(tx),
186                input.state.as_ref(),
187            ),
188        )
189        .with_prefix_sets(input.prefix_sets.freeze())
190        .root()
191    }
192
193    fn overlay_root_from_nodes_with_updates(
194        tx: &'a TX,
195        input: TrieInputSorted,
196    ) -> Result<(B256, TrieUpdates), StateRootError> {
197        StateRoot::new(
198            InMemoryTrieCursorFactory::new(
199                DatabaseTrieCursorFactory::<_, A>::new(tx),
200                input.nodes.as_ref(),
201            ),
202            HashedPostStateCursorFactory::new(
203                DatabaseHashedCursorFactory::new(tx),
204                input.state.as_ref(),
205            ),
206        )
207        .with_prefix_sets(input.prefix_sets.freeze())
208        .root_with_updates()
209    }
210}
211
212impl DatabaseHashedPostState for HashedPostStateSorted {
213    /// Builds a sorted hashed post-state from reverts.
214    ///
215    /// Reads changesets one block at a time, so memory grows with the number of distinct changed
216    /// keys rather than with the number of changeset rows in the range. `HashSet`s track seen
217    /// keys; changeset rows are already sorted, so no intermediate `HashMap` is needed.
218    ///
219    /// - Reads the first occurrence of each changed account/storage slot in the range.
220    /// - Addresses are always keccak256-hashed.
221    /// - Storage keys are always plain and are hashed via `keccak256`.
222    /// - Returns keys already ordered for trie iteration.
223    #[instrument(target = "trie::db", skip(provider))]
224    fn from_reverts(
225        provider: &(impl ChangeSetReader + StorageChangeSetReader),
226        range: RangeInclusive<BlockNumber>,
227    ) -> Result<Self, ProviderError> {
228        let mut accounts = Vec::new();
229        let mut seen_accounts = HashSet::new();
230        // Only keep the first (oldest) occurrence of each (address, slot) pair.
231        let mut storages = B256Map::<Vec<_>>::default();
232        let mut seen_storage_keys = HashSet::new();
233        // Rows of a block are ordered by address, so all slots of one account arrive
234        // consecutively and the address hash can be reused across them.
235        let mut last_address: Option<(Address, B256)> = None;
236
237        // Blocks are visited oldest first, so the first occurrence of a key holds its value
238        // before the range.
239        for block in range {
240            for AccountBeforeTx { address, info } in provider.account_block_changeset(block)? {
241                if seen_accounts.insert(address) {
242                    accounts.push((keccak256(address), info));
243                }
244            }
245
246            for (BlockNumberAddress((_, address)), storage) in provider.storage_changeset(block)? {
247                if seen_storage_keys.insert((address, storage.key)) {
248                    let hashed_address = match last_address {
249                        Some((last, hashed)) if last == address => hashed,
250                        _ => {
251                            let hashed = keccak256(address);
252                            last_address = Some((address, hashed));
253                            hashed
254                        }
255                    };
256                    storages
257                        .entry(hashed_address)
258                        .or_default()
259                        .push((keccak256(storage.key), storage.value));
260                }
261            }
262        }
263        accounts.sort_unstable_by_key(|(hash, _)| *hash);
264
265        // Sort storage slots and convert to HashedStorageSorted
266        let hashed_storages = storages
267            .into_iter()
268            .map(|(address, mut slots)| {
269                slots.sort_unstable_by_key(|(slot, _)| *slot);
270                (address, HashedStorageSorted { storage_slots: slots })
271            })
272            .collect();
273
274        Ok(Self::new(accounts, hashed_storages))
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use alloy_primitives::{hex, keccak256, map::HashMap, Address, B256, U256};
282    use evm2::evm::AccountInfo;
283    use reth_db_api::{
284        models::{AccountBeforeTx, BlockNumberAddress, StorageBeforeTx, StorageSettings},
285        tables,
286        transaction::DbTxMut,
287    };
288    use reth_execution_errors::StateRootError;
289    use reth_primitives_traits::{Account, StorageEntry};
290    use reth_provider::{
291        test_utils::create_test_provider_factory, StaticFileProviderFactory, StaticFileSegment,
292        StaticFileWriter,
293    };
294    use reth_storage_api::StorageSettingsCache;
295    use reth_trie::{
296        HashedPostState, HashedPostStateSorted, HashedStorage, KeccakKeyHasher, StateRoot,
297    };
298    use reth_trie_common::bundle_state::BundleState;
299
300    fn overlay_root_for_provider<TX: reth_db_api::transaction::DbTx>(
301        provider: &impl StorageSettingsCache,
302        tx: &TX,
303        sorted: &HashedPostStateSorted,
304    ) -> Result<B256, StateRootError> {
305        crate::with_adapter!(provider, |A| {
306            type S<'a, TX> = StateRoot<
307                crate::DatabaseTrieCursorFactory<&'a TX, A>,
308                crate::DatabaseHashedCursorFactory<&'a TX>,
309            >;
310            S::overlay_root(tx, sorted)
311        })
312    }
313
314    /// Overlay root calculation works with sorted state.
315    #[test]
316    fn overlay_root_with_sorted_state() {
317        let factory = create_test_provider_factory();
318        let provider = factory.provider_rw().unwrap();
319
320        let mut hashed_state = HashedPostState::default();
321        hashed_state.accounts.insert(
322            B256::with_last_byte(1),
323            Some(Account { nonce: 1, balance: U256::from(10), ..Default::default() }),
324        );
325        hashed_state.accounts.insert(B256::with_last_byte(2), None);
326        hashed_state.storages.insert(
327            B256::with_last_byte(1),
328            HashedStorage::from_iter([(B256::with_last_byte(3), U256::from(30))]),
329        );
330
331        let sorted = hashed_state.into_sorted();
332        let overlay_root =
333            overlay_root_for_provider(&*provider, provider.tx_ref(), &sorted).unwrap();
334
335        // Just verify it produces a valid root
336        assert!(!overlay_root.is_zero());
337    }
338
339    /// Builds hashed state from a bundle and checks the known state root.
340    #[test]
341    fn from_bundle_state_with_rayon() {
342        let address1 = Address::with_last_byte(1);
343        let address2 = Address::with_last_byte(2);
344        let slot1 = U256::from(1015);
345        let slot2 = U256::from(2015);
346
347        let account1 = AccountInfo { nonce: 1, ..Default::default() };
348        let account2 = AccountInfo { nonce: 2, ..Default::default() };
349
350        let bundle_state = BundleState::builder(2..=2)
351            .state_present_account_info(address1, account1)
352            .state_present_account_info(address2, account2)
353            .state_storage(address1, HashMap::from_iter([(slot1, (U256::ZERO, U256::from(10)))]))
354            .state_storage(address2, HashMap::from_iter([(slot2, (U256::ZERO, U256::from(20)))]))
355            .build();
356        assert_eq!(bundle_state.reverts.len(), 1);
357
358        let post_state = HashedPostState::from_bundle_state::<KeccakKeyHasher>(&bundle_state.state);
359        assert_eq!(post_state.accounts.len(), 2);
360        assert_eq!(post_state.storages.len(), 2);
361
362        let factory = create_test_provider_factory();
363        let provider = factory.provider_rw().unwrap();
364        let sorted = post_state.into_sorted();
365        assert_eq!(
366            overlay_root_for_provider(&*provider, provider.tx_ref(), &sorted).unwrap(),
367            hex!("b464525710cafcf5d4044ac85b72c08b1e76231b8d91f288fe438cc41d8eaafd")
368        );
369    }
370
371    /// Verifies `from_reverts` keeps first occurrence per key and preserves ordering guarantees.
372    #[test]
373    fn from_reverts_keeps_first_occurrence_and_ordering() {
374        let factory = create_test_provider_factory();
375        let provider = factory.provider_rw().unwrap();
376
377        let address1 = Address::with_last_byte(1);
378        let address2 = Address::with_last_byte(2);
379        let slot1 = B256::with_last_byte(11);
380        let slot2 = B256::with_last_byte(22);
381
382        // Account changesets: only first occurrence per address should be kept.
383        provider
384            .tx_ref()
385            .put::<tables::AccountChangeSets>(
386                1,
387                AccountBeforeTx {
388                    address: address1,
389                    info: Some(Account { nonce: 1, ..Default::default() }),
390                },
391            )
392            .unwrap();
393        provider
394            .tx_ref()
395            .put::<tables::AccountChangeSets>(
396                2,
397                AccountBeforeTx {
398                    address: address1,
399                    info: Some(Account { nonce: 2, ..Default::default() }),
400                },
401            )
402            .unwrap();
403        provider
404            .tx_ref()
405            .put::<tables::AccountChangeSets>(3, AccountBeforeTx { address: address2, info: None })
406            .unwrap();
407
408        // Storage changesets: only first occurrence per slot should be kept, and slots sorted.
409        provider
410            .tx_ref()
411            .put::<tables::StorageChangeSets>(
412                BlockNumberAddress((1, address1)),
413                StorageEntry { key: slot2, value: U256::from(200) },
414            )
415            .unwrap();
416        provider
417            .tx_ref()
418            .put::<tables::StorageChangeSets>(
419                BlockNumberAddress((2, address1)),
420                StorageEntry { key: slot1, value: U256::from(100) },
421            )
422            .unwrap();
423        provider
424            .tx_ref()
425            .put::<tables::StorageChangeSets>(
426                BlockNumberAddress((3, address1)),
427                StorageEntry { key: slot1, value: U256::from(999) }, // should be ignored
428            )
429            .unwrap();
430
431        let sorted = HashedPostStateSorted::from_reverts(&*provider, 1..=3).unwrap();
432
433        // Verify first occurrences were kept (nonce 1, not 2)
434        assert_eq!(sorted.accounts.len(), 2);
435        let hashed_addr1 = keccak256(address1);
436        let account1 = sorted.accounts.iter().find(|(addr, _)| *addr == hashed_addr1).unwrap();
437        assert_eq!(account1.1.as_ref().unwrap().nonce, 1);
438
439        // Ordering guarantees - accounts sorted by hashed address
440        assert!(sorted.accounts.windows(2).all(|w| w[0].0 <= w[1].0));
441
442        // Ordering guarantees - storage slots sorted by hashed slot
443        for storage in sorted.storages.values() {
444            assert!(storage.storage_slots.windows(2).all(|w| w[0].0 <= w[1].0));
445        }
446    }
447
448    /// Empty block range returns empty state.
449    #[test]
450    fn from_reverts_empty_range() {
451        let factory = create_test_provider_factory();
452        let provider = factory.provider_rw().unwrap();
453
454        // Insert data outside the query range
455        provider
456            .tx_ref()
457            .put::<tables::AccountChangeSets>(
458                100,
459                AccountBeforeTx {
460                    address: Address::with_last_byte(1),
461                    info: Some(Account { nonce: 1, ..Default::default() }),
462                },
463            )
464            .unwrap();
465
466        // Query a range with no data
467        let sorted = HashedPostStateSorted::from_reverts(&*provider, 1..=10).unwrap();
468        assert!(sorted.accounts.is_empty());
469        assert!(sorted.storages.is_empty());
470    }
471
472    #[test]
473    fn from_reverts_with_hashed_state() {
474        let factory = create_test_provider_factory();
475
476        factory.set_storage_settings_cache(StorageSettings::v2());
477
478        let provider = factory.provider_rw().unwrap();
479
480        let address1 = Address::with_last_byte(1);
481        let address2 = Address::with_last_byte(2);
482
483        let plain_slot1 = B256::with_last_byte(11);
484        let plain_slot2 = B256::with_last_byte(22);
485        let hashed_slot1 = keccak256(plain_slot1);
486        let hashed_slot2 = keccak256(plain_slot2);
487
488        {
489            let sf = factory.static_file_provider();
490
491            // Write account changesets to static files (v2 reads from here)
492            let mut aw = sf.latest_writer(StaticFileSegment::AccountChangeSets).unwrap();
493            aw.append_account_changeset(vec![], 0).unwrap();
494            aw.append_account_changeset(
495                vec![AccountBeforeTx {
496                    address: address1,
497                    info: Some(Account { nonce: 1, ..Default::default() }),
498                }],
499                1,
500            )
501            .unwrap();
502            aw.append_account_changeset(
503                vec![AccountBeforeTx {
504                    address: address1,
505                    info: Some(Account { nonce: 2, ..Default::default() }),
506                }],
507                2,
508            )
509            .unwrap();
510            aw.append_account_changeset(vec![AccountBeforeTx { address: address2, info: None }], 3)
511                .unwrap();
512            aw.commit().unwrap();
513
514            let mut writer = sf.latest_writer(StaticFileSegment::StorageChangeSets).unwrap();
515            writer.append_storage_changeset(vec![], 0).unwrap();
516            writer
517                .append_storage_changeset(
518                    vec![StorageBeforeTx {
519                        address: address1,
520                        key: plain_slot2,
521                        value: U256::from(200),
522                    }],
523                    1,
524                )
525                .unwrap();
526            writer
527                .append_storage_changeset(
528                    vec![StorageBeforeTx {
529                        address: address1,
530                        key: plain_slot1,
531                        value: U256::from(100),
532                    }],
533                    2,
534                )
535                .unwrap();
536            writer
537                .append_storage_changeset(
538                    vec![StorageBeforeTx {
539                        address: address1,
540                        key: plain_slot1,
541                        value: U256::from(999),
542                    }],
543                    3,
544                )
545                .unwrap();
546            writer.commit().unwrap();
547        }
548
549        let sorted = HashedPostStateSorted::from_reverts(&*provider, 1..=3).unwrap();
550
551        assert_eq!(sorted.accounts.len(), 2);
552
553        let hashed_addr1 = keccak256(address1);
554        let hashed_addr2 = keccak256(address2);
555
556        let account1 = sorted.accounts.iter().find(|(addr, _)| *addr == hashed_addr1).unwrap();
557        assert_eq!(account1.1.as_ref().unwrap().nonce, 1);
558
559        let account2 = sorted.accounts.iter().find(|(addr, _)| *addr == hashed_addr2).unwrap();
560        assert!(account2.1.is_none());
561
562        assert!(sorted.accounts.windows(2).all(|w| w[0].0 <= w[1].0));
563
564        let storage = sorted.storages.get(&hashed_addr1).expect("storage for address1");
565        assert_eq!(storage.storage_slots.len(), 2);
566
567        let found_slot1 = storage.storage_slots.iter().find(|(k, _)| *k == hashed_slot1).unwrap();
568        assert_eq!(found_slot1.1, U256::from(100));
569
570        let found_slot2 = storage.storage_slots.iter().find(|(k, _)| *k == hashed_slot2).unwrap();
571        assert_eq!(found_slot2.1, U256::from(200));
572
573        assert_ne!(hashed_slot1, plain_slot1);
574        assert_ne!(hashed_slot2, plain_slot2);
575
576        assert!(storage.storage_slots.windows(2).all(|w| w[0].0 <= w[1].0));
577    }
578
579    #[test]
580    fn from_reverts_legacy_keccak_hashes_all_keys() {
581        let factory = create_test_provider_factory();
582        let provider = factory.provider_rw().unwrap();
583
584        let address1 = Address::with_last_byte(1);
585        let address2 = Address::with_last_byte(2);
586        let plain_slot1 = B256::with_last_byte(11);
587        let plain_slot2 = B256::with_last_byte(22);
588
589        provider
590            .tx_ref()
591            .put::<tables::AccountChangeSets>(
592                1,
593                AccountBeforeTx {
594                    address: address1,
595                    info: Some(Account { nonce: 10, ..Default::default() }),
596                },
597            )
598            .unwrap();
599        provider
600            .tx_ref()
601            .put::<tables::AccountChangeSets>(
602                2,
603                AccountBeforeTx {
604                    address: address2,
605                    info: Some(Account { nonce: 20, ..Default::default() }),
606                },
607            )
608            .unwrap();
609        provider
610            .tx_ref()
611            .put::<tables::AccountChangeSets>(
612                3,
613                AccountBeforeTx {
614                    address: address1,
615                    info: Some(Account { nonce: 99, ..Default::default() }),
616                },
617            )
618            .unwrap();
619
620        provider
621            .tx_ref()
622            .put::<tables::StorageChangeSets>(
623                BlockNumberAddress((1, address1)),
624                StorageEntry { key: plain_slot1, value: U256::from(100) },
625            )
626            .unwrap();
627        provider
628            .tx_ref()
629            .put::<tables::StorageChangeSets>(
630                BlockNumberAddress((2, address1)),
631                StorageEntry { key: plain_slot2, value: U256::from(200) },
632            )
633            .unwrap();
634        provider
635            .tx_ref()
636            .put::<tables::StorageChangeSets>(
637                BlockNumberAddress((3, address2)),
638                StorageEntry { key: plain_slot1, value: U256::from(300) },
639            )
640            .unwrap();
641
642        let sorted = HashedPostStateSorted::from_reverts(&*provider, 1..=3).unwrap();
643
644        let expected_hashed_addr1 = keccak256(address1);
645        let expected_hashed_addr2 = keccak256(address2);
646        assert_eq!(sorted.accounts.len(), 2);
647
648        let account1 =
649            sorted.accounts.iter().find(|(addr, _)| *addr == expected_hashed_addr1).unwrap();
650        assert_eq!(account1.1.as_ref().unwrap().nonce, 10);
651
652        let account2 =
653            sorted.accounts.iter().find(|(addr, _)| *addr == expected_hashed_addr2).unwrap();
654        assert_eq!(account2.1.as_ref().unwrap().nonce, 20);
655
656        assert!(sorted.accounts.windows(2).all(|w| w[0].0 <= w[1].0));
657
658        let expected_hashed_slot1 = keccak256(plain_slot1);
659        let expected_hashed_slot2 = keccak256(plain_slot2);
660
661        assert_ne!(expected_hashed_slot1, plain_slot1);
662        assert_ne!(expected_hashed_slot2, plain_slot2);
663
664        let storage1 = sorted.storages.get(&expected_hashed_addr1).expect("storage for address1");
665        assert_eq!(storage1.storage_slots.len(), 2);
666        assert!(storage1
667            .storage_slots
668            .iter()
669            .any(|(k, v)| *k == expected_hashed_slot1 && *v == U256::from(100)));
670        assert!(storage1
671            .storage_slots
672            .iter()
673            .any(|(k, v)| *k == expected_hashed_slot2 && *v == U256::from(200)));
674        assert!(storage1.storage_slots.windows(2).all(|w| w[0].0 <= w[1].0));
675
676        let storage2 = sorted.storages.get(&expected_hashed_addr2).expect("storage for address2");
677        assert_eq!(storage2.storage_slots.len(), 1);
678        assert_eq!(storage2.storage_slots[0].0, expected_hashed_slot1);
679        assert_eq!(storage2.storage_slots[0].1, U256::from(300));
680    }
681}