use itertools::Itertools;
use prost::DecodeError;
use crate::schema::structs::{Hash, HashFormatType, MerkleProof};
use crate::util;
use crate::util::vec_to_fixed;
use crate::schema::{bytes_data};
use prost::Message;
use redgold_schema::HashClear;
use redgold_schema::structs::HashType;
use redgold_schema::util::{dhash, dhash_vec, merge_hash};
#[derive(Debug)]
pub struct TempMerkleNode {
parent: [u8; 32],
left: [u8; 32],
right: [u8; 32],
}
fn round(
leafs: &Vec<[u8; 32]>,
store_child_to_parent_map: &mut Option<&mut Vec<TempMerkleNode>>,
) -> (Vec<[u8; 32]>, Option<[u8; 32]>) {
let mut remainder: Option<[u8; 32]> = None;
let mut parent_hashes: Vec<[u8; 32]> = Vec::new();
for chunk in leafs.chunks(2) {
let left = chunk.get(0).unwrap();
let right = chunk.get(1);
match right {
None => {
remainder = Some(*left);
}
Some(r) => {
let mut merged = left.to_vec();
merged.extend(r.to_vec());
let parent_hash = dhash_vec(&merged);
println!(
"left {:?}, right {:?} merged {:?}",
hex::encode(left),
hex::encode(r),
hex::encode(parent_hash)
);
parent_hashes.push(parent_hash);
match store_child_to_parent_map {
None => {}
Some(ref mut m) => m.push(TempMerkleNode {
parent: parent_hash,
left: *left,
right: *r,
}),
}
}
}
}
return (parent_hashes, remainder);
}
pub fn build_root_simple(leafs: &Vec<Vec<u8>>) -> Hash {
let res = leafs
.iter()
.map(|l| {
let mut merged = [0u8; 32];
merged[0..32].clone_from_slice(&*l);
merged
})
.collect_vec();
let res = build_root(&res, None, &mut None).to_vec();
return Hash {
bytes: bytes_data(res),
hash_format_type: HashFormatType::Sha3256 as i32,
hash_type: HashType::ObservationMerkleRoot as i32,
};
}
#[allow(unused_assignments)]
pub fn build_root(
leafs: &Vec<[u8; 32]>,
mut store_intermediate: Option<&mut Vec<[u8; 32]>>,
mut store_child_to_parent_map: &mut Option<&mut Vec<TempMerkleNode>>,
) -> [u8; 32] {
let mut active_round = leafs.clone();
if active_round.len() == 1 {
let input = active_round.get(0).unwrap();
let root = dhash(input);
match store_child_to_parent_map {
None => {}
Some(ref mut m) => m.push(TempMerkleNode {
parent: root,
left: input.clone(),
right: input.clone(),
}),
}
return root;
}
let mut remainder: Option<[u8; 32]> = None;
let mut _round_idx = 0;
while active_round.len() > 1 {
let (this_round, this_remainder) = round(&active_round, &mut store_child_to_parent_map);
active_round = this_round.clone();
remainder = this_remainder;
if active_round.len() % 2 != 0 && remainder.is_some() {
active_round.push(remainder.unwrap());
}
if active_round.len() > 1 {
match store_intermediate {
None => {}
Some(ref mut inter) => {
inter.extend(this_round);
}
}
}
_round_idx += 1
}
let root = active_round.get(0).unwrap();
return *root;
}
fn create_proof(nodes: Vec<TempMerkleNode>, hash: [u8; 32]) -> Vec<[u8; 32]> {
let mut find_hash = hash;
let mut proof: Vec<[u8; 32]> = Vec::new();
loop {
let node = nodes
.iter()
.find(|n| n.left == find_hash || n.right == find_hash);
match node {
None => {
break;
}
Some(n) => {
proof.push(n.left);
proof.push(n.right);
find_hash = n.parent;
}
}
}
return proof;
}
fn verify_proof(proof: Vec<[u8; 32]>, hash: [u8; 32]) -> bool {
let first = proof.get(0).unwrap();
let second = proof.get(1).unwrap();
if !(*first == hash || *second == hash) {
return false;
}
if proof.len() == 2 {
return dhash(first) == *second;
}
for chunk in proof.chunks(2) {
let left = chunk.get(0).unwrap();
match chunk.get(1) {
None => {}
Some(right) => {
let mut merged = left.to_vec();
merged.extend(right.to_vec());
}
}
}
return true;
}
fn build_merkle_proof(
root: [u8; 32],
child_map: &Vec<TempMerkleNode>,
leaf: [u8; 32],
) -> Vec<[u8; 32]> {
let mut active_node = leaf.clone();
let mut proof: Vec<[u8; 32]> = vec![];
while active_node != root {
let n = child_map
.iter()
.find(|n| n.left == active_node || n.right == active_node)
.unwrap();
active_node = n.parent;
proof.push(n.left);
proof.push(n.right);
}
return proof;
}
#[allow(unused_assignments)]
fn verify_merkle_proof(root: [u8; 32], leaf: [u8; 32], proof: Vec<[u8; 32]>) -> bool {
if proof.len() % 2 != 0 {
return false;
}
let mut prev: Option<[u8; 32]> = None;
for chunk in proof.chunks_exact(2) {
let left = chunk[0];
let right = chunk[1];
let next_parent = merge_hash(left, right);
match prev {
Some(p) => {
if !(p == left || p == right) {
return false;
}
}
None => {
if !(leaf == left || leaf == right) {
return false;
}
prev = Some(next_parent);
}
}
prev = Some(next_parent);
}
prev == Some(root)
}
#[test]
fn merkle() {
let h1 = util::dhash_str("h1");
let h2 = util::dhash_str("h2");
let h3 = util::dhash_str("h3");
let leafs = vec![h1, h2, h3];
println!(
"Original leafs: {:?}",
leafs
.clone()
.iter()
.map(|l| hex::encode(l))
.collect::<Vec<String>>()
);
let mut intermediates: Vec<[u8; 32]> = Vec::new();
let mut child_map: Vec<TempMerkleNode> = Vec::new();
let root = build_root(&leafs, Some(&mut intermediates), &mut Some(&mut child_map));
println!("Root: {:?}", hex::encode(root));
println!(
"Intermediates: {:?}",
intermediates
.iter()
.map(hex::encode)
.collect::<Vec<String>>()
);
println!(
"Child map {:?}",
child_map
.iter()
.map(
|TempMerkleNode {
parent,
left,
right,
}| hex::encode(parent)
+ " : "
+ &*hex::encode(left)
+ " : "
+ &*hex::encode(right)
)
.collect::<Vec<String>>()
);
let proof = build_merkle_proof(root, &child_map, h1);
verify_merkle_proof(root, h1, proof);
}