Files
zk-kit/packages/protocols/src/utils.ts
cedoor 63131b8685 chore: fix typo
Former-commit-id: 2d1381007355b41f4b48032266a5d61d87c9359d [formerly 9fc594c3f0640bba2110ef05e4d70c7745ef6399] [formerly 2dc9ca7296434f2b8adb5afbf15265a46bf3c725 [formerly 90ada17841e5c9fd8d3872dfa313d4cf99a7d93b]] [formerly b52925a9706035c29d19e5aed18f6db608f44bf6 [formerly c19af43e2edad84c73d53dbabcb975f4765f301d] [formerly 991421c4386e7bf8506357336b8ac7812f62d506 [formerly 1345dd6a111db15c36814f89a9e8f3b61a4b9fda]]]
Former-commit-id: c0911c17d5dcd9ada575493371f38bca36456974 [formerly 863b16a8b3932e325e0fa191ea49845e46cc5a2a] [formerly 843f5dd13067262bed45a1107cd4345d58a4d0d2 [formerly 68d755520feddcfbb87d6656fff4a3c7397c9480]]
Former-commit-id: 888c1f489511771dae6e045693b18976ec6ec9b0 [formerly ab833c711639606740d754aee5bba200c7f6ec0e]
Former-commit-id: 1a41dd2dcce60655a310445a87c7a5bc98929a3c
2022-04-17 18:28:26 +02:00

67 lines
1.9 KiB
TypeScript

import { keccak256 } from "@ethersproject/solidity"
import { IncrementalMerkleTree, MerkleProof } from "@zk-kit/incremental-merkle-tree"
import { poseidon } from "circomlibjs"
import { ZqField } from "ffjavascript"
import { StrBigInt } from "./types"
export const SNARK_FIELD_SIZE = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617")
export const Fq = new ZqField(SNARK_FIELD_SIZE)
export function genExternalNullifier(plaintext: string): string {
const hashed = keccak256(["string"], [plaintext])
const hexStr = `0x${hashed.slice(8)}`
const len = 32 * 2
const h = hexStr.slice(2, len + 2)
return `0x${h.padStart(len, "0")}`
}
/**
* Creates a Merkle tree.
* @param depth The depth of the tree.
* @param zeroValue The zero value of the tree.
* @param leaves The list of the leaves of the tree.
* @returns The Merkle tree.
*/
export function generateMerkleTree(depth: number, zeroValue: StrBigInt, leaves: StrBigInt[]): IncrementalMerkleTree {
const tree = new IncrementalMerkleTree(poseidon, depth, zeroValue, 2)
for (const leaf of leaves) {
tree.insert(BigInt(leaf))
}
return tree
}
/**
* Creates a Merkle proof.
* @param depth The depth of the tree.
* @param zeroValue The zero value of the tree.
* @param leaves The list of the leaves of the tree.
* @param leaf The leaf for which Merkle proof should be created.
* @returns The Merkle proof.
*/
export function generateMerkleProof(
depth: number,
zeroValue: StrBigInt,
leaves: StrBigInt[],
leaf: StrBigInt
): MerkleProof {
if (leaf === zeroValue) throw new Error("Can't generate a proof for a zero leaf")
const tree = generateMerkleTree(depth, zeroValue, leaves)
const leafIndex = tree.leaves.indexOf(BigInt(leaf))
if (leafIndex === -1) {
throw new Error("The leaf does not exist")
}
const merkleProof = tree.createProof(leafIndex)
merkleProof.siblings = merkleProof.siblings.map((s) => s[0])
return merkleProof
}