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.

87 lines
2.0 KiB

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