diff --git a/packages/incremental-merkle-tree.sol/contracts/IncrementalBinaryTree.sol b/packages/incremental-merkle-tree.sol/contracts/IncrementalBinaryTree.sol index 3658c5d..b33f54f 100644 --- a/packages/incremental-merkle-tree.sol/contracts/IncrementalBinaryTree.sol +++ b/packages/incremental-merkle-tree.sol/contracts/IncrementalBinaryTree.sol @@ -92,7 +92,11 @@ library IncrementalBinaryTree { uint256[] calldata proofSiblings, uint8[] calldata proofPathIndices ) public { - + require( + leaf < SNARK_SCALAR_FIELD, + "IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD" + ); + uint256 hash = leaf; for (uint8 i = 0; i < self.depth; i++) { if (proofPathIndices[i] == 0) { diff --git a/packages/incremental-merkle-tree.sol/test/IncrementalBinaryTreeTest.ts b/packages/incremental-merkle-tree.sol/test/IncrementalBinaryTreeTest.ts index 2d338d7..6256e0e 100644 --- a/packages/incremental-merkle-tree.sol/test/IncrementalBinaryTreeTest.ts +++ b/packages/incremental-merkle-tree.sol/test/IncrementalBinaryTreeTest.ts @@ -83,6 +83,40 @@ describe("IncrementalBinaryTreeTest", () => { await expect(transaction).to.be.revertedWith("IncrementalBinaryTree: tree is full") }) + it("Should not update a leaf if the tree does not exist", async () => { + const treeId = ethers.utils.formatBytes32String("none") + + const transaction = contract.updateLeaf(treeId, leaf, [0, 1], [0, 1]) + }) + + it("Should not update a leaf if its value is > SNARK_SCALAR_FIELD", async () => { + const leaf = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495618") + + const transaction = contract.updateLeaf(treeId, leaf, [0, 1], [0, 1]) + + await expect(transaction).to.be.revertedWith("IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD") + }) + + it("Should update a leaf", async () => { + const treeId = ethers.utils.formatBytes32String("tree2") + const tree = createTree(depth, 0) + for (let i = 0; i < 4; i += 1) + tree.insert(BigInt(i + 1)) + + const leaf = BigInt(22) + tree.update(2, leaf) + const { root, pathIndices, siblings } = tree.createProof(2) + const transaction = contract.updateLeaf( + treeId, + leaf, + siblings.map((s) => s[0]), + pathIndices + ) + + await expect(transaction).to.emit(contract, "LeafUpdated").withArgs(treeId, leaf, root); + + }) + it("Should not remove a leaf if the tree does not exist", async () => { const treeId = ethers.utils.formatBytes32String("none") @@ -111,7 +145,6 @@ describe("IncrementalBinaryTreeTest", () => { await contract.insertLeaf(treeId, BigInt(3)) const { siblings, pathIndices, root } = tree.createProof(0) - const transaction = contract.removeLeaf( treeId, BigInt(1),