anvil_core/eth/
trie.rs

1//! Utility functions for Ethereum adapted from <https://github.com/rust-blockchain/ethereum/blob/755dffaa4903fbec1269f50cde9863cf86269a14/src/util.rs>
2
3use alloy_primitives::{fixed_bytes, B256};
4use alloy_trie::{HashBuilder, Nibbles};
5use std::collections::BTreeMap;
6
7/// The KECCAK of the RLP encoding of empty data.
8pub const KECCAK_NULL_RLP: B256 =
9    fixed_bytes!("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421");
10
11/// Generates a trie root hash for a vector of values
12pub fn ordered_trie_root<I, V>(input: I) -> B256
13where
14    I: IntoIterator<Item = V>,
15    V: AsRef<[u8]>,
16{
17    let mut builder = HashBuilder::default();
18
19    let input = input
20        .into_iter()
21        .enumerate()
22        .map(|(i, v)| (alloy_rlp::encode(i), v))
23        .collect::<BTreeMap<_, _>>();
24
25    for (key, value) in input {
26        builder.add_leaf(Nibbles::unpack(key), value.as_ref());
27    }
28
29    builder.root()
30}