keccak160.move 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. module pyth::keccak160 {
  2. use std::vector;
  3. use pyth::error;
  4. use std::aptos_hash;
  5. struct Hash has drop {
  6. data: vector<u8>,
  7. }
  8. const HASH_LENGTH: u64 = 20;
  9. public fun get_data(hash: &Hash): vector<u8> {
  10. hash.data
  11. }
  12. public fun get_hash_length(): u64 {
  13. HASH_LENGTH
  14. }
  15. public fun new(data: vector<u8>): Hash {
  16. assert!(vector::length(&data) == HASH_LENGTH, error::invalid_keccak160_length());
  17. Hash { data }
  18. }
  19. public fun from_data(data: vector<u8>): Hash {
  20. let hash = aptos_hash::keccak256(data);
  21. while (vector::length(&hash) > HASH_LENGTH) {
  22. vector::pop_back(&mut hash);
  23. };
  24. new(hash)
  25. }
  26. public fun is_smaller(lhs: &Hash, rhs: &Hash): bool {
  27. let i = 0;
  28. while (i < vector::length(&get_data(lhs))) {
  29. let lhs_val: u8 = *vector::borrow(&get_data(lhs), i);
  30. let rhs_val: u8 = *vector::borrow(&get_data(rhs), i);
  31. if (lhs_val != rhs_val) {
  32. return lhs_val < rhs_val
  33. };
  34. i = i + 1;
  35. };
  36. false
  37. }
  38. #[test]
  39. fun test_from_data() {
  40. let hash = from_data(vector[0]);
  41. let expected = new(x"bc36789e7a1e281436464229828f817d6612f7b4");
  42. assert!(&hash == &expected, 1);
  43. }
  44. #[test]
  45. fun test_is_smaller() {
  46. let h1 = new(x"0000000000000000010000000000000000000000");
  47. let h2 = new(x"0000000000000000000300000000000000000000");
  48. let h3 = new(x"0000000000000000000200000000000000000000");
  49. assert!(is_smaller(&h3, &h2), 1);
  50. assert!(!is_smaller(&h2, &h3), 1);
  51. assert!(is_smaller(&h2, &h1), 1);
  52. assert!(!is_smaller(&h1, &h2), 1);
  53. assert!(is_smaller(&h3, &h1), 1);
  54. assert!(!is_smaller(&h1, &h3), 1);
  55. assert!(!is_smaller(&h1, &h1), 1);
  56. assert!(!is_smaller(&h2, &h2), 1);
  57. assert!(!is_smaller(&h3, &h3), 1);
  58. }
  59. #[test]
  60. fun test_new_success() {
  61. new(x"05c51b04b820c0f704e3fdd2e4fc1e70aff26dff");
  62. }
  63. #[test]
  64. #[expected_failure(abort_code = 65566, location = pyth::keccak160)]
  65. fun test_new_wrong_size() {
  66. new(vector[1, 2, 3]);
  67. }
  68. }