Add method verifyProof to Tree

This commit is contained in:
Daniel Tehrani
2023-05-29 12:14:23 +02:00
parent 85fc788204
commit 19e1ddd4ef
3 changed files with 36 additions and 9 deletions

View File

@@ -1,7 +1,6 @@
import { IncrementalMerkleTree } from "@zk-kit/incremental-merkle-tree";
import { Poseidon } from "./poseidon";
import { MerkleProof } from "../types";
import { bytesToBigInt } from "./utils";
export class Tree {
depth: number;
@@ -38,17 +37,14 @@ export class Tree {
createProof(index: number): MerkleProof {
const proof = this.treeInner.createProof(index);
const siblings = proof.siblings.map(s =>
typeof s[0] === "bigint" ? s : bytesToBigInt(s[0])
);
return {
siblings,
siblings: proof.siblings,
pathIndices: proof.pathIndices,
root: proof.root
};
}
// TODO: Add more functions that expose the IncrementalMerkleTree API
verifyProof(proof: MerkleProof, leaf: bigint): boolean {
return this.treeInner.verifyProof({ ...proof, leaf });
}
}

View File

@@ -5,7 +5,7 @@ import { PublicInput } from "./helpers/public_input";
// library users can choose whatever merkle tree management method they want.
export interface MerkleProof {
root: bigint;
siblings: bigint[];
siblings: [bigint][];
pathIndices: number[];
}
export interface EffECDSAPubInput {

View File

@@ -0,0 +1,31 @@
import { Tree, Poseidon } from "../src/lib";
describe("Merkle tree prove and verify", () => {
let poseidon: Poseidon;
let tree: Tree;
const members = new Array(10).fill(0).map((_, i) => BigInt(i));
beforeAll(async () => {
// Init Poseidon
poseidon = new Poseidon();
await poseidon.initWasm();
const treeDepth = 20;
tree = new Tree(treeDepth, poseidon);
for (const member of members) {
tree.insert(member);
}
});
it("should prove and verify a valid Merkle proof", async () => {
const proof = tree.createProof(0);
expect(tree.verifyProof(proof, members[0])).toBe(true);
});
it("should assert an invalid Merkle proof", async () => {
const proof = tree.createProof(0);
proof.siblings[0][0] = proof.siblings[0][0] += BigInt(1);
expect(tree.verifyProof(proof, members[0])).toBe(false);
proof.siblings[0][0] = proof.siblings[0][0] -= BigInt(1);
});
});