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.

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