MerkleProof.test.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const { MerkleTree } = require('../helpers/merkleTree.js');
  2. const { sha3, bufferToHex } = require('ethereumjs-util');
  3. const MerkleProofWrapper = artifacts.require('MerkleProofWrapper');
  4. require('chai')
  5. .should();
  6. contract('MerkleProof', function () {
  7. let merkleProof;
  8. beforeEach(async function () {
  9. merkleProof = await MerkleProofWrapper.new();
  10. });
  11. describe('verifyProof', function () {
  12. it('should return true for a valid Merkle proof', async function () {
  13. const elements = ['a', 'b', 'c', 'd'];
  14. const merkleTree = new MerkleTree(elements);
  15. const root = merkleTree.getHexRoot();
  16. const proof = merkleTree.getHexProof(elements[0]);
  17. const leaf = bufferToHex(sha3(elements[0]));
  18. (await merkleProof.verifyProof(proof, root, leaf)).should.equal(true);
  19. });
  20. it('should return false for an invalid Merkle proof', async function () {
  21. const correctElements = ['a', 'b', 'c'];
  22. const correctMerkleTree = new MerkleTree(correctElements);
  23. const correctRoot = correctMerkleTree.getHexRoot();
  24. const correctLeaf = bufferToHex(sha3(correctElements[0]));
  25. const badElements = ['d', 'e', 'f'];
  26. const badMerkleTree = new MerkleTree(badElements);
  27. const badProof = badMerkleTree.getHexProof(badElements[0]);
  28. (await merkleProof.verifyProof(badProof, correctRoot, correctLeaf)).should.equal(false);
  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. (await merkleProof.verifyProof(badProof, root, leaf)).should.equal(false);
  38. });
  39. });
  40. });