MerkleProof.sol 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)
  3. // This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
  4. pragma solidity ^0.8.20;
  5. import {Hashes} from "./Hashes.sol";
  6. /**
  7. * @dev These functions deal with verification of Merkle Tree proofs.
  8. *
  9. * The tree and the proofs can be generated using our
  10. * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
  11. * You will find a quickstart guide in the readme.
  12. *
  13. * WARNING: You should avoid using leaf values that are 64 bytes long prior to
  14. * hashing, or use a hash function other than keccak256 for hashing leaves.
  15. * This is because the concatenation of a sorted pair of internal nodes in
  16. * the Merkle tree could be reinterpreted as a leaf value.
  17. * OpenZeppelin's JavaScript library generates Merkle trees that are safe
  18. * against this attack out of the box.
  19. *
  20. * NOTE: This library supports proof verification for merkle trees built using
  21. * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
  22. * leaf inclusion in trees built using non-commutative hashing functions requires
  23. * additional logic that is not supported by this library.
  24. */
  25. library MerkleProof {
  26. /**
  27. *@dev The multiproof provided is not valid.
  28. */
  29. error MerkleProofInvalidMultiproof();
  30. /**
  31. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  32. * defined by `root`. For this, a `proof` must be provided, containing
  33. * sibling hashes on the branch from the leaf to the root of the tree. Each
  34. * pair of leaves and each pair of pre-images are assumed to be sorted.
  35. *
  36. * This version handles proofs in memory with the default hashing function.
  37. */
  38. function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  39. return processProof(proof, leaf) == root;
  40. }
  41. /**
  42. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  43. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  44. * hash matches the root of the tree. When processing the proof, the pairs
  45. * of leafs & pre-images are assumed to be sorted.
  46. *
  47. * This version handles proofs in memory with the default hashing function.
  48. */
  49. function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
  50. bytes32 computedHash = leaf;
  51. for (uint256 i = 0; i < proof.length; i++) {
  52. computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
  53. }
  54. return computedHash;
  55. }
  56. /**
  57. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  58. * defined by `root`. For this, a `proof` must be provided, containing
  59. * sibling hashes on the branch from the leaf to the root of the tree. Each
  60. * pair of leaves and each pair of pre-images are assumed to be sorted.
  61. *
  62. * This version handles proofs in memory with a custom hashing function.
  63. */
  64. function verify(
  65. bytes32[] memory proof,
  66. bytes32 root,
  67. bytes32 leaf,
  68. function(bytes32, bytes32) view returns (bytes32) hasher
  69. ) internal view returns (bool) {
  70. return processProof(proof, leaf, hasher) == root;
  71. }
  72. /**
  73. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  74. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  75. * hash matches the root of the tree. When processing the proof, the pairs
  76. * of leafs & pre-images are assumed to be sorted.
  77. *
  78. * This version handles proofs in memory with a custom hashing function.
  79. */
  80. function processProof(
  81. bytes32[] memory proof,
  82. bytes32 leaf,
  83. function(bytes32, bytes32) view returns (bytes32) hasher
  84. ) internal view returns (bytes32) {
  85. bytes32 computedHash = leaf;
  86. for (uint256 i = 0; i < proof.length; i++) {
  87. computedHash = hasher(computedHash, proof[i]);
  88. }
  89. return computedHash;
  90. }
  91. /**
  92. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  93. * defined by `root`. For this, a `proof` must be provided, containing
  94. * sibling hashes on the branch from the leaf to the root of the tree. Each
  95. * pair of leaves and each pair of pre-images are assumed to be sorted.
  96. *
  97. * This version handles proofs in calldata with the default hashing function.
  98. */
  99. function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  100. return processProofCalldata(proof, leaf) == root;
  101. }
  102. /**
  103. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  104. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  105. * hash matches the root of the tree. When processing the proof, the pairs
  106. * of leafs & pre-images are assumed to be sorted.
  107. *
  108. * This version handles proofs in calldata with the default hashing function.
  109. */
  110. function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
  111. bytes32 computedHash = leaf;
  112. for (uint256 i = 0; i < proof.length; i++) {
  113. computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
  114. }
  115. return computedHash;
  116. }
  117. /**
  118. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  119. * defined by `root`. For this, a `proof` must be provided, containing
  120. * sibling hashes on the branch from the leaf to the root of the tree. Each
  121. * pair of leaves and each pair of pre-images are assumed to be sorted.
  122. *
  123. * This version handles proofs in calldata with a custom hashing function.
  124. */
  125. function verifyCalldata(
  126. bytes32[] calldata proof,
  127. bytes32 root,
  128. bytes32 leaf,
  129. function(bytes32, bytes32) view returns (bytes32) hasher
  130. ) internal view returns (bool) {
  131. return processProofCalldata(proof, leaf, hasher) == root;
  132. }
  133. /**
  134. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  135. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  136. * hash matches the root of the tree. When processing the proof, the pairs
  137. * of leafs & pre-images are assumed to be sorted.
  138. *
  139. * This version handles proofs in calldata with a custom hashing function.
  140. */
  141. function processProofCalldata(
  142. bytes32[] calldata proof,
  143. bytes32 leaf,
  144. function(bytes32, bytes32) view returns (bytes32) hasher
  145. ) internal view returns (bytes32) {
  146. bytes32 computedHash = leaf;
  147. for (uint256 i = 0; i < proof.length; i++) {
  148. computedHash = hasher(computedHash, proof[i]);
  149. }
  150. return computedHash;
  151. }
  152. /**
  153. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  154. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  155. *
  156. * This version handles multiproofs in memory with the default hashing function.
  157. *
  158. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  159. *
  160. * NOTE: The _empty set_ (i.e. the case where `proof.length == 0 && leaves.length == 0`) is considered a noop,
  161. * and therefore a valid multiproof (i.e. it returns `true`). Consider disallowing this case if you're not
  162. * validating the leaves elsewhere.
  163. */
  164. function multiProofVerify(
  165. bytes32[] memory proof,
  166. bool[] memory proofFlags,
  167. bytes32 root,
  168. bytes32[] memory leaves
  169. ) internal pure returns (bool) {
  170. return processMultiProof(proof, proofFlags, leaves) == root;
  171. }
  172. /**
  173. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  174. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  175. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  176. * respectively.
  177. *
  178. * This version handles multiproofs in memory with the default hashing function.
  179. *
  180. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  181. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  182. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  183. */
  184. function processMultiProof(
  185. bytes32[] memory proof,
  186. bool[] memory proofFlags,
  187. bytes32[] memory leaves
  188. ) internal pure returns (bytes32 merkleRoot) {
  189. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  190. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  191. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  192. // the Merkle tree.
  193. uint256 leavesLen = leaves.length;
  194. uint256 proofFlagsLen = proofFlags.length;
  195. // Check proof validity.
  196. if (leavesLen + proof.length != proofFlagsLen + 1) {
  197. revert MerkleProofInvalidMultiproof();
  198. }
  199. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  200. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  201. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  202. uint256 leafPos = 0;
  203. uint256 hashPos = 0;
  204. uint256 proofPos = 0;
  205. // At each step, we compute the next hash using two values:
  206. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  207. // get the next hash.
  208. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  209. // `proof` array.
  210. for (uint256 i = 0; i < proofFlagsLen; i++) {
  211. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  212. bytes32 b = proofFlags[i]
  213. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  214. : proof[proofPos++];
  215. hashes[i] = Hashes.commutativeKeccak256(a, b);
  216. }
  217. if (proofFlagsLen > 0) {
  218. if (proofPos != proof.length) {
  219. revert MerkleProofInvalidMultiproof();
  220. }
  221. unchecked {
  222. return hashes[proofFlagsLen - 1];
  223. }
  224. } else if (leavesLen > 0) {
  225. return leaves[0];
  226. } else {
  227. return proof[0];
  228. }
  229. }
  230. /**
  231. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  232. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  233. *
  234. * This version handles multiproofs in memory with a custom hashing function.
  235. *
  236. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  237. *
  238. * NOTE: The _empty set_ (i.e. the case where `proof.length == 0 && leaves.length == 0`) is considered a noop,
  239. * and therefore a valid multiproof (i.e. it returns `true`). Consider disallowing this case if you're not
  240. * validating the leaves elsewhere.
  241. */
  242. function multiProofVerify(
  243. bytes32[] memory proof,
  244. bool[] memory proofFlags,
  245. bytes32 root,
  246. bytes32[] memory leaves,
  247. function(bytes32, bytes32) view returns (bytes32) hasher
  248. ) internal view returns (bool) {
  249. return processMultiProof(proof, proofFlags, leaves, hasher) == root;
  250. }
  251. /**
  252. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  253. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  254. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  255. * respectively.
  256. *
  257. * This version handles multiproofs in memory with a custom hashing function.
  258. *
  259. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  260. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  261. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  262. */
  263. function processMultiProof(
  264. bytes32[] memory proof,
  265. bool[] memory proofFlags,
  266. bytes32[] memory leaves,
  267. function(bytes32, bytes32) view returns (bytes32) hasher
  268. ) internal view returns (bytes32 merkleRoot) {
  269. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  270. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  271. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  272. // the Merkle tree.
  273. uint256 leavesLen = leaves.length;
  274. uint256 proofFlagsLen = proofFlags.length;
  275. // Check proof validity.
  276. if (leavesLen + proof.length != proofFlagsLen + 1) {
  277. revert MerkleProofInvalidMultiproof();
  278. }
  279. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  280. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  281. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  282. uint256 leafPos = 0;
  283. uint256 hashPos = 0;
  284. uint256 proofPos = 0;
  285. // At each step, we compute the next hash using two values:
  286. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  287. // get the next hash.
  288. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  289. // `proof` array.
  290. for (uint256 i = 0; i < proofFlagsLen; i++) {
  291. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  292. bytes32 b = proofFlags[i]
  293. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  294. : proof[proofPos++];
  295. hashes[i] = hasher(a, b);
  296. }
  297. if (proofFlagsLen > 0) {
  298. if (proofPos != proof.length) {
  299. revert MerkleProofInvalidMultiproof();
  300. }
  301. unchecked {
  302. return hashes[proofFlagsLen - 1];
  303. }
  304. } else if (leavesLen > 0) {
  305. return leaves[0];
  306. } else {
  307. return proof[0];
  308. }
  309. }
  310. /**
  311. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  312. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  313. *
  314. * This version handles multiproofs in calldata with the default hashing function.
  315. *
  316. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  317. *
  318. * NOTE: The _empty set_ (i.e. the case where `proof.length == 0 && leaves.length == 0`) is considered a noop,
  319. * and therefore a valid multiproof (i.e. it returns `true`). Consider disallowing this case if you're not
  320. * validating the leaves elsewhere.
  321. */
  322. function multiProofVerifyCalldata(
  323. bytes32[] calldata proof,
  324. bool[] calldata proofFlags,
  325. bytes32 root,
  326. bytes32[] memory leaves
  327. ) internal pure returns (bool) {
  328. return processMultiProofCalldata(proof, proofFlags, leaves) == root;
  329. }
  330. /**
  331. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  332. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  333. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  334. * respectively.
  335. *
  336. * This version handles multiproofs in calldata with the default hashing function.
  337. *
  338. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  339. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  340. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  341. */
  342. function processMultiProofCalldata(
  343. bytes32[] calldata proof,
  344. bool[] calldata proofFlags,
  345. bytes32[] memory leaves
  346. ) internal pure returns (bytes32 merkleRoot) {
  347. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  348. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  349. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  350. // the Merkle tree.
  351. uint256 leavesLen = leaves.length;
  352. uint256 proofFlagsLen = proofFlags.length;
  353. // Check proof validity.
  354. if (leavesLen + proof.length != proofFlagsLen + 1) {
  355. revert MerkleProofInvalidMultiproof();
  356. }
  357. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  358. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  359. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  360. uint256 leafPos = 0;
  361. uint256 hashPos = 0;
  362. uint256 proofPos = 0;
  363. // At each step, we compute the next hash using two values:
  364. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  365. // get the next hash.
  366. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  367. // `proof` array.
  368. for (uint256 i = 0; i < proofFlagsLen; i++) {
  369. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  370. bytes32 b = proofFlags[i]
  371. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  372. : proof[proofPos++];
  373. hashes[i] = Hashes.commutativeKeccak256(a, b);
  374. }
  375. if (proofFlagsLen > 0) {
  376. if (proofPos != proof.length) {
  377. revert MerkleProofInvalidMultiproof();
  378. }
  379. unchecked {
  380. return hashes[proofFlagsLen - 1];
  381. }
  382. } else if (leavesLen > 0) {
  383. return leaves[0];
  384. } else {
  385. return proof[0];
  386. }
  387. }
  388. /**
  389. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  390. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  391. *
  392. * This version handles multiproofs in calldata with a custom hashing function.
  393. *
  394. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  395. *
  396. * NOTE: The _empty set_ (i.e. the case where `proof.length == 0 && leaves.length == 0`) is considered a noop,
  397. * and therefore a valid multiproof (i.e. it returns `true`). Consider disallowing this case if you're not
  398. * validating the leaves elsewhere.
  399. */
  400. function multiProofVerifyCalldata(
  401. bytes32[] calldata proof,
  402. bool[] calldata proofFlags,
  403. bytes32 root,
  404. bytes32[] memory leaves,
  405. function(bytes32, bytes32) view returns (bytes32) hasher
  406. ) internal view returns (bool) {
  407. return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
  408. }
  409. /**
  410. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  411. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  412. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  413. * respectively.
  414. *
  415. * This version handles multiproofs in calldata with a custom hashing function.
  416. *
  417. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  418. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  419. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  420. */
  421. function processMultiProofCalldata(
  422. bytes32[] calldata proof,
  423. bool[] calldata proofFlags,
  424. bytes32[] memory leaves,
  425. function(bytes32, bytes32) view returns (bytes32) hasher
  426. ) internal view returns (bytes32 merkleRoot) {
  427. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  428. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  429. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  430. // the Merkle tree.
  431. uint256 leavesLen = leaves.length;
  432. uint256 proofFlagsLen = proofFlags.length;
  433. // Check proof validity.
  434. if (leavesLen + proof.length != proofFlagsLen + 1) {
  435. revert MerkleProofInvalidMultiproof();
  436. }
  437. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  438. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  439. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  440. uint256 leafPos = 0;
  441. uint256 hashPos = 0;
  442. uint256 proofPos = 0;
  443. // At each step, we compute the next hash using two values:
  444. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  445. // get the next hash.
  446. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  447. // `proof` array.
  448. for (uint256 i = 0; i < proofFlagsLen; i++) {
  449. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  450. bytes32 b = proofFlags[i]
  451. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  452. : proof[proofPos++];
  453. hashes[i] = hasher(a, b);
  454. }
  455. if (proofFlagsLen > 0) {
  456. if (proofPos != proof.length) {
  457. revert MerkleProofInvalidMultiproof();
  458. }
  459. unchecked {
  460. return hashes[proofFlagsLen - 1];
  461. }
  462. } else if (leavesLen > 0) {
  463. return leaves[0];
  464. } else {
  465. return proof[0];
  466. }
  467. }
  468. }