use sha2::{Digest, Sha256}; #[derive(Debug, Clone)] enum Position { Right, Left, } #[derive(Debug, Clone)] struct Node { left: String, right: String, parent: String, sibling: String, position: Position, data: String, } fn hash(data: String) -> String { let h = Sha256::digest(data.clone()); hex::encode(h).to_string() } fn sha256hash(right_data: String, left_data: String) -> String { let s = format!("{}{}", right_data, left_data); let h = Sha256::digest(s); hex::encode(h).to_string() } #[derive(Debug, Clone)] struct Tree { leaves: Vec<Node>, layer: Vec<Node>, root: String, } impl Tree { fn build_layer(&mut self) { let mut new_layer: Vec<Node> = Vec::new(); if self.layer.len() % 2 == 1 { self.layer.push(self.layer[self.layer.len() - 1].clone()); } for i in (0..self.layer.len()).step_by(2) { let parent_data = sha256hash(self.layer[i].data.clone(), self.layer[i+1].data.clone()); let left = Node {left: "".to_string(), right: "".to_string(), parent: parent_data.clone(), sibling: self.layer[i+1].data.clone(), position: Position::Left, data: self.layer[i].data.clone()}; let right = Node {left: "".to_string(), right: "".to_string(), parent: parent_data.clone(), sibling: self.layer[i].data.clone(), position: Position::Right, data: self.layer[i+1].data.clone()}; let parent = Node {left: self.layer[i].data.clone(), right: self.layer[i+1].data.clone(), parent: "".to_string(), sibling: self.layer[i].data.clone(), position: Position::Left, data: parent_data.clone()}; new_layer.push(parent.clone()); self.leaves.push(left.clone()); self.leaves.push(right.clone()); self.leaves.push(parent.clone()); } self.layer = new_layer; } fn build_tree(&mut self) { while self.layer.len() > 1 { let _ = self.build_layer(); } self.root = self.layer[0].data.clone(); } fn search(&mut self, data: String) -> Node { let hash_value = data.clone(); let mut target = Node {left: "".to_string(), right: "".to_string(), parent: "".to_string(), sibling: "".to_string(), position: Position::Left, data: "".to_string()}; for node in &self.leaves { if node.data == hash_value { let target: Node = node.clone(); } } return target } fn get_pass(&mut self, data: String) -> Vec<String>{ let mut target = self.search(hash(data.clone())); let mut markle_pass: Vec<String> = Vec::new(); markle_pass.push(target.data); while target.parent != "" { markle_pass.push(target.sibling); target = self.search(target.parent); } return markle_pass } } fn merkle_root(v: Vec<&str>) -> String { let mut t = Tree {leaves: [].to_vec(), layer: [].to_vec(), root: "".to_string()}; for n in v { let mut s = Node {left: "".to_string(), right: "".to_string(), parent: "".to_string(), sibling: "".to_string(), position: Position::Left, data: hash(n.to_string())}; t.layer.push(s.clone()); } t.build_tree(); t.root } fn main(){ let v= vec!["aaa", "bbb", "ccc", "ddd", "eee", "fff", "gggg"]; let m = merkle_root(v); println!("{}", m); }
うーん….