MerkleProof.test.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. // For demonstration, it is also possible to create valid proofs for certain 64-byte values *not* in elements:
  19. const noSuchLeaf = keccak256(
  20. Buffer.concat([keccak256(elements[0]), keccak256(elements[1])].sort(Buffer.compare)),
  21. );
  22. expect(await this.merkleProof.verify(proof.slice(1), root, noSuchLeaf)).to.equal(true);
  23. });
  24. it('returns false for an invalid Merkle proof', async function () {
  25. const correctElements = ['a', 'b', 'c'];
  26. const correctMerkleTree = new MerkleTree(correctElements, keccak256, { hashLeaves: true, sortPairs: true });
  27. const correctRoot = correctMerkleTree.getHexRoot();
  28. const correctLeaf = keccak256(correctElements[0]);
  29. const badElements = ['d', 'e', 'f'];
  30. const badMerkleTree = new MerkleTree(badElements);
  31. const badProof = badMerkleTree.getHexProof(badElements[0]);
  32. expect(await this.merkleProof.verify(badProof, correctRoot, correctLeaf)).to.equal(false);
  33. });
  34. it('returns false for a Merkle proof of invalid length', async function () {
  35. const elements = ['a', 'b', 'c'];
  36. const merkleTree = new MerkleTree(elements, keccak256, { hashLeaves: true, sortPairs: true });
  37. const root = merkleTree.getHexRoot();
  38. const leaf = keccak256(elements[0]);
  39. const proof = merkleTree.getHexProof(leaf);
  40. const badProof = proof.slice(0, proof.length - 5);
  41. expect(await this.merkleProof.verify(badProof, root, leaf)).to.equal(false);
  42. });
  43. });
  44. });