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