reth_trie/
test_utils.rs

1use alloy_primitives::{Address, B256, U256};
2use alloy_rlp::encode_fixed_size;
3use reth_primitives_traits::Account;
4use reth_trie_common::triehash::KeccakHasher;
5
6/// Re-export of [triehash].
7pub use triehash;
8
9/// Compute the state root of a given set of accounts using [`triehash::sec_trie_root`].
10pub fn state_root<I, S>(accounts: I) -> B256
11where
12    I: IntoIterator<Item = (Address, (Account, S))>,
13    S: IntoIterator<Item = (B256, U256)>,
14{
15    let encoded_accounts = accounts.into_iter().map(|(address, (account, storage))| {
16        let storage_root = storage_root(storage);
17        let account = account.into_trie_account(storage_root);
18        (address, alloy_rlp::encode(account))
19    });
20    triehash::sec_trie_root::<KeccakHasher, _, _, _>(encoded_accounts)
21}
22
23/// Compute the storage root for a given account using [`triehash::sec_trie_root`].
24pub fn storage_root<I: IntoIterator<Item = (B256, U256)>>(storage: I) -> B256 {
25    let encoded_storage = storage.into_iter().map(|(k, v)| (k, encode_fixed_size(&v)));
26    triehash::sec_trie_root::<KeccakHasher, _, _, _>(encoded_storage)
27}
28
29/// Compute the state root of a given set of accounts with prehashed keys using
30/// [`triehash::trie_root`].
31pub fn state_root_prehashed<I, S>(accounts: I) -> B256
32where
33    I: IntoIterator<Item = (B256, (Account, S))>,
34    S: IntoIterator<Item = (B256, U256)>,
35{
36    let encoded_accounts = accounts.into_iter().map(|(address, (account, storage))| {
37        let storage_root = storage_root_prehashed(storage);
38        let account = account.into_trie_account(storage_root);
39        (address, alloy_rlp::encode(account))
40    });
41
42    triehash::trie_root::<KeccakHasher, _, _, _>(encoded_accounts)
43}
44
45/// Compute the storage root for a given account with prehashed slots using [`triehash::trie_root`].
46pub fn storage_root_prehashed<I: IntoIterator<Item = (B256, U256)>>(storage: I) -> B256 {
47    let encoded_storage = storage.into_iter().map(|(k, v)| (k, encode_fixed_size(&v)));
48    triehash::trie_root::<KeccakHasher, _, _, _>(encoded_storage)
49}