revme/cmd/statetest/
merkle_trie.rs1use alloy_rlp::{RlpEncodable, RlpMaxEncodedLen};
2use database::PlainAccount;
3use hash_db::Hasher;
4use plain_hasher::PlainHasher;
5use revm::primitives::{keccak256, Address, Log, B256, U256};
6use triehash::sec_trie_root;
7
8pub fn log_rlp_hash(logs: &[Log]) -> B256 {
9 let mut out = Vec::with_capacity(alloy_rlp::list_length(logs));
10 alloy_rlp::encode_list(logs, &mut out);
11 keccak256(&out)
12}
13
14pub fn state_merkle_trie_root<'a>(
15 accounts: impl IntoIterator<Item = (Address, &'a PlainAccount)>,
16) -> B256 {
17 trie_root(accounts.into_iter().map(|(address, acc)| {
18 (
19 address,
20 alloy_rlp::encode_fixed_size(&TrieAccount::new(acc)),
21 )
22 }))
23}
24
25#[derive(RlpEncodable, RlpMaxEncodedLen)]
26struct TrieAccount {
27 nonce: u64,
28 balance: U256,
29 root_hash: B256,
30 code_hash: B256,
31}
32
33impl TrieAccount {
34 fn new(acc: &PlainAccount) -> Self {
35 Self {
36 nonce: acc.info.nonce,
37 balance: acc.info.balance,
38 root_hash: sec_trie_root::<KeccakHasher, _, _, _>(
39 acc.storage
40 .iter()
41 .filter(|(_k, &v)| !v.is_zero())
42 .map(|(k, v)| (k.to_be_bytes::<32>(), alloy_rlp::encode_fixed_size(v))),
43 ),
44 code_hash: acc.info.code_hash,
45 }
46 }
47}
48
49#[inline]
50pub fn trie_root<I, A, B>(input: I) -> B256
51where
52 I: IntoIterator<Item = (A, B)>,
53 A: AsRef<[u8]>,
54 B: AsRef<[u8]>,
55{
56 sec_trie_root::<KeccakHasher, _, _, _>(input)
57}
58
59#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
60pub struct KeccakHasher;
61
62impl Hasher for KeccakHasher {
63 type Out = B256;
64 type StdHasher = PlainHasher;
65 const LENGTH: usize = 32;
66
67 #[inline]
68 fn hash(x: &[u8]) -> Self::Out {
69 keccak256(x)
70 }
71}