arnaucube
arnaucube/merkletree-rsPublic Self-hosted repository
merkletree-rs/src/utils.rs
src/utils.rsRaw
 1use node;
 2use tiny_keccak::Keccak;
 3use constants;
 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(until_level: u32, path: &[bool], leaf_hash: [u8;32]) -> [u8;32] {
22    let mut node_curr_lvl = leaf_hash;
23    for i in 0..until_level {
24        if path[i as usize] {
25            let node = node::TreeNode {
26                child_l: constants::EMPTYNODEVALUE,
27                child_r: node_curr_lvl,
28            };
29            node_curr_lvl = node.ht();
30        } else {
31            let node = node::TreeNode {
32                child_l: node_curr_lvl,
33                child_r: constants::EMPTYNODEVALUE,
34            };
35            node_curr_lvl = node.ht();
36        }
37    }
38    node_curr_lvl
39}
40
41pub fn cut_path(path: &[bool], i: usize) -> Vec<bool> {
42    let mut path_res: Vec<bool> = Vec::new();
43    for j in 0..path.len() {
44        if j>=i {
45            path_res.push(path[j]);
46        }
47    }
48    path_res
49}
50
51pub fn compare_paths(a: &[bool], b: &[bool]) -> u32 {
52    for i in (0..a.len()).rev() {
53        if a[i] != b[i] {
54            return i as u32;
55        }
56    }
57    999
58}
59
60pub fn get_empties_between_i_and_pos(i: u32, pos: u32) -> Vec<[u8;32]> {
61    let mut sibl: Vec<[u8;32]> = Vec::new();
62    for _ in (pos..=i).rev() {
63        sibl.push(constants::EMPTYNODEVALUE);
64    }
65    sibl
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71    use rustc_hex::ToHex;
72
73    #[test]
74    fn test_hash_vec() {
75        let a: Vec<u8> = From::from("test");
76        assert_eq!("74657374", a.to_hex());
77        let h = hash_vec(a);
78        assert_eq!("9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658", h.to_hex());
79    }
80}