MerkleProof.test.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const { contract } = require('@openzeppelin/test-environment');
  2. require('@openzeppelin/test-helpers');
  3. const { MerkleTree } = require('../helpers/merkleTree.js');
  4. const { keccakFromString, bufferToHex } = require('ethereumjs-util');
  5. const { expect } = require('chai');
  6. const MerkleProofWrapper = contract.fromArtifact('MerkleProofWrapper');
  7. describe('MerkleProof', function () {
  8. beforeEach(async function () {
  9. this.merkleProof = await MerkleProofWrapper.new();
  10. });
  11. describe('verify', 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(keccakFromString(elements[0]));
  18. expect(await this.merkleProof.verify(proof, root, leaf)).to.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(keccakFromString(correctElements[0]));
  25. const badElements = ['d', 'e', 'f'];
  26. const badMerkleTree = new MerkleTree(badElements);
  27. const badProof = badMerkleTree.getHexProof(badElements[0]);
  28. expect(await this.merkleProof.verify(badProof, correctRoot, correctLeaf)).to.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(keccakFromString(elements[0]));
  37. expect(await this.merkleProof.verify(badProof, root, leaf)).to.equal(false);
  38. });
  39. });
  40. });