MerkleProof.test.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. require('@openzeppelin/test-helpers');
  2. const { MerkleTree } = require('merkletreejs');
  3. const keccak256 = require('keccak256');
  4. const { expect } = require('chai');
  5. const MerkleProofWrapper = artifacts.require('MerkleProofWrapper');
  6. contract('MerkleProof', function (accounts) {
  7. beforeEach(async function () {
  8. this.merkleProof = await MerkleProofWrapper.new();
  9. });
  10. describe('verify', function () {
  11. it('returns true for a valid Merkle proof', async function () {
  12. const elements = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('');
  13. const merkleTree = new MerkleTree(elements, keccak256, { hashLeaves: true, sortPairs: true });
  14. const root = merkleTree.getHexRoot();
  15. const leaf = keccak256(elements[0]);
  16. const proof = merkleTree.getHexProof(leaf);
  17. expect(await this.merkleProof.verify(proof, root, leaf)).to.equal(true);
  18. });
  19. it('returns false for an invalid Merkle proof', async function () {
  20. const correctElements = ['a', 'b', 'c'];
  21. const correctMerkleTree = new MerkleTree(correctElements, keccak256, { hashLeaves: true, sortPairs: true });
  22. const correctRoot = correctMerkleTree.getHexRoot();
  23. const correctLeaf = keccak256(correctElements[0]);
  24. const badElements = ['d', 'e', 'f'];
  25. const badMerkleTree = new MerkleTree(badElements);
  26. const badProof = badMerkleTree.getHexProof(badElements[0]);
  27. expect(await this.merkleProof.verify(badProof, correctRoot, correctLeaf)).to.equal(false);
  28. });
  29. it('returns false for a Merkle proof of invalid length', async function () {
  30. const elements = ['a', 'b', 'c'];
  31. const merkleTree = new MerkleTree(elements, keccak256, { hashLeaves: true, sortPairs: true });
  32. const root = merkleTree.getHexRoot();
  33. const leaf = keccak256(elements[0]);
  34. const proof = merkleTree.getHexProof(leaf);
  35. const badProof = proof.slice(0, proof.length - 5);
  36. expect(await this.merkleProof.verify(badProof, root, leaf)).to.equal(false);
  37. });
  38. });
  39. });