MerkleProof.sol 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 processProof(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 processProof(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. function multiProofVerify(
  161. bytes32[] memory proof,
  162. bool[] memory proofFlags,
  163. bytes32 root,
  164. bytes32[] memory leaves
  165. ) internal pure returns (bool) {
  166. return processMultiProof(proof, proofFlags, leaves) == root;
  167. }
  168. /**
  169. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  170. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  171. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  172. * respectively.
  173. *
  174. * This version handles multiproofs in memory with the default hashing function.
  175. *
  176. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  177. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  178. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  179. */
  180. function processMultiProof(
  181. bytes32[] memory proof,
  182. bool[] memory proofFlags,
  183. bytes32[] memory leaves
  184. ) internal pure returns (bytes32 merkleRoot) {
  185. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  186. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  187. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  188. // the Merkle tree.
  189. uint256 leavesLen = leaves.length;
  190. // Check proof validity.
  191. if (leavesLen + proof.length != proofFlags.length + 1) {
  192. revert MerkleProofInvalidMultiproof();
  193. }
  194. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  195. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  196. bytes32[] memory hashes = new bytes32[](proofFlags.length);
  197. uint256 leafPos = 0;
  198. uint256 hashPos = 0;
  199. uint256 proofPos = 0;
  200. // At each step, we compute the next hash using two values:
  201. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  202. // get the next hash.
  203. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  204. // `proof` array.
  205. for (uint256 i = 0; i < proofFlags.length; i++) {
  206. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  207. bytes32 b = proofFlags[i]
  208. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  209. : proof[proofPos++];
  210. hashes[i] = Hashes.commutativeKeccak256(a, b);
  211. }
  212. if (proofFlags.length > 0) {
  213. if (proofPos != proof.length) {
  214. revert MerkleProofInvalidMultiproof();
  215. }
  216. unchecked {
  217. return hashes[proofFlags.length - 1];
  218. }
  219. } else if (leavesLen > 0) {
  220. return leaves[0];
  221. } else {
  222. return proof[0];
  223. }
  224. }
  225. /**
  226. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  227. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  228. *
  229. * This version handles multiproofs in memory with a custom hashing function.
  230. *
  231. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  232. */
  233. function multiProofVerify(
  234. bytes32[] memory proof,
  235. bool[] memory proofFlags,
  236. bytes32 root,
  237. bytes32[] memory leaves,
  238. function(bytes32, bytes32) view returns (bytes32) hasher
  239. ) internal view returns (bool) {
  240. return processMultiProof(proof, proofFlags, leaves, hasher) == root;
  241. }
  242. /**
  243. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  244. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  245. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  246. * respectively.
  247. *
  248. * This version handles multiproofs in memory with a custom hashing function.
  249. *
  250. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  251. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  252. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  253. */
  254. function processMultiProof(
  255. bytes32[] memory proof,
  256. bool[] memory proofFlags,
  257. bytes32[] memory leaves,
  258. function(bytes32, bytes32) view returns (bytes32) hasher
  259. ) internal view returns (bytes32 merkleRoot) {
  260. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  261. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  262. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  263. // the Merkle tree.
  264. uint256 leavesLen = leaves.length;
  265. // Check proof validity.
  266. if (leavesLen + proof.length != proofFlags.length + 1) {
  267. revert MerkleProofInvalidMultiproof();
  268. }
  269. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  270. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  271. bytes32[] memory hashes = new bytes32[](proofFlags.length);
  272. uint256 leafPos = 0;
  273. uint256 hashPos = 0;
  274. uint256 proofPos = 0;
  275. // At each step, we compute the next hash using two values:
  276. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  277. // get the next hash.
  278. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  279. // `proof` array.
  280. for (uint256 i = 0; i < proofFlags.length; i++) {
  281. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  282. bytes32 b = proofFlags[i]
  283. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  284. : proof[proofPos++];
  285. hashes[i] = hasher(a, b);
  286. }
  287. if (proofFlags.length > 0) {
  288. if (proofPos != proof.length) {
  289. revert MerkleProofInvalidMultiproof();
  290. }
  291. unchecked {
  292. return hashes[proofFlags.length - 1];
  293. }
  294. } else if (leavesLen > 0) {
  295. return leaves[0];
  296. } else {
  297. return proof[0];
  298. }
  299. }
  300. /**
  301. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  302. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  303. *
  304. * This version handles multiproofs in calldata with the default hashing function.
  305. *
  306. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  307. */
  308. function multiProofVerifyCalldata(
  309. bytes32[] calldata proof,
  310. bool[] calldata proofFlags,
  311. bytes32 root,
  312. bytes32[] calldata leaves
  313. ) internal pure returns (bool) {
  314. return processMultiProof(proof, proofFlags, leaves) == root;
  315. }
  316. /**
  317. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  318. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  319. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  320. * respectively.
  321. *
  322. * This version handles multiproofs in calldata with the default hashing function.
  323. *
  324. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  325. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  326. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  327. */
  328. function processMultiProofCalldata(
  329. bytes32[] calldata proof,
  330. bool[] calldata proofFlags,
  331. bytes32[] calldata leaves
  332. ) internal pure returns (bytes32 merkleRoot) {
  333. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  334. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  335. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  336. // the Merkle tree.
  337. uint256 leavesLen = leaves.length;
  338. // Check proof validity.
  339. if (leavesLen + proof.length != proofFlags.length + 1) {
  340. revert MerkleProofInvalidMultiproof();
  341. }
  342. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  343. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  344. bytes32[] memory hashes = new bytes32[](proofFlags.length);
  345. uint256 leafPos = 0;
  346. uint256 hashPos = 0;
  347. uint256 proofPos = 0;
  348. // At each step, we compute the next hash using two values:
  349. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  350. // get the next hash.
  351. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  352. // `proof` array.
  353. for (uint256 i = 0; i < proofFlags.length; i++) {
  354. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  355. bytes32 b = proofFlags[i]
  356. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  357. : proof[proofPos++];
  358. hashes[i] = Hashes.commutativeKeccak256(a, b);
  359. }
  360. if (proofFlags.length > 0) {
  361. if (proofPos != proof.length) {
  362. revert MerkleProofInvalidMultiproof();
  363. }
  364. unchecked {
  365. return hashes[proofFlags.length - 1];
  366. }
  367. } else if (leavesLen > 0) {
  368. return leaves[0];
  369. } else {
  370. return proof[0];
  371. }
  372. }
  373. /**
  374. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  375. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  376. *
  377. * This version handles multiproofs in calldata with a custom hashing function.
  378. *
  379. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  380. */
  381. function multiProofVerifyCalldata(
  382. bytes32[] calldata proof,
  383. bool[] calldata proofFlags,
  384. bytes32 root,
  385. bytes32[] calldata leaves,
  386. function(bytes32, bytes32) view returns (bytes32) hasher
  387. ) internal view returns (bool) {
  388. return processMultiProof(proof, proofFlags, leaves, hasher) == root;
  389. }
  390. /**
  391. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  392. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  393. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  394. * respectively.
  395. *
  396. * This version handles multiproofs in calldata with a custom hashing function.
  397. *
  398. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  399. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  400. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  401. */
  402. function processMultiProofCalldata(
  403. bytes32[] calldata proof,
  404. bool[] calldata proofFlags,
  405. bytes32[] calldata leaves,
  406. function(bytes32, bytes32) view returns (bytes32) hasher
  407. ) internal view returns (bytes32 merkleRoot) {
  408. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  409. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  410. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  411. // the Merkle tree.
  412. uint256 leavesLen = leaves.length;
  413. // Check proof validity.
  414. if (leavesLen + proof.length != proofFlags.length + 1) {
  415. revert MerkleProofInvalidMultiproof();
  416. }
  417. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  418. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  419. bytes32[] memory hashes = new bytes32[](proofFlags.length);
  420. uint256 leafPos = 0;
  421. uint256 hashPos = 0;
  422. uint256 proofPos = 0;
  423. // At each step, we compute the next hash using two values:
  424. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  425. // get the next hash.
  426. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  427. // `proof` array.
  428. for (uint256 i = 0; i < proofFlags.length; i++) {
  429. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  430. bytes32 b = proofFlags[i]
  431. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  432. : proof[proofPos++];
  433. hashes[i] = hasher(a, b);
  434. }
  435. if (proofFlags.length > 0) {
  436. if (proofPos != proof.length) {
  437. revert MerkleProofInvalidMultiproof();
  438. }
  439. unchecked {
  440. return hashes[proofFlags.length - 1];
  441. }
  442. } else if (leavesLen > 0) {
  443. return leaves[0];
  444. } else {
  445. return proof[0];
  446. }
  447. }
  448. }