You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

770 lines
26 KiB

4 years ago
  1. #[macro_use]
  2. extern crate arrayref;
  3. extern crate hex;
  4. extern crate rustc_hex;
  5. extern crate tiny_keccak;
  6. use rustc_hex::ToHex;
  7. pub mod constants;
  8. pub mod db;
  9. pub mod node;
  10. pub mod utils;
  11. type Result<T> = std::result::Result<T, String>;
  12. pub struct TestValue {
  13. pub bytes: Vec<u8>,
  14. pub index_length: u32,
  15. }
  16. pub trait Value {
  17. fn bytes(&self) -> &Vec<u8>;
  18. fn index_length(&self) -> u32;
  19. fn hi(&self) -> [u8; 32];
  20. fn ht(&self) -> [u8; 32];
  21. }
  22. impl Value for TestValue {
  23. fn bytes(&self) -> &Vec<u8> {
  24. &self.bytes
  25. }
  26. fn index_length(&self) -> u32 {
  27. self.index_length
  28. }
  29. fn hi(&self) -> [u8; 32] {
  30. utils::hash_vec(
  31. self.bytes()
  32. .to_vec()
  33. .split_at(self.index_length() as usize)
  34. .0
  35. .to_vec(),
  36. )
  37. }
  38. fn ht(&self) -> [u8; 32] {
  39. utils::hash_vec(self.bytes().to_vec())
  40. }
  41. }
  42. pub struct MerkleTree<'a> {
  43. root: [u8; 32],
  44. num_levels: u32,
  45. sto: &'a mut db::Db,
  46. root_node_key: [u8;32],
  47. }
  48. impl<'a> MerkleTree<'a> {
  49. pub fn new(database: &'a mut db::Db, num_levels: u32) -> MerkleTree<'a> {
  50. let rnk: [u8; 32] = utils::hash_vec("root".as_bytes().to_vec());
  51. let (_, _, root_vec) = database.get(&rnk);
  52. let mut root: [u8; 32] = [0;32];
  53. root.copy_from_slice(&root_vec); // root will be [0;32] if not found (EMPTYNODEVALUE)
  54. MerkleTree {
  55. root: root,
  56. num_levels,
  57. sto: database,
  58. root_node_key: rnk,
  59. }
  60. }
  61. pub fn get_root(&mut self) -> [u8; 32] {
  62. self.root
  63. }
  64. pub fn get_num_levels(&mut self) -> u32 {
  65. self.num_levels
  66. }
  67. pub fn add(&mut self, v: &TestValue) -> Result<()> {
  68. // add the leaf that we are adding
  69. self.sto.insert(
  70. v.ht(),
  71. constants::TYPENODEVALUE,
  72. v.index_length(),
  73. v.bytes().to_vec(),
  74. );
  75. let hi = v.hi();
  76. let path = utils::get_path(self.num_levels, hi);
  77. let mut siblings: Vec<[u8; 32]> = Vec::new();
  78. let mut node_hash = self.root;
  79. for i in (0..=self.num_levels - 2).rev() {
  80. // get node
  81. let (t, il, node_bytes) = self.sto.get(&node_hash);
  82. if t == constants::TYPENODEFINAL {
  83. let hi_child =
  84. utils::hash_vec(node_bytes.to_vec().split_at(il as usize).0.to_vec());
  85. let path_child = utils::get_path(self.num_levels, hi_child);
  86. let pos_diff = utils::compare_paths(&path_child, &path);
  87. if pos_diff == -1 {
  88. return Err("node already exists".to_owned());
  89. }
  90. let final_node_1_hash = utils::calc_hash_from_leaf_and_level(
  91. pos_diff as u32,
  92. &path_child,
  93. utils::hash_vec(node_bytes.to_vec()),
  94. );
  95. self.sto.insert(
  96. final_node_1_hash,
  97. constants::TYPENODEFINAL,
  98. il,
  99. node_bytes.to_vec(),
  100. );
  101. let final_node_2_hash =
  102. utils::calc_hash_from_leaf_and_level(pos_diff as u32, &path, v.ht());
  103. self.sto.insert(
  104. final_node_2_hash,
  105. constants::TYPENODEFINAL,
  106. v.index_length(),
  107. v.bytes().to_vec(),
  108. );
  109. // parent node
  110. let parent_node: node::TreeNode;
  111. if path[pos_diff as usize] {
  112. parent_node = node::TreeNode {
  113. child_l: final_node_1_hash,
  114. child_r: final_node_2_hash,
  115. }
  116. } else {
  117. parent_node = node::TreeNode {
  118. child_l: final_node_2_hash,
  119. child_r: final_node_1_hash,
  120. }
  121. }
  122. let empties = utils::get_empties_between_i_and_pos(i, pos_diff as u32 + 1);
  123. for empty in &empties {
  124. siblings.push(*empty);
  125. }
  126. let path_from_pos_diff = utils::cut_path(&path, (pos_diff + 1) as usize);
  127. self.root = self.replace_leaf(
  128. path_from_pos_diff,
  129. &siblings,
  130. parent_node.ht(),
  131. constants::TYPENODENORMAL,
  132. 0,
  133. parent_node.bytes().to_vec(),
  134. );
  135. self.sto
  136. .insert(self.root_node_key, constants::TYPENODEROOT, 0, self.root.to_vec());
  137. return Ok(());
  138. }
  139. let node = node::parse_node_bytes(node_bytes);
  140. let sibling: [u8; 32];
  141. if !path[i as usize] {
  142. node_hash = node.child_l;
  143. sibling = node.child_r;
  144. } else {
  145. sibling = node.child_l;
  146. node_hash = node.child_r;
  147. }
  148. siblings.push(*array_ref!(sibling, 0, 32));
  149. if node_hash == constants::EMPTYNODEVALUE {
  150. if i == self.num_levels - 2
  151. && siblings[siblings.len() - 1] == constants::EMPTYNODEVALUE
  152. {
  153. let final_node_hash =
  154. utils::calc_hash_from_leaf_and_level(i + 1, &path, v.ht());
  155. self.sto.insert(
  156. final_node_hash,
  157. constants::TYPENODEFINAL,
  158. v.index_length(),
  159. v.bytes().to_vec(),
  160. );
  161. self.root = final_node_hash;
  162. self.sto
  163. .insert(self.root_node_key, constants::TYPENODEROOT, 0, self.root.to_vec());
  164. return Ok(());
  165. }
  166. let final_node_hash = utils::calc_hash_from_leaf_and_level(i, &path, v.ht());
  167. let path_from_i = utils::cut_path(&path, i as usize);
  168. self.root = self.replace_leaf(
  169. path_from_i,
  170. &siblings,
  171. final_node_hash,
  172. constants::TYPENODEFINAL,
  173. v.index_length(),
  174. v.bytes().to_vec(),
  175. );
  176. self.sto
  177. .insert(self.root_node_key, constants::TYPENODEROOT, 0, self.root.to_vec());
  178. return Ok(());
  179. }
  180. }
  181. self.root = self.replace_leaf(
  182. path,
  183. &siblings,
  184. v.ht(),
  185. constants::TYPENODEVALUE,
  186. v.index_length(),
  187. v.bytes().to_vec(),
  188. );
  189. self.sto
  190. .insert(self.root_node_key, constants::TYPENODEROOT, 0, self.root.to_vec());
  191. return Ok(());
  192. }
  193. pub fn replace_leaf(
  194. &mut self,
  195. path: Vec<bool>,
  196. siblings: &Vec<[u8; 32]>,
  197. leaf_hash: [u8; 32],
  198. node_type: u8,
  199. index_length: u32,
  200. leaf_value: Vec<u8>,
  201. ) -> [u8; 32] {
  202. self.sto
  203. .insert(leaf_hash, node_type, index_length, leaf_value);
  204. let mut curr_node = leaf_hash;
  205. for i in 0..siblings.len() {
  206. if !path[i as usize] {
  207. let node = node::TreeNode {
  208. child_l: curr_node,
  209. child_r: siblings[siblings.len() - 1 - i],
  210. };
  211. self.sto
  212. .insert(node.ht(), constants::TYPENODENORMAL, 0, node.bytes());
  213. curr_node = node.ht();
  214. } else {
  215. let node = node::TreeNode {
  216. child_l: siblings[siblings.len() - 1 - i],
  217. child_r: curr_node,
  218. };
  219. self.sto
  220. .insert(node.ht(), constants::TYPENODENORMAL, 0, node.bytes());
  221. curr_node = node.ht();
  222. }
  223. }
  224. curr_node
  225. }
  226. pub fn get_value_in_pos(&mut self, hi: [u8; 32]) -> Vec<u8> {
  227. let path = utils::get_path(self.num_levels, hi);
  228. let mut node_hash = self.root;
  229. for i in (0..=self.num_levels - 2).rev() {
  230. let (t, il, node_bytes) = self.sto.get(&node_hash);
  231. if t == constants::TYPENODEFINAL {
  232. let hi_node = utils::hash_vec(node_bytes.to_vec().split_at(il as usize).0.to_vec());
  233. let path_node = utils::get_path(self.num_levels, hi_node);
  234. let pos_diff = utils::compare_paths(&path_node, &path);
  235. if pos_diff != -1 {
  236. return constants::EMPTYNODEVALUE.to_vec();
  237. }
  238. return node_bytes;
  239. }
  240. let node = node::parse_node_bytes(node_bytes);
  241. if !path[i as usize] {
  242. node_hash = node.child_l;
  243. } else {
  244. node_hash = node.child_r;
  245. }
  246. }
  247. let (_t, _il, node_bytes) = self.sto.get(&node_hash);
  248. node_bytes
  249. }
  250. pub fn generate_proof(&mut self, hi: [u8; 32]) -> Vec<u8> {
  251. let mut mp: Vec<u8> = Vec::new();
  252. let mut empties: [u8; 32] = [0; 32];
  253. let path = utils::get_path(self.num_levels, hi);
  254. let mut siblings: Vec<[u8; 32]> = Vec::new();
  255. let mut node_hash = self.root;
  256. for i in 0..self.num_levels {
  257. let (t, il, node_bytes) = self.sto.get(&node_hash);
  258. if t == constants::TYPENODEFINAL {
  259. let real_value_in_pos = self.get_value_in_pos(hi);
  260. if real_value_in_pos == constants::EMPTYNODEVALUE {
  261. let leaf_hi =
  262. utils::hash_vec(node_bytes.to_vec().split_at(il as usize).0.to_vec());
  263. let path_child = utils::get_path(self.num_levels, leaf_hi);
  264. let pos_diff = utils::compare_paths(&path_child, &path);
  265. if pos_diff as u32 == self.num_levels {
  266. return mp;
  267. }
  268. if pos_diff as u32 != self.num_levels - 1 - i {
  269. let sibling = utils::calc_hash_from_leaf_and_level(
  270. pos_diff as u32,
  271. &path_child,
  272. utils::hash_vec(node_bytes.to_vec()),
  273. );
  274. let mut new_siblings: Vec<[u8; 32]> = Vec::new();
  275. new_siblings.push(sibling);
  276. new_siblings.extend(siblings);
  277. siblings = new_siblings;
  278. // set empties bit
  279. let bit_pos = self.num_levels - 2 - pos_diff as u32;
  280. empties[(empties.len() as isize + (bit_pos as isize / 8 - 1) as isize)
  281. as usize] |= 1 << (bit_pos % 8);
  282. }
  283. }
  284. break;
  285. }
  286. let node = node::parse_node_bytes(node_bytes);
  287. let sibling: [u8; 32];
  288. if !path[self.num_levels as usize - i as usize - 2] {
  289. node_hash = node.child_l;
  290. sibling = node.child_r;
  291. } else {
  292. sibling = node.child_l;
  293. node_hash = node.child_r;
  294. }
  295. if sibling != constants::EMPTYNODEVALUE {
  296. // set empties bit
  297. empties[(empties.len() as isize + (i as isize / 8 - 1) as isize) as usize] |=
  298. 1 << (i % 8);
  299. let mut new_siblings: Vec<[u8; 32]> = Vec::new();
  300. new_siblings.push(sibling);
  301. new_siblings.extend(siblings);
  302. siblings = new_siblings;
  303. }
  304. }
  305. mp.append(&mut empties[..].to_vec());
  306. for s in siblings {
  307. mp.append(&mut s.to_vec());
  308. }
  309. mp
  310. }
  311. pub fn print_level(&mut self, parent: [u8; 32], mut lvl: u32, max_level: u32) {
  312. let mut line: String = "".to_string();
  313. for _ in 0..lvl {
  314. line += &format!(" ");
  315. }
  316. line += &format!("lvl {}", lvl);
  317. line += &format!(" - '{}' = ", parent.to_hex());
  318. let (t, _, node_bytes) = self.sto.get(&parent);
  319. let mut node = node::TreeNode {
  320. child_l: constants::EMPTYNODEVALUE,
  321. child_r: constants::EMPTYNODEVALUE,
  322. };
  323. if t == constants::TYPENODENORMAL {
  324. node = node::parse_node_bytes(node_bytes);
  325. line += &format!("'{}' - '{}'", node.child_l.to_hex(), node.child_r.to_hex());
  326. } else if t == constants::TYPENODEVALUE {
  327. //
  328. } else if t == constants::TYPENODEFINAL {
  329. let hash_node_bytes = utils::hash_vec(node_bytes);
  330. line += &format!("[final] final tree node: {} \n", hash_node_bytes.to_hex());
  331. let (_, _, leaf_node_bytes) = self.sto.get(&hash_node_bytes);
  332. for _ in 0..lvl {
  333. line += " ";
  334. }
  335. let leaf_node_string = String::from_utf8_lossy(&leaf_node_bytes);
  336. line += &format!("leaf value: {}", leaf_node_string);
  337. } else {
  338. line += "[EMPTY Branch]"
  339. }
  340. println!("{}", line);
  341. lvl += 1;
  342. if node.child_r.len() > 0
  343. && lvl < max_level
  344. && t != constants::TYPENODEEMPTY
  345. && t != constants::TYPENODEFINAL
  346. {
  347. self.print_level(node.child_l, lvl, max_level);
  348. self.print_level(node.child_r, lvl, max_level);
  349. }
  350. }
  351. pub fn print_full_tree(&mut self) {
  352. let root = self.root.clone();
  353. let num_levels = self.num_levels.clone();
  354. self.print_level(root, 0, num_levels - 1);
  355. println!("root {:?}", &self.root.to_hex());
  356. }
  357. pub fn print_levels_tree(&mut self, max_level: u32) {
  358. let root = self.root.clone();
  359. let num_levels = self.num_levels.clone();
  360. self.print_level(root, 0, num_levels - 1 - max_level);
  361. println!("root {:?}", self.root.to_hex());
  362. }
  363. }
  364. pub fn verify_proof(
  365. root: [u8; 32],
  366. mp: &Vec<u8>,
  367. hi: [u8; 32],
  368. ht: [u8; 32],
  369. num_levels: u32,
  370. ) -> bool {
  371. let empties: Vec<u8>;
  372. empties = mp.split_at(32).0.to_vec();
  373. let mut siblings: Vec<[u8; 32]> = Vec::new();
  374. for i in (empties.len()..mp.len()).step_by(constants::EMPTYNODEVALUE.len()) {
  375. let mut sibling: [u8; 32] = [0; 32];
  376. sibling.copy_from_slice(&mp[i..i + constants::EMPTYNODEVALUE.len()]);
  377. siblings.push(sibling);
  378. }
  379. let path = utils::get_path(num_levels, hi);
  380. let mut node_hash = ht;
  381. let mut sibling_used_pos = 0;
  382. for i in (0..=num_levels - 2).rev() {
  383. let sibling: [u8; 32];
  384. if (empties[empties.len() - i as usize / 8 - 1] & (1 << (i % 8))) > 0 {
  385. sibling = siblings[sibling_used_pos];
  386. sibling_used_pos += 1;
  387. } else {
  388. sibling = constants::EMPTYNODEVALUE;
  389. }
  390. let n: node::TreeNode;
  391. if path[num_levels as usize - i as usize - 2] {
  392. n = node::TreeNode {
  393. child_l: sibling,
  394. child_r: node_hash,
  395. }
  396. } else {
  397. n = node::TreeNode {
  398. child_l: node_hash,
  399. child_r: sibling,
  400. }
  401. }
  402. if node_hash == constants::EMPTYNODEVALUE && sibling == constants::EMPTYNODEVALUE {
  403. node_hash = constants::EMPTYNODEVALUE;
  404. } else {
  405. node_hash = n.ht();
  406. }
  407. }
  408. if node_hash == root {
  409. return true;
  410. }
  411. false
  412. }
  413. #[cfg(test)]
  414. mod tests {
  415. use super::*;
  416. use rustc_hex::ToHex;
  417. #[test]
  418. fn test_hash_vec() {
  419. let a: Vec<u8> = From::from("test".to_string());
  420. let h = utils::hash_vec(a);
  421. assert_eq!(
  422. "9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658",
  423. h.to_hex()
  424. );
  425. }
  426. #[test]
  427. fn test_new_mt() {
  428. let mut sto = db::Db::new("test".to_string(), true);
  429. let mt = MerkleTree::new(&mut sto, 140);
  430. assert_eq!(140, mt.num_levels);
  431. assert_eq!(
  432. "0000000000000000000000000000000000000000000000000000000000000000",
  433. mt.root.to_hex()
  434. );
  435. let (_t, _il, b) = mt.sto.get(&[0; 32]);
  436. assert_eq!(mt.root.to_vec(), b);
  437. }
  438. #[test]
  439. fn test_tree_node() {
  440. let n = node::TreeNode {
  441. child_l: [1; 32],
  442. child_r: [2; 32],
  443. };
  444. assert_eq!("01010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202",
  445. n.bytes().to_hex());
  446. assert_eq!(
  447. "346d8c96a2454213fcc0daff3c96ad0398148181b9fa6488f7ae2c0af5b20aa0",
  448. n.ht().to_hex()
  449. );
  450. }
  451. #[test]
  452. fn test_add() {
  453. let mut sto = db::Db::new("test".to_string(), true);
  454. let mut mt = MerkleTree::new(&mut sto, 140);
  455. assert_eq!(
  456. "0000000000000000000000000000000000000000000000000000000000000000",
  457. mt.root.to_hex()
  458. );
  459. let val = TestValue {
  460. bytes: vec![1, 2, 3, 4, 5],
  461. index_length: 3,
  462. };
  463. mt.add(&val).unwrap();
  464. let (_t, _il, b) = mt.sto.get(&val.ht());
  465. assert_eq!(*val.bytes(), b);
  466. assert_eq!(
  467. "a0e72cc948119fcb71b413cf5ada12b2b825d5133299b20a6d9325ffc3e2fbf1",
  468. mt.root.to_hex()
  469. );
  470. }
  471. #[test]
  472. fn test_add_2() {
  473. let mut sto = db::Db::new("test".to_string(), true);
  474. let mut mt = MerkleTree::new(&mut sto, 140);
  475. let val = TestValue {
  476. bytes: "this is a test leaf".as_bytes().to_vec(),
  477. index_length: 15,
  478. };
  479. assert_eq!(
  480. "0000000000000000000000000000000000000000000000000000000000000000",
  481. mt.root.to_hex()
  482. );
  483. mt.add(&val).unwrap();
  484. let (_t, _il, b) = mt.sto.get(&val.ht());
  485. assert_eq!(*val.bytes(), b);
  486. assert_eq!(
  487. "b4fdf8a653198f0e179ccb3af7e4fc09d76247f479d6cfc95cd92d6fda589f27",
  488. mt.root.to_hex()
  489. );
  490. let val2 = TestValue {
  491. bytes: "this is a second test leaf".as_bytes().to_vec(),
  492. index_length: 15,
  493. };
  494. mt.add(&val2).unwrap();
  495. let (_t, _il, b) = mt.sto.get(&val2.ht());
  496. assert_eq!(*val2.bytes(), b);
  497. assert_eq!(
  498. "8ac95e9c8a6fbd40bb21de7895ee35f9c8f30ca029dbb0972c02344f49462e82",
  499. mt.root.to_hex()
  500. );
  501. }
  502. #[test]
  503. fn test_generate_proof_and_verify_proof() {
  504. let mut sto = db::Db::new("test".to_string(), true);
  505. let mut mt = MerkleTree::new(&mut sto, 140);
  506. let val = TestValue {
  507. bytes: "this is a test leaf".as_bytes().to_vec(),
  508. index_length: 15,
  509. };
  510. assert_eq!(
  511. "0000000000000000000000000000000000000000000000000000000000000000",
  512. mt.root.to_hex()
  513. );
  514. mt.add(&val).unwrap();
  515. let (_t, _il, b) = mt.sto.get(&val.ht());
  516. assert_eq!(*val.bytes(), b);
  517. assert_eq!(
  518. "b4fdf8a653198f0e179ccb3af7e4fc09d76247f479d6cfc95cd92d6fda589f27",
  519. mt.root.to_hex()
  520. );
  521. let val2 = TestValue {
  522. bytes: "this is a second test leaf".as_bytes().to_vec(),
  523. index_length: 15,
  524. };
  525. mt.add(&val2).unwrap();
  526. let (_t, _il, b) = mt.sto.get(&val2.ht());
  527. assert_eq!(*val2.bytes(), b);
  528. assert_eq!(
  529. "8ac95e9c8a6fbd40bb21de7895ee35f9c8f30ca029dbb0972c02344f49462e82",
  530. mt.root.to_hex()
  531. );
  532. let mp = mt.generate_proof(val2.hi());
  533. assert_eq!("0000000000000000000000000000000000000000000000000000000000000001fd8e1a60cdb23c0c7b2cf8462c99fafd905054dccb0ed75e7c8a7d6806749b6b", mp.to_hex());
  534. // verify
  535. let v = verify_proof(mt.root, &mp, val2.hi(), val2.ht(), mt.num_levels);
  536. assert_eq!(true, v);
  537. }
  538. #[test]
  539. fn test_generate_proof_empty_leaf_and_verify_proof() {
  540. let mut sto = db::Db::new("test".to_string(), true);
  541. let mut mt = MerkleTree::new(&mut sto, 140);
  542. let val = TestValue {
  543. bytes: "this is a test leaf".as_bytes().to_vec(),
  544. index_length: 15,
  545. };
  546. mt.add(&val).unwrap();
  547. let val2 = TestValue {
  548. bytes: "this is a second test leaf".as_bytes().to_vec(),
  549. index_length: 15,
  550. };
  551. mt.add(&val2).unwrap();
  552. assert_eq!(
  553. "8ac95e9c8a6fbd40bb21de7895ee35f9c8f30ca029dbb0972c02344f49462e82",
  554. mt.root.to_hex()
  555. );
  556. // proof of empty leaf
  557. let val3 = TestValue {
  558. bytes: "this is a third test leaf".as_bytes().to_vec(),
  559. index_length: 15,
  560. };
  561. let mp = mt.generate_proof(val3.hi());
  562. assert_eq!("000000000000000000000000000000000000000000000000000000000000000389741fa23da77c259781ad8f4331a5a7d793eef1db7e5200ddfc8e5f5ca7ce2bfd8e1a60cdb23c0c7b2cf8462c99fafd905054dccb0ed75e7c8a7d6806749b6b", mp.to_hex());
  563. // verify that is a proof of an empty leaf (constants::EMPTYNODEVALUE)
  564. let v = verify_proof(
  565. mt.root,
  566. &mp,
  567. val3.hi(),
  568. constants::EMPTYNODEVALUE,
  569. mt.num_levels,
  570. );
  571. assert_eq!(true, v);
  572. }
  573. #[test]
  574. fn test_harcoded_proofs_of_existing_leaf() {
  575. // check proof of value in leaf
  576. let mut root: [u8; 32] = [0; 32];
  577. root.copy_from_slice(
  578. &hex::decode("7d7c5e8f4b3bf434f3d9d223359c4415e2764dd38de2e025fbf986e976a7ed3d")
  579. .unwrap(),
  580. );
  581. let mp = hex::decode("0000000000000000000000000000000000000000000000000000000000000002d45aada6eec346222eaa6b5d3a9260e08c9b62fcf63c72bc05df284de07e6a52").unwrap();
  582. let mut hi: [u8; 32] = [0; 32];
  583. hi.copy_from_slice(
  584. &hex::decode("786677808ba77bdd9090a969f1ef2cbd1ac5aecd9e654f340500159219106878")
  585. .unwrap(),
  586. );
  587. let mut ht: [u8; 32] = [0; 32];
  588. ht.copy_from_slice(
  589. &hex::decode("786677808ba77bdd9090a969f1ef2cbd1ac5aecd9e654f340500159219106878")
  590. .unwrap(),
  591. );
  592. let v = verify_proof(root, &mp, hi, ht, 140);
  593. assert_eq!(true, v);
  594. }
  595. #[test]
  596. fn test_harcoded_proofs_of_empty_leaf() {
  597. // check proof of value in leaf
  598. let mut root: [u8; 32] = [0; 32];
  599. root.copy_from_slice(
  600. &hex::decode("8f021d00c39dcd768974ddfe0d21f5d13f7215bea28db1f1cb29842b111332e7")
  601. .unwrap(),
  602. );
  603. let mp = hex::decode("0000000000000000000000000000000000000000000000000000000000000004bf8e980d2ed328ae97f65c30c25520aeb53ff837579e392ea1464934c7c1feb9").unwrap();
  604. let mut hi: [u8; 32] = [0; 32];
  605. hi.copy_from_slice(
  606. &hex::decode("a69792a4cff51f40b7a1f7ae596c6ded4aba241646a47538898f17f2a8dff647")
  607. .unwrap(),
  608. );
  609. let v = verify_proof(root, &mp, hi, constants::EMPTYNODEVALUE, 140);
  610. assert_eq!(true, v);
  611. }
  612. #[test]
  613. fn test_add_leafs_different_order() {
  614. let mut sto1 = db::Db::new("test".to_string(), true);
  615. let mut mt1 = MerkleTree::new(&mut sto1, 140);
  616. mt1.add(&TestValue {
  617. bytes: "0 this is a test leaf".as_bytes().to_vec(),
  618. index_length: 15,
  619. })
  620. .unwrap();
  621. mt1.add(&TestValue {
  622. bytes: "1 this is a test leaf".as_bytes().to_vec(),
  623. index_length: 15,
  624. })
  625. .unwrap();
  626. mt1.add(&TestValue {
  627. bytes: "2 this is a test leaf".as_bytes().to_vec(),
  628. index_length: 15,
  629. })
  630. .unwrap();
  631. mt1.add(&TestValue {
  632. bytes: "3 this is a test leaf".as_bytes().to_vec(),
  633. index_length: 15,
  634. })
  635. .unwrap();
  636. mt1.add(&TestValue {
  637. bytes: "4 this is a test leaf".as_bytes().to_vec(),
  638. index_length: 15,
  639. })
  640. .unwrap();
  641. mt1.add(&TestValue {
  642. bytes: "5 this is a test leaf".as_bytes().to_vec(),
  643. index_length: 15,
  644. })
  645. .unwrap();
  646. // mt1.print_full_tree();
  647. let mut sto2 = db::Db::new("test".to_string(), true);
  648. let mut mt2 = MerkleTree::new(&mut sto2, 140);
  649. mt2.add(&TestValue {
  650. bytes: "2 this is a test leaf".as_bytes().to_vec(),
  651. index_length: 15,
  652. })
  653. .unwrap();
  654. mt2.add(&TestValue {
  655. bytes: "1 this is a test leaf".as_bytes().to_vec(),
  656. index_length: 15,
  657. })
  658. .unwrap();
  659. mt2.add(&TestValue {
  660. bytes: "0 this is a test leaf".as_bytes().to_vec(),
  661. index_length: 15,
  662. })
  663. .unwrap();
  664. mt2.add(&TestValue {
  665. bytes: "5 this is a test leaf".as_bytes().to_vec(),
  666. index_length: 15,
  667. })
  668. .unwrap();
  669. mt2.add(&TestValue {
  670. bytes: "3 this is a test leaf".as_bytes().to_vec(),
  671. index_length: 15,
  672. })
  673. .unwrap();
  674. mt2.add(&TestValue {
  675. bytes: "4 this is a test leaf".as_bytes().to_vec(),
  676. index_length: 15,
  677. })
  678. .unwrap();
  679. // mt2.print_full_tree();
  680. assert_eq!(mt1.root, mt2.root);
  681. assert_eq!(
  682. &mt1.root.to_hex(),
  683. "264397f84da141b3134dcde1d7540d27a2bf0d787bbe8365d9ad5c9c18d3c621"
  684. );
  685. }
  686. #[test]
  687. fn test_add_1000_leafs() {
  688. let mut sto = db::Db::new("test".to_string(), true);
  689. let mut mt = MerkleTree::new(&mut sto, 140);
  690. for i in 0..1000 {
  691. mt.add(&TestValue {
  692. bytes: (i.to_string() + " this is a test leaf").as_bytes().to_vec(),
  693. index_length: 15,
  694. })
  695. .unwrap();
  696. }
  697. assert_eq!(
  698. mt.root.to_hex(),
  699. "6e2da580b2920cd78ed8d4e4bf41e209dfc99ef28bc19560042f0ac803e0d6f7"
  700. );
  701. }
  702. #[test]
  703. fn test_get_root_in_db() {
  704. let mut sto = db::Db::new("test".to_string(), true);
  705. let mut mt = MerkleTree::new(&mut sto, 140);
  706. for i in 0..10 {
  707. mt.add(&TestValue {
  708. bytes: (i.to_string() + " this is a test leaf").as_bytes().to_vec(),
  709. index_length: 15,
  710. })
  711. .unwrap();
  712. }
  713. assert_eq!(
  714. mt.root.to_hex(),
  715. "9418fd35bae19de4ab033efaf7cc624adf6a42827e39029d8da13288e9c3170d"
  716. );
  717. let mt2 = MerkleTree::new(&mut sto, 140);
  718. assert_eq!(
  719. mt2.root.to_hex(),
  720. "9418fd35bae19de4ab033efaf7cc624adf6a42827e39029d8da13288e9c3170d"
  721. );
  722. }
  723. }