Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

port: migrated functions for computing trie root from reth to alloy #55

Merged
merged 3 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ pub mod proof;
mod mask;
pub use mask::TrieMask;

#[allow(missing_docs)]
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 alloc::vec::Vec;
use alloy_primitives::B256;
use alloy_rlp::Encodable;
use nybbles::Nibbles;

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()
}
Loading