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.

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