MerkleProof.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var MerkleProof = artifacts.require("./MerkleProof.sol");
  2. import MerkleTree from "./helpers/merkleTree.js";
  3. import { sha3, bufferToHex } from "ethereumjs-util";
  4. contract('MerkleProof', function(accounts) {
  5. let merkleProof;
  6. before(async function() {
  7. merkleProof = await MerkleProof.new();
  8. });
  9. describe("verifyProof", function() {
  10. it("should return true for a valid Merkle proof", async function() {
  11. const elements = ["a", "b", "c", "d"];
  12. const merkleTree = new MerkleTree(elements);
  13. const root = merkleTree.getHexRoot();
  14. const proof = merkleTree.getHexProof(elements[0]);
  15. const leaf = bufferToHex(sha3(elements[0]));
  16. const result = await merkleProof.verifyProof(proof, root, leaf);
  17. assert.isOk(result, "verifyProof did not return true for a valid proof");
  18. });
  19. it("should return false for an invalid Merkle proof", async function() {
  20. const correctElements = ["a", "b", "c"]
  21. const correctMerkleTree = new MerkleTree(correctElements);
  22. const correctRoot = correctMerkleTree.getHexRoot();
  23. const correctLeaf = bufferToHex(sha3(correctElements[0]));
  24. const badElements = ["d", "e", "f"]
  25. const badMerkleTree = new MerkleTree(badElements)
  26. const badProof = badMerkleTree.getHexProof(badElements[0])
  27. const result = await merkleProof.verifyProof(badProof, correctRoot, correctLeaf);
  28. assert.isNotOk(result, "verifyProof did not return false for an invalid proof");
  29. });
  30. it("should return false for a Merkle proof of invalid length", async function() {
  31. const elements = ["a", "b", "c"]
  32. const merkleTree = new MerkleTree(elements);
  33. const root = merkleTree.getHexRoot();
  34. const proof = merkleTree.getHexProof(elements[0]);
  35. const badProof = proof.slice(0, proof.length - 5);
  36. const leaf = bufferToHex(sha3(elements[0]));
  37. const result = await merkleProof.verifyProof(badProof, root, leaf);
  38. assert.isNotOk(result, "verifyProof did not return false for proof of invalid length");
  39. })
  40. });
  41. });