MerkleProof.test.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. require('@openzeppelin/test-helpers');
  2. const { MerkleTree } = require('../helpers/merkleTree.js');
  3. const { keccakFromString, bufferToHex } = require('ethereumjs-util');
  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 = ['a', 'b', 'c', 'd'];
  13. const merkleTree = new MerkleTree(elements);
  14. const root = merkleTree.getHexRoot();
  15. const proof = merkleTree.getHexProof(elements[0]);
  16. const leaf = bufferToHex(keccakFromString(elements[0]));
  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);
  22. const correctRoot = correctMerkleTree.getHexRoot();
  23. const correctLeaf = bufferToHex(keccakFromString(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);
  32. const root = merkleTree.getHexRoot();
  33. const proof = merkleTree.getHexProof(elements[0]);
  34. const badProof = proof.slice(0, proof.length - 5);
  35. const leaf = bufferToHex(keccakFromString(elements[0]));
  36. expect(await this.merkleProof.verify(badProof, root, leaf)).to.equal(false);
  37. });
  38. });
  39. });