From 35499fefe0de323f2c218fee3777960f6a2f8599 Mon Sep 17 00:00:00 2001 From: Andrija Date: Thu, 25 Nov 2021 15:51:56 +0100 Subject: [PATCH] enable in browser proofs --- packages/protocols/package.json | 2 +- packages/protocols/src/zk-protocol.ts | 33 +++++++++++++++++++-------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/packages/protocols/package.json b/packages/protocols/package.json index 34c2e12..f3df6fe 100644 --- a/packages/protocols/package.json +++ b/packages/protocols/package.json @@ -1,6 +1,6 @@ { "name": "@libsem/protocols", - "version": "1.0.22", + "version": "1.0.23", "description": "Client library for generating and verifying Semaphore & Rln ZK proofs.", "main": "dist/index.node.js", "types": "dist/types/index.d.ts", diff --git a/packages/protocols/src/zk-protocol.ts b/packages/protocols/src/zk-protocol.ts index fe3cafe..828cb0a 100644 --- a/packages/protocols/src/zk-protocol.ts +++ b/packages/protocols/src/zk-protocol.ts @@ -14,15 +14,21 @@ export class ZkProtocol { * @param witnessFileName where to save witness * @returns creates and saves witness to witnessFileName */ - async buildWnts(input: any, wasmFilePath: string, witnessFileName: string) { - const buffer = fs.readFileSync(wasmFilePath); + async genWtns(input: any, wasmFilePath: string) { + let wntsBuff: ArrayBuffer; + //window exists only in browser + if(typeof window !== 'undefined') { + const resp = await fetch(wasmFilePath); + wntsBuff = await resp.arrayBuffer(); + } else { + wntsBuff = fs.readFileSync(wasmFilePath); + } return new Promise((resolve, reject) => { - builder(buffer) + builder(wntsBuff) .then(async witnessCalculator => { - const buff= await witnessCalculator.calculateWTNSBin(input, 0); - fs.writeFileSync(witnessFileName, buff); - resolve(witnessFileName); + const buff = await witnessCalculator.calculateWTNSBin(input, 0); + resolve(buff); }).catch((error) => { reject(error); }); @@ -36,10 +42,17 @@ export class ZkProtocol { * @returns zero knowledge proof */ async genProof(grothInput: any, wasmFilePath: string, finalZkeyPath: string): Promise { - await this.buildWnts(grothInput, wasmFilePath, 'witness.wtns'); - const { proof, publicSignals } = await groth16.prove(finalZkeyPath, 'witness.wtns', null); - const exists = fs.existsSync('witness.wtns'); - if(exists) fs.unlinkSync('witness.wtns'); + let zkeyBuff: ArrayBuffer; + const wtnsBuff = await this.genWtns(grothInput, wasmFilePath); + //window exists only in browser + if(typeof window !== 'undefined') { + const resp = await fetch(finalZkeyPath); + zkeyBuff = await resp.arrayBuffer(); + } else { + zkeyBuff = fs.readFileSync(finalZkeyPath); + } + + const { proof, publicSignals } = await groth16.prove(new Uint8Array(zkeyBuff), wtnsBuff, null); return { proof, publicSignals }; }