MerkleProof.sol 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. pragma solidity ^0.4.18;
  2. /*
  3. * @title MerkleProof
  4. * @dev Merkle proof verification
  5. * @note Based on 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 is 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 verifyProof(bytes32[] _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) {
  16. bytes32 computedHash = _leaf;
  17. for (uint256 i = 0; i < _proof.length; i++) {
  18. bytes32 proofElement = _proof[i];
  19. if (computedHash < proofElement) {
  20. // Hash(current computed hash + current element of the proof)
  21. computedHash = keccak256(computedHash, proofElement);
  22. } else {
  23. // Hash(current element of the proof + current computed hash)
  24. computedHash = keccak256(proofElement, computedHash);
  25. }
  26. }
  27. // Check if the computed hash (root) is equal to the provided root
  28. return computedHash == _root;
  29. }
  30. }