Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use snarkjs API and remove the hardcoding of the snarkjs command line path #782

Merged
merged 8 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 24 additions & 65 deletions circuits/ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,26 @@ import * as fs from 'fs'
import * as path from 'path'
import * as shelljs from 'shelljs'
import * as tmp from 'tmp'
import { zKey, groth16 } from 'snarkjs'

import { stringifyBigInts } from 'maci-crypto'

const snarkjsPath = path.join(
__dirname,
'..',
'./node_modules/snarkjs/cli.js',
)
/*
* https://github.com/iden3/snarkjs/issues/152
* Need to cleanup the threads to avoid stalling
*/
const cleanThreads = async () => {
if (!globalThis) {
return Promise.resolve(true)
}

const curves = ['curve_bn128', 'curve_bls12381']
const promises = Promise.all(curves.map(curve => {
return globalThis[curve]?.terminate? globalThis[curve]?.terminate() : null
}).filter(Boolean))

return promises
}

const genProof = (
inputs: string[],
Expand Down Expand Up @@ -71,69 +83,16 @@ const genProof = (
return { proof, publicInputs }
}

const verifyProof = (
publicInputs: any,
proof: any,
vk: any,
) => {
// Create tmp directory
const tmpObj = tmp.dirSync()
const tmpDirPath = tmpObj.name

const publicJsonPath = path.join(tmpDirPath, 'public.json')
const proofJsonPath = path.join(tmpDirPath, 'proof.json')
const vkJsonPath = path.join(tmpDirPath, 'vk.json')

fs.writeFileSync(
publicJsonPath,
JSON.stringify(stringifyBigInts(publicInputs)),
)

fs.writeFileSync(
proofJsonPath,
JSON.stringify(stringifyBigInts(proof)),
)

fs.writeFileSync(
vkJsonPath,
JSON.stringify(stringifyBigInts(vk)),
)

const verifyCmd = `node ${snarkjsPath} g16v ${vkJsonPath} ${publicJsonPath} ${proofJsonPath}`
const output = shelljs.exec(verifyCmd, { silent: true })
const isValid = output.stdout && output.stdout.indexOf('OK!') > -1

//// Generate calldata
//const calldataCmd = `node ${snarkjsPath} zkesc ${publicJsonPath} ${proofJsonPath}`
//console.log(shelljs.exec(calldataCmd).stdout)

fs.unlinkSync(proofJsonPath)
fs.unlinkSync(publicJsonPath)
fs.unlinkSync(vkJsonPath)
tmpObj.removeCallback()

const verifyProof = async (publicInputs: any, proof: any, vk: any) => {
ctrlc03 marked this conversation as resolved.
Show resolved Hide resolved
const isValid = await groth16.verify(vk, publicInputs, proof)
await cleanThreads()
return isValid
}

const extractVk = (zkeyPath: string) => {
// Create tmp directory
const tmpObj = tmp.dirSync()
const tmpDirPath = tmpObj.name
const vkJsonPath = path.join(tmpDirPath, 'vk.json')

const exportCmd = `node ${snarkjsPath} zkev ${zkeyPath} ${vkJsonPath}`
shelljs.exec(exportCmd)

const vk = JSON.parse(fs.readFileSync(vkJsonPath).toString())

fs.unlinkSync(vkJsonPath)
tmpObj.removeCallback()

const extractVk = async (zkeyPath: string) => {
const vk = await zKey.exportVerificationKey(zkeyPath)
await cleanThreads()
return vk
}

export {
genProof,
verifyProof,
extractVk,
}
export { genProof, verifyProof, extractVk }
28 changes: 28 additions & 0 deletions circuits/ts/snarkjs.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
declare module 'snarkjs' {
export type NumericString = `${number}` | string
export type PublicSignals = NumericString[]

export interface Groth16Proof {
pi_a: NumericString[];
pi_b: NumericString[][];
pi_c: NumericString[];
protocol: string;
curve: string;
}

export namespace zKey {
function exportVerificationKey(
zkeyName: any,
logger?: any,
): Promise<any>
}

export namespace groth16 {
function verify(
_vk_verifier: any,
_publicSignals: PublicSignals,
_proof: Groth16Proof,
logger?: any,
): Promise<boolean>
}
}
4 changes: 2 additions & 2 deletions cli/ts/checkVerifyingKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ const checkVerifyingKey = async (args: any) => {
const pmZkeyFile = path.resolve(args.process_messages_zkey)
const tvZkeyFile = path.resolve(args.tally_votes_zkey)

const processVk: VerifyingKey = VerifyingKey.fromObj(extractVk(pmZkeyFile))
const tallyVk: VerifyingKey = VerifyingKey.fromObj(extractVk(tvZkeyFile))
const processVk: VerifyingKey = VerifyingKey.fromObj(await extractVk(pmZkeyFile))
const tallyVk: VerifyingKey = VerifyingKey.fromObj(await extractVk(tvZkeyFile))

const signer = await getDefaultSigner()
if (!await contractExists(signer.provider, maciAddress)) {
Expand Down
12 changes: 6 additions & 6 deletions cli/ts/genProofs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,12 @@ const genProofs = async (args: any) => {
return 1
}

subsidyVk = extractVk(args.subsidy_zkey)
subsidyVk = await extractVk(args.subsidy_zkey)
}

// Extract the verifying keys
const processVk = extractVk(args.process_zkey)
const tallyVk = extractVk(args.tally_zkey)
const processVk = await extractVk(args.process_zkey)
const tallyVk = await extractVk(args.tally_zkey)

// The coordinator's MACI private key
let serializedPrivkey
Expand Down Expand Up @@ -394,7 +394,7 @@ const genProofs = async (args: any) => {
}

// Verify the proof
const isValid = verifyProof(
const isValid = await verifyProof(
r.publicInputs,
r.proof,
processVk,
Expand Down Expand Up @@ -440,7 +440,7 @@ const genProofs = async (args: any) => {
subsidyCircuitInputs = poll.subsidyPerBatch()
const r = genProof(subsidyCircuitInputs, rapidsnarkExe, args.subsidy_witnessgen, args.subsidy_zkey)

const isValid = verifyProof(r.publicInputs, r.proof, subsidyVk)
const isValid = await verifyProof(r.publicInputs, r.proof, subsidyVk)
if (!isValid) {
console.error('Error: generated an invalid subsidy calc proof')
return 1
Expand Down Expand Up @@ -501,7 +501,7 @@ const genProofs = async (args: any) => {
)

// Verify the proof
const isValid = verifyProof(
const isValid = await verifyProof(
r.publicInputs,
r.proof,
tallyVk,
Expand Down
6 changes: 3 additions & 3 deletions cli/ts/setVerifyingKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ const setVerifyingKeys = async (args: any) => {
return 1
}

const processVk: VerifyingKey = VerifyingKey.fromObj(extractVk(pmZkeyFile))
const tallyVk: VerifyingKey = VerifyingKey.fromObj(extractVk(tvZkeyFile))
const processVk: VerifyingKey = VerifyingKey.fromObj(await extractVk(pmZkeyFile))
const tallyVk: VerifyingKey = VerifyingKey.fromObj(await extractVk(tvZkeyFile))


let ssZkeyFile: string
Expand All @@ -144,7 +144,7 @@ const setVerifyingKeys = async (args: any) => {
return 1
}

subsidyVk = VerifyingKey.fromObj(extractVk(ssZkeyFile))
subsidyVk = VerifyingKey.fromObj(await extractVk(ssZkeyFile))
}

// Simple validation
Expand Down
2 changes: 1 addition & 1 deletion integrationTests/integrations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ invalidVote:
voteCreditBalance: 1
constants:
poll:
duration: 120
duration: 300
intStateTreeDepth: 1
messageTreeDepth: 2
messageBatchDepth: 1
Expand Down
2 changes: 1 addition & 1 deletion integrationTests/ts/__tests__/suites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ const executeSuite = async (data: any, expect: any) => {
}
}

const timeTravelCommand = `node build/index.js timeTravel -s ${config.constants.maci.votingDuration}`
const timeTravelCommand = `node build/index.js timeTravel -s ${config.constants.poll.duration}`
execute(timeTravelCommand)

const mergeMessagesCommand = `node build/index.js mergeMessages -x ${maciAddress} -o ${pollId}`
Expand Down
Loading