Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@0xpolygonid/js-sdk",
"version": "1.43.0",
"version": "1.43.1",
"description": "SDK to work with Polygon ID",
"source": "./src/index.ts",
"exports": {
Expand Down
5 changes: 3 additions & 2 deletions src/proof/proof-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
parseQueryMetadata,
transformQueryValueToBigInts
} from './common';
import { IZKProver, NativeProver } from './provers/prover';
import { IZKProver, NativeProver, ProverOptions } from './provers/prover';

import { Merklizer, Options, getDocumentLoader } from '@iden3/js-jsonld-merklization';
import { ZKProof } from '@iden3/js-jwz';
Expand Down Expand Up @@ -80,6 +80,7 @@ export type VerificationResultMetadata = {
export type ProofServiceOptions = Options & {
prover?: IZKProver;
proofsCacheStorage?: IProofStorage;
defaultProverOptions?: ProverOptions;
};
Comment thread
volodymyr-basiuk marked this conversation as resolved.

export interface ProofVerifyOpts {
Expand Down Expand Up @@ -234,7 +235,7 @@ export class ProofService implements IProofService {
private readonly _stateStorage: IStateStorage,
opts?: ProofServiceOptions
) {
this._prover = opts?.prover ?? new NativeProver(_circuitStorage);
this._prover = opts?.prover ?? new NativeProver(_circuitStorage, opts?.defaultProverOptions);
this._ldOptions = { ...opts, documentLoader: opts?.documentLoader ?? cacheLoader(opts) };
this._inputsGenerator = new InputGenerator(_identityWallet, _credentialWallet, _stateStorage);
this._pubSignalsVerifier = new PubSignalsVerifier(
Expand Down
95 changes: 78 additions & 17 deletions src/proof/provers/prover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ export interface IZKProver {
verify(zkp: ZKProof, circuitId: string): Promise<boolean>;
}

/**
* Options for NativeProver
* @public
* @interface ProverOptions
*/
export interface ProverOptions {
/**
* Maximum number of proofs that can be generated in parallel.
*
* If not set or set to a non-positive value, no concurrency
* limiting is applied.
*/
maxParallelProofs?: number;
}

/**
* NativeProver service responsible for zk generation and verification of groth16 algorithm with bn128 curve
* @public
Expand All @@ -39,7 +54,13 @@ export interface IZKProver {
*/
export class NativeProver implements IZKProver {
private static readonly curveName = 'bn128';
constructor(private readonly _circuitStorage: ICircuitStorage) {}
private readonly _maxParallelProofs?: number;
private _activeProofs = 0;
private _queue: Array<() => void> = [];

constructor(private readonly _circuitStorage: ICircuitStorage, options?: ProverOptions) {
this._maxParallelProofs = options?.maxParallelProofs;
}

/**
* verifies zero knowledge proof
Expand Down Expand Up @@ -77,32 +98,72 @@ export class NativeProver implements IZKProver {
const circuitData = await this._circuitStorage.loadCircuitData(circuitId, {
mode: CircuitLoadMode.Proving
});
if (!circuitData.wasm) {
throw new Error(`wasm file doesn't exist for circuit ${circuitId}`);
}
return this.withConcurrencyLimit(async () => {
if (!circuitData.wasm) {
throw new Error(`wasm file doesn't exist for circuit ${circuitId}`);
}

const witnessCalculator = await witnessBuilder(circuitData.wasm.buffer as ArrayBuffer);
const witnessCalculator = await witnessBuilder(circuitData.wasm.buffer as ArrayBuffer);

const parsedData = JSON.parse(byteDecoder.decode(inputs));
const parsedData = JSON.parse(byteDecoder.decode(inputs));

const wtnsBytes: Uint8Array = await witnessCalculator.calculateWTNSBin(parsedData, 0);
const wtnsBytes: Uint8Array = await witnessCalculator.calculateWTNSBin(parsedData, 0);

if (!circuitData.provingKey) {
throw new Error(`proving file doesn't exist for circuit ${circuitId}`);
}
const { proof, publicSignals } = await snarkjs.groth16.prove(circuitData.provingKey, wtnsBytes);
if (!circuitData.provingKey) {
throw new Error(`proving file doesn't exist for circuit ${circuitId}`);
}
const { proof, publicSignals } = await snarkjs.groth16.prove(
circuitData.provingKey,
wtnsBytes
);

// we need to terminate curve manually
await this.terminateCurve();
// we need to terminate curve manually
await this.terminateCurve();

return {
proof,
pub_signals: publicSignals
};
return {
proof,
pub_signals: publicSignals
};
});
}

private async terminateCurve(): Promise<void> {
const curve = await ffjavascript.getCurveFromName(NativeProver.curveName);
curve.terminate();
}

private async withConcurrencyLimit<T>(fn: () => Promise<T>): Promise<T> {
if (!this._maxParallelProofs || this._maxParallelProofs <= 0) {
return fn();
}

await this.acquireSlot();
try {
return await fn();
} finally {
this.releaseSlot();
}
}

private async acquireSlot(): Promise<void> {
if (this._activeProofs < (this._maxParallelProofs as number)) {
this._activeProofs++;
return;
Comment on lines +149 to +151
}

return new Promise((resolve) => {
this._queue.push(() => {
this._activeProofs++;
resolve();
});
});
}

private releaseSlot(): void {
this._activeProofs--;
const next = this._queue.shift();
if (next) {
next();
}
Comment on lines +162 to +167

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

queue won't be big in this case

}
}
7 changes: 6 additions & 1 deletion tests/handlers/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2128,7 +2128,12 @@ describe('auth', () => {
credWallet = new CredentialWallet(dataStorage, resolvers);
idWallet = new IdentityWallet(kms, dataStorage, credWallet);

proofService = new ProofService(idWallet, credWallet, circuitStorage, eth, merklizeOpts);
proofService = new ProofService(idWallet, credWallet, circuitStorage, eth, {
...merklizeOpts,
proverOptions: {
maxParallelProofs: 1
}
});
const { did: issuerDID } = await createIdentity(idWallet, {
seed: getRandomBytes(32)
});
Expand Down
Loading