Skip to content
Snippets Groups Projects
Commit 150213f9 authored by Surya Bakshi's avatar Surya Bakshi
Browse files

cleaned up code a bid

parent 80ee414f
Branches master
No related tags found
No related merge requests found
......@@ -20,7 +20,6 @@ impl std::fmt::Display for MerkleTree {
}
}
impl MerkleTree {
pub fn new<T>(data: &[T]) -> Self where T: Hashable, {
let mut v = Vec::<&T>::new();
......@@ -77,19 +76,9 @@ impl MerkleTree {
/// Returns the Merkle Proof of data at index i
pub fn proof(&self, index: usize) -> Vec<H256> {
let mut left_idx : usize = 0;
let mut right_idx : usize = self.numleaves-1; // will always be an odd number
if index > right_idx { return Vec::<H256>::new() }
// Compute the virtual number of leaves: round up to closest power of 2
let mut i : u32 = 0;
loop {
let new_pow = 2usize.pow(i);
if new_pow >= self.numleaves {
right_idx = new_pow-1;
break;
}
i = i+1;
}
let mut right_idx = powerof2(self.numleaves)-1;
if index > right_idx { return Vec::<H256>::new() }
let mut curr_root = self;
let mut out = Vec::<H256>::new();
......@@ -121,24 +110,31 @@ impl MerkleTree {
}
}
/// Verify that the datum hash with a vector of proofs will produce the Merkle root. Also need the
/// index of datum and `leaf_size`, the total number of leaves.
pub fn verify(root: &H256, datum: &H256, proof: &[H256], index: usize, leaf_size: usize) -> bool {
let mut new_proof = proof.to_vec();
let mut curr_index = index;
let mut num_leaves = leaf_size;
pub fn powerof2(x: usize) -> usize {
// Compute the virtual number of leaves: round up to closest power of 2
let mut i : u32 = 0;
let mut out : usize;
loop {
let new_pow = 2usize.pow(i);
if new_pow >= leaf_size {
num_leaves = new_pow;
if new_pow >= x {
out = new_pow;
break;
}
i = i+1;
}
out
}
/// Verify that the datum hash with a vector of proofs will produce the Merkle root. Also need the
/// index of datum and `leaf_size`, the total number of leaves.
pub fn verify(root: &H256, datum: &H256, proof: &[H256], index: usize, leaf_size: usize) -> bool {
let mut new_proof = proof.to_vec();
let mut curr_index = index;
let mut num_leaves = leaf_size;
//// Compute the virtual number of leaves: round up to closest power of 2
num_leaves = powerof2(leaf_size);
let mut running_hash = Vec::<H256>::new();
println!("Proof: {:?}", proof);
println!("Datum: {:?}", datum);
......@@ -228,7 +224,7 @@ mod tests {
fn verifying() {
let input_data: Vec<H256> = gen_merkle_tree_data!();
let merkle_tree = MerkleTree::new(&input_data);
let proof = merkle_tree.proof(0);
assert!(verify(&merkle_tree.root(), &input_data[0].hash(), &proof, 0, input_data.len()));
let proof = merkle_tree.proof(1);
assert!(verify(&merkle_tree.root(), &input_data[1].hash(), &proof, 1, input_data.len()));
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment