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.

81 lines
2.0 KiB

  1. use node;
  2. use tiny_keccak::Keccak;
  3. pub fn hash_vec(b: Vec<u8>) -> [u8; 32] {
  4. let mut sha3 = Keccak::new_keccak256();
  5. sha3.update(&b);
  6. let mut res: [u8; 32] = [0; 32];
  7. sha3.finalize(&mut res);
  8. res
  9. }
  10. #[allow(dead_code)]
  11. pub fn get_path(num_levels: u32, hi: [u8;32]) -> Vec<bool> {
  12. let mut path = Vec::new();
  13. for i in (0..=num_levels as usize-2).rev() {
  14. path.push((hi[hi.len()-i/8-1] & (1 << (i%8))) > 0);
  15. }
  16. path
  17. }
  18. #[allow(dead_code)]
  19. pub fn calc_hash_from_leaf_and_level(until_level: u32, path: &[bool], leaf_hash: [u8;32]) -> [u8;32] {
  20. let mut node_curr_lvl = leaf_hash;
  21. for i in 0..until_level {
  22. if path[i as usize] {
  23. let node = node::TreeNode {
  24. child_l: ::EMPTYNODEVALUE,
  25. child_r: node_curr_lvl,
  26. };
  27. node_curr_lvl = node.ht();
  28. } else {
  29. let node = node::TreeNode {
  30. child_l: node_curr_lvl,
  31. child_r: ::EMPTYNODEVALUE,
  32. };
  33. node_curr_lvl = node.ht();
  34. }
  35. }
  36. node_curr_lvl
  37. }
  38. pub fn cut_path(path: &[bool], i: usize) -> Vec<bool> {
  39. let mut path_res: Vec<bool> = Vec::new();
  40. for j in 0..path.len() {
  41. if j>=i {
  42. path_res.push(path[j]);
  43. }
  44. }
  45. path_res
  46. }
  47. pub fn compare_paths(a: &[bool], b: &[bool]) -> u32 {
  48. for i in (0..a.len()).rev() {
  49. if a[i] != b[i] {
  50. return i as u32;
  51. }
  52. }
  53. 999
  54. }
  55. pub fn get_empties_between_i_and_pos(i: u32, pos: u32) -> Vec<[u8;32]> {
  56. let mut sibl: Vec<[u8;32]> = Vec::new();
  57. for _ in (pos..=i).rev() {
  58. sibl.push(::EMPTYNODEVALUE);
  59. }
  60. sibl
  61. }
  62. #[cfg(test)]
  63. mod tests {
  64. use super::*;
  65. use rustc_hex::ToHex;
  66. #[test]
  67. fn test_hash_vec() {
  68. let a: Vec<u8> = From::from("test");
  69. assert_eq!("74657374", a.to_hex());
  70. let h = hash_vec(a);
  71. assert_eq!("9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658", h.to_hex());
  72. }
  73. }