-
Notifications
You must be signed in to change notification settings - Fork 53
/
verify.ts
364 lines (334 loc) · 8.45 KB
/
verify.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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { defaultAbiCoder as abi } from "@ethersproject/abi";
import { internal as IDKitInternal } from "@worldcoin/idkit";
import { BigNumber, ethers } from "ethers";
import { CredentialType, IInternalError } from "src/lib/types";
import { ApolloClient, NormalizedCacheObject, gql } from "@apollo/client";
import { sequencerMapping } from "src/lib/utils";
import { logger } from "src/lib/logger";
// TODO: Pull router updated error codes from the ABI of the contract
const KNOWN_ERROR_CODES = [
{
rawCode: "0x504570e3",
rawMessage: "invalid root",
code: "invalid_merkle_root",
detail:
"The provided Merkle root is invalid. User appears to be unverified.",
},
{
rawCode: "0x09bde339",
rawMessage: "invalid proof",
code: "invalid_proof",
detail:
"The provided proof is invalid and it cannot be verified. Please check all inputs and try again.",
},
];
export interface IInputParams {
merkle_root: string;
signal: string;
nullifier_hash: string;
external_nullifier: string;
proof: string;
}
export interface IVerifyParams {
is_staging: boolean;
credential_type: CredentialType;
}
interface IAppAction {
app: {
id: string;
is_staging: true;
engine: string;
actions: {
id: string;
action: string;
status: string;
external_nullifier: string;
nullifiers: {
uses: number;
created_at: string;
nullifier_hash: string;
}[];
max_verifications: number;
}[];
}[];
}
const queryFetchAppAction = gql`
query FetchAppAction(
$app_id: String!
$action: String!
$nullifier_hash: String!
) {
app(
where: {
id: { _eq: $app_id }
status: { _eq: "active" }
is_archived: { _eq: false }
}
) {
id
is_staging
engine
actions(where: { action: { _eq: $action } }) {
id
action
max_verifications
external_nullifier
status
nullifiers(where: { nullifier_hash: { _eq: $nullifier_hash } }) {
uses
created_at
nullifier_hash
}
}
}
}
`;
function decodeProof(encodedProof: string) {
const binArray = abi.decode(["uint256[8]"], encodedProof)[0] as BigInt[];
const hexArray = binArray.map((item) =>
ethers.utils.hexlify(item as bigint).toString()
);
if (hexArray.length !== 8) {
throw new Error("Input array must have exactly 8 elements.");
}
return [
[hexArray[0], hexArray[1]],
[
[hexArray[2], hexArray[3]],
[hexArray[4], hexArray[5]],
],
[hexArray[6], hexArray[7]],
];
}
export const fetchActionForProof = async (
graphQLClient: ApolloClient<NormalizedCacheObject>,
app_id: string,
nullifier_hash: string,
action: string
) => {
const result = await graphQLClient.query<IAppAction>({
query: queryFetchAppAction,
variables: {
app_id,
nullifier_hash,
action,
},
});
if (!result.data.app.length) {
return {
error: {
message: "App not found. App may be no longer active.",
code: "not_found",
statusCode: 404,
},
};
}
const app = result.data.app[0];
if (!app.actions.length) {
return {
error: {
message: "Action not found.",
code: "invalid_action",
statusCode: 400,
attribute: "action",
},
};
}
if (app.engine !== "cloud") {
return {
error: {
message: "This action runs on-chain and can't be verified here.",
code: "invalid_engine",
statusCode: 400,
attribute: "engine",
},
};
}
return {
app: {
...app,
actions: undefined,
action: app.actions[0],
nullifier: app.actions[0]?.nullifiers?.[0],
},
};
};
/**
* Parses and validates the inputs to verify a proof
* @param body
* @param res
* @returns
*/
export const parseProofInputs = (params: IInputParams) => {
let proof,
nullifier_hash,
external_nullifier,
signal_hash,
merkle_root = null;
try {
proof = decodeProof(params.proof);
} catch (error) {
logger.error("Error decode proof", { error });
return {
error: {
message:
"This attribute is improperly formatted. Expected an ABI-encoded uint256[8].",
code: "invalid_format",
statusCode: 400,
attribute: "proof",
},
};
}
try {
nullifier_hash = (
abi.decode(["uint256"], params.nullifier_hash)[0] as BigNumber
).toHexString();
} catch (error) {
logger.error("Error create nullifier hash", { error });
return {
error: {
message:
"This attribute is improperly formatted. Expected an ABI-encoded uint256.",
code: "invalid_format",
statusCode: 400,
attribute: "nullifier_hash",
},
};
}
try {
merkle_root = (
abi.decode(["uint256"], params.merkle_root)[0] as BigNumber
).toHexString();
} catch (error) {
logger.error("Error create merkle root", { error });
return {
error: {
message:
"This attribute is improperly formatted. Expected an ABI-encoded uint256.",
code: "invalid_format",
statusCode: 400,
attribute: "merkle_root",
},
};
}
try {
external_nullifier = (
abi.decode(["uint256"], params.external_nullifier)[0] as BigNumber
).toHexString();
} catch (error) {
logger.error("Error create external nullifier", { error });
return {
error: {
message:
"This attribute is improperly formatted. Expected an ABI-encoded uint256.",
code: "invalid_format",
statusCode: 400,
attribute: "external_nullifier",
},
};
}
if (IDKitInternal.validateABILikeEncoding(params.signal)) {
try {
signal_hash = (
abi.decode(["uint256"], params.signal)[0] as BigNumber
).toHexString();
} catch (error) {
logger.error("Error create signal hash", { error });
return {
error: {
message:
"This attribute is improperly formatted. Expected an ABI-encoded uint256 or a string.",
code: "invalid_format",
statusCode: 400,
attribute: "signal",
},
};
}
} else {
signal_hash = BigNumber.from(
IDKitInternal.hashToField(params.signal).hash
).toHexString();
}
return {
params: {
proof,
nullifier_hash,
external_nullifier,
signal_hash,
merkle_root,
},
};
};
/**
* Verifies a ZKP with the World ID smart contract
*/
export const verifyProof = async (
proofParams: IInputParams,
verifyParams: IVerifyParams
): Promise<{
success?: true;
status?: string;
error?: IInternalError;
}> => {
// Parse the inputs
const parsed = parseProofInputs(proofParams);
if (parsed.error || !parsed.params) {
return { error: parsed.error };
}
const { params: parsedParams } = parsed;
// Query the signup sequencer to verify the proof
const body = JSON.stringify({
root: parsedParams.merkle_root,
nullifierHash: parsedParams.nullifier_hash,
externalNullifierHash: parsedParams.external_nullifier,
signalHash: parsedParams.signal_hash,
proof: parsedParams.proof,
});
const sequencerUrl =
sequencerMapping[verifyParams.credential_type]?.[
verifyParams.is_staging.toString()
];
const response = await fetch(`${sequencerUrl}/verifySemaphoreProof`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body,
});
if (!response.ok) {
try {
const rawErrorMessage = await response.text();
const knownError = KNOWN_ERROR_CODES.find(
({ rawMessage }) => rawMessage === rawErrorMessage
);
return {
error: {
message:
knownError?.detail ||
`We couldn't verify the provided proof (error code ${rawErrorMessage}).`,
code: knownError?.code || "invalid_proof",
statusCode: 400,
attribute: null,
},
};
} catch {
return {
error: {
message: "There was an internal issue verifying this proof.",
code: "internal_error",
statusCode: 500,
},
};
}
}
const result = await response.json();
const status = result.status === "mined" ? "on-chain" : "pending";
if (!status) {
console.error("Unexpected response received from sequencer.", {
result,
sequencerUrl,
});
throw new Error("Unexpected response received from sequencer.");
}
return { success: true, status };
};