MerkleProof.sol 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  20. bytes32 computedHash = leaf;
  21. for (uint256 i = 0; i < proof.length; i++) {
  22. bytes32 proofElement = proof[i];
  23. if (computedHash <= proofElement) {
  24. // Hash(current computed hash + current element of the proof)
  25. computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
  26. } else {
  27. // Hash(current element of the proof + current computed hash)
  28. computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
  29. }
  30. }
  31. // Check if the computed hash (root) is equal to the provided root
  32. return computedHash == root;
  33. }
  34. }