storage_outpost/helpers/
filetree_helpers.rs

1//! # filetree_helpers
2//!
3//! helper functions to prepare a filetree msg for broadcasting
4//! full documentation for filetree module here https://github.com/JackalLabs/canine-chain/tree/master/x/filetree
5//! TODO: update documentation comments for v4 chain upgrade
6
7use sha2::{Sha256, Digest};
8use hex::encode;
9
10/// hash a string input and encode to hex string
11pub fn hash_and_hex(input: &str) -> String {
12    let mut hasher = Sha256::new();
13    hasher.update(input.as_bytes());
14    let hash_result = hasher.finalize();
15    encode(hash_result)
16}
17
18/// full markle path
19pub fn merkle_path(path: &str) -> String {
20    let trim_path = path.trim_end_matches('/');
21    let chunks: Vec<&str> = trim_path.split('/').collect();
22    let mut total = String::new();
23
24    for chunk in chunks {
25        let mut hasher = Sha256::new();
26        hasher.update(chunk.as_bytes());
27        let b = encode(hasher.finalize());
28        let k = format!("{}{}", total, b);
29
30        let mut hasher1 = Sha256::new();
31        hasher1.update(k.as_bytes());
32        total = encode(hasher1.finalize());
33    }
34
35    total
36}
37
38/// return the merkle path of the parent and the hash_and_hex of the child
39pub fn merkle_helper(arg_hashpath: &str) -> (String, String) {
40    let trim_path = arg_hashpath.trim_end_matches('/');
41    let chunks: Vec<&str> = trim_path.split('/').collect();
42
43    let parent_string = chunks[..chunks.len() - 1].join("/");
44    let child_string = chunks[chunks.len() - 1].to_string();
45    
46    let parent_hash = merkle_path(&parent_string);
47
48    let mut hasher = Sha256::new();
49    hasher.update(child_string.as_bytes());
50    let child_hash = encode(hasher.finalize());
51
52    (parent_hash, child_hash)
53}
54