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_sha3_256();
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
13#[allow(dead_code)]
14pub fn get_path(num_levels: u32, hi: [u8;32]) -> Vec<bool> {
15 let mut path = Vec::new();
16 for i in (0..num_levels as usize-1).rev() {
17 path.push((hi[hi.len()-i/8-1] & (1 << (i%8))) > 0);
18 }
19 path
20}
21
22#[allow(dead_code)]
23pub fn calc_hash_from_leaf_and_level(until_level: u32, path: &[bool], leaf_hash: [u8;32]) -> [u8;32] {
24 let mut node_curr_lvl = leaf_hash;
25 for i in 0..until_level {
26 if path[i as usize] {
27 let node = node::TreeNode {
28 child_l: ::EMPTYNODEVALUE,
29 child_r: node_curr_lvl,
30 };
31 node_curr_lvl = node.ht();
32 } else {
33 let node = node::TreeNode {
34 child_l: node_curr_lvl,
35 child_r: ::EMPTYNODEVALUE,
36 };
37 node_curr_lvl = node.ht();
38 }
39 }
40 node_curr_lvl
41}
42
43pub fn cut_path(path: &[bool], i: usize) -> Vec<bool> {
44 let mut path_res: Vec<bool> = Vec::new();
45 for (j, path_elem) in path.iter().enumerate() {
46 if j >= i {
47 path_res.push(*path_elem);
48 }
49 }
50 path_res
51}
52
53pub fn compare_paths(a: &[bool], b: &[bool]) -> u32 {
54 for i in (0..a.len()).rev() {
55 if a[i] != b[i] {
56 return i as u32;
57 }
58 }
59 999
60}
61
62pub fn get_empties_between_i_and_pos(i: u32, pos: u32) -> Vec<[u8;32]> {
63 let mut sibl: Vec<[u8;32]> = Vec::new();
64 for _j in (pos..i).rev() {
65 sibl.push(::EMPTYNODEVALUE);
66 }
67 sibl.to_vec()
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73 use rustc_hex::ToHex;
74
75 #[test]
76 fn test_hash_vec() {
77 let a: Vec<u8> = From::from("test");
78 assert_eq!("74657374", a.to_hex());
79 let h = hash_vec(a);
80 assert_eq!("9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658", h.to_hex());
81 }
82}