Skip to content

Commit

Permalink
Add equivalency test
Browse files Browse the repository at this point in the history
  • Loading branch information
Dzejkop committed Sep 24, 2024
1 parent 4b8491c commit c5fb38f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
9 changes: 5 additions & 4 deletions crates/trees/src/imt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,13 @@ pub mod test {
use keccak::keccak::Keccak256;

#[test_case(0 => None)]
#[test_case(1 => Some(0))]
#[test_case(2 => Some(0))]
#[test_case(1 => None)]
#[test_case(2 => Some(1))]
#[test_case(3 => Some(1))]
#[test_case(4 => Some(1))]
#[test_case(4 => Some(2))]
#[test_case(5 => Some(2))]
#[test_case(6 => Some(2))]
#[test_case(6 => Some(3))]
#[test_case(27 => Some(13))]
fn parent_of(index: usize) -> Option<usize> {
parent(index)
}
Expand Down
41 changes: 41 additions & 0 deletions crates/trees/tests/equivalent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use keccak::keccak::Keccak256;
use rand::{thread_rng, Rng};
use trees::cascading::CascadingMerkleTree;
use trees::imt::MerkleTree;
use trees::lazy::{Canonical, LazyMerkleTree};

const DEPTH: usize = 20;
const DENSE_PREFIX: usize = 16;
const EMPTY_VALUE: [u8; 32] = [0; 32];

#[test]
fn equivalent() {
let mut lazy: LazyMerkleTree<Keccak256, Canonical> =
LazyMerkleTree::<Keccak256, Canonical>::new_with_dense_prefix(
DEPTH,
DENSE_PREFIX,
&EMPTY_VALUE,
);
let mut lazy_derived = lazy.derived();
let mut imt: MerkleTree<Keccak256> = MerkleTree::new(DEPTH, EMPTY_VALUE);
let mut cascading: CascadingMerkleTree<Keccak256> =
CascadingMerkleTree::new(vec![], DEPTH, &EMPTY_VALUE);

assert_eq!(lazy.root(), imt.root());
assert_eq!(lazy.root(), cascading.root());

let mut rng = thread_rng();

let random_leaves = (0..1_000)
.map(|_| rng.gen::<[u8; 32]>())
.collect::<Vec<_>>();

for (i, leaf) in random_leaves.iter().enumerate() {
lazy_derived = lazy_derived.update(i, leaf);
imt.set(i, *leaf);
cascading.push(*leaf).unwrap();
}

assert_eq!(lazy_derived.root(), imt.root());
assert_eq!(lazy_derived.root(), cascading.root());
}

0 comments on commit c5fb38f

Please sign in to comment.