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

support verification for noop and exists for v3 circuit #205

Merged
merged 4 commits into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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.9.2",
"version": "1.9.3",
"description": "SDK to work with Polygon ID",
"main": "dist/node/cjs/index.js",
"module": "dist/node/esm/index.js",
Expand Down
5 changes: 5 additions & 0 deletions src/circuits/comparer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ export const QueryOperators = {
$nullify: Operators.NULLIFY
};

export const getOperatorNameByValue = (operator: number): string => {
const ops = Object.entries(QueryOperators).find(([, queryOp]) => queryOp === operator);
return ops ? ops[0] : 'unknown';
};

const allOperations = Object.values(QueryOperators);

export const availableTypesOperators: Map<string, Operators[]> = new Map([
Expand Down
3 changes: 1 addition & 2 deletions src/iden3comm/handlers/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,9 @@ const getGroupedQueries = (
return acc;
}, new Map<number, { query: JSONObject; linkNonce: number }>());


/**
* Processes zero knowledge proof requests.
*
*
* @param senderIdentifier - The identifier of the sender.
* @param requests - An array of zero knowledge proof requests.
* @param from - The identifier of the sender.
Expand Down
3 changes: 1 addition & 2 deletions src/proof/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import {
GISTProof,
isValidOperation,
Operators,
QueryOperators,
XSDNS
QueryOperators
} from '../circuits';
import { StateProof } from '../storage/entities/state';
import {
Expand Down
30 changes: 29 additions & 1 deletion src/proof/provers/inputs-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ import {
Query,
QueryOperators,
TreeState,
ValueProof
ValueProof,
getOperatorNameByValue
} from '../../circuits';
import {
PreparedAuthBJJCredential,
Expand Down Expand Up @@ -237,6 +238,8 @@ export class InputGenerator {
circuitInputs.profileNonce = BigInt(params.authProfileNonce);
circuitInputs.skipClaimRevocationCheck = params.skipRevocation;

this.checkOperatorSupport(CircuitId.AtomicQueryMTPV2, query.operator);

return circuitInputs.inputsMarshal();
};

Expand Down Expand Up @@ -305,6 +308,8 @@ export class InputGenerator {
circuitInputs.profileNonce = BigInt(params.authProfileNonce);
circuitInputs.skipClaimRevocationCheck = params.skipRevocation;

this.checkOperatorSupport(CircuitId.AtomicQueryMTPV2OnChain, query.operator);

return circuitInputs.inputsMarshal();
};

Expand Down Expand Up @@ -336,6 +341,9 @@ export class InputGenerator {
query.operator = this.transformV2QueryOperator(query.operator);
circuitInputs.query = query;
circuitInputs.currentTimeStamp = getUnixTimestamp(new Date());

this.checkOperatorSupport(CircuitId.AtomicQuerySigV2, query.operator);

return circuitInputs.inputsMarshal();
};

Expand Down Expand Up @@ -405,6 +413,8 @@ export class InputGenerator {
circuitInputs.signature = signature;
circuitInputs.challenge = params.challenge;

this.checkOperatorSupport(CircuitId.AtomicQuerySigV2OnChain, query.operator);

return circuitInputs.inputsMarshal();
};

Expand Down Expand Up @@ -464,6 +474,9 @@ export class InputGenerator {
circuitInputs.nullifierSessionID = proofReq.params?.nullifierSessionId
? BigInt(proofReq.params?.nullifierSessionId?.toString())
: BigInt(0);

this.checkOperatorSupport(CircuitId.AtomicQueryV3, query.operator);

return circuitInputs.inputsMarshal();
};

Expand Down Expand Up @@ -560,6 +573,9 @@ export class InputGenerator {
circuitInputs.treeState = authClaimData.treeState;
circuitInputs.signature = signature;
}

this.checkOperatorSupport(CircuitId.AtomicQueryV3OnChain, query.operator);

return circuitInputs.inputsMarshal();
};

Expand All @@ -577,10 +593,22 @@ export class InputGenerator {
circuitInputs.claim = circuitClaimData.claim;
circuitInputs.query = circuitQueries;

circuitQueries.forEach((query) => {
this.checkOperatorSupport(CircuitId.LinkedMultiQuery10, query.operator);
});

return circuitInputs.inputsMarshal();
};

private transformV2QueryOperator(operator: number): number {
return operator === Operators.SD || operator === Operators.NOOP ? Operators.EQ : operator;
}
private checkOperatorSupport(circuitId: string, operator: number) {
const supportedOperators = circuitValidator[circuitId as CircuitId].supportedOperations;
if (!supportedOperators.includes(operator)) {
throw new Error(
`operator ${getOperatorNameByValue(operator)} is not supported by ${circuitId}`
);
}
}
}
161 changes: 148 additions & 13 deletions src/proof/verifiers/pub-signals-verifier.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DID, getDateFromUnixTimestamp, Id } from '@iden3/js-iden3-core';
import { DocumentLoader, Path } from '@iden3/js-jsonld-merklization';
import { DocumentLoader, getDocumentLoader, Path } from '@iden3/js-jsonld-merklization';
import { Hash } from '@iden3/js-merkletree';
import { JSONObject } from '../../iden3comm';
import { IStateStorage, RootInfo, StateInfo } from '../../storage';
Expand All @@ -19,11 +19,19 @@ import {
checkQueryRequest,
ClaimOutputs,
VerifyOpts,
fieldValueFromVerifiablePresentation
fieldValueFromVerifiablePresentation,
validateDisclosureV2Circuit,
validateEmptyCredentialSubjectV2Circuit,
validateOperators,
verifyFieldValueInclusionV2,
validateDisclosureNativeSDSupport,
validateEmptyCredentialSubjectNoopNativeSupport,
verifyFieldValueInclusionNativeExistsSupport
} from './query';
import { parseQueriesMetadata, QueryMetadata } from '../common';
import { Operators } from '../../circuits';
import { calculateQueryHashV3 } from './query-hash';
import { JsonLd } from 'jsonld/jsonld-spec';

/**
* Verify Context - params for pub signal verification
Expand Down Expand Up @@ -120,14 +128,15 @@ export class PubSignalsVerifier {
valueArraySize: mtpv2PubSignals.getValueArrSize(),
isRevocationChecked: mtpv2PubSignals.isRevocationChecked
};
await checkQueryRequest(

await this.checkQueryV2Circuits(
CircuitId.AtomicQueryMTPV2,
query,
outs,
CircuitId.AtomicQueryMTPV2,
this._documentLoader,
verifiablePresentation,
opts
opts,
verifiablePresentation
);

// verify state
await this.checkStateExistenceForId(
mtpv2PubSignals.issuerID,
Expand Down Expand Up @@ -177,14 +186,15 @@ export class PubSignalsVerifier {
valueArraySize: sigV2PubSignals.getValueArrSize(),
isRevocationChecked: sigV2PubSignals.isRevocationChecked
};
await checkQueryRequest(

await this.checkQueryV2Circuits(
CircuitId.AtomicQuerySigV2,
query,
outs,
CircuitId.AtomicQuerySigV2,
this._documentLoader,
verifiablePresentation,
opts
opts,
verifiablePresentation
);

// verify state
await this.checkStateExistenceForId(sigV2PubSignals.issuerID, sigV2PubSignals.issuerAuthState);

Expand Down Expand Up @@ -227,17 +237,75 @@ export class PubSignalsVerifier {
merklized: v3PubSignals.merklized,
claimPathKey: v3PubSignals.claimPathKey,
valueArraySize: v3PubSignals.getValueArrSize(),
operatorOutput: v3PubSignals.operatorOutput,
isRevocationChecked: v3PubSignals.isRevocationChecked
};

if (!query.type) {
throw new Error(`proof query type is undefined`);
}

const loader = this._documentLoader ?? getDocumentLoader();

// validate schema
let context: JsonLd;
try {
context = (await loader(query.context ?? '')).document;
} catch (e) {
throw new Error(`can't load schema for request query`);
}

const queriesMetadata = await parseQueriesMetadata(
query.type,
JSON.stringify(context),
query.credentialSubject as JSONObject,
{
documentLoader: loader
}
);

await checkQueryRequest(
query,
queriesMetadata,
context,
outs,
CircuitId.AtomicQueryV3,
this._documentLoader,
verifiablePresentation,
opts
);

const queryMetadata = queriesMetadata[0]; // only one query is supported

// validate selective disclosure
if (queryMetadata.operator === Operators.SD) {
try {
await validateDisclosureNativeSDSupport(
queryMetadata,
outs,
verifiablePresentation,
loader
);
} catch (e) {
throw new Error(`failed to validate selective disclosure: ${(e as Error).message}`);
}
} else if (!queryMetadata.fieldName && queryMetadata.operator == Operators.NOOP) {
try {
await validateEmptyCredentialSubjectNoopNativeSupport(queryMetadata, outs);
} catch (e: unknown) {
throw new Error(`failed to validate operators: ${(e as Error).message}`);
}
} else {
try {
await validateOperators(queryMetadata, outs);
} catch (e) {
throw new Error(`failed to validate operators: ${(e as Error).message}`);
}
}

// verify field inclusion / non-inclusion

verifyFieldValueInclusionNativeExistsSupport(outs, queryMetadata);

const { proofType, verifierID, nullifier, nullifierSessionID, linkID } = v3PubSignals;

switch (query.proofType) {
Expand Down Expand Up @@ -447,6 +515,73 @@ export class PubSignalsVerifier {
}
};

private async checkQueryV2Circuits(
circuitId: CircuitId.AtomicQueryMTPV2 | CircuitId.AtomicQuerySigV2,
query: ProofQuery,
outs: ClaimOutputs,
opts: VerifyOpts | undefined,
verifiablePresentation: JSON | undefined
) {
if (!query.type) {
throw new Error(`proof query type is undefined`);
}

const loader = this._documentLoader ?? getDocumentLoader();

// validate schema
let context: JsonLd;
try {
context = (await loader(query.context ?? '')).document;
} catch (e) {
throw new Error(`can't load schema for request query`);
}

const queriesMetadata = await parseQueriesMetadata(
query.type,
JSON.stringify(context),
query.credentialSubject as JSONObject,
{
documentLoader: loader
}
);

await checkQueryRequest(
query,
queriesMetadata,
context,
outs,
circuitId,
this._documentLoader,
opts
);

const queryMetadata = queriesMetadata[0]; // only one query is supported

// validate selective disclosure
if (queryMetadata.operator === Operators.SD) {
try {
await validateDisclosureV2Circuit(queryMetadata, outs, verifiablePresentation, loader);
} catch (e) {
throw new Error(`failed to validate selective disclosure: ${(e as Error).message}`);
}
} else if (!queryMetadata.fieldName && queryMetadata.operator == Operators.NOOP) {
try {
await validateEmptyCredentialSubjectV2Circuit(queryMetadata, outs);
} catch (e: unknown) {
throw new Error(`failed to validate operators: ${(e as Error).message}`);
}
} else {
try {
await validateOperators(queryMetadata, outs);
} catch (e) {
throw new Error(`failed to validate operators: ${(e as Error).message}`);
}
}

// verify field inclusion
verifyFieldValueInclusionV2(outs, queryMetadata);
}

private async resolve(
id: Id,
state: bigint
Expand Down
Loading
Loading