Repository navigation
Expand file tree
/
Copy pathquery.ts
More file actions
298 lines (267 loc) · 9.37 KB
/
Copy pathquery.ts
File metadata and controls
298 lines (267 loc) · 9.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import { DID, getDateFromUnixTimestamp, Id, SchemaHash } from '@iden3/js-iden3-core';
import { DocumentLoader, Merklizer, MtValue, Path } from '@iden3/js-jsonld-merklization';
import { Proof } from '@iden3/js-merkletree';
import { byteEncoder } from '../../utils';
import { getOperatorNameByValue, Operators, QueryOperators } from '../../circuits/comparer';
import { CircuitId } from '../../circuits/models';
import { calculateCoreSchemaHash, ProofQuery, VerifiableConstants } from '../../verifiable';
import { QueryMetadata } from '../common';
import { circuitValidator } from '../provers';
import { JsonLd } from 'jsonld/jsonld-spec';
/**
* Options to verify state
*/
export type VerifyOpts = {
// acceptedStateTransitionDelay is the period of time in milliseconds that a revoked state remains valid.
acceptedStateTransitionDelay?: number;
// acceptedProofGenerationDelay is the period of time in milliseconds that a generated proof remains valid.
acceptedProofGenerationDelay?: number;
};
const defaultProofGenerationDelayOpts = 24 * 60 * 60 * 1000; // 24 hours
// ClaimOutputs fields that are used in proof generation
export interface ClaimOutputs {
issuerId: Id;
schemaHash: SchemaHash;
slotIndex?: number;
operator: number;
operatorOutput?: bigint;
value: bigint[];
timestamp: number;
merklized: number;
claimPathKey?: bigint;
claimPathNotExists?: number;
valueArraySize: number;
isRevocationChecked: number;
}
export async function checkQueryRequest(
query: ProofQuery,
queriesMetadata: QueryMetadata[],
ldContext: JsonLd,
outputs: ClaimOutputs,
circuitId: CircuitId,
schemaLoader?: DocumentLoader,
opts?: VerifyOpts
): Promise<void> {
// validate issuer
const userDID = DID.parseFromId(outputs.issuerId);
const issuerAllowed =
!query.allowedIssuers ||
query.allowedIssuers?.some((issuer) => issuer === '*' || issuer === userDID.string());
if (!issuerAllowed) {
throw new Error('issuer is not in allowed list');
}
if (!query.type) {
throw new Error('query type is missing');
}
const schemaId: string = await Path.getTypeIDFromContext(JSON.stringify(ldContext), query.type, {
documentLoader: schemaLoader
});
const schemaHash = calculateCoreSchemaHash(byteEncoder.encode(schemaId));
if (schemaHash.bigInt() !== outputs.schemaHash.bigInt()) {
throw new Error(`schema that was used is not equal to requested in query`);
}
if (!query.skipClaimRevocationCheck && outputs.isRevocationChecked === 0) {
throw new Error(`check revocation is required`);
}
checkCircuitQueriesLength(circuitId, queriesMetadata);
// verify timestamp
let acceptedProofGenerationDelay = defaultProofGenerationDelayOpts;
if (opts?.acceptedProofGenerationDelay) {
acceptedProofGenerationDelay = opts.acceptedProofGenerationDelay;
}
const timeDiff = Date.now() - getDateFromUnixTimestamp(Number(outputs.timestamp)).getTime();
if (timeDiff > acceptedProofGenerationDelay) {
throw new Error('generated proof is outdated');
}
return;
}
export function checkCircuitQueriesLength(circuitId: CircuitId, queriesMetadata: QueryMetadata[]) {
const circuitValidationData = circuitValidator[circuitId];
if (queriesMetadata.length > circuitValidationData.maxQueriesCount) {
throw new Error(
`circuit ${circuitId} supports only ${
circuitValidator[circuitId as CircuitId].maxQueriesCount
} queries`
);
}
}
export function checkCircuitOperator(circuitId: CircuitId, operator: number) {
const circuitValidationData = circuitValidator[circuitId];
if (!circuitValidationData.supportedOperations.includes(operator)) {
throw new Error(
`circuit ${circuitId} not support ${getOperatorNameByValue(operator)} operator`
);
}
}
export function verifyFieldValueInclusionV2(outputs: ClaimOutputs, metadata: QueryMetadata) {
if (outputs.operator == QueryOperators.$noop) {
return;
}
if (outputs.merklized === 1) {
if (outputs.claimPathNotExists === 1) {
throw new Error(`proof doesn't contains target query key`);
}
if (outputs.claimPathKey !== metadata.claimPathKey) {
throw new Error(`proof was generated for another path`);
}
} else {
if (outputs.slotIndex !== metadata.slotIndex) {
throw new Error(`wrong claim slot was used in claim`);
}
}
}
export function verifyFieldValueInclusionNativeExistsSupport(
outputs: ClaimOutputs,
metadata: QueryMetadata
) {
if (outputs.operator == Operators.NOOP) {
return;
}
if (outputs.operator === Operators.EXISTS && !outputs.merklized) {
throw new Error('$exists operator is not supported for non-merklized credential');
}
if (outputs.merklized === 1) {
if (outputs.claimPathKey !== metadata.claimPathKey) {
throw new Error(`proof was generated for another path`);
}
} else {
if (outputs.slotIndex !== metadata.slotIndex) {
throw new Error(`wrong claim slot was used in claim`);
}
}
}
export async function validateEmptyCredentialSubjectV2Circuit(
cq: QueryMetadata,
outputs: ClaimOutputs
) {
if (outputs.operator !== Operators.EQ) {
throw new Error('empty credentialSubject request available only for equal operation');
}
for (let index = 1; index < outputs.value.length; index++) {
if (outputs.value[index] !== 0n) {
throw new Error(`empty credentialSubject request not available for array of values`);
}
}
const path = Path.newPath([VerifiableConstants.CREDENTIAL_SUBJECT_PATH]);
const subjectEntry = await path.mtEntry();
if (outputs.claimPathKey !== subjectEntry) {
throw new Error(`proof doesn't contain credentialSubject in claimPathKey`);
}
return;
}
export async function validateOperators(cq: QueryMetadata, outputs: ClaimOutputs) {
if (outputs.operator !== cq.operator) {
throw new Error(`operator that was used is not equal to request`);
}
if (outputs.operator === Operators.NOOP) {
// for noop operator slot and value are not used in this case
return;
}
for (let index = 0; index < outputs.value.length; index++) {
if (outputs.value[index] !== cq.values[index]) {
if (outputs.value[index] === 0n && cq.values[index] === undefined) {
continue;
}
throw new Error(`comparison value that was used is not equal to requested in query`);
}
}
}
export async function validateDisclosureV2Circuit(
cq: QueryMetadata,
outputs: ClaimOutputs,
verifiablePresentation?: JSON,
ldLoader?: DocumentLoader
) {
const bi = await fieldValueFromVerifiablePresentation(
cq.fieldName,
verifiablePresentation,
ldLoader
);
if (bi !== outputs.value[0]) {
throw new Error(`value that was used is not equal to requested in query`);
}
if (outputs.operator !== Operators.EQ) {
throw new Error(`operator for selective disclosure must be $eq`);
}
for (let index = 1; index < outputs.value.length; index++) {
if (outputs.value[index] !== 0n) {
throw new Error(`selective disclosure not available for array of values`);
}
}
}
export async function validateDisclosureNativeSDSupport(
cq: QueryMetadata,
outputs: ClaimOutputs,
verifiablePresentation?: JSON,
ldLoader?: DocumentLoader
) {
const bi = await fieldValueFromVerifiablePresentation(
cq.fieldName,
verifiablePresentation,
ldLoader
);
if (bi !== outputs.operatorOutput) {
throw new Error(`operator output should be equal to disclosed value`);
}
if (outputs.operator !== Operators.SD) {
throw new Error(`operator for selective disclosure must be $sd`);
}
for (let index = 0; index < outputs.value.length; index++) {
if (outputs.value[index] !== 0n) {
throw new Error(`public signal values must be zero`);
}
}
}
export async function validateEmptyCredentialSubjectNoopNativeSupport(outputs: ClaimOutputs) {
if (outputs.operator !== Operators.NOOP) {
throw new Error('empty credentialSubject request available only for $noop operation');
}
for (let index = 1; index < outputs.value.length; index++) {
if (outputs.value[index] !== 0n) {
throw new Error(`empty credentialSubject request not available for array of values`);
}
}
}
export const fieldValueFromVerifiablePresentation = async (
fieldName: string,
verifiablePresentation?: JSON,
ldLoader?: DocumentLoader
): Promise<bigint> => {
if (!verifiablePresentation) {
throw new Error(`verifiablePresentation is required for selective disclosure request`);
}
let mz: Merklizer;
const strVerifiablePresentation: string = JSON.stringify(verifiablePresentation);
try {
mz = await Merklizer.merklizeJSONLD(strVerifiablePresentation, {
documentLoader: ldLoader
});
} catch (e) {
throw new Error(`can't merklize verifiablePresentation`);
}
let merklizedPath: Path;
try {
const p = `verifiableCredential.credentialSubject.${fieldName}`;
merklizedPath = await Path.fromDocument(null, strVerifiablePresentation, p, {
documentLoader: ldLoader
});
} catch (e) {
throw new Error(`can't build path to '${fieldName}' key`);
}
let proof: Proof;
let value: MtValue | undefined;
try {
({ proof, value } = await mz.proof(merklizedPath));
} catch (e) {
throw new Error(`can't get value by path '${fieldName}'`);
}
if (!value) {
throw new Error(`can't get merkle value for field '${fieldName}'`);
}
if (!proof.existence) {
throw new Error(
`path [${merklizedPath.parts}] doesn't exist in verifiablePresentation document`
);
}
return await value.mtEntry();
};