MerkleProof.sol 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. bytes32 computedHash = leaf;
  25. for (uint256 i = 0; i < proof.length; i++) {
  26. bytes32 proofElement = proof[i];
  27. if (computedHash <= proofElement) {
  28. // Hash(current computed hash + current element of the proof)
  29. computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
  30. } else {
  31. // Hash(current element of the proof + current computed hash)
  32. computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
  33. }
  34. }
  35. // Check if the computed hash (root) is equal to the provided root
  36. return computedHash == root;
  37. }
  38. }