merkle_tree.move 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Implementation of a Merkle tree in Move. Supports constructing a new tree
  2. // with a given depth, as well as proving that a leaf node belongs to the tree.
  3. module pyth::merkle_tree {
  4. use std::vector::{Self};
  5. use sui::hash::{keccak256};
  6. use wormhole::bytes20::{Self, Bytes20, data};
  7. use wormhole::cursor::{Self, Cursor};
  8. use pyth::deserialize::{Self};
  9. const MERKLE_LEAF_PREFIX: u8 = 0;
  10. const MERKLE_NODE_PREFIX: u8 = 1;
  11. const MERKLE_EMPTY_LEAF_PREFIX: u8 = 2;
  12. const E_DEPTH_NOT_LARGE_ENOUGH_FOR_MESSAGES: u64 = 1212121;
  13. // take keccak256 of input data, then return 20 leftmost bytes of result
  14. fun hash(bytes: &vector<u8>): Bytes20 {
  15. let hashed_bytes = keccak256(bytes);
  16. let hash_prefix = vector::empty<u8>();
  17. let i = 0;
  18. while (i < 20) {
  19. vector::push_back(&mut hash_prefix, *vector::borrow(&hashed_bytes, i));
  20. i = i + 1;
  21. };
  22. bytes20::new(hash_prefix)
  23. }
  24. fun empty_leaf_hash(): Bytes20 {
  25. let v = vector<u8>[MERKLE_EMPTY_LEAF_PREFIX];
  26. hash(&v)
  27. }
  28. fun leaf_hash(data: &vector<u8>): Bytes20 {
  29. let v = vector<u8>[MERKLE_LEAF_PREFIX];
  30. let i = 0;
  31. while (i < vector::length(data)) {
  32. vector::push_back(&mut v, *vector::borrow(data, i));
  33. i = i + 1;
  34. };
  35. hash(&v)
  36. }
  37. fun node_hash(
  38. childA: Bytes20,
  39. childB: Bytes20
  40. ): Bytes20 {
  41. if (greater_than(&childA, &childB)) {
  42. (childA, childB) = (childB, childA);
  43. };
  44. // append data_B to data_A
  45. let data_A = bytes20::data(&childA);
  46. let data_B = bytes20::data(&childB);
  47. // create a vector containing MERKLE_NODE_PREFIX + data_A + data_B
  48. let v = vector<u8>[MERKLE_NODE_PREFIX];
  49. let i = 0;
  50. while (i < 20) {
  51. vector::push_back(&mut v, *vector::borrow(&data_A, i));
  52. i = i + 1;
  53. };
  54. let i = 0;
  55. while (i < 20) {
  56. vector::push_back(&mut v, *vector::borrow(&data_B, i));
  57. i = i + 1;
  58. };
  59. hash(&v)
  60. }
  61. // greater_than returns whether a is strictly greater than b
  62. // note that data(&a) and data(&b) are both vector<u8>s of length 20
  63. fun greater_than(a: &Bytes20, b: &Bytes20): bool {
  64. // aa and bb both have length 20
  65. let a_vector = data(a);
  66. let b_vector = data(b);
  67. let i = 0;
  68. while (i < 20) {
  69. let a_value = *vector::borrow(&a_vector, i);
  70. let b_value = *vector::borrow(&b_vector, i);
  71. if (a_value > b_value) {
  72. return true
  73. } else if (b_value > a_value) {
  74. return false
  75. };
  76. i = i + 1;
  77. };
  78. false
  79. }
  80. // The Sui Move stdlb insert function shifts v[i] and subsequent elements to the right.
  81. // We don't want this behavior, so we define our own set_element function that instead replaces the ith element.
  82. // Reference: https://github.com/MystenLabs/sui/blob/main/crates/sui-framework/packages/move-stdlib/sources/vector.move
  83. fun set_element<T: drop>(a: &mut vector<T>, value: T, index: u64){
  84. vector::push_back<T>(a, value); // push value to end
  85. vector::swap_remove(a, index); // swap value to correct position and pop last value
  86. }
  87. // is_proof_valid returns whether a merkle proof is valid
  88. public fun is_proof_valid(
  89. encoded_proof: &mut Cursor<u8>,
  90. root: Bytes20,
  91. leaf_data: vector<u8>,
  92. ): bool {
  93. let current_digest: Bytes20 = leaf_hash(&leaf_data);
  94. let proofSize: u8 = deserialize::deserialize_u8(encoded_proof);
  95. while (proofSize > 0){
  96. let sibling_digest: Bytes20 = bytes20::new(
  97. deserialize::deserialize_vector(encoded_proof, 20)
  98. );
  99. current_digest = node_hash(
  100. current_digest,
  101. sibling_digest
  102. );
  103. proofSize = proofSize - 1;
  104. };
  105. bytes20::data(&current_digest) == bytes20::data(&root)
  106. }
  107. // construct_proofs constructs a merkle tree and returns the root of the tree as
  108. // a Bytes20 as well as the vector of encoded proofs
  109. public fun construct_proofs(
  110. messages: &vector<vector<u8>>,
  111. depth: u8
  112. ) : (Bytes20, vector<u8>) {
  113. if ( 1 << depth < vector::length(messages)) {
  114. abort E_DEPTH_NOT_LARGE_ENOUGH_FOR_MESSAGES
  115. };
  116. // empty tree
  117. // The tree is structured as follows:
  118. // 1
  119. // 2 3
  120. // 4 5 6 7
  121. // ...
  122. // In this structure the parent of node x is x//2 and the children
  123. // of node x are x*2 and x*2 + 1. Also, the sibling of the node x
  124. // is x^1. The root is at index 1 and index 0 is not used.
  125. let tree = vector::empty<Bytes20>();
  126. // empty leaf hash
  127. let cachedEmptyLeafHash: Bytes20 = empty_leaf_hash();
  128. // Instantiate tree to be a full binary tree with the appropriate depth.
  129. // Add an entry at the end for swapping
  130. let i: u64 = 0;
  131. while (i < (1 << (depth+1)) + 1){
  132. vector::push_back(&mut tree, cachedEmptyLeafHash);
  133. i = i + 1;
  134. };
  135. // Fill in bottom row with leaf hashes
  136. let j: u64 = 0;
  137. while (j < vector::length(messages)){
  138. set_element<Bytes20>(&mut tree, leaf_hash(vector::borrow(messages, j)), (1 << depth) + j);
  139. j = j + 1;
  140. };
  141. // Filling the node hashes from bottom to top
  142. let k: u8 = depth;
  143. while (k>0){
  144. let level: u8 = k-1;
  145. let levelNumNodes = 1 << level;
  146. let i: u64 = 0;
  147. while (i < levelNumNodes ){
  148. let id = (1 << level) + i;
  149. let node_hash = node_hash(*vector::borrow(&tree, id * 2), *vector::borrow(&tree, id * 2 + 1));
  150. set_element<Bytes20>(&mut tree, node_hash, id);
  151. i = i + 1;
  152. };
  153. k = k - 1;
  154. };
  155. let root = *vector::borrow(&tree, 1);
  156. // construct proofs and create encoded proofs vector
  157. let proofs = vector::empty<u8>();
  158. let i: u64 = 0;
  159. while (i < vector::length(messages)){
  160. let cur_proof = vector::empty<u8>();
  161. vector::push_back(&mut cur_proof, depth);
  162. let idx = (1 << depth) + i;
  163. while (idx > 1) {
  164. vector::append(&mut cur_proof, bytes20::data(vector::borrow(&tree, idx ^ 1)));
  165. // Jump to parent
  166. idx = idx / 2;
  167. };
  168. vector::append(&mut proofs, cur_proof);
  169. i = i + 1;
  170. };
  171. (root, proofs)
  172. }
  173. #[test]
  174. fun testGreaterThan(){
  175. // test 1
  176. let x = bytes20::new(x"0000000000000000000000000000000000001000");
  177. let y = bytes20::new(x"0000000000000000000000000000000000000001");
  178. let res = greater_than(&x, &y);
  179. assert!(res==true, 0);
  180. res = greater_than(&y, &x);
  181. assert!(res==false, 0);
  182. // test 2
  183. x = bytes20::new(x"1100000000000000000000000000000000001000");
  184. y = bytes20::new(x"1100000000000000000000000000000000000001");
  185. res = greater_than(&x, &y);
  186. assert!(res==true, 0);
  187. // equality case
  188. x = bytes20::new(x"1100000000000000000000000000000000001001");
  189. y = bytes20::new(x"1100000000000000000000000000000000001001");
  190. res = greater_than(&x, &y);
  191. assert!(res==false, 0);
  192. }
  193. #[test]
  194. fun test_hash_leaf() {
  195. let data: vector<u8> = x"00640000000000000000000000000000000000000000000000000000000000000000000000000000640000000000000064000000640000000000000064000000000000006400000000000000640000000000000064";
  196. let hash = leaf_hash(&data);
  197. let expected = bytes20::new(x"afc6a8ac466430f35895055f8a4c951785dad5ce");
  198. assert!(hash == expected, 1);
  199. }
  200. #[test]
  201. fun test_hash_node() {
  202. let h1 = bytes20::new(x"05c51b04b820c0f704e3fdd2e4fc1e70aff26dff");
  203. let h2 = bytes20::new(x"1e108841c8d21c7a5c4860c8c3499c918ea9e0ac");
  204. let hash = node_hash(h1, h2);
  205. let expected = bytes20::new(x"2d0e4fde68184c7ce8af426a0865bd41ef84dfa4");
  206. assert!(hash == expected, 1);
  207. }
  208. #[test]
  209. fun testMerkleTreeDepth1(){
  210. let messages = vector::empty<vector<u8>>();
  211. vector::push_back(&mut messages, x"1234");
  212. let (root, proofs) = construct_proofs(&messages, 1);
  213. let proofs_cursor = cursor::new(proofs);
  214. let valid = is_proof_valid(&mut proofs_cursor, root, x"1234");
  215. assert!(valid==true, 0);
  216. // destroy cursor
  217. cursor::take_rest<u8>(proofs_cursor);
  218. }
  219. #[test]
  220. fun testMerkleTreeDepth2(){
  221. let messages = vector::empty<vector<u8>>();
  222. vector::push_back(&mut messages, x"1234");
  223. vector::push_back(&mut messages, x"4321");
  224. vector::push_back(&mut messages, x"11");
  225. vector::push_back(&mut messages, x"22");
  226. let (root, proofs) = construct_proofs(&messages, 2);
  227. let proofs_cursor = cursor::new(proofs);
  228. assert!(is_proof_valid(&mut proofs_cursor, root, x"1234")==true, 0);
  229. assert!(is_proof_valid(&mut proofs_cursor, root, x"4321")==true, 0);
  230. assert!(is_proof_valid(&mut proofs_cursor, root, x"11")==true, 0);
  231. assert!(is_proof_valid(&mut proofs_cursor, root, x"22")==true, 0);
  232. // destroy cursor
  233. cursor::take_rest<u8>(proofs_cursor);
  234. }
  235. #[test]
  236. fun test_merkle_tree_depth_3(){
  237. let messages = vector::empty<vector<u8>>();
  238. vector::push_back(&mut messages, x"00");
  239. vector::push_back(&mut messages, x"4321");
  240. vector::push_back(&mut messages, x"444444");
  241. vector::push_back(&mut messages, x"22222222");
  242. vector::push_back(&mut messages, x"22");
  243. vector::push_back(&mut messages, x"11");
  244. vector::push_back(&mut messages, x"100000");
  245. vector::push_back(&mut messages, x"eeeeee");
  246. let (root, proofs) = construct_proofs(&messages, 3);
  247. let proofs_cursor = cursor::new(proofs);
  248. assert!(is_proof_valid(&mut proofs_cursor, root, x"00")==true, 0);
  249. assert!(is_proof_valid(&mut proofs_cursor, root, x"4321")==true, 0);
  250. assert!(is_proof_valid(&mut proofs_cursor, root, x"444444")==true, 0);
  251. assert!(is_proof_valid(&mut proofs_cursor, root, x"22222222")==true, 0);
  252. assert!(is_proof_valid(&mut proofs_cursor, root, x"22")==true, 0);
  253. assert!(is_proof_valid(&mut proofs_cursor, root, x"11")==true, 0);
  254. assert!(is_proof_valid(&mut proofs_cursor, root, x"100000")==true, 0);
  255. assert!(is_proof_valid(&mut proofs_cursor, root, x"eeeeee")==true, 0);
  256. // destroy cursor
  257. cursor::take_rest<u8>(proofs_cursor);
  258. }
  259. #[test]
  260. fun test_merkle_tree_depth_1_invalid_proofs(){
  261. let messages = vector::empty<vector<u8>>();
  262. vector::push_back(&mut messages, x"1234");
  263. let (root, proofs) = construct_proofs(&messages, 1);
  264. let proofs_cursor = cursor::new(proofs);
  265. // use wrong leaf data (it is not included in the tree)
  266. let valid = is_proof_valid(&mut proofs_cursor, root, x"432222");
  267. assert!(valid==false, 0);
  268. // destroy cursor
  269. cursor::take_rest<u8>(proofs_cursor);
  270. }
  271. #[test]
  272. fun test_merkle_tree_depth_2_invalid_proofs(){
  273. let messages = vector::empty<vector<u8>>();
  274. vector::push_back(&mut messages, x"1234");
  275. vector::push_back(&mut messages, x"4321");
  276. vector::push_back(&mut messages, x"11");
  277. vector::push_back(&mut messages, x"22");
  278. let (root, proofs) = construct_proofs(&messages, 2);
  279. let proofs_cursor = cursor::new(proofs);
  280. // proof fails because we used the proof of x"1234" to try to prove that x"4321" is in the tree
  281. assert!(is_proof_valid(&mut proofs_cursor, root, x"4321")==false, 0);
  282. // proof succeeds
  283. assert!(is_proof_valid(&mut proofs_cursor, root, x"4321")==true, 0);
  284. // proof fails because we used the proof of x"11" to try to prove that x"22" is in the tree
  285. assert!(is_proof_valid(&mut proofs_cursor, root, x"22")==false, 0);
  286. // proof succeeds
  287. assert!(is_proof_valid(&mut proofs_cursor, root, x"22")==true, 0);
  288. // destroy cursor
  289. cursor::take_rest<u8>(proofs_cursor);
  290. }
  291. #[test]
  292. fun test_merkle_tree_depth_3_invalid_proofs(){
  293. let messages = vector::empty<vector<u8>>();
  294. vector::push_back(&mut messages, x"00");
  295. vector::push_back(&mut messages, x"4321");
  296. vector::push_back(&mut messages, x"444444");
  297. vector::push_back(&mut messages, x"22222222");
  298. vector::push_back(&mut messages, x"22");
  299. vector::push_back(&mut messages, x"11");
  300. vector::push_back(&mut messages, x"100000");
  301. vector::push_back(&mut messages, x"eeeeee");
  302. let (root, proofs) = construct_proofs(&messages, 3);
  303. let proofs_cursor = cursor::new(proofs);
  304. // test various proof failure cases (because of mismatch between proof and leaf data)
  305. assert!(is_proof_valid(&mut proofs_cursor, root, x"00")==true, 0);
  306. assert!(is_proof_valid(&mut proofs_cursor, root, x"22")==false, 0);
  307. assert!(is_proof_valid(&mut proofs_cursor, root, x"22222222")==false, 0);
  308. assert!(is_proof_valid(&mut proofs_cursor, root, x"22222222")==true, 0);
  309. assert!(is_proof_valid(&mut proofs_cursor, root, x"22")==true, 0);
  310. assert!(is_proof_valid(&mut proofs_cursor, root, x"eeeeee")==false, 0);
  311. assert!(is_proof_valid(&mut proofs_cursor, root, x"4321")==false, 0);
  312. assert!(is_proof_valid(&mut proofs_cursor, root, x"eeeeee")==true, 0);
  313. // destroy cursor
  314. cursor::take_rest<u8>(proofs_cursor);
  315. }
  316. #[test]
  317. #[expected_failure(abort_code = pyth::merkle_tree::E_DEPTH_NOT_LARGE_ENOUGH_FOR_MESSAGES)]
  318. fun test_merkle_tree_depth_exceeded_1(){
  319. let messages = vector::empty<vector<u8>>();
  320. vector::push_back(&mut messages, x"00");
  321. vector::push_back(&mut messages, x"4321");
  322. vector::push_back(&mut messages, x"444444");
  323. construct_proofs(&messages, 1); //depth 1
  324. }
  325. #[test]
  326. #[expected_failure(abort_code = pyth::merkle_tree::E_DEPTH_NOT_LARGE_ENOUGH_FOR_MESSAGES)]
  327. fun test_merkle_tree_depth_exceeded_2(){
  328. let messages = vector::empty<vector<u8>>();
  329. vector::push_back(&mut messages, x"00");
  330. vector::push_back(&mut messages, x"4321");
  331. vector::push_back(&mut messages, x"444444");
  332. vector::push_back(&mut messages, x"22222222");
  333. vector::push_back(&mut messages, x"22");
  334. construct_proofs(&messages, 2); // depth 2
  335. }
  336. }