Skip to content

Commit a382fb0

Browse files
committed
Add default state transition delay
1 parent d46ce5c commit a382fb0

File tree

8 files changed

+81
-23
lines changed

8 files changed

+81
-23
lines changed

src/iden3comm/constants.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,6 @@ export const SUPPORTED_PUBLIC_KEY_TYPES = {
7272
'JsonWebKey2020'
7373
]
7474
};
75+
76+
export const DEFAULT_PROOF_VERIFY_OPT = 1 * 60 * 60 * 1000; // 1 hour
77+
export const DEFAULT_AUTH_VERIFY_OPTS = 5 * 60 * 1000; // 5 minutes

src/iden3comm/handlers/auth.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { IProofService } from '../../proof/proof-service';
33
import { PROTOCOL_MESSAGE_TYPE } from '../constants';
44

55
import {
6+
StateVerificationOpts,
67
AuthorizationRequestMessage,
78
AuthorizationResponseMessage,
89
BasicMessage,
@@ -64,19 +65,17 @@ export function createAuthorizationRequestWithMessage(
6465
};
6566
return request;
6667
}
68+
6769
/**
6870
*
6971
* Options to pass to auth response handler
7072
*
7173
* @public
72-
* @interface AuthResponseHandlerOptions
7374
*/
74-
export interface AuthResponseHandlerOptions {
75-
// acceptedStateTransitionDelay is the period of time in milliseconds that a revoked state remains valid.
76-
acceptedStateTransitionDelay?: number;
75+
export type AuthResponseHandlerOptions = StateVerificationOpts & {
7776
// acceptedProofGenerationDelay is the period of time in milliseconds that a generated proof remains valid.
7877
acceptedProofGenerationDelay?: number;
79-
}
78+
};
8079

8180
/**
8281
* Interface that allows the processing of the authorization request in the raw format for given identifier

src/iden3comm/packers/zkp.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
StateVerificationOpts,
23
AuthDataPrepareFunc,
34
BasicMessage,
45
IPacker,
@@ -21,6 +22,7 @@ import {
2122
} from '../errors';
2223
import { MediaType } from '../constants';
2324
import { byteDecoder, byteEncoder } from '../../utils';
25+
import { DEFAULT_AUTH_VERIFY_OPTS } from '../constants';
2426

2527
const { getProvingMethod } = proving;
2628

@@ -70,8 +72,8 @@ export class VerificationHandlerFunc {
7072
* @param {Array<string>} pubSignals - signals that must contain user id and state
7173
* @returns `Promise<boolean>`
7274
*/
73-
verify(id: string, pubSignals: Array<string>): Promise<boolean> {
74-
return this.stateVerificationFunc(id, pubSignals);
75+
verify(id: string, pubSignals: Array<string>, opts?: StateVerificationOpts): Promise<boolean> {
76+
return this.stateVerificationFunc(id, pubSignals, opts);
7577
}
7678
}
7779

@@ -89,8 +91,11 @@ export class ZKPPacker implements IPacker {
8991
* @param {Map<string, VerificationParams>} verificationParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
9092
*/
9193
constructor(
92-
public provingParamsMap: Map<string, ProvingParams>,
93-
public verificationParamsMap: Map<string, VerificationParams>
94+
public readonly provingParamsMap: Map<string, ProvingParams>,
95+
public readonly verificationParamsMap: Map<string, VerificationParams>,
96+
private readonly _opts: StateVerificationOpts = {
97+
acceptedStateTransitionDelay: DEFAULT_AUTH_VERIFY_OPTS
98+
}
9499
) {}
95100

96101
/**
@@ -150,8 +155,10 @@ export class ZKPPacker implements IPacker {
150155

151156
const verificationResult = await verificationParams?.verificationFn?.verify(
152157
token.circuitId,
153-
token.zkProof.pub_signals
158+
token.zkProof.pub_signals,
159+
this._opts
154160
);
161+
155162
if (!verificationResult) {
156163
throw new Error(ErrStateVerificationFailed);
157164
}

src/iden3comm/types/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ export * from './protocol/proposal-request';
88
export * from './protocol/payment';
99

1010
export * from './packer';
11+
export * from './models';
1112
export * from './packageManager';

src/iden3comm/types/models.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/**
2+
* State verification options
3+
*/
4+
export type StateVerificationOpts = {
5+
// acceptedStateTransitionDelay is the period of time in milliseconds that a revoked state remains valid.
6+
acceptedStateTransitionDelay?: number;
7+
};

src/iden3comm/types/packer.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { ProvingMethodAlg } from '@iden3/js-jwz';
44
import { CircuitId } from '../../circuits';
55
import { MediaType } from '../constants';
66
import { DIDDocument, VerificationMethod } from 'did-resolver';
7+
import { StateVerificationOpts } from './models';
78
/**
89
* Protocol message type
910
*/
@@ -79,7 +80,11 @@ export type AuthDataPrepareFunc = (
7980
/**
8081
* signature of state function verifier
8182
*/
82-
export type StateVerificationFunc = (id: string, pubSignals: Array<string>) => Promise<boolean>;
83+
export type StateVerificationFunc = (
84+
id: string,
85+
pubSignals: Array<string>,
86+
opts?: StateVerificationOpts
87+
) => Promise<boolean>;
8388

8489
/**
8590
* Defines method that must be implemented by any packer

src/proof/proof-service.ts

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,19 @@
1-
import { BytesHelper, DID, MerklizedRootPosition } from '@iden3/js-iden3-core';
1+
import {
2+
BytesHelper,
3+
DID,
4+
MerklizedRootPosition,
5+
getDateFromUnixTimestamp
6+
} from '@iden3/js-iden3-core';
27
import { Hash } from '@iden3/js-merkletree';
3-
import { AuthV2Inputs, CircuitId, Operators, Query, TreeState, ValueProof } from '../circuits';
8+
import {
9+
AuthV2Inputs,
10+
AuthV2PubSignals,
11+
CircuitId,
12+
Operators,
13+
Query,
14+
TreeState,
15+
ValueProof
16+
} from '../circuits';
417
import { ICredentialWallet } from '../credentials';
518
import { IIdentityWallet } from '../identity';
619
import {
@@ -22,7 +35,13 @@ import { IZKProver, NativeProver } from './provers/prover';
2235
import { Merklizer, Options, getDocumentLoader } from '@iden3/js-jsonld-merklization';
2336
import { ZKProof } from '@iden3/js-jwz';
2437
import { Signer } from 'ethers';
25-
import { JSONObject, ZeroKnowledgeProofRequest, ZeroKnowledgeProofResponse } from '../iden3comm';
38+
import {
39+
StateVerificationOpts,
40+
JSONObject,
41+
ZeroKnowledgeProofRequest,
42+
ZeroKnowledgeProofResponse,
43+
PROTOCOL_CONSTANTS
44+
} from '../iden3comm';
2645
import { cacheLoader } from '../schema-processor';
2746
import { ICircuitStorage, IStateStorage } from '../storage';
2847
import { byteDecoder, byteEncoder } from '../utils/encoding';
@@ -469,12 +488,22 @@ export class ProofService implements IProofService {
469488
return authInputs.inputsMarshal();
470489
}
471490

472-
async verifyState(circuitId: string, pubSignals: string[]): Promise<boolean> {
491+
async verifyState(
492+
circuitId: string,
493+
pubSignals: string[],
494+
opts: StateVerificationOpts = {
495+
acceptedStateTransitionDelay: PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_OPTS
496+
}
497+
): Promise<boolean> {
473498
if (circuitId !== CircuitId.AuthV2) {
474499
throw new Error(`CircuitId is not supported ${circuitId}`);
475500
}
476-
const gistRoot = Hash.fromString(pubSignals[2]).bigInt();
477-
const userId = BigInt(pubSignals[0]);
501+
502+
const authV2PubSignals = new AuthV2PubSignals().pubSignalsUnmarshal(
503+
byteEncoder.encode(JSON.stringify(pubSignals))
504+
);
505+
const gistRoot = authV2PubSignals.GISTRoot.bigInt();
506+
const userId = authV2PubSignals.userID.bigInt();
478507
const globalStateInfo = await this._stateStorage.getGISTRootInfo(gistRoot, userId);
479508

480509
if (globalStateInfo.createdAtTimestamp === 0n) {
@@ -489,7 +518,16 @@ export class ProofService implements IProofService {
489518
if (globalStateInfo.replacedAtTimestamp === 0n) {
490519
throw new Error(`state was replaced, but replaced time unknown`);
491520
}
492-
return false;
521+
522+
const timeDiff =
523+
Date.now() -
524+
getDateFromUnixTimestamp(Number(globalStateInfo.replacedAtTimestamp)).getTime();
525+
526+
if (timeDiff > (opts?.acceptedStateTransitionDelay ?? 300_000)) {
527+
throw new Error('global state is outdated');
528+
}
529+
530+
return true;
493531
}
494532

495533
return true;

src/proof/verifiers/pub-signals-verifier.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { DID, getDateFromUnixTimestamp, Id } from '@iden3/js-iden3-core';
22
import { DocumentLoader, getDocumentLoader, Path } from '@iden3/js-jsonld-merklization';
33
import { Hash } from '@iden3/js-merkletree';
4-
import { JSONObject } from '../../iden3comm';
54
import { IStateStorage, RootInfo, StateInfo } from '../../storage';
65
import { byteEncoder, isGenesisState } from '../../utils';
76
import { calculateCoreSchemaHash, ProofQuery, ProofType } from '../../verifiable';
@@ -33,6 +32,7 @@ import { parseQueriesMetadata, QueryMetadata } from '../common';
3332
import { Operators } from '../../circuits';
3433
import { calculateQueryHashV3 } from './query-hash';
3534
import { JsonLd } from 'jsonld/jsonld-spec';
35+
import { PROTOCOL_CONSTANTS, JSONObject } from '../../iden3comm';
3636

3737
/**
3838
* Verify Context - params for pub signal verification
@@ -50,8 +50,6 @@ export type VerifyContext = {
5050

5151
export const userStateError = new Error(`user state is not valid`);
5252
const zeroInt = 0n;
53-
const defaultProofVerifyOpts = 1 * 60 * 60 * 1000; // 1 hour
54-
const defaultAuthVerifyOpts = 5 * 60 * 1000; // 5 minutes
5553

5654
/**
5755
* PubSignalsVerifier provides verify method
@@ -395,7 +393,7 @@ export class PubSignalsVerifier {
395393
// verify state
396394
const gist = await this.checkGlobalState(authV2PubSignals.GISTRoot, this.userId);
397395

398-
let acceptedStateTransitionDelay = defaultAuthVerifyOpts;
396+
let acceptedStateTransitionDelay = PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_OPTS;
399397
if (opts?.acceptedStateTransitionDelay) {
400398
acceptedStateTransitionDelay = opts.acceptedStateTransitionDelay;
401399
}
@@ -714,7 +712,7 @@ export class PubSignalsVerifier {
714712
);
715713

716714
const acceptedStateTransitionDelay =
717-
opts?.acceptedStateTransitionDelay ?? defaultProofVerifyOpts;
715+
opts?.acceptedStateTransitionDelay ?? PROTOCOL_CONSTANTS.DEFAULT_PROOF_VERIFY_OPT;
718716

719717
if (!issuerNonRevStateResolved.latest) {
720718
const timeDiff =

0 commit comments

Comments
 (0)