MerkleProof.sol 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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(bytes _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) {
  16. // Check if proof length is a multiple of 32
  17. if (_proof.length % 32 != 0) {
  18. return false;
  19. }
  20. bytes32 proofElement;
  21. bytes32 computedHash = _leaf;
  22. for (uint256 i = 32; i <= _proof.length; i += 32) {
  23. assembly {
  24. // Load the current element of the proof
  25. proofElement := mload(add(_proof, i))
  26. }
  27. if (computedHash < proofElement) {
  28. // Hash(current computed hash + current element of the proof)
  29. computedHash = keccak256(computedHash, proofElement);
  30. } else {
  31. // Hash(current element of the proof + current computed hash)
  32. computedHash = keccak256(proofElement, computedHash);
  33. }
  34. }
  35. // Check if the computed hash (root) is equal to the provided root
  36. return computedHash == _root;
  37. }
  38. }