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

Introduce trie level cache & recorder #157

Merged
merged 133 commits into from
Aug 4, 2022
Merged
Show file tree
Hide file tree
Changes from 123 commits
Commits
Show all changes
133 commits
Select commit Hold shift + click to select a range
8da6ae1
optim aligned nibbleslices
cheme Nov 2, 2021
fe050f7
Yep
bkchr Nov 3, 2021
ef53d6b
Shitty implementation
bkchr Nov 5, 2021
3838b2c
Start cleaning up
bkchr Nov 19, 2021
67891cd
New constructor
bkchr Nov 19, 2021
5ddba5d
Switch to `&mut self`
bkchr Nov 19, 2021
f1ecab3
Add `NodeCache` trait
bkchr Nov 20, 2021
a944234
Small fixes
bkchr Nov 22, 2021
0d323ad
Fix PartialEq implementation
bkchr Nov 24, 2021
caca226
Adds hacky fast cache
bkchr Nov 24, 2021
677b701
Revert "Switch to `&mut self`"
bkchr Nov 25, 2021
2ae95a8
Use RefCell
bkchr Nov 25, 2021
aafd185
Refactor a little bit more
bkchr Nov 25, 2021
648d6b6
Use reference
bkchr Nov 26, 2021
1a2db59
Revert "Use reference"
bkchr Nov 26, 2021
2a7d54a
Cache nodes in `TrieDbMut`
bkchr Nov 26, 2021
1ad99b5
Use `Bytes`
bkchr Nov 26, 2021
e9e07c2
Cache the data
bkchr Nov 26, 2021
4b92b53
Adds `from_existing_with_cache` function
bkchr Nov 26, 2021
070cd50
Some more cleanups
bkchr Nov 27, 2021
beb93f3
Change `leaf_node` signature
bkchr Nov 30, 2021
422e343
Start implementing `to_encoded` for `NodeOwned`
bkchr Nov 30, 2021
55ad8f5
Finish and fix `right_iter` for `NibbleVec`
bkchr Nov 30, 2021
f8fa97c
Finish `to_encoded` and add test
bkchr Nov 30, 2021
05c71ae
Remove useless lifetime
bkchr Nov 30, 2021
67e0d8a
Remove useless parameter
bkchr Nov 30, 2021
112bd31
Introduce `TrieDBBuilder`
bkchr Dec 1, 2021
a0c19c6
New recorder trait
bkchr Dec 1, 2021
a2c4e24
Improve `Lookup`
bkchr Dec 2, 2021
570fb80
Cleanups
bkchr Dec 2, 2021
9ea2d3e
Fix stupid casting error
bkchr Dec 2, 2021
18bc442
Add recorder to Lookup
bkchr Dec 3, 2021
dad4030
Make most tests work again
bkchr Dec 3, 2021
1ba2004
Fix all tests
bkchr Dec 3, 2021
99ec515
Support cache in `TrieDBMut`
bkchr Dec 3, 2021
85947f5
Adds `TrieDBMutBuilder`
bkchr Dec 4, 2021
d137af2
Add some test
bkchr Dec 6, 2021
8ab61a3
Adds `TrieCache` implementation
bkchr Dec 7, 2021
4a7fb94
Adds test with recorder and caching
bkchr Dec 7, 2021
37ae2c2
Use Vec to make generate function happy...
bkchr Dec 8, 2021
dad4a35
Fix recording with active cache.
bkchr Dec 8, 2021
05e5472
Port recorder test to `TrieDBMut`
bkchr Dec 8, 2021
09485ad
Add second test for triedbmut
bkchr Dec 8, 2021
1ea5d5b
Rename `TrieCache` to reflect that it should only be used in tests
bkchr Dec 8, 2021
d4e9d33
Check that we cache data in triedbmut
bkchr Dec 10, 2021
fa9b5d0
Adds test for adding removing key values
bkchr Dec 10, 2021
192d8e1
Fix triedbmut data caching
bkchr Dec 10, 2021
79432ac
Ensure the iterator works with the recorder
bkchr Dec 11, 2021
3a526ca
Switch to custom Bytes
bkchr Dec 11, 2021
c25a56c
Adds some failing test
bkchr Dec 20, 2021
a2b9702
FMT
bkchr Jan 6, 2022
e926f22
Fmt again
bkchr Jan 7, 2022
fbc1131
Merge remote-tracking branch 'origin/master' into HEAD
bkchr Jan 7, 2022
e892e04
Fixes
bkchr Jan 12, 2022
e266dac
More fixes
bkchr Jan 12, 2022
99f9a70
Moare
bkchr Jan 12, 2022
30088df
Yep
bkchr Jan 12, 2022
2136da6
Make it compile
bkchr Jan 13, 2022
2a1161d
Fix some tests
bkchr Jan 13, 2022
e1876e8
Fix more tests
bkchr Jan 13, 2022
62d7e4b
Rework the tests
bkchr Jan 13, 2022
d1ef0c1
Fixes
bkchr Jan 13, 2022
1ce76e8
Make all tests work
bkchr Jan 14, 2022
9d7fd67
Support inline nodes better
bkchr Jan 14, 2022
ea01371
Make value recording explicit and fix caching
bkchr Jan 17, 2022
235cad6
Switch to `TrieAccess::Value`
bkchr Jan 17, 2022
5352bc5
Fix bug with recording
bkchr Jan 17, 2022
308ba6d
Cache values as node
bkchr Jan 17, 2022
63faaec
Use`NodeCodec` as generic argument for `TrieCache`
bkchr Jan 18, 2022
4fdf382
Use borrow from alloc
bkchr Jan 19, 2022
8bf24e0
Implement Debug
bkchr Jan 26, 2022
e0938b6
Also test cache when draining the recorder
bkchr Jan 28, 2022
9ecbc0f
Feature gate `Debug`
bkchr Feb 8, 2022
801be37
Merge branch 'bkchr-funny-branch' of github.com:paritytech/trie into …
bkchr Feb 8, 2022
1543eb3
Provide functions to pass an optional recorder/cache
bkchr Feb 11, 2022
5b5d530
Start adding keys
bkchr Feb 15, 2022
0cff4c8
Fixes
bkchr Feb 15, 2022
4d2cac1
We don't need to pass full keys for nodes
bkchr Feb 16, 2022
f5cf25d
Remove unnecessary argument of `Value::Node`
bkchr Feb 16, 2022
8a42ad7
Also remove the variant from triedbmut
bkchr Feb 16, 2022
53aab18
Small updates
bkchr Feb 16, 2022
2fe3274
Let `traverse_to` return if the key was found in the trie.
bkchr Mar 1, 2022
a20762e
Remove warning
bkchr Mar 1, 2022
fbda8ad
Merge remote-tracking branch 'origin/master' into bkchr-funny-branch
bkchr Mar 2, 2022
d224f32
Ensure to also record the value access in triedbmut
bkchr Mar 14, 2022
6548b6e
Cache hash alongside the actual value data
bkchr Mar 14, 2022
d217cb7
Start fixing a test and adding more tests
bkchr Mar 14, 2022
e631416
Fix tests
bkchr Mar 14, 2022
5c87812
More tests
bkchr Mar 14, 2022
4842bb7
Start adding `get_hash`
bkchr Mar 15, 2022
df49a18
Introduce new `KeyTrieAccessValue`
bkchr Mar 15, 2022
88b5957
Rework the `CachedValue` handling
bkchr Mar 16, 2022
956f3fc
Make it compile
bkchr Mar 17, 2022
caa65c3
Adds `exists` function
bkchr Mar 20, 2022
740df1c
Do not check for root in `TrieDB` and `TrieDBMut` constructors
bkchr Apr 8, 2022
47db0ae
FMT
bkchr Apr 8, 2022
27b7573
Update Changelog
bkchr Apr 8, 2022
507c583
Fix benchmarks
bkchr Apr 8, 2022
1e93e54
Merge branch 'bkchr-do-not-check-for-root' into bkchr-funny-branch
bkchr Apr 8, 2022
c6e4bac
Do not check for `root` on construction of `TrieDB` or `TrieDBMut`
bkchr Apr 8, 2022
a1ef2e0
Take &mut self
bkchr Apr 27, 2022
4e0e5db
Implement `size_in_bytes`
bkchr May 2, 2022
83368df
Also visit childs of childs
bkchr May 3, 2022
678d87a
Ensure we check for nodes before inserting them into the cache
bkchr May 11, 2022
09e4a5f
Ensure the lookup works when the data can not be upgraded anymore
bkchr May 11, 2022
a1937db
Remove function that isn't required
bkchr May 11, 2022
da20585
:see_no_evil:
bkchr May 12, 2022
7a07ff6
Merge remote-tracking branch 'origin/master' into bkchr-funny-branch
bkchr May 12, 2022
8a0dc1f
FMT
bkchr May 12, 2022
172a15d
Apply suggestions from code review
bkchr May 31, 2022
ea82a66
Fix compilation
bkchr Jun 1, 2022
3625b19
Review comment
bkchr Jun 1, 2022
ea59e5b
Update trie-db/src/node.rs
bkchr Jun 1, 2022
423fcf8
Prepare traverse to with hash only
bkchr Jun 1, 2022
f9ad2b6
Merge branch 'bkchr-funny-branch' of github.com:paritytech/trie into …
bkchr Jun 1, 2022
1c855d0
Make recording with the cache deterministic
bkchr Jun 8, 2022
1f322a5
Add some requested test
bkchr Jun 8, 2022
ce3c178
More tests and bug fixes
bkchr Jun 8, 2022
db1cea0
Add `NonExisting` as variant to `TrieAccess`
bkchr Jun 8, 2022
7d7c922
Update trie-db/src/triedbmut.rs
bkchr Jun 13, 2022
2a70e33
Update trie-db/src/triedbmut.rs
bkchr Jun 13, 2022
4de50b8
Feedback
bkchr Jun 13, 2022
b41b01e
More feedback
bkchr Jun 13, 2022
15ac61b
Update trie-db/src/lib.rs
bkchr Jun 21, 2022
f7d2349
Update trie-db/src/lib.rs
bkchr Jun 21, 2022
efb2466
Update trie-db/src/lib.rs
bkchr Jun 21, 2022
da5020f
Update trie-db/src/lib.rs
bkchr Jun 21, 2022
9f2896e
Remove some redudant code
bkchr Jun 21, 2022
16e3ff3
Some docs
bkchr Jun 21, 2022
86ed58d
Update test-support/keccak-hasher/src/lib.rs
bkchr Jun 23, 2022
2561d9d
Update trie-db/src/lib.rs
bkchr Jun 23, 2022
f06e942
Apply suggestions from code review
bkchr Aug 2, 2022
78af8d6
Pr feedback
bkchr Aug 4, 2022
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
5 changes: 4 additions & 1 deletion test-support/keccak-hasher/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ use hash256_std_hasher::Hash256StdHasher;
use hash_db::Hasher;
use tiny_keccak::{Hasher as _, Keccak};

/// The keccack hash type.
bkchr marked this conversation as resolved.
Show resolved Hide resolved
pub type KeccakHash = [u8; 32];

/// Concrete `Hasher` impl for the Keccak-256 hash
#[derive(Default, Debug, Clone, PartialEq)]
pub struct KeccakHasher;
impl Hasher for KeccakHasher {
type Out = [u8; 32];
type Out = KeccakHash;

type StdHasher = Hash256StdHasher;

Expand Down
1 change: 1 addition & 0 deletions test-support/reference-trie/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ keccak-hasher = { path = "../keccak-hasher", version = "0.15.3" }
trie-db = { path = "../../trie-db", default-features = false, version = "0.23.0" }
trie-root = { path = "../../trie-root", default-features = false, version = "0.17.0" }
parity-scale-codec = { version = "3.0.0", features = ["derive"] }
hashbrown = { version = "0.12.0", default-features = false, features = ["ahash"] }

[dev-dependencies]
trie-bench = { path = "../trie-bench" }
Expand Down
180 changes: 108 additions & 72 deletions test-support/reference-trie/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,21 @@

//! Reference implementation of a streamer.

mod substrate_like;

use hashbrown::{hash_map::Entry, HashMap};
use parity_scale_codec::{Compact, Decode, Encode, Error as CodecError, Input, Output};
use std::{borrow::Borrow, fmt, iter::once, marker::PhantomData, ops::Range};
use trie_db::{
node::{NibbleSlicePlan, NodeHandlePlan, NodePlan, Value, ValuePlan},
nibble_ops,
node::{NibbleSlicePlan, NodeHandlePlan, NodeOwned, NodePlan, Value, ValuePlan},
trie_visit,
triedbmut::ChildReference,
DBValue, Partial, TrieBuilder, TrieRoot,
};
use trie_root::Hasher;

use trie_db::{
nibble_ops, NodeCodec, Trie, TrieConfiguration, TrieDB, TrieDBMut, TrieLayout, TrieMut,
DBValue, NodeCodec, Trie, TrieBuilder, TrieConfiguration, TrieDBBuilder, TrieDBMutBuilder,
TrieHash, TrieLayout, TrieMut, TrieRoot,
};
pub use trie_root::TrieStream;
use trie_root::Value as TrieStreamValue;
use trie_root::{Hasher, Value as TrieStreamValue};

mod substrate_like;
pub mod node {
pub use trie_db::node::Node;
}
Expand All @@ -49,10 +47,14 @@ macro_rules! test_layouts {
($test:ident, $test_internal:ident) => {
#[test]
fn $test() {
$test_internal::<reference_trie::HashedValueNoExtThreshold>();
$test_internal::<reference_trie::HashedValueNoExt>();
$test_internal::<reference_trie::NoExtensionLayout>();
$test_internal::<reference_trie::ExtensionLayout>();
eprintln!("Running with layout `HashedValueNoExtThreshold`");
$test_internal::<$crate::HashedValueNoExtThreshold>();
eprintln!("Running with layout `HashedValueNoExt`");
$test_internal::<$crate::HashedValueNoExt>();
eprintln!("Running with layout `NoExtensionLayout`");
$test_internal::<$crate::NoExtensionLayout>();
eprintln!("Running with layout `ExtensionLayout`");
$test_internal::<$crate::ExtensionLayout>();
}
};
}
Expand All @@ -63,8 +65,8 @@ macro_rules! test_layouts_no_meta {
($test:ident, $test_internal:ident) => {
#[test]
fn $test() {
$test_internal::<reference_trie::NoExtensionLayout>();
$test_internal::<reference_trie::ExtensionLayout>();
$test_internal::<$crate::NoExtensionLayout>();
$test_internal::<$crate::ExtensionLayout>();
}
};
}
Expand Down Expand Up @@ -152,16 +154,22 @@ impl Bitmap {
}
}

pub type RefTrieDB<'a> = trie_db::TrieDB<'a, ExtensionLayout>;
pub type RefTrieDBBuilder<'a, 'cache> = trie_db::TrieDBBuilder<'a, 'cache, ExtensionLayout>;
pub type RefTrieDB<'a, 'cache> = trie_db::TrieDB<'a, 'cache, ExtensionLayout>;
bkchr marked this conversation as resolved.
Show resolved Hide resolved
pub type RefTrieDBMut<'a> = trie_db::TrieDBMut<'a, ExtensionLayout>;
pub type RefTrieDBMutBuilder<'a> = trie_db::TrieDBMutBuilder<'a, ExtensionLayout>;
pub type RefTrieDBMutNoExt<'a> = trie_db::TrieDBMut<'a, NoExtensionLayout>;
pub type RefTrieDBMutNoExtBuilder<'a> = trie_db::TrieDBMutBuilder<'a, NoExtensionLayout>;
pub type RefTrieDBMutAllowEmpty<'a> = trie_db::TrieDBMut<'a, AllowEmptyLayout>;
pub type RefFatDB<'a> = trie_db::FatDB<'a, ExtensionLayout>;
pub type RefTrieDBMutAllowEmptyBuilder<'a> = trie_db::TrieDBMutBuilder<'a, AllowEmptyLayout>;
pub type RefTestTrieDBCache = TestTrieCache<ExtensionLayout>;
pub type RefTestTrieDBCacheNoExt = TestTrieCache<NoExtensionLayout>;
pub type RefFatDB<'a, 'cache> = trie_db::FatDB<'a, 'cache, ExtensionLayout>;
pub type RefFatDBMut<'a> = trie_db::FatDBMut<'a, ExtensionLayout>;
pub type RefSecTrieDB<'a> = trie_db::SecTrieDB<'a, ExtensionLayout>;
pub type RefSecTrieDB<'a, 'cache> = trie_db::SecTrieDB<'a, 'cache, ExtensionLayout>;
pub type RefSecTrieDBMut<'a> = trie_db::SecTrieDBMut<'a, ExtensionLayout>;
pub type RefLookup<'a, Q> = trie_db::Lookup<'a, ExtensionLayout, Q>;
pub type RefLookupNoExt<'a, Q> = trie_db::Lookup<'a, NoExtensionLayout, Q>;
pub type RefLookup<'a, 'cache, Q> = trie_db::Lookup<'a, 'cache, ExtensionLayout, Q>;
pub type RefLookupNoExt<'a, 'cache, Q> = trie_db::Lookup<'a, 'cache, NoExtensionLayout, Q>;

pub fn reference_trie_root<T: TrieLayout, I, A, B>(input: I) -> <T::Hash as Hasher>::Out
where
Expand All @@ -170,11 +178,11 @@ where
B: AsRef<[u8]> + fmt::Debug,
{
if T::USE_EXTENSION {
trie_root::trie_root::<T::Hash, ReferenceTrieStream, _, _, _>(input, Default::default())
trie_root::trie_root::<T::Hash, ReferenceTrieStream, _, _, _>(input, T::MAX_INLINE_VALUE)
bkchr marked this conversation as resolved.
Show resolved Hide resolved
} else {
trie_root::trie_root_no_extension::<T::Hash, ReferenceTrieStreamNoExt, _, _, _>(
input,
Default::default(),
T::MAX_INLINE_VALUE,
)
}
}
Expand Down Expand Up @@ -488,18 +496,6 @@ pub struct ReferenceNodeCodec<H>(PhantomData<H>);
#[derive(Default, Clone)]
pub struct ReferenceNodeCodecNoExt<H>(PhantomData<H>);

fn partial_to_key(partial: Partial, offset: u8, over: u8) -> Vec<u8> {
let number_nibble_encoded = (partial.0).0 as usize;
let nibble_count = partial.1.len() * nibble_ops::NIBBLE_PER_BYTE + number_nibble_encoded;
assert!(nibble_count < over as usize);
let mut output = vec![offset + nibble_count as u8];
if number_nibble_encoded > 0 {
output.push(nibble_ops::pad_right((partial.0).1));
}
output.extend_from_slice(&partial.1[..]);
output
}

fn partial_from_iterator_to_key<I: Iterator<Item = u8>>(
partial: I,
nibble_count: usize,
Expand Down Expand Up @@ -532,27 +528,6 @@ fn partial_from_iterator_encode<I: Iterator<Item = u8>>(
output
}

fn partial_encode(partial: Partial, node_kind: NodeKindNoExt) -> Vec<u8> {
let number_nibble_encoded = (partial.0).0 as usize;
let nibble_count = partial.1.len() * nibble_ops::NIBBLE_PER_BYTE + number_nibble_encoded;

let nibble_count = ::std::cmp::min(NIBBLE_SIZE_BOUND_NO_EXT, nibble_count);

let mut output = Vec::with_capacity(3 + partial.1.len());
match node_kind {
NodeKindNoExt::Leaf => NodeHeaderNoExt::Leaf(nibble_count).encode_to(&mut output),
NodeKindNoExt::BranchWithValue =>
NodeHeaderNoExt::Branch(true, nibble_count).encode_to(&mut output),
NodeKindNoExt::BranchNoValue =>
NodeHeaderNoExt::Branch(false, nibble_count).encode_to(&mut output),
};
if number_nibble_encoded > 0 {
output.push(nibble_ops::pad_right((partial.0).1));
}
output.extend_from_slice(&partial.1[..]);
output
}

struct ByteSliceInput<'a> {
data: &'a [u8],
offset: usize,
Expand Down Expand Up @@ -684,8 +659,9 @@ impl<H: Hasher> NodeCodec for ReferenceNodeCodec<H> {
&[EMPTY_TRIE]
}

fn leaf_node(partial: Partial, value: Value) -> Vec<u8> {
let mut output = partial_to_key(partial, LEAF_NODE_OFFSET, LEAF_NODE_OVER);
fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> {
let mut output =
partial_from_iterator_to_key(partial, number_nibble, LEAF_NODE_OFFSET, LEAF_NODE_OVER);
match value {
Value::Inline(value) => {
Compact(value.len() as u32).encode_to(&mut output);
Expand Down Expand Up @@ -839,8 +815,8 @@ impl<H: Hasher> NodeCodec for ReferenceNodeCodecNoExt<H> {
&[EMPTY_TRIE_NO_EXT]
}

fn leaf_node(partial: Partial, value: Value) -> Vec<u8> {
let mut output = partial_encode(partial, NodeKindNoExt::Leaf);
fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> {
let mut output = partial_from_iterator_encode(partial, number_nibble, NodeKindNoExt::Leaf);
match value {
Value::Inline(value) => {
Compact(value.len() as u32).encode_to(&mut output);
Expand Down Expand Up @@ -918,7 +894,7 @@ where
let root_new = calc_root_build::<T, _, _, _, _>(data.clone(), &mut hashdb);
let root = {
let mut root = Default::default();
let mut t = TrieDBMut::<T>::new(&mut memdb, &mut root);
let mut t = TrieDBMutBuilder::<T>::new(&mut memdb, &mut root).build();
for i in 0..data.len() {
t.insert(&data[i].0[..], &data[i].1[..]).unwrap();
}
Expand All @@ -928,15 +904,15 @@ where
if root_new != root {
{
let db: &dyn hash_db::HashDB<_, _> = &hashdb;
let t = TrieDB::<T>::new(&db, &root_new);
let t = TrieDBBuilder::<T>::new(&db, &root_new).build();
println!("{:?}", t);
for a in t.iter().unwrap() {
println!("a:{:x?}", a);
}
}
{
let db: &dyn hash_db::HashDB<_, _> = &memdb;
let t = TrieDB::<T>::new(&db, &root);
let t = TrieDBBuilder::<T>::new(&db, &root).build();
println!("{:?}", t);
for a in t.iter().unwrap() {
println!("a:{:x?}", a);
Expand All @@ -957,7 +933,7 @@ pub fn compare_root<T: TrieLayout, DB: hash_db::HashDB<T::Hash, DBValue>>(
let root_new = reference_trie_root_iter_build::<T, _, _, _>(data.clone());
let root = {
let mut root = Default::default();
let mut t = trie_db::TrieDBMut::<T>::new(&mut memdb, &mut root);
let mut t = TrieDBMutBuilder::<T>::new(&mut memdb, &mut root).build();
for i in 0..data.len() {
t.insert(&data[i].0[..], &data[i].1[..]).unwrap();
}
Expand Down Expand Up @@ -1032,7 +1008,7 @@ pub fn compare_implementations_unordered<T, DB>(
let mut b_map = std::collections::btree_map::BTreeMap::new();
let root = {
let mut root = Default::default();
let mut t = TrieDBMut::<T>::new(&mut memdb, &mut root);
let mut t = TrieDBMutBuilder::<T>::new(&mut memdb, &mut root).build();
for i in 0..data.len() {
t.insert(&data[i].0[..], &data[i].1[..]).unwrap();
b_map.insert(data[i].0.clone(), data[i].1.clone());
Expand All @@ -1048,15 +1024,15 @@ pub fn compare_implementations_unordered<T, DB>(
if root != root_new {
{
let db: &dyn hash_db::HashDB<_, _> = &memdb;
let t = TrieDB::<T>::new(&db, &root);
let t = TrieDBBuilder::<T>::new(&db, &root).build();
println!("{:?}", t);
for a in t.iter().unwrap() {
println!("a:{:?}", a);
}
}
{
let db: &dyn hash_db::HashDB<_, _> = &hashdb;
let t = TrieDB::<T>::new(&db, &root_new);
let t = TrieDBBuilder::<T>::new(&db, &root_new).build();
println!("{:?}", t);
for a in t.iter().unwrap() {
println!("a:{:?}", a);
Expand All @@ -1080,13 +1056,13 @@ pub fn compare_insert_remove<T, DB: hash_db::HashDB<T::Hash, DBValue>>(
let mut root = Default::default();
let mut a = 0;
{
let mut t = TrieDBMut::<T>::new(&mut memdb, &mut root);
let mut t = TrieDBMutBuilder::<T>::new(&mut memdb, &mut root).build();
t.commit();
}
while a < data.len() {
// new triemut every 3 element
root = {
let mut t = TrieDBMut::<T>::from_existing(&mut memdb, &mut root);
let mut t = TrieDBMutBuilder::<T>::from_existing(&mut memdb, &mut root).build();
for _ in 0..3 {
if data[a].0 {
// remove
Expand All @@ -1107,16 +1083,75 @@ pub fn compare_insert_remove<T, DB: hash_db::HashDB<T::Hash, DBValue>>(
*t.root()
};
}
let mut t = TrieDBMut::<T>::from_existing(&mut memdb, &mut root);
let mut t = TrieDBMutBuilder::<T>::from_existing(&mut memdb, &mut root).build();
// we are testing the RefTrie code here so we do not sort or check uniqueness
// before.
assert_eq!(*t.root(), calc_root::<T, _, _, _>(data2));
}

/// Example trie cache implementation.
///
/// Should not be used for anything in production.
pub struct TestTrieCache<L: TrieLayout> {
/// In a real implementation we need to make sure that this is unique per trie root.
value_cache: HashMap<Vec<u8>, trie_db::CachedValue<TrieHash<L>>>,
node_cache: HashMap<TrieHash<L>, NodeOwned<TrieHash<L>>>,
}

impl<L: TrieLayout> TestTrieCache<L> {
/// Clear the value cache.
pub fn clear_value_cache(&mut self) {
self.value_cache.clear();
}

/// Clear the node cache.
pub fn clear_node_cache(&mut self) {
self.node_cache.clear();
}
}

impl<L: TrieLayout> Default for TestTrieCache<L> {
fn default() -> Self {
Self { value_cache: Default::default(), node_cache: Default::default() }
}
}

impl<L: TrieLayout> trie_db::TrieCache<L::Codec> for TestTrieCache<L> {
fn lookup_value_for_key(&mut self, key: &[u8]) -> Option<&trie_db::CachedValue<TrieHash<L>>> {
self.value_cache.get(key)
}

fn cache_value_for_key(&mut self, key: &[u8], value: trie_db::CachedValue<TrieHash<L>>) {
self.value_cache.insert(key.to_vec(), value);
}

fn get_or_insert_node(
&mut self,
hash: TrieHash<L>,
fetch_node: &mut dyn FnMut() -> trie_db::Result<
NodeOwned<TrieHash<L>>,
TrieHash<L>,
trie_db::CError<L>,
>,
) -> trie_db::Result<&NodeOwned<TrieHash<L>>, TrieHash<L>, trie_db::CError<L>> {
match self.node_cache.entry(hash) {
Entry::Occupied(e) => Ok(e.into_mut()),
Entry::Vacant(e) => {
let node = (*fetch_node)()?;
Ok(e.insert(node))
},
}
}

fn get_node(&mut self, hash: &TrieHash<L>) -> Option<&NodeOwned<TrieHash<L>>> {
self.node_cache.get(hash)
}
}

#[cfg(test)]
mod tests {
use super::*;
use trie_db::node::Node;
use trie_db::{nibble_ops::NIBBLE_PER_BYTE, node::Node};

#[test]
fn test_encoding_simple_trie() {
Expand All @@ -1140,7 +1175,8 @@ mod tests {
// + 1 for 0 added byte of nibble encode
let input = vec![0u8; (NIBBLE_SIZE_BOUND_NO_EXT as usize + 1) / 2 + 1];
let enc = <ReferenceNodeCodecNoExt<RefHasher> as NodeCodec>::leaf_node(
((0, 0), &input),
input.iter().cloned(),
input.len() * NIBBLE_PER_BYTE,
Value::Inline(&[1]),
);
let dec = <ReferenceNodeCodecNoExt<RefHasher> as NodeCodec>::decode(&enc).unwrap();
Expand Down
Loading