Skip to main content

reth_trie_common/
key.rs

1use alloy_primitives::{keccak256, B256};
2
3/// Trait for hashing keys in state.
4pub trait KeyHasher: Default + Clone + Send + Sync + 'static {
5    /// Hashes the given bytes into a 256-bit hash.
6    fn hash_key<T: AsRef<[u8]>>(bytes: T) -> B256;
7}
8
9/// A key hasher that uses the Keccak-256 hash function.
10#[derive(Clone, Debug, Default)]
11pub struct KeccakKeyHasher;
12
13impl KeyHasher for KeccakKeyHasher {
14    #[inline]
15    fn hash_key<T: AsRef<[u8]>>(bytes: T) -> B256 {
16        keccak256(bytes)
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    #[test]
25    fn test_keccak_key_hasher_always_hashes_regardless_of_length() {
26        use alloy_primitives::Address;
27
28        let addr = Address::repeat_byte(0x42);
29        assert_eq!(KeccakKeyHasher::hash_key(addr), keccak256(addr));
30
31        let slot = B256::repeat_byte(0x42);
32        assert_eq!(KeccakKeyHasher::hash_key(slot), keccak256(slot));
33        assert_ne!(KeccakKeyHasher::hash_key(slot), slot);
34    }
35}