Skip to content

Commit

Permalink
port: migrated functions for computing trie root from reth to alloy
Browse files Browse the repository at this point in the history
  • Loading branch information
c0np4nn4 committed Oct 14, 2024
1 parent 7a1baa0 commit 18411ae
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ alloy-primitives = { version = "0.8.5", default-features = false, features = [
] }
alloy-rlp = { version = "0.3.8", default-features = false, features = [
"derive",
"arrayvec",
] }

arrayvec = { version = "0.7", default-features = false }
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ pub mod proof;
mod mask;
pub use mask::TrieMask;

pub mod root;

#[doc(hidden)]
pub use alloy_primitives::map::HashMap;

Expand Down
49 changes: 49 additions & 0 deletions src/root.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use alloy_primitives::B256;
use alloy_rlp::Encodable;
use nybbles::Nibbles;
use alloc::vec::Vec;

use crate::{HashBuilder, EMPTY_ROOT_HASH};

/// Adjust the index of an item for rlp encoding.
pub const fn adjust_index_for_rlp(i: usize, len: usize) -> usize {
if i > 0x7f {
i
} else if i == 0x7f || i + 1 == len {
0
} else {
i + 1
}
}

/// Compute a trie root of the collection of rlp encodable items.
pub fn ordered_trie_root<T: Encodable>(items: &[T]) -> B256 {
ordered_trie_root_with_encoder(items, |item, buf| item.encode(buf))
}

/// Compute a trie root of the collection of items with a custom encoder.
pub fn ordered_trie_root_with_encoder<T, F>(items: &[T], mut encode: F) -> B256
where
F: FnMut(&T, &mut Vec<u8>),
{
if items.is_empty() {
return EMPTY_ROOT_HASH;
}

let mut value_buffer = Vec::new();

let mut hb = HashBuilder::default();
let items_len = items.len();
for i in 0..items_len {
let index = adjust_index_for_rlp(i, items_len);

let index_buffer = alloy_rlp::encode_fixed_size(&index);

value_buffer.clear();
encode(&items[index], &mut value_buffer);

hb.add_leaf(Nibbles::unpack(&index_buffer), &value_buffer);
}

hb.root()
}

0 comments on commit 18411ae

Please sign in to comment.