@reclaimprotocol/attestor-core 5.0.1-beta.27 → 5.0.1-beta.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/browser/resources/attestor-browser.min.mjs +4513 -0
  2. package/browser/resources/attestor-browser.min.mjs.map +7 -0
  3. package/browser/resources/attestor-jsc.min.mjs +4511 -0
  4. package/lib/external-rpc/index.js +10400 -3
  5. package/lib/external-rpc/index.js.map +7 -0
  6. package/lib/index.js +8331 -11
  7. package/lib/index.js.map +7 -0
  8. package/package.json +9 -3
  9. package/lib/avs/abis/avsDirectoryABI.js +0 -340
  10. package/lib/avs/abis/delegationABI.js +0 -1
  11. package/lib/avs/abis/registryABI.js +0 -725
  12. package/lib/avs/client/create-claim-on-avs.js +0 -140
  13. package/lib/avs/config.js +0 -20
  14. package/lib/avs/contracts/ReclaimServiceManager.js +0 -1
  15. package/lib/avs/contracts/common.js +0 -1
  16. package/lib/avs/contracts/factories/ReclaimServiceManager__factory.js +0 -1166
  17. package/lib/avs/contracts/factories/index.js +0 -4
  18. package/lib/avs/contracts/index.js +0 -2
  19. package/lib/avs/types/index.js +0 -1
  20. package/lib/avs/utils/contracts.js +0 -33
  21. package/lib/avs/utils/register.js +0 -79
  22. package/lib/avs/utils/tasks.js +0 -41
  23. package/lib/client/create-claim.js +0 -432
  24. package/lib/client/index.js +0 -3
  25. package/lib/client/tunnels/make-rpc-tcp-tunnel.js +0 -51
  26. package/lib/client/tunnels/make-rpc-tls-tunnel.js +0 -131
  27. package/lib/client/utils/attestor-pool.js +0 -25
  28. package/lib/client/utils/client-socket.js +0 -97
  29. package/lib/client/utils/message-handler.js +0 -87
  30. package/lib/config/index.js +0 -44
  31. package/lib/external-rpc/benchmark.js +0 -69
  32. package/lib/external-rpc/event-bus.js +0 -14
  33. package/lib/external-rpc/handle-incoming-msg.js +0 -232
  34. package/lib/external-rpc/jsc-polyfills/1.js +0 -82
  35. package/lib/external-rpc/jsc-polyfills/2.js +0 -20
  36. package/lib/external-rpc/jsc-polyfills/event.js +0 -14
  37. package/lib/external-rpc/jsc-polyfills/index.js +0 -2
  38. package/lib/external-rpc/jsc-polyfills/ws.js +0 -81
  39. package/lib/external-rpc/setup-browser.js +0 -33
  40. package/lib/external-rpc/setup-jsc.js +0 -22
  41. package/lib/external-rpc/types.js +0 -1
  42. package/lib/external-rpc/utils.js +0 -100
  43. package/lib/external-rpc/zk.js +0 -63
  44. package/lib/mechain/abis/governanceABI.js +0 -458
  45. package/lib/mechain/abis/taskABI.js +0 -509
  46. package/lib/mechain/client/create-claim-on-mechain.js +0 -28
  47. package/lib/mechain/client/index.js +0 -1
  48. package/lib/mechain/constants/index.js +0 -3
  49. package/lib/mechain/index.js +0 -2
  50. package/lib/mechain/types/index.js +0 -1
  51. package/lib/proto/api.js +0 -4363
  52. package/lib/proto/tee-bundle.js +0 -1316
  53. package/lib/providers/http/index.js +0 -653
  54. package/lib/providers/http/patch-parse5-tree.js +0 -32
  55. package/lib/providers/http/utils.js +0 -324
  56. package/lib/providers/index.js +0 -4
  57. package/lib/server/create-server.js +0 -103
  58. package/lib/server/handlers/claimTeeBundle.js +0 -252
  59. package/lib/server/handlers/claimTunnel.js +0 -73
  60. package/lib/server/handlers/completeClaimOnChain.js +0 -24
  61. package/lib/server/handlers/createClaimOnChain.js +0 -26
  62. package/lib/server/handlers/createTaskOnMechain.js +0 -47
  63. package/lib/server/handlers/createTunnel.js +0 -93
  64. package/lib/server/handlers/disconnectTunnel.js +0 -5
  65. package/lib/server/handlers/fetchCertificateBytes.js +0 -41
  66. package/lib/server/handlers/index.js +0 -22
  67. package/lib/server/handlers/init.js +0 -32
  68. package/lib/server/handlers/toprf.js +0 -16
  69. package/lib/server/index.js +0 -4
  70. package/lib/server/socket.js +0 -109
  71. package/lib/server/tunnels/make-tcp-tunnel.js +0 -177
  72. package/lib/server/utils/apm.js +0 -36
  73. package/lib/server/utils/assert-valid-claim-request.js +0 -325
  74. package/lib/server/utils/config-env.js +0 -4
  75. package/lib/server/utils/dns.js +0 -18
  76. package/lib/server/utils/gcp-attestation.js +0 -289
  77. package/lib/server/utils/generics.js +0 -51
  78. package/lib/server/utils/iso.js +0 -256
  79. package/lib/server/utils/keep-alive.js +0 -38
  80. package/lib/server/utils/nitro-attestation.js +0 -324
  81. package/lib/server/utils/oprf-raw.js +0 -54
  82. package/lib/server/utils/process-handshake.js +0 -215
  83. package/lib/server/utils/proxy-session.js +0 -6
  84. package/lib/server/utils/tee-oprf-mpc-verification.js +0 -90
  85. package/lib/server/utils/tee-oprf-verification.js +0 -174
  86. package/lib/server/utils/tee-transcript-reconstruction.js +0 -187
  87. package/lib/server/utils/tee-verification.js +0 -421
  88. package/lib/server/utils/validation.js +0 -38
  89. package/lib/tls-exports.js +0 -5
  90. package/lib/types/bgp.js +0 -1
  91. package/lib/types/claims.js +0 -1
  92. package/lib/types/client.js +0 -1
  93. package/lib/types/general.js +0 -1
  94. package/lib/types/handlers.js +0 -1
  95. package/lib/types/index.js +0 -10
  96. package/lib/types/providers.gen.js +0 -10
  97. package/lib/types/providers.js +0 -1
  98. package/lib/types/rpc.js +0 -1
  99. package/lib/types/signatures.js +0 -1
  100. package/lib/types/tunnel.js +0 -1
  101. package/lib/types/zk.js +0 -1
  102. package/lib/utils/auth.js +0 -59
  103. package/lib/utils/b64-json.js +0 -17
  104. package/lib/utils/bgp-listener.js +0 -119
  105. package/lib/utils/claims.js +0 -98
  106. package/lib/utils/env.js +0 -15
  107. package/lib/utils/error.js +0 -50
  108. package/lib/utils/generics.js +0 -317
  109. package/lib/utils/http-parser.js +0 -246
  110. package/lib/utils/index.js +0 -13
  111. package/lib/utils/logger.js +0 -91
  112. package/lib/utils/prepare-packets.js +0 -71
  113. package/lib/utils/redactions.js +0 -177
  114. package/lib/utils/retries.js +0 -24
  115. package/lib/utils/signatures/eth.js +0 -32
  116. package/lib/utils/signatures/index.js +0 -7
  117. package/lib/utils/socket-base.js +0 -92
  118. package/lib/utils/tls.js +0 -58
  119. package/lib/utils/ws.js +0 -22
  120. package/lib/utils/zk.js +0 -585
package/lib/utils/zk.js DELETED
@@ -1,585 +0,0 @@
1
- import { concatenateUint8Arrays, crypto, generateIV } from '@reclaimprotocol/tls';
2
- import { ceilToBlockSizeMultiple, CONFIG as ZK_CONFIG, generateProof, getBlockSizeBytes, makeLocalFileFetch, makeRemoteFileFetch, verifyProof } from '@reclaimprotocol/zk-symmetric-crypto';
3
- import { makeGnarkOPRFOperator, makeGnarkZkOperator, } from '@reclaimprotocol/zk-symmetric-crypto/gnark';
4
- import { makeSnarkJsZKOperator } from '@reclaimprotocol/zk-symmetric-crypto/snarkjs';
5
- import { makeStwoZkOperator } from '@reclaimprotocol/zk-symmetric-crypto/stwo';
6
- import PQueue from 'p-queue';
7
- import { DEFAULT_REMOTE_FILE_FETCH_BASE_URL, DEFAULT_ZK_CONCURRENCY, TOPRF_DOMAIN_SEPARATOR } from "../config/index.js";
8
- import { ZKProofEngine } from "../proto/api.js";
9
- import { detectEnvironment, getEnvVariable } from "./env.js";
10
- import { AttestorError } from "./error.js";
11
- import { getPureCiphertext, getRecordIV, getZkAlgorithmForCipherSuite, isTls13Suite, strToUint8Array } from "./generics.js";
12
- import { logger as LOGGER } from "./logger.js";
13
- import { binaryHashToStr, isFullyRedacted, isRedactionCongruent, REDACTION_CHAR_CODE } from "./redactions.js";
14
- const ZK_CONCURRENCY = +(getEnvVariable('ZK_CONCURRENCY') || DEFAULT_ZK_CONCURRENCY);
15
- export async function makeZkProofGenerator({ zkOperators, oprfOperators, logger = LOGGER, zkProofConcurrency = ZK_CONCURRENCY, cipherSuite, zkEngine = 'snarkjs' }) {
16
- const zkQueue = new PQueue({ concurrency: zkProofConcurrency, autoStart: true });
17
- const packetsToProve = [];
18
- logger = logger.child({ module: 'zk', zkEngine });
19
- let zkProofsToGen = 0;
20
- return {
21
- /**
22
- * Adds the given packet to the list of packets to
23
- * generate ZK proofs for.
24
- *
25
- * Call `generateProofs()` to finally generate the proofs
26
- */
27
- async addPacketToProve(packet, { redactedPlaintext, toprfs = [], overshotToprfFromPrevBlock }, onGeneratedProofs, getNextPacket) {
28
- if (packet.type === 'plaintext') {
29
- throw new Error('Cannot generate proof for plaintext');
30
- }
31
- const alg = getZkAlgorithmForCipherSuite(cipherSuite);
32
- const chunkSizeBytes = getChunkSizeBytes(alg);
33
- const key = await crypto.exportKey(packet.encKey);
34
- const iv = packet.iv;
35
- const ciphertext = getPureCiphertext(packet.ciphertext, cipherSuite);
36
- // if the packet starts with TOPRF overflow from previous packet,
37
- // we can just redact that part of the ciphertext as it's not required
38
- // to be proven. Decrypting the raw ciphertext of this part would also
39
- // reveal the raw underlying text, which we don't want.
40
- if (overshotToprfFromPrevBlock) {
41
- redactedPlaintext.set(new Uint8Array(overshotToprfFromPrevBlock.length)
42
- .fill(REDACTION_CHAR_CODE));
43
- }
44
- const trueCiphertextLength = isTls13Suite(cipherSuite)
45
- ? ciphertext.length - 1 // remove content type byte
46
- : ciphertext.length;
47
- const packetToProve = {
48
- onGeneratedProofs,
49
- algorithm: alg,
50
- proofsToGenerate: [],
51
- toprfsToGenerate: [],
52
- iv: packet.fixedIv,
53
- };
54
- // first we'll handle all TOPRF blocks
55
- // we do these first, because they can span multiple chunks
56
- // & we need to be able to span the right chunks
57
- for (const toprf of toprfs) {
58
- // if the TOPRF data overshoots the ciphertext length,
59
- // then it means that the OPRF data is spread across multiple
60
- // TLS records & we need to include the next record's ciphertext
61
- // in our proof.
62
- // At most we support the OPRF data being spread across 2 records
63
- const toprfDistFromEnd = trueCiphertextLength
64
- - (toprf.dataLocation.fromIndex + toprf.dataLocation.length);
65
- if (toprfDistFromEnd < 0) {
66
- const nextPacket = getNextPacket();
67
- if (nextPacket?.type !== 'ciphertext') {
68
- throw new AttestorError('ERROR_INTERNAL', 'TOPRF data overshoots ciphertext length, '
69
- + 'but no next ciphertext packet found');
70
- }
71
- if (nextPacket.encKey !== packet.encKey) {
72
- throw new AttestorError('ERROR_INTERNAL', 'TOPRF data overshoots ciphertext length, '
73
- + 'but next packet has different encryption key');
74
- }
75
- const nextCiphertext = nextPacket.ciphertext
76
- .slice(0, Math.abs(toprfDistFromEnd));
77
- const iv = nextPacket.iv;
78
- toprf.overshoot = {
79
- ciphertext: nextCiphertext,
80
- iv,
81
- recordNumber: nextPacket.recordNumber,
82
- };
83
- }
84
- const fromIndex = getIdealOffsetForToprfBlock(alg, toprf);
85
- const toIndex = Math
86
- .min(fromIndex + chunkSizeBytes, ciphertext.length);
87
- // ensure this OPRF block doesn't overlap with any other OPRF block
88
- const slice = { fromIndex, toIndex };
89
- packetToProve.toprfsToGenerate.push(getTOPRFProofGenerationParamsForSlice({
90
- key,
91
- iv,
92
- ciphertext,
93
- slice,
94
- toprf: {
95
- ...toprf,
96
- dataLocation: {
97
- ...toprf.dataLocation,
98
- fromIndex: toprf.dataLocation.fromIndex - fromIndex
99
- }
100
- }
101
- }));
102
- zkProofsToGen += 1;
103
- // we'll redact the OPRF part of the plaintext to not reveal
104
- // the actual plaintext to the attestor
105
- const pktToIndex = Math.min(trueCiphertextLength, toprf.dataLocation.fromIndex + toprf.dataLocation.length);
106
- const pktFromIndex = toprf.dataLocation.fromIndex;
107
- for (let i = pktFromIndex; i < pktToIndex; i++) {
108
- redactedPlaintext[i] = REDACTION_CHAR_CODE;
109
- }
110
- }
111
- for (let i = 0; i < ciphertext.length; i += chunkSizeBytes) {
112
- const slice = {
113
- fromIndex: i,
114
- toIndex: Math.min(i + chunkSizeBytes, ciphertext.length)
115
- };
116
- const proofParams = getProofGenerationParamsForSlice({ key, iv, ciphertext, redactedPlaintext, slice });
117
- if (!proofParams) {
118
- continue;
119
- }
120
- packetToProve.proofsToGenerate.push(proofParams);
121
- zkProofsToGen += 1;
122
- }
123
- packetsToProve.push(packetToProve);
124
- },
125
- getTotalChunksToProve() {
126
- return zkProofsToGen;
127
- },
128
- async generateProofs(onChunkDone) {
129
- if (!packetsToProve.length) {
130
- return;
131
- }
132
- const start = Date.now();
133
- const tasks = [];
134
- for (const { onGeneratedProofs, algorithm, proofsToGenerate, toprfsToGenerate } of packetsToProve) {
135
- const proofs = [];
136
- const toprfs = [];
137
- let proofsLeft = proofsToGenerate.length
138
- + toprfsToGenerate.length;
139
- for (const proofToGen of proofsToGenerate) {
140
- tasks.push(zkQueue.add(async () => {
141
- const proof = await generateZkProofForChunk(algorithm, proofToGen);
142
- onChunkDone?.();
143
- proofs.push(proof);
144
- proofsLeft -= 1;
145
- if (proofsLeft === 0) {
146
- onGeneratedProofs(proofs, toprfs);
147
- }
148
- }, { throwOnTimeout: true }));
149
- }
150
- for (const toprfToGen of toprfsToGenerate) {
151
- tasks.push(zkQueue.add(async () => {
152
- const toprf = await generateOprfProofForChunk(algorithm, toprfToGen);
153
- onChunkDone?.();
154
- toprfs.push(toprf);
155
- proofsLeft -= 1;
156
- if (proofsLeft === 0) {
157
- onGeneratedProofs(proofs, toprfs);
158
- }
159
- }, { throwOnTimeout: true }));
160
- }
161
- }
162
- await Promise.all(tasks);
163
- logger?.info({ durationMs: Date.now() - start, zkProofsToGen }, 'generated ZK proofs');
164
- // reset the packets to prove
165
- packetsToProve.splice(0, packetsToProve.length);
166
- zkProofsToGen = 0;
167
- // release ZK resources to free up memory
168
- const alg = getZkAlgorithmForCipherSuite(cipherSuite);
169
- const zkOperator = await getZkOperatorForAlgorithm(alg);
170
- zkOperator.release?.();
171
- },
172
- };
173
- async function generateZkProofForChunk(algorithm, { startIdx, redactedPlaintext, privateInput, publicInput }) {
174
- const operator = getZkOperatorForAlgorithm(algorithm);
175
- const proof = await generateProof({ algorithm, privateInput, publicInput, operator, logger });
176
- logger?.debug({ startIdx }, 'generated proof for chunk');
177
- return {
178
- proofData: typeof proof.proofData === 'string'
179
- ? strToUint8Array(proof.proofData)
180
- : proof.proofData,
181
- decryptedRedactedCiphertext: proof.plaintext || new Uint8Array(),
182
- redactedPlaintext,
183
- startIdx
184
- };
185
- }
186
- async function generateOprfProofForChunk(algorithm, { startIdx, privateInput, publicInput, toprf }) {
187
- const operator = getOprfOperatorForAlgorithm(algorithm);
188
- const toprfLocations = [];
189
- if (toprf?.overshoot) {
190
- const { dataLocation, overshoot: { ciphertext } } = toprf;
191
- toprfLocations.push({
192
- pos: dataLocation.fromIndex,
193
- len: dataLocation.length - ciphertext.length
194
- }, {
195
- pos: ceilToBlockSizeMultiple(dataLocation.fromIndex + dataLocation.length, algorithm),
196
- len: ciphertext.length
197
- });
198
- }
199
- else if (toprf) {
200
- toprfLocations.push({
201
- pos: toprf.dataLocation.fromIndex,
202
- len: toprf.dataLocation.length,
203
- });
204
- }
205
- const proof = await generateProof({
206
- algorithm,
207
- privateInput,
208
- publicInput,
209
- operator,
210
- logger,
211
- ...(toprf
212
- ? {
213
- toprf: {
214
- locations: toprfLocations,
215
- output: toprf.nullifier,
216
- responses: toprf.responses,
217
- domainSeparator: TOPRF_DOMAIN_SEPARATOR
218
- },
219
- mask: toprf.mask,
220
- }
221
- : {})
222
- });
223
- logger?.debug({ toprfLocations }, 'generated TOPRF proof for chunk');
224
- return {
225
- startIdx,
226
- proofData: typeof proof.proofData === 'string'
227
- ? strToUint8Array(proof.proofData)
228
- : proof.proofData,
229
- payload: toprf,
230
- };
231
- }
232
- function getZkOperatorForAlgorithm(algorithm) {
233
- return zkOperators?.[algorithm]
234
- || makeDefaultZkOperator(algorithm, zkEngine, logger);
235
- }
236
- function getOprfOperatorForAlgorithm(algorithm) {
237
- return oprfOperators?.[algorithm]
238
- || makeDefaultOPRFOperator(algorithm, zkEngine, logger);
239
- }
240
- }
241
- /**
242
- * Verify the given ZK proof
243
- */
244
- export async function verifyZkPacket({ cipherSuite, ciphertext, zkReveal, zkOperators, oprfOperators, logger = LOGGER, zkEngine = 'snarkjs', iv, recordNumber, toprfOvershotNullifier, getNextPacket }) {
245
- const { proofs, toprfs, oprfRawMarkers } = zkReveal;
246
- const algorithm = getZkAlgorithmForCipherSuite(cipherSuite);
247
- const recordIV = getRecordIV(ciphertext, cipherSuite);
248
- ciphertext = new Uint8Array(getPureCiphertext(ciphertext, cipherSuite));
249
- const realRedactedPlaintext = new Uint8Array(ciphertext.length).fill(REDACTION_CHAR_CODE);
250
- const replacements = await Promise.all(toprfs.map(async (toprf, i) => {
251
- try {
252
- return await verifyToprfProofPacket(toprf);
253
- }
254
- catch (e) {
255
- e.message += ` (TOPRF proof ${i}, `
256
- + `from ${toprf.payload?.dataLocation?.fromIndex}, `
257
- + `record ${recordNumber})`;
258
- throw e;
259
- }
260
- }));
261
- await Promise.all(proofs.map(async (proof, i) => {
262
- try {
263
- await verifyZkProofPacket(proof);
264
- }
265
- catch (e) {
266
- e.message +=
267
- ` (ZK proof ${i}, startIdx ${proof.startIdx}, record ${recordNumber})`;
268
- throw e;
269
- }
270
- }));
271
- for (const { set, startIdx } of replacements) {
272
- realRedactedPlaintext.set(set, startIdx);
273
- }
274
- /**
275
- * to verify if the user has given us the correct redacted plaintext,
276
- * and isn't providing plaintext that they haven't proven they have
277
- * we start with a fully redacted plaintext, and then replace the
278
- * redacted parts with the plaintext that the user has provided
279
- * in the proofs
280
- */
281
- if (toprfOvershotNullifier) {
282
- realRedactedPlaintext.set(toprfOvershotNullifier);
283
- }
284
- return { redactedPlaintext: realRedactedPlaintext, oprfRawMarkers };
285
- async function verifyZkProofPacket({ proofData, decryptedRedactedCiphertext, redactedPlaintext, startIdx, }) {
286
- // get the ciphertext chunk we received from the server
287
- // the ZK library, will verify that the decrypted redacted
288
- // ciphertext matches the ciphertext received from the server
289
- const ciphertextChunkEnd = startIdx + redactedPlaintext.length;
290
- const ciphertextChunk = ciphertext.slice(startIdx, ciphertextChunkEnd);
291
- // redact ciphertext if plaintext is redacted
292
- // to prepare for decryption in ZK circuit
293
- // the ZK circuit will take in the redacted ciphertext,
294
- // which shall produce the redacted plaintext
295
- for (let i = 0; i < ciphertextChunk.length; i++) {
296
- if (redactedPlaintext[i] === REDACTION_CHAR_CODE) {
297
- ciphertextChunk[i] = REDACTION_CHAR_CODE;
298
- }
299
- }
300
- let nonce = concatenateUint8Arrays([iv, recordIV]);
301
- if (!recordIV.length) {
302
- nonce = generateIV(nonce, recordNumber);
303
- }
304
- const ciphertextInput = {
305
- ciphertext: ciphertextChunk,
306
- iv: nonce,
307
- offsetBytes: startIdx
308
- };
309
- if (!isRedactionCongruent(redactedPlaintext, decryptedRedactedCiphertext)) {
310
- throw new Error('redacted ciphertext not congruent');
311
- }
312
- await verifyProof({
313
- proof: {
314
- algorithm,
315
- proofData: proofData,
316
- plaintext: decryptedRedactedCiphertext,
317
- },
318
- publicInput: ciphertextInput,
319
- logger,
320
- operator: getZkOperator()
321
- });
322
- logger?.debug({ startIdx, endIdx: startIdx + redactedPlaintext.length }, 'verified proof');
323
- realRedactedPlaintext.set(redactedPlaintext, startIdx);
324
- }
325
- async function verifyToprfProofPacket({ startIdx, proofData, payload: toprf }) {
326
- if (!toprf?.dataLocation || !toprf.responses || !toprf.nullifier) {
327
- throw new Error('invalid TOPRF proof payload');
328
- }
329
- const { dataLocation, nullifier } = toprf;
330
- const ciphertextChunkEnd = Math
331
- .min(ciphertext.length, getChunkSizeBytes(algorithm) + startIdx);
332
- const isLastChunk = ciphertextChunkEnd >= ciphertext.length;
333
- const ciphertextChunk = ciphertext.slice(startIdx, ciphertextChunkEnd);
334
- let nonce = concatenateUint8Arrays([iv, recordIV]);
335
- if (!recordIV.length) {
336
- nonce = generateIV(nonce, recordNumber);
337
- }
338
- const ciphertextInput = {
339
- ciphertext: ciphertextChunk,
340
- iv: nonce,
341
- offsetBytes: startIdx
342
- };
343
- let pubInput = ciphertextInput;
344
- const nulliferStr = binaryHashToStr(nullifier, dataLocation.length);
345
- const locations = [];
346
- const toprfEndIdx = dataLocation.fromIndex + dataLocation.length;
347
- const trueCiphLen = isLastChunk && isTls13Suite(cipherSuite)
348
- ? ciphertextChunk.length - 1
349
- : ciphertextChunk.length;
350
- const overshoot = toprfEndIdx - trueCiphLen;
351
- if (overshoot > 0) {
352
- // fetch the overshoot part of the nullifier
353
- const nextPkt = getNextPacket(strToUint8Array(nulliferStr.slice(dataLocation.length - overshoot)));
354
- if (!nextPkt) {
355
- throw new Error('OPRF data overshot, but no next packet found');
356
- }
357
- const nextRecordIV = getRecordIV(ciphertext, cipherSuite);
358
- let nextNonce = concatenateUint8Arrays([iv, nextRecordIV]);
359
- if (!nextRecordIV.length) {
360
- nextNonce = generateIV(nextNonce, recordNumber + 1);
361
- }
362
- pubInput = [
363
- ciphertextInput,
364
- {
365
- ciphertext: nextPkt.slice(0, overshoot),
366
- iv: nextNonce,
367
- offsetBytes: 0,
368
- }
369
- ];
370
- locations.push({
371
- pos: dataLocation.fromIndex,
372
- len: dataLocation.length - overshoot
373
- }, {
374
- pos: ceilToBlockSizeMultiple(dataLocation.fromIndex + dataLocation.length, algorithm),
375
- len: overshoot
376
- });
377
- }
378
- else {
379
- locations.push({
380
- pos: dataLocation.fromIndex,
381
- len: dataLocation.length,
382
- });
383
- }
384
- await verifyProof({
385
- proof: { algorithm, proofData: proofData, plaintext: undefined },
386
- publicInput: pubInput,
387
- logger,
388
- operator: getOprfOperator(),
389
- toprf: {
390
- locations,
391
- domainSeparator: TOPRF_DOMAIN_SEPARATOR,
392
- output: nullifier,
393
- responses: toprf.responses,
394
- }
395
- });
396
- logger?.debug({ locations }, 'verified TOPRF proof');
397
- return {
398
- set: strToUint8Array(nulliferStr.slice(0, locations[0].len)),
399
- startIdx: locations[0].pos + startIdx,
400
- };
401
- }
402
- function getZkOperator() {
403
- return zkOperators?.[algorithm]
404
- || makeDefaultZkOperator(algorithm, zkEngine, logger);
405
- }
406
- function getOprfOperator() {
407
- return oprfOperators?.[algorithm]
408
- || makeDefaultOPRFOperator(algorithm, zkEngine, logger);
409
- }
410
- }
411
- // the chunk size of the ZK circuit in bytes
412
- // this will be >= the block size
413
- function getChunkSizeBytes(alg) {
414
- const { chunkSize, bitsPerWord } = ZK_CONFIG[alg];
415
- return chunkSize * bitsPerWord / 8;
416
- }
417
- const zkEngines = {};
418
- const oprfEngines = {};
419
- const operatorMakers = {
420
- 'snarkjs': makeSnarkJsZKOperator,
421
- 'gnark': makeGnarkZkOperator,
422
- 'stwo': makeStwoZkOperator,
423
- };
424
- const OPRF_OPERATOR_MAKERS = {
425
- 'gnark': makeGnarkOPRFOperator
426
- };
427
- export function makeDefaultZkOperator(algorithm, zkEngine, logger) {
428
- let zkOperators = zkEngines[zkEngine];
429
- if (!zkOperators) {
430
- zkEngines[zkEngine] = {};
431
- zkOperators = zkEngines[zkEngine];
432
- }
433
- if (!zkOperators[algorithm]) {
434
- const opType = getOperatorType();
435
- const zkBaseUrl = opType === 'remote' ? getZkResourcesBaseUrl() : undefined;
436
- logger?.info({ type: opType, algorithm, zkBaseUrl }, 'fetching zk operator');
437
- const fetcher = opType === 'local'
438
- ? makeLocalFileFetch()
439
- : makeRemoteFileFetch({ baseUrl: zkBaseUrl, logger });
440
- const maker = operatorMakers[zkEngine];
441
- if (!maker) {
442
- throw new Error(`No ZK operator maker for ${zkEngine}`);
443
- }
444
- zkOperators[algorithm] = maker({ algorithm, fetcher });
445
- }
446
- return zkOperators[algorithm];
447
- }
448
- function getOperatorType() {
449
- const envop = getEnvVariable('ZK_OPERATOR_TYPE');
450
- if (envop === 'local' || envop === 'remote') {
451
- return envop;
452
- }
453
- return detectEnvironment() === 'node' ? 'local' : 'remote';
454
- }
455
- export function makeDefaultOPRFOperator(algorithm, zkEngine, logger) {
456
- let operators = oprfEngines[zkEngine];
457
- if (!operators) {
458
- oprfEngines[zkEngine] = {};
459
- operators = oprfEngines[zkEngine];
460
- }
461
- if (!operators[algorithm]) {
462
- const type = getOperatorType();
463
- const zkBaseUrl = type === 'remote' ? getZkResourcesBaseUrl() : undefined;
464
- logger?.info({ type, algorithm, zkBaseUrl }, 'fetching oprf operator');
465
- const fetcher = type === 'local'
466
- ? makeLocalFileFetch()
467
- : makeRemoteFileFetch({ baseUrl: zkBaseUrl, logger });
468
- const maker = OPRF_OPERATOR_MAKERS[zkEngine];
469
- if (!maker) {
470
- throw new Error(`No OPRF operator maker for ${zkEngine}`);
471
- }
472
- operators[algorithm] = maker({ algorithm, fetcher });
473
- }
474
- return operators[algorithm];
475
- }
476
- export function getEngineString(engine) {
477
- if (engine === ZKProofEngine.ZK_ENGINE_GNARK) {
478
- return 'gnark';
479
- }
480
- if (engine === ZKProofEngine.ZK_ENGINE_SNARKJS) {
481
- return 'snarkjs';
482
- }
483
- if (engine === ZKProofEngine.ZK_ENGINE_STWO) {
484
- return 'stwo';
485
- }
486
- throw new Error(`Unknown ZK engine: ${engine}`);
487
- }
488
- export function getEngineProto(engine) {
489
- if (engine === 'gnark') {
490
- return ZKProofEngine.ZK_ENGINE_GNARK;
491
- }
492
- if (engine === 'snarkjs') {
493
- return ZKProofEngine.ZK_ENGINE_SNARKJS;
494
- }
495
- if (engine === 'stwo') {
496
- return ZKProofEngine.ZK_ENGINE_STWO;
497
- }
498
- throw new Error(`Unknown ZK engine: ${engine}`);
499
- }
500
- function getProofGenerationParamsForSlice({ key, iv, ciphertext, redactedPlaintext, slice: { fromIndex, toIndex }, }) {
501
- const ciphertextChunk = ciphertext.slice(fromIndex, toIndex);
502
- const plaintextChunk = redactedPlaintext.slice(fromIndex, toIndex);
503
- if (isFullyRedacted(plaintextChunk)) {
504
- return;
505
- }
506
- // redact ciphertext if plaintext is redacted
507
- // to prepare for decryption in ZK circuit
508
- // the ZK circuit will take in the redacted ciphertext,
509
- // which shall produce the redacted plaintext
510
- for (let i = 0; i < ciphertextChunk.length; i++) {
511
- if (plaintextChunk[i] === REDACTION_CHAR_CODE) {
512
- ciphertextChunk[i] = REDACTION_CHAR_CODE;
513
- }
514
- }
515
- return {
516
- startIdx: fromIndex,
517
- redactedPlaintext: plaintextChunk,
518
- privateInput: { key },
519
- publicInput: { ciphertext: ciphertextChunk, iv, offsetBytes: fromIndex },
520
- };
521
- }
522
- function getTOPRFProofGenerationParamsForSlice({ key, iv, ciphertext, slice: { fromIndex, toIndex }, toprf, }) {
523
- const ciphertextChunk = ciphertext.slice(fromIndex, toIndex);
524
- if (toprf?.overshoot) {
525
- const { overshoot: { ciphertext: overshootCiphertext, iv: overshootIv } } = toprf;
526
- return {
527
- privateInput: { key },
528
- publicInput: [
529
- {
530
- ciphertext: ciphertextChunk,
531
- iv,
532
- offsetBytes: fromIndex,
533
- },
534
- { ciphertext: overshootCiphertext, iv: overshootIv }
535
- ],
536
- toprf,
537
- startIdx: fromIndex,
538
- };
539
- }
540
- return {
541
- privateInput: { key },
542
- publicInput: { ciphertext: ciphertextChunk, iv, offsetBytes: fromIndex },
543
- toprf,
544
- startIdx: fromIndex,
545
- };
546
- }
547
- /**
548
- * Get the ideal location to generate a ZK proof for a TOPRF block.
549
- * Ideally it should be put into a slice that's a divisor of the chunk size,
550
- * as that'll minimize the number of proofs that need to be generated.
551
- * @returns the offset in bytes
552
- */
553
- function getIdealOffsetForToprfBlock(alg, { dataLocation, overshoot }) {
554
- const chunkSizeBytes = getChunkSizeBytes(alg);
555
- const blockSizeBytes = getBlockSizeBytes(alg);
556
- const offsetChunks = Math
557
- .floor(dataLocation.fromIndex / chunkSizeBytes);
558
- const endOffsetChunks = Math
559
- .floor((dataLocation.fromIndex + dataLocation.length) / chunkSizeBytes);
560
- // happy case -- the OPRF block fits into a single chunk, that's a
561
- // divisor of the chunk size
562
- if (endOffsetChunks === offsetChunks) {
563
- const start = offsetChunks * chunkSizeBytes;
564
- if (overshoot) {
565
- const overshootBlocks = Math
566
- .ceil(overshoot.ciphertext.length / blockSizeBytes);
567
- return start + (overshootBlocks * blockSizeBytes);
568
- }
569
- return start;
570
- }
571
- const offsetBytes = Math
572
- .floor(dataLocation.fromIndex / blockSizeBytes) * blockSizeBytes;
573
- const endOffsetBytes = Math
574
- .ceil((dataLocation.fromIndex + dataLocation.length) / blockSizeBytes);
575
- if (endOffsetBytes - offsetBytes > chunkSizeBytes) {
576
- throw new AttestorError('ERROR_BAD_REQUEST', 'OPRF data cannot fit into a single chunk');
577
- }
578
- return offsetBytes;
579
- }
580
- function getZkResourcesBaseUrl() {
581
- if (typeof ATTESTOR_BASE_URL !== 'string') {
582
- return DEFAULT_REMOTE_FILE_FETCH_BASE_URL;
583
- }
584
- return new URL(DEFAULT_REMOTE_FILE_FETCH_BASE_URL, ATTESTOR_BASE_URL).toString();
585
- }