Skip to content

Commit

Permalink
Merge branch 'feature/circuits-v3' into feature/linked-poc
Browse files Browse the repository at this point in the history
  • Loading branch information
Kolezhniuk committed Jan 18, 2024
2 parents fa514d6 + f509221 commit 2a614fd
Show file tree
Hide file tree
Showing 13 changed files with 1,377 additions and 898 deletions.
1,940 changes: 1,193 additions & 747 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@
"url": "https://github.com/iden3/js-iden3-auth"
},
"dependencies": {
"@0xpolygonid/js-sdk": "file:../js-sdk",
"@iden3/js-iden3-core": "1.1.0",
"@iden3/js-crypto": "1.0.3",
"@0xpolygonid/js-sdk": "1.7.1",
"@iden3/js-iden3-core": "1.2.1",
"@iden3/js-jsonld-merklization": "1.1.2",
"@iden3/js-jwz": "1.1.2",
"@iden3/js-jwz": "1.2.1",
"@iden3/js-merkletree": "1.1.2",
"did-resolver": "^4.1.0",
"ethers": "^5.4.0",
Expand Down
12 changes: 7 additions & 5 deletions src/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import {
IZKProver,
FSCircuitStorage,
ICircuitStorage,
cacheLoader
cacheLoader,
byteEncoder
} from '@0xpolygonid/js-sdk';
import { Resolvable } from 'did-resolver';
import { Options, DocumentLoader } from '@iden3/js-jsonld-merklization';
Expand Down Expand Up @@ -292,9 +293,9 @@ export class Verifier {
throw new Error(`circuit ${circuitId} is not supported by the library`);
}

opts = opts?.verifierDID ? opts : { ...opts, verifierDID: DID.parse(request.from) };
const params = proofRequest.params ?? {};

opts = opts?.params ? opts : { ...opts, params: proofRequest.params };
params.verifierDid = DID.parse(request.from);

// verify query
const verifier = new CircuitVerifier(proofResp.pub_signals);
Expand All @@ -303,7 +304,8 @@ export class Verifier {
proofRequest.query as unknown as Query,
this.schemaLoader,
proofResp.vp as JSON,
opts
opts,
params
);

// write linkId to the proof response
Expand Down Expand Up @@ -391,7 +393,7 @@ export class Verifier {
request: AuthorizationRequestMessage,
opts?: VerifyOpts
): Promise<AuthorizationResponseMessage> {
const msg = await this.packageManager.unpack(new TextEncoder().encode(tokenStr));
const msg = await this.packageManager.unpack(byteEncoder.encode(tokenStr));
const response = msg.unpackedMessage as AuthorizationResponseMessage;
await this.verifyAuthResponse(response, request, opts);
return response;
Expand Down
27 changes: 11 additions & 16 deletions src/circuits/atomicMtpV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,44 +40,39 @@ export class AtomicQueryMTPV2PubSignalsVerifier
opts?: VerifyOpts
): Promise<BaseConfig> {
const outs: ClaimOutputs = {
// TODO: update when js-sdk is fixed for AtomicQueryMTPV2PubSignals
issuerId: this.pubSignals.issuerID!,
schemaHash: this.pubSignals.claimSchema!,
issuerId: this.pubSignals.issuerID,
schemaHash: this.pubSignals.claimSchema,
slotIndex: this.pubSignals.slotIndex,
operator: this.pubSignals.operator!,
operator: this.pubSignals.operator,
value: this.pubSignals.value,
timestamp: this.pubSignals.timestamp!,
merklized: this.pubSignals.merklized!,
timestamp: this.pubSignals.timestamp,
merklized: this.pubSignals.merklized,
claimPathKey: this.pubSignals.claimPathKey,
claimPathNotExists: this.pubSignals.claimPathNotExists,
valueArraySize: valuesSize,
isRevocationChecked: this.pubSignals.isRevocationChecked!
isRevocationChecked: this.pubSignals.isRevocationChecked
};
await checkQueryRequest(query, outs, schemaLoader, verifiablePresentation, opts);

return this.pubSignals;
}

async verifyStates(resolvers: Resolvers, opts?: VerifyOpts): Promise<void> {
const resolver = getResolverByID(resolvers, this.pubSignals.issuerID!);
const resolver = getResolverByID(resolvers, this.pubSignals.issuerID);
if (!resolver) {
throw new Error(`resolver not found for issuerID ${this.pubSignals.issuerID!.string()}`);
throw new Error(`resolver not found for issuerID ${this.pubSignals.issuerID.string()}`);
}

await checkUserState(
resolver,
this.pubSignals.issuerID!,
this.pubSignals.issuerClaimIdenState!
);
await checkUserState(resolver, this.pubSignals.issuerID, this.pubSignals.issuerClaimIdenState);

if (this.pubSignals.isRevocationChecked === 0) {
return;
}

const issuerNonRevStateResolved = await checkIssuerNonRevState(
resolver,
this.pubSignals.issuerID!,
this.pubSignals.issuerClaimNonRevState!
this.pubSignals.issuerID,
this.pubSignals.issuerClaimNonRevState
);

let acceptedStateTransitionDelay = defaultProofVerifyOpts;
Expand Down
100 changes: 57 additions & 43 deletions src/circuits/atomicV3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import { IDOwnershipPubSignals } from '@lib/circuits/ownershipVerifier';
import { checkIssuerNonRevState, checkUserState, getResolverByID } from '@lib/circuits/common';
import { DID, getDateFromUnixTimestamp } from '@iden3/js-iden3-core';
import { DocumentLoader } from '@iden3/js-jsonld-merklization';
import { AtomicQueryV3PubSignals, BaseConfig, byteEncoder, ProofType } from '@0xpolygonid/js-sdk';
import {
AtomicQueryV3PubSignals,
BaseConfig,
byteEncoder,
JSONObject,
ProofType
} from '@0xpolygonid/js-sdk';

const valuesSize = 64;
const defaultProofVerifyOpts = 1 * 60 * 60 * 1000; // 1 hour
Expand All @@ -30,7 +36,8 @@ export class AtomicQueryV3PubSignalsVerifier
query: Query,
schemaLoader?: DocumentLoader,
verifiablePresentation?: JSON,
opts?: VerifyOpts
opts?: VerifyOpts,
params?: JSONObject
): Promise<BaseConfig> {
const outs: ClaimOutputs = {
issuerId: this.pubSignals.issuerID,
Expand All @@ -47,46 +54,56 @@ export class AtomicQueryV3PubSignalsVerifier
};
await checkQueryRequest(query, outs, schemaLoader, verifiablePresentation, opts);

const { proofType, verifierID, nullifier, nullifierSessionID } = this.pubSignals;

if (
!(query.proofType === ProofType.BJJSignature && proofType === 1) &&
!(query.proofType === ProofType.Iden3SparseMerkleTreeProof && proofType === 2)
) {
throw new Error('invalid proof type');
const { proofType, verifierID, nullifier, nullifierSessionID, linkID } = this.pubSignals;

switch (query.proofType) {
case ProofType.BJJSignature:
if (proofType !== 1) {
throw new Error('wrong proof type for BJJSignature');
}
break;
case ProofType.Iden3SparseMerkleTreeProof:
if (proofType !== 2) {
throw new Error('wrong proof type for Iden3SparseMerkleTreeProof');
}
break;
default:
throw new Error('invalid proof type');
}

if (nullifier && BigInt(nullifier) !== 0n) {
// verify nullifier information
if (!opts?.verifierDID) {
throw new Error('verifierDID is required');
}
const nullifierSessionIDparam = params?.nullifierSessionId;

const id = DID.idFromDID(opts.verifierDID);
if (nullifierSessionIDparam) {
if (nullifier && BigInt(nullifier) !== 0n) {
// verify nullifier information
const verifierDIDParam = params?.verifierDid;
if (!verifierDIDParam) {
throw new Error('verifierDid is required');
}

if (verifierID.bigInt() != id.bigInt()) {
throw new Error('wrong verifier is used for nullification');
}
const id = DID.idFromDID(verifierDIDParam as DID);

if (!opts.params?.nullifierSessionId) {
throw new Error('nullifierSessionId is required');
}
if (verifierID.bigInt() != id.bigInt()) {
throw new Error('wrong verifier is used for nullification');
}
const nSessionId = BigInt(nullifierSessionIDparam as string);

const nSessionId = BigInt(opts.params.nullifierSessionId.toString());

if (nullifierSessionID !== nSessionId) {
throw new Error(
`wrong verifier session id is used for nullification, expected ${nSessionId}, got ${nullifierSessionID}`
);
if (nullifierSessionID !== nSessionId) {
throw new Error(
`wrong verifier session id is used for nullification, expected ${nSessionId}, got ${nullifierSessionID}`
);
}
}
} else if (nullifierSessionID !== 0n) {
throw new Error(`Nullifier id is generated but wasn't requested`);
}

if (typeof query.groupId !== 'undefined' && this.pubSignals.linkID === 0n) {
throw new Error('linkID is required');
if (!query.groupId && linkID !== 0n) {
throw new Error(`proof contains link id, but group id is not provided`);
}

if (typeof query.groupId === 'undefined' && this.pubSignals.linkID !== 0n) {
throw new Error('Query should not have groupId');
if (query.groupId && linkID === 0n) {
throw new Error("proof doesn't contain link id, but group id is provided");
}

return this.pubSignals;
Expand All @@ -104,11 +121,6 @@ export class AtomicQueryV3PubSignalsVerifier
return;
}

// if IsRevocationChecked is set to 0. Skip validation revocation status of issuer.
if (this.pubSignals.isRevocationChecked === 0) {
return;
}

const issuerNonRevStateResolved = await checkIssuerNonRevState(
resolver,
this.pubSignals.issuerID,
Expand All @@ -118,13 +130,15 @@ export class AtomicQueryV3PubSignalsVerifier
const acceptedStateTransitionDelay =
opts?.acceptedStateTransitionDelay ?? defaultProofVerifyOpts;

if (!issuerNonRevStateResolved.latest) {
const timeDiff =
Date.now() -
getDateFromUnixTimestamp(Number(issuerNonRevStateResolved.transitionTimestamp)).getTime();
if (timeDiff > acceptedStateTransitionDelay) {
throw new Error('issuer state is outdated');
}
if (issuerNonRevStateResolved.latest) {
return;
}

const timeDiff =
Date.now() -
getDateFromUnixTimestamp(Number(issuerNonRevStateResolved.transitionTimestamp)).getTime();
if (timeDiff > acceptedStateTransitionDelay) {
throw new Error('issuer state is outdated');
}
}
}
5 changes: 2 additions & 3 deletions src/circuits/authV2.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { getDateFromUnixTimestamp } from '@iden3/js-iden3-core';
import { Query } from '@lib/circuits/query';
import { PubSignalsVerifier, VerifyOpts } from '@lib/circuits/registry';
import { IDOwnershipPubSignals } from '@lib/circuits/ownershipVerifier';
import { checkGlobalState, getResolverByID } from '@lib/circuits/common';
Expand All @@ -19,8 +18,8 @@ export class AuthPubSignalsV2 extends IDOwnershipPubSignals implements PubSignal
this.challenge = this.pubSignals.challenge;
}

async verifyQuery(_query: Query): Promise<BaseConfig> {
throw new Error(`auth circuit doesn't support queries`);
verifyQuery(): Promise<BaseConfig> {
return Promise.resolve(new BaseConfig());
}

async verifyStates(resolvers: Resolvers, opts?: VerifyOpts): Promise<void> {
Expand Down
12 changes: 0 additions & 12 deletions src/circuits/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,3 @@ export function getResolverByDID(resolvers: Resolvers, did: DID): IStateResolver
const { blockchain, networkId } = DID.decodePartsFromId(DID.idFromDID(did));
return resolvers[`${blockchain}:${networkId}`];
}

export enum XSDNS {
Boolean = 'http://www.w3.org/2001/XMLSchema#boolean',
Integer = 'http://www.w3.org/2001/XMLSchema#integer',
NonNegativeInteger = 'http://www.w3.org/2001/XMLSchema#nonNegativeInteger',
NonPositiveInteger = 'http://www.w3.org/2001/XMLSchema#nonPositiveInteger',
NegativeInteger = 'http://www.w3.org/2001/XMLSchema#negativeInteger',
PositiveInteger = 'http://www.w3.org/2001/XMLSchema#positiveInteger',
DateTime = 'http://www.w3.org/2001/XMLSchema#dateTime',
Double = 'http://www.w3.org/2001/XMLSchema#double',
String = 'http://www.w3.org/2001/XMLSchema#string'
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { PubSignalsVerifier, VerifyOpts } from '@lib/circuits/registry';
import { PubSignalsVerifier } from '@lib/circuits/registry';
import { Query } from '@lib/circuits/query';
import { Resolvers } from '@lib/state/resolver';
import { DocumentLoader, Path } from '@iden3/js-jsonld-merklization';
import {
BaseConfig,
Expand All @@ -13,30 +12,25 @@ import {
parseQueriesMetadata
} from '@0xpolygonid/js-sdk';
import { poseidon } from '@iden3/js-crypto';

export class LinkedMultiQueryVerifier implements PubSignalsVerifier {
pubSignals = new LinkedMultiQueryPubSignals();
readonly pubSignals = new LinkedMultiQueryPubSignals();

constructor(pubSignals: string[]) {
this.pubSignals = this.pubSignals.pubSignalsUnmarshal(
byteEncoder.encode(JSON.stringify(pubSignals)),
3
10
);
}

verifyIdOwnership(sender: string, challenge: bigint): Promise<void> {
verifyIdOwnership(): Promise<void> {
return Promise.resolve();
}

async verifyQuery(
query: Query,
schemaLoader?: DocumentLoader,
verifiablePresentation?: JSON,
opts?: VerifyOpts
): Promise<BaseConfig> {
async verifyQuery(query: Query, schemaLoader?: DocumentLoader): Promise<BaseConfig> {
let schema: JSONObject;
const ldOpts = { documentLoader: schemaLoader ?? cacheLoader() };
try {
const loader = schemaLoader ?? cacheLoader();
schema = (await ldOpts.documentLoader(query.context)).document as JSONObject;
} catch (e) {
throw new Error(`can't load schema for request query`);
Expand Down Expand Up @@ -64,8 +58,7 @@ export class LinkedMultiQueryVerifier implements PubSignalsVerifier {
BigInt(queryMeta.slotIndex),
BigInt(queryMeta.operator),
BigInt(queryMeta.claimPathKey),
// TODO: claimAPathNotExists
BigInt(0),
queryMeta.merklizedSchema ? 0n : 1n,
valueHash
]);
});
Expand All @@ -77,7 +70,7 @@ export class LinkedMultiQueryVerifier implements PubSignalsVerifier {
return this.pubSignals as unknown as BaseConfig;
}

async verifyStates(resolvers: Resolvers, opts?: VerifyOpts): Promise<void> {
async verifyStates(): Promise<void> {
return Promise.resolve();
}
}
Loading

0 comments on commit 2a614fd

Please sign in to comment.