merkletree-rs/src/node.rs
src/node.rsRaw
1use utils;
2use constants;
3
4
5pub struct TreeNode {
6 pub child_l: [u8;32],
7 pub child_r: [u8;32],
8}
9
10impl TreeNode {
11 pub fn bytes(&self) -> Vec<u8> {
12 concatenate_arrays(&self.child_l, &self.child_r)
13 }
14 pub fn ht(&self) -> [u8;32] {
15 utils::hash_vec(self.bytes())
16 }
17}
18
19fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
20 let mut concat = x.to_vec();
21 concat.extend_from_slice(y);
22
23 concat
24}
25
26pub fn parse_node_bytes(b: Vec<u8>) -> TreeNode {
27 if b==constants::EMPTYNODEVALUE {
28 let n = TreeNode {
29 child_l: constants::EMPTYNODEVALUE,
30 child_r: constants::EMPTYNODEVALUE,
31 };
32 return n;
33 }
34 let child_l = &b[0..32];
35 let child_r = &b[32..];
36 TreeNode {
37 child_l: *array_ref!(child_l, 0, 32),
38 child_r: *array_ref!(child_r, 0, 32),
39 }
40}
41
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46 use rustc_hex::ToHex;
47
48 #[test]
49 fn test_hash_vec() {
50 let n = TreeNode {
51 child_l: constants::EMPTYNODEVALUE,
52 child_r: constants::EMPTYNODEVALUE,
53 };
54 assert_eq!("ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5", n.ht().to_hex())
55 }
56}