-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathcommon.ts
210 lines (185 loc) · 6.64 KB
/
common.ts
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
import { getRandomBytes } from '@iden3/js-crypto';
import {
AcceptProfile,
AuthProofResponse,
BasicMessage,
JsonDocumentObject,
JWSPackerParams,
ZeroKnowledgeProofAuth,
ZeroKnowledgeProofAuthResponse,
ZeroKnowledgeProofQuery,
ZeroKnowledgeProofRequest,
ZeroKnowledgeProofResponse
} from '../types';
import { mergeObjects } from '../../utils';
import { RevocationStatus, W3CCredential } from '../../verifiable';
import { DID, getUnixTimestamp } from '@iden3/js-iden3-core';
import { IProofService } from '../../proof';
import { CircuitId } from '../../circuits';
import { defaultAcceptProfile, MediaType } from '../constants';
import { Signer } from 'ethers';
/**
* Groups the ZeroKnowledgeProofRequest objects based on their groupId.
* Returns a Map where the key is the groupId and the value is an object containing the query and linkNonce.
*
* @param requestScope - An array of ZeroKnowledgeProofRequest objects.
* @returns A Map<number, { query: ZeroKnowledgeProofQuery; linkNonce: number }> representing the grouped queries.
*/
const getGroupedQueries = (
requestScope: ZeroKnowledgeProofRequest[]
): Map<number, { query: ZeroKnowledgeProofQuery; linkNonce: number }> =>
requestScope.reduce((acc, proofReq) => {
const groupId = proofReq.query.groupId as number | undefined;
if (!groupId) {
return acc;
}
const existedData = acc.get(groupId);
if (!existedData) {
const seed = getRandomBytes(12);
const dataView = new DataView(seed.buffer);
const linkNonce = dataView.getUint32(0);
acc.set(groupId, { query: proofReq.query, linkNonce });
return acc;
}
const credentialSubject = mergeObjects(
existedData.query.credentialSubject as JsonDocumentObject,
proofReq.query.credentialSubject as JsonDocumentObject
);
acc.set(groupId, {
...existedData,
query: {
skipClaimRevocationCheck:
existedData.query.skipClaimRevocationCheck || proofReq.query.skipClaimRevocationCheck,
...existedData.query,
credentialSubject
}
});
return acc;
}, new Map<number, { query: ZeroKnowledgeProofQuery; linkNonce: number }>());
/**
* Processes zero knowledge proof requests.
*
* @param to - The identifier of the recipient.
* @param requests - An array of zero knowledge proof requests.
* @param from - The identifier of the sender.
* @param proofService - The proof service.
* @param opts - Additional options for processing the requests.
* @returns A promise that resolves to an array of zero knowledge proof responses.
*/
export const processZeroKnowledgeProofRequests = async (
to: DID,
requests: ZeroKnowledgeProofRequest[] | undefined,
from: DID | undefined,
proofService: IProofService,
opts: {
mediaType?: MediaType;
packerOptions?: JWSPackerParams;
supportedCircuits: CircuitId[];
ethSigner?: Signer;
challenge?: bigint;
}
): Promise<ZeroKnowledgeProofResponse[]> => {
const requestScope = requests ?? [];
const combinedQueries = getGroupedQueries(requestScope);
const groupedCredentialsCache = new Map<
number,
{ cred: W3CCredential; revStatus?: RevocationStatus }
>();
const zkpResponses = [];
for (const proofReq of requestScope) {
if (!opts.supportedCircuits.includes(proofReq.circuitId as CircuitId)) {
throw new Error(`Circuit ${proofReq.circuitId} is not allowed`);
}
const query = proofReq.query;
const groupId = query.groupId as number | undefined;
const combinedQueryData = combinedQueries.get(groupId as number);
if (groupId) {
if (!combinedQueryData) {
throw new Error(`Invalid group id ${query.groupId}`);
}
const combinedQuery = combinedQueryData.query;
if (!groupedCredentialsCache.has(groupId)) {
const credWithRevStatus = await proofService.findCredentialByProofQuery(
to,
combinedQueryData.query
);
if (!credWithRevStatus.cred) {
throw new Error(`Credential not found for query ${JSON.stringify(combinedQuery)}`);
}
groupedCredentialsCache.set(groupId, credWithRevStatus);
}
}
const credWithRevStatus = groupedCredentialsCache.get(groupId as number);
const zkpRes: ZeroKnowledgeProofResponse = await proofService.generateProof(proofReq, to, {
verifierDid: from,
challenge: opts.challenge,
skipRevocation: Boolean(query.skipClaimRevocationCheck),
credential: credWithRevStatus?.cred,
credentialRevocationStatus: credWithRevStatus?.revStatus,
linkNonce: combinedQueryData?.linkNonce ? BigInt(combinedQueryData.linkNonce) : undefined
});
zkpResponses.push(zkpRes);
}
return zkpResponses;
};
/**
* Processes zero knowledge proof requests.
*
* @param to - The identifier of the recipient.
* @param requests - An array of zero knowledge proof requests.
* @param from - The identifier of the sender.
* @param proofService - The proof service.
* @param opts - Additional options for processing the requests.
* @returns A promise that resolves to an array of zero knowledge proof responses.
*/
export const processProofAuth = async (
to: DID,
proofService: IProofService,
opts: {
supportedCircuits: CircuitId[];
acceptProfile?: AcceptProfile;
challenge?: bigint;
}
): Promise<AuthProofResponse> => {
if (!opts.acceptProfile) {
opts.acceptProfile = defaultAcceptProfile;
}
let authResponse: any;
// First version we only generate proof for ZKPMessage
if (opts.acceptProfile.env === MediaType.ZKPMessage) {
if (!opts.acceptProfile.circuits) {
throw new Error('Circuit not specified');
}
for (const circuitId of opts.acceptProfile.circuits) {
if (!opts.supportedCircuits.includes(circuitId as unknown as CircuitId)) {
throw new Error(`Circuit ${circuitId} is not supported`);
}
const authProof: ZeroKnowledgeProofAuth = {
circuitId: circuitId as unknown as CircuitId
};
const zkpRes: ZeroKnowledgeProofAuthResponse = await proofService.generateAuthProof(
authProof,
to,
{ challenge: opts.challenge, skipRevocation: true }
);
authResponse = {
authMethod: ('zk-' + circuitId) as string,
circuitId: authProof.circuitId,
proof: zkpRes.proof,
pub_signals: zkpRes.pub_signals
};
break;
}
}
return authResponse;
};
/**
* Verifies that the expires_time field of a message is not in the past. Throws an error if it is.
*
* @param message - Basic message to verify.
*/
export const verifyExpiresTime = (message: BasicMessage) => {
if (message?.expires_time && message.expires_time < getUnixTimestamp(new Date())) {
throw new Error('Message expired');
}
};