MerkleProof.sol 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. /**
  4. * @dev These functions deal with verification of Merkle Trees proofs.
  5. *
  6. * The proofs can be generated using the JavaScript library
  7. * https://github.com/miguelmota/merkletreejs[merkletreejs].
  8. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
  9. *
  10. * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
  11. */
  12. library MerkleProof {
  13. /**
  14. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  15. * defined by `root`. For this, a `proof` must be provided, containing
  16. * sibling hashes on the branch from the leaf to the root of the tree. Each
  17. * pair of leaves and each pair of pre-images are assumed to be sorted.
  18. */
  19. function verify(
  20. bytes32[] memory proof,
  21. bytes32 root,
  22. bytes32 leaf
  23. ) internal pure returns (bool) {
  24. return processProof(proof, leaf) == root;
  25. }
  26. /**
  27. * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
  28. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  29. * hash matches the root of the tree. When processing the proof, the pairs
  30. * of leafs & pre-images are assumed to be sorted.
  31. *
  32. * _Available since v4.4._
  33. */
  34. function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
  35. bytes32 computedHash = leaf;
  36. for (uint256 i = 0; i < proof.length; i++) {
  37. bytes32 proofElement = proof[i];
  38. if (computedHash <= proofElement) {
  39. // Hash(current computed hash + current element of the proof)
  40. computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
  41. } else {
  42. // Hash(current element of the proof + current computed hash)
  43. computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
  44. }
  45. }
  46. return computedHash;
  47. }
  48. }