MerkleProof.test.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. require('openzeppelin-test-helpers');
  2. const { MerkleTree } = require('../helpers/merkleTree.js');
  3. const { keccak256, bufferToHex } = require('ethereumjs-util');
  4. const MerkleProofWrapper = artifacts.require('MerkleProofWrapper');
  5. contract('MerkleProof', function () {
  6. beforeEach(async function () {
  7. this.merkleProof = await MerkleProofWrapper.new();
  8. });
  9. describe('verify', 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(keccak256(elements[0]));
  16. (await this.merkleProof.verify(proof, root, leaf)).should.equal(true);
  17. });
  18. it('should return false for an invalid Merkle proof', async function () {
  19. const correctElements = ['a', 'b', 'c'];
  20. const correctMerkleTree = new MerkleTree(correctElements);
  21. const correctRoot = correctMerkleTree.getHexRoot();
  22. const correctLeaf = bufferToHex(keccak256(correctElements[0]));
  23. const badElements = ['d', 'e', 'f'];
  24. const badMerkleTree = new MerkleTree(badElements);
  25. const badProof = badMerkleTree.getHexProof(badElements[0]);
  26. (await this.merkleProof.verify(badProof, correctRoot, correctLeaf)).should.equal(false);
  27. });
  28. it('should return false for a Merkle proof of invalid length', async function () {
  29. const elements = ['a', 'b', 'c'];
  30. const merkleTree = new MerkleTree(elements);
  31. const root = merkleTree.getHexRoot();
  32. const proof = merkleTree.getHexProof(elements[0]);
  33. const badProof = proof.slice(0, proof.length - 5);
  34. const leaf = bufferToHex(keccak256(elements[0]));
  35. (await this.merkleProof.verify(badProof, root, leaf)).should.equal(false);
  36. });
  37. });
  38. });