arnaucube
arnaucube/merkletree-rsPublic Self-hosted repository
merkletree-rs/src/utils.rs
src/utils.rsRaw
 1use super::constants;
 2use super::node;
 3use tiny_keccak::Keccak;
 4
 5pub fn hash_vec(b: Vec<u8>) -> [u8; 32] {
 6    let mut sha3 = Keccak::new_keccak256();
 7    sha3.update(&b);
 8    let mut res: [u8; 32] = [0; 32];
 9    sha3.finalize(&mut res);
10    res
11}
12
13pub fn get_path(num_levels: u32, hi: [u8; 32]) -> Vec<bool> {
14    let mut path = Vec::new();
15    for i in (0..=num_levels as usize - 2).rev() {
16        path.push((hi[hi.len() - i / 8 - 1] & (1 << (i % 8))) > 0);
17    }
18    path
19}
20
21pub fn calc_hash_from_leaf_and_level(
22    until_level: u32,
23    path: &[bool],
24    leaf_hash: [u8; 32],
25) -> [u8; 32] {
26    let mut node_curr_lvl = leaf_hash;
27    for i in 0..until_level {
28        if path[i as usize] {
29            let node = node::TreeNode {
30                child_l: constants::EMPTYNODEVALUE,
31                child_r: node_curr_lvl,
32            };
33            node_curr_lvl = node.ht();
34        } else {
35            let node = node::TreeNode {
36                child_l: node_curr_lvl,
37                child_r: constants::EMPTYNODEVALUE,
38            };
39            node_curr_lvl = node.ht();
40        }
41    }
42    node_curr_lvl
43}
44
45pub fn cut_path(path: &[bool], i: usize) -> Vec<bool> {
46    let mut path_res: Vec<bool> = Vec::new();
47    for j in 0..path.len() {
48        if j >= i {
49            path_res.push(path[j]);
50        }
51    }
52    path_res
53}
54
55pub fn compare_paths(a: &[bool], b: &[bool]) -> i32 {
56    for i in (0..a.len()).rev() {
57        if a[i] != b[i] {
58            return i as i32;
59        }
60    }
61    -1
62}
63
64pub fn get_empties_between_i_and_pos(i: u32, pos: u32) -> Vec<[u8; 32]> {
65    let mut sibl: Vec<[u8; 32]> = Vec::new();
66    for _ in (pos..=i).rev() {
67        sibl.push(constants::EMPTYNODEVALUE);
68    }
69    sibl
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use rustc_hex::ToHex;
76
77    #[test]
78    fn test_hash_vec() {
79        let a: Vec<u8> = From::from("test");
80        assert_eq!("74657374", a.to_hex());
81        let h = hash_vec(a);
82        assert_eq!(
83            "9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658",
84            h.to_hex()
85        );
86    }
87}