MerkleProof.sol 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. pragma solidity ^0.4.11;
  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) constant returns (bool) {
  16. bytes32 proofElement;
  17. bytes32 computedHash = _leaf;
  18. for (uint256 i = 32; i <= _proof.length; i += 32) {
  19. assembly {
  20. // Load the current element of the proof
  21. proofElement := mload(add(_proof, i))
  22. }
  23. if (computedHash < proofElement) {
  24. // Hash(current computed hash + current element of the proof)
  25. computedHash = sha3(computedHash, proofElement);
  26. } else {
  27. // Hash(current element of the proof + current computed hash)
  28. computedHash = sha3(proofElement, computedHash);
  29. }
  30. }
  31. // Check if the computed hash (root) is equal to the provided root
  32. return computedHash == _root;
  33. }
  34. }