-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
port: migrated functions for computing trie root from reth to alloy
- Loading branch information
Showing
3 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} |