MerkleProof.sol 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. pragma solidity ^0.4.24;
  2. /**
  3. * @title MerkleProof
  4. * @dev Merkle proof verification based on
  5. * https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol
  6. */
  7. library MerkleProof {
  8. /**
  9. * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves
  10. * and each pair of pre-images are sorted.
  11. * @param proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree
  12. * @param root Merkle root
  13. * @param leaf Leaf of Merkle tree
  14. */
  15. function verify(
  16. bytes32[] proof,
  17. bytes32 root,
  18. bytes32 leaf
  19. )
  20. internal
  21. pure
  22. returns (bool)
  23. {
  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. }