@devtion/actions 0.0.0-7e983e3

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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -0
  3. package/dist/index.mjs +2608 -0
  4. package/dist/index.node.js +2714 -0
  5. package/dist/types/hardhat.config.d.ts +6 -0
  6. package/dist/types/hardhat.config.d.ts.map +1 -0
  7. package/dist/types/src/helpers/authentication.d.ts +21 -0
  8. package/dist/types/src/helpers/authentication.d.ts.map +1 -0
  9. package/dist/types/src/helpers/constants.d.ts +194 -0
  10. package/dist/types/src/helpers/constants.d.ts.map +1 -0
  11. package/dist/types/src/helpers/contracts.d.ts +57 -0
  12. package/dist/types/src/helpers/contracts.d.ts.map +1 -0
  13. package/dist/types/src/helpers/crypto.d.ts +27 -0
  14. package/dist/types/src/helpers/crypto.d.ts.map +1 -0
  15. package/dist/types/src/helpers/database.d.ts +105 -0
  16. package/dist/types/src/helpers/database.d.ts.map +1 -0
  17. package/dist/types/src/helpers/functions.d.ts +145 -0
  18. package/dist/types/src/helpers/functions.d.ts.map +1 -0
  19. package/dist/types/src/helpers/security.d.ts +10 -0
  20. package/dist/types/src/helpers/security.d.ts.map +1 -0
  21. package/dist/types/src/helpers/services.d.ts +38 -0
  22. package/dist/types/src/helpers/services.d.ts.map +1 -0
  23. package/dist/types/src/helpers/storage.d.ts +121 -0
  24. package/dist/types/src/helpers/storage.d.ts.map +1 -0
  25. package/dist/types/src/helpers/tasks.d.ts +2 -0
  26. package/dist/types/src/helpers/tasks.d.ts.map +1 -0
  27. package/dist/types/src/helpers/utils.d.ts +139 -0
  28. package/dist/types/src/helpers/utils.d.ts.map +1 -0
  29. package/dist/types/src/helpers/verification.d.ts +95 -0
  30. package/dist/types/src/helpers/verification.d.ts.map +1 -0
  31. package/dist/types/src/helpers/vm.d.ts +112 -0
  32. package/dist/types/src/helpers/vm.d.ts.map +1 -0
  33. package/dist/types/src/index.d.ts +15 -0
  34. package/dist/types/src/index.d.ts.map +1 -0
  35. package/dist/types/src/types/enums.d.ts +133 -0
  36. package/dist/types/src/types/enums.d.ts.map +1 -0
  37. package/dist/types/src/types/index.d.ts +603 -0
  38. package/dist/types/src/types/index.d.ts.map +1 -0
  39. package/package.json +87 -0
  40. package/src/helpers/authentication.ts +37 -0
  41. package/src/helpers/constants.ts +312 -0
  42. package/src/helpers/contracts.ts +268 -0
  43. package/src/helpers/crypto.ts +55 -0
  44. package/src/helpers/database.ts +221 -0
  45. package/src/helpers/functions.ts +438 -0
  46. package/src/helpers/security.ts +86 -0
  47. package/src/helpers/services.ts +83 -0
  48. package/src/helpers/storage.ts +329 -0
  49. package/src/helpers/tasks.ts +56 -0
  50. package/src/helpers/utils.ts +743 -0
  51. package/src/helpers/verification.ts +354 -0
  52. package/src/helpers/vm.ts +392 -0
  53. package/src/index.ts +162 -0
  54. package/src/types/enums.ts +141 -0
  55. package/src/types/index.ts +650 -0
@@ -0,0 +1,743 @@
1
+ import { Firestore } from "firebase/firestore"
2
+ import fs, { ReadPosition } from "fs"
3
+ import { utils as ffUtils } from "ffjavascript"
4
+ import winston, { Logger } from "winston"
5
+ import { S3Client, GetObjectCommand, HeadObjectCommand } from "@aws-sdk/client-s3"
6
+ import {
7
+ CircuitMetadata,
8
+ Contribution,
9
+ CircuitDocument,
10
+ CircuitInputData,
11
+ ContributionValidity,
12
+ FirebaseDocumentInfo,
13
+ SetupCeremonyData,
14
+ CeremonySetupTemplate,
15
+ CeremonySetupTemplateCircuitArtifacts,
16
+ } from "../types/index"
17
+ import { finalContributionIndex, genesisZkeyIndex, potFilenameTemplate } from "./constants"
18
+ import {
19
+ getCircuitContributionsFromContributor,
20
+ getDocumentById,
21
+ getCircuitsCollectionPath,
22
+ getContributionsCollectionPath
23
+ } from "./database"
24
+ import { CeremonyTimeoutType } from "../types/enums"
25
+ import {
26
+ getPotStorageFilePath,
27
+ getR1csStorageFilePath,
28
+ getWasmStorageFilePath,
29
+ getZkeyStorageFilePath
30
+ } from "./storage"
31
+ import { blake512FromPath } from "./crypto"
32
+ import { Readable, pipeline } from "stream"
33
+ import { promisify } from "util"
34
+
35
+ /**
36
+ * Parse and validate that the ceremony configuration is correct
37
+ * @notice this does not upload any files to storage
38
+ * @param path <string> - the path to the configuration file
39
+ * @param cleanup <boolean> - whether to delete the r1cs file after parsing
40
+ * @returns any - the data to pass to the cloud function for setup and the circuit artifacts
41
+ */
42
+ export const parseCeremonyFile = async (path: string, cleanup: boolean = false): Promise<SetupCeremonyData> => {
43
+ // check that the path exists
44
+ if (!fs.existsSync(path)) throw new Error("The provided path to the configuration file does not exist. Please provide an absolute path and try again.")
45
+
46
+ try {
47
+ // read the data
48
+ const data: CeremonySetupTemplate = JSON.parse(fs.readFileSync(path).toString())
49
+
50
+ // verify that the data is correct
51
+ if (data['timeoutMechanismType'] !== CeremonyTimeoutType.DYNAMIC && data['timeoutMechanismType'] !== CeremonyTimeoutType.FIXED)
52
+ throw new Error("Invalid timeout type. Please choose between DYNAMIC and FIXED.")
53
+
54
+ // validate that we have at least 1 circuit input data
55
+ if (!data.circuits || data.circuits.length === 0)
56
+ throw new Error("You need to provide the data for at least 1 circuit.")
57
+
58
+ // validate that the end date is in the future
59
+ let endDate: Date
60
+ let startDate: Date
61
+ try {
62
+ endDate = new Date(data.endDate)
63
+ startDate = new Date(data.startDate)
64
+ } catch (error: any) {
65
+ throw new Error("The dates should follow this format: 2023-07-04T00:00:00.")
66
+ }
67
+
68
+ if (endDate <= startDate) throw new Error("The end date should be greater than the start date.")
69
+
70
+ const currentDate = new Date()
71
+
72
+ if (endDate <= currentDate || startDate <= currentDate)
73
+ throw new Error("The start and end dates should be in the future.")
74
+
75
+ // validate penalty
76
+ if (data.penalty <= 0) throw new Error("The penalty should be greater than zero.")
77
+
78
+ const circuits: CircuitDocument[] = []
79
+ const urlPattern = /(https?:\/\/[^\s]+)/g
80
+ const commitHashPattern = /^[a-f0-9]{40}$/i
81
+
82
+ const circuitArtifacts: CeremonySetupTemplateCircuitArtifacts[] = []
83
+
84
+ for (let i = 0; i < data.circuits.length; i++) {
85
+ const circuitData = data.circuits[i]
86
+ const artifacts = circuitData.artifacts
87
+ circuitArtifacts.push({
88
+ artifacts: artifacts
89
+ })
90
+ const r1csPath = artifacts.r1csStoragePath
91
+ const wasmPath = artifacts.wasmStoragePath
92
+
93
+ // where we storing the r1cs downloaded
94
+ const localR1csPath = `./${circuitData.name}.r1cs`
95
+
96
+ // check that the artifacts exist in S3
97
+ // we don't need any privileges to download this
98
+ // just the correct region
99
+ const s3 = new S3Client({region: artifacts.region})
100
+
101
+ try {
102
+ await s3.send(new HeadObjectCommand({
103
+ Bucket: artifacts.bucket,
104
+ Key: r1csPath
105
+ }))
106
+ } catch (error: any) {
107
+ throw new Error(`The r1cs file (${r1csPath}) seems to not exist. Please ensure this is correct and that the object is publicly available.`)
108
+ }
109
+
110
+ try {
111
+ await s3.send(new HeadObjectCommand({
112
+ Bucket: artifacts.bucket,
113
+ Key: wasmPath
114
+ }))
115
+ } catch (error: any) {
116
+ throw new Error(`The wasm file (${wasmPath}) seems to not exist. Please ensure this is correct and that the object is publicly available.`)
117
+ }
118
+
119
+ // download the r1cs to extract the metadata
120
+ const command = new GetObjectCommand({ Bucket: artifacts.bucket, Key: artifacts.r1csStoragePath })
121
+ const response = await s3.send(command)
122
+ const streamPipeline = promisify(pipeline)
123
+
124
+ if (response.$metadata.httpStatusCode !== 200)
125
+ throw new Error("There was an error while trying to download the r1cs file. Please check that the file has the correct permissions (public) set.")
126
+
127
+ if (response.Body instanceof Readable)
128
+ await streamPipeline(response.Body, fs.createWriteStream(localR1csPath))
129
+
130
+ // extract the metadata from the r1cs
131
+ const metadata = getR1CSInfo(localR1csPath)
132
+
133
+ // validate that the circuit hash and template links are valid
134
+ const template = circuitData.template
135
+
136
+ const URLMatch = template.source.match(urlPattern)
137
+ if (!URLMatch || URLMatch.length === 0 || URLMatch.length > 1) throw new Error("You should provide the URL to the circuits templates on GitHub.")
138
+
139
+ const hashMatch = template.commitHash.match(commitHashPattern)
140
+ if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1) throw new Error("You should provide a valid commit hash of the circuit templates.")
141
+
142
+ // calculate the hash of the r1cs file
143
+ const r1csBlake2bHash = await blake512FromPath(localR1csPath)
144
+
145
+ const circuitPrefix = extractPrefix(circuitData.name)
146
+
147
+ // filenames
148
+ const doubleDigitsPowers = convertToDoubleDigits(metadata.pot!)
149
+ const r1csCompleteFilename = `${circuitData.name}.r1cs`
150
+ const wasmCompleteFilename = `${circuitData.name}.wasm`
151
+ const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`
152
+ const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`
153
+
154
+ // storage paths
155
+ const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename)
156
+ const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename)
157
+ const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit)
158
+ const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename)
159
+
160
+ const files: any = {
161
+ potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
162
+ r1csFilename: r1csCompleteFilename,
163
+ wasmFilename: wasmCompleteFilename,
164
+ initialZkeyFilename: firstZkeyCompleteFilename,
165
+ potStoragePath: potStorageFilePath,
166
+ r1csStoragePath: r1csStorageFilePath,
167
+ wasmStoragePath: wasmStorageFilePath,
168
+ initialZkeyStoragePath: zkeyStorageFilePath,
169
+ r1csBlake2bHash: r1csBlake2bHash
170
+ }
171
+
172
+ // validate that the compiler hash is a valid hash
173
+ const compiler = circuitData.compiler
174
+ const compilerHashMatch = compiler.commitHash.match(commitHashPattern)
175
+ if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1) throw new Error("You should provide a valid commit hash of the circuit compiler.")
176
+
177
+ // validate that the verification options are valid
178
+ const verification = circuitData.verification
179
+ if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
180
+ throw new Error("Please enter a valid verification mechanism: either CF or VM")
181
+
182
+ // @todo VM parameters verification
183
+ // if (verification['cfOrVM'] === "VM") {}
184
+
185
+ // check that the timeout is provided for the correct configuration
186
+ let dynamicThreshold: number | undefined
187
+ let fixedTimeWindow: number | undefined
188
+
189
+ let circuit: CircuitDocument | CircuitInputData = {} as CircuitDocument | CircuitInputData
190
+
191
+ if (data.timeoutMechanismType === CeremonyTimeoutType.DYNAMIC) {
192
+ if (circuitData.dynamicThreshold <= 0)
193
+ throw new Error("The dynamic threshold should be > 0.")
194
+ dynamicThreshold = circuitData.dynamicThreshold
195
+
196
+ // the Circuit data for the ceremony setup
197
+ circuit = {
198
+ name: circuitData.name,
199
+ description: circuitData.description,
200
+ prefix: circuitPrefix,
201
+ sequencePosition: i+1,
202
+ metadata: metadata,
203
+ files: files,
204
+ template: template,
205
+ compiler: compiler,
206
+ verification: verification,
207
+ dynamicThreshold: dynamicThreshold,
208
+ avgTimings: {
209
+ contributionComputation: 0,
210
+ fullContribution: 0,
211
+ verifyCloudFunction: 0
212
+ },
213
+
214
+ }
215
+ }
216
+
217
+ if (data.timeoutMechanismType === CeremonyTimeoutType.FIXED) {
218
+ if (circuitData.fixedTimeWindow <= 0)
219
+ throw new Error("The fixed time window threshold should be > 0.")
220
+ fixedTimeWindow = circuitData.fixedTimeWindow
221
+
222
+
223
+ // the Circuit data for the ceremony setup
224
+ circuit = {
225
+ name: circuitData.name,
226
+ description: circuitData.description,
227
+ prefix: circuitPrefix,
228
+ sequencePosition: i+1,
229
+ metadata: metadata,
230
+ files: files,
231
+ template: template,
232
+ compiler: compiler,
233
+ verification: verification,
234
+ fixedTimeWindow: fixedTimeWindow,
235
+ avgTimings: {
236
+ contributionComputation: 0,
237
+ fullContribution: 0,
238
+ verifyCloudFunction: 0
239
+ },
240
+
241
+ }
242
+ }
243
+
244
+
245
+ circuits.push(circuit)
246
+
247
+ // remove the local r1cs download (if used for verifying the config only vs setup)
248
+ if (cleanup) fs.unlinkSync(localR1csPath)
249
+ }
250
+
251
+ const setupData: SetupCeremonyData = {
252
+ ceremonyInputData: {
253
+ title: data.title,
254
+ description: data.description,
255
+ startDate: startDate.valueOf(),
256
+ endDate: endDate.valueOf(),
257
+ timeoutMechanismType: data.timeoutMechanismType,
258
+ penalty: data.penalty
259
+ },
260
+ ceremonyPrefix: extractPrefix(data.title),
261
+ circuits: circuits,
262
+ circuitArtifacts: circuitArtifacts
263
+ }
264
+
265
+ return setupData
266
+
267
+ } catch (error: any) {
268
+ throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`)
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Extract data from a R1CS metadata file generated with a custom file-based logger.
274
+ * @notice useful for extracting metadata circuits contained in the generated file using a logger
275
+ * on the `r1cs.info()` method of snarkjs.
276
+ * @param fullFilePath <string> - the full path of the file.
277
+ * @param keyRgx <RegExp> - the regular expression linked to the key from which you want to extract the value.
278
+ * @returns <string> - the stringified extracted value.
279
+ */
280
+ export const extractR1CSInfoValueForGivenKey = (fullFilePath: string, keyRgx: RegExp): string => {
281
+ // Read the logger file.
282
+ const fileContents = fs.readFileSync(fullFilePath, "utf-8")
283
+
284
+ // Check for the matching value.
285
+ const matchingValue = fileContents.match(keyRgx)
286
+
287
+ if (!matchingValue)
288
+ throw new Error(
289
+ `Unable to retrieve circuit metadata. Possible causes may involve an error while using the logger. Please, check whether the corresponding \`.log\` file is present in your local \`output/setup/metadata\` folder. In any case, we kindly ask you to terminate the current session and repeat the process.`
290
+ )
291
+
292
+ // Elaborate spaces and special characters to extract the value.
293
+ // nb. this is a manual process which follows this custom arbitrary extraction rule
294
+ // accordingly to the output produced by the `r1cs.info()` method from snarkjs library.
295
+ return matchingValue?.at(0)?.split(":")[1].replace(" ", "").split("#")[0].replace("\n", "")!
296
+ }
297
+
298
+ /**
299
+ * Calculate the smallest amount of Powers of Tau needed for a circuit with a constraint size.
300
+ * @param constraints <number> - the number of circuit constraints (extracted from metadata).
301
+ * @param outputs <number> - the number of circuit outputs (extracted from metadata)
302
+ * @returns <number> - the smallest amount of Powers of Tau for the given constraint size.
303
+ */
304
+ export const computeSmallestPowersOfTauForCircuit = (constraints: number, outputs: number) => {
305
+ let power = 2
306
+ let tau = 2 ** power
307
+
308
+ while (constraints + outputs > tau) {
309
+ power += 1
310
+ tau = 2 ** power
311
+ }
312
+
313
+ return power
314
+ }
315
+
316
+ /**
317
+ * Transform a number in a zKey index format.
318
+ * @dev this method is aligned with the number of characters of the genesis zKey index (which is a constant).
319
+ * @param progress <number> - the progression in zKey index.
320
+ * @returns <string> - the progression in a zKey index format (`XYZAB`).
321
+ */
322
+ export const formatZkeyIndex = (progress: number): string => {
323
+ let index = progress.toString()
324
+
325
+ // Pad with zeros if the progression has less digits.
326
+ while (index.length < genesisZkeyIndex.length) {
327
+ index = `0${index}`
328
+ }
329
+
330
+ return index
331
+ }
332
+
333
+ /**
334
+ * Extract the amount of powers from Powers of Tau file name.
335
+ * @dev the PoT files must follow these convention (i_am_a_pot_file_09.ptau) where the numbers before '.ptau' are the powers.
336
+ * @param potCompleteFilename <string> - the complete filename of the Powers of Tau file.
337
+ * @returns <number> - the amount of powers.
338
+ */
339
+ export const extractPoTFromFilename = (potCompleteFilename: string): number =>
340
+ Number(potCompleteFilename.split("_").pop()?.split(".").at(0))
341
+
342
+ /**
343
+ * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
344
+ * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
345
+ * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
346
+ * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
347
+ * @param str <string> - the arbitrary string from which to extract the prefix.
348
+ * @returns <string> - the resulting prefix.
349
+ */
350
+ export const extractPrefix = (str: string): string =>
351
+ // eslint-disable-next-line no-useless-escape
352
+ str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase()
353
+
354
+ /**
355
+ * Automate the generation of an entropy for a contribution.
356
+ * @dev Took inspiration from here https://github.com/glamperd/setup-mpc-ui/blob/master/client/src/state/Compute.tsx#L112.
357
+ * @todo we need to improve the entropy generation (too naive).
358
+ * @returns <string> - the auto-generated entropy.
359
+ */
360
+ export const autoGenerateEntropy = () => new Uint8Array(256).map(() => Math.random() * 256).toString()
361
+
362
+ /**
363
+ * Check and return the circuit document based on its sequence position among a set of circuits (if any).
364
+ * @dev there should be only one circuit with a provided sequence position. This method checks and return an
365
+ * error if none is found.
366
+ * @param circuits <Array<FirebaseDocumentInfo>> - the set of ceremony circuits documents.
367
+ * @param sequencePosition <number> - the sequence position (index) of the circuit to be found and returned.
368
+ * @returns <FirebaseDocumentInfo> - the document of the circuit in the set of circuits that has the provided sequence position.
369
+ */
370
+ export const getCircuitBySequencePosition = (
371
+ circuits: Array<FirebaseDocumentInfo>,
372
+ sequencePosition: number
373
+ ): FirebaseDocumentInfo => {
374
+ // Filter by sequence position.
375
+ const matchedCircuits = circuits.filter(
376
+ (circuitDocument: FirebaseDocumentInfo) => circuitDocument.data.sequencePosition === sequencePosition
377
+ )
378
+
379
+ if (matchedCircuits.length !== 1)
380
+ throw new Error(
381
+ `Unable to find the circuit having position ${sequencePosition}. Run the command again and, if this error persists please contact the coordinator.`
382
+ )
383
+
384
+ return matchedCircuits.at(0)!
385
+ }
386
+
387
+ /**
388
+ * Convert bytes or chilobytes into gigabytes with customizable precision.
389
+ * @param bytesOrKb <number> - the amount of bytes or chilobytes to be converted.
390
+ * @param isBytes <boolean> - true when the amount to be converted is in bytes; otherwise false (= Chilobytes).
391
+ * @returns <number> - the converted amount in GBs.
392
+ */
393
+ export const convertBytesOrKbToGb = (bytesOrKb: number, isBytes: boolean): number =>
394
+ Number(bytesOrKb / 1024 ** (isBytes ? 3 : 2))
395
+
396
+ /**
397
+ * Get the validity of contributors' contributions for each circuit of the given ceremony (if any).
398
+ * @param firestoreDatabase <Firestore> - the Firestore service instance associated to the current Firebase application.
399
+ * @param circuits <Array<FirebaseDocumentInfo>> - the array of ceremony circuits documents.
400
+ * @param ceremonyId <string> - the unique identifier of the ceremony.
401
+ * @param participantId <string> - the unique identifier of the contributor.
402
+ * @param isFinalizing <boolean> - flag to discriminate between ceremony finalization (true) and contribution (false).
403
+ * @returns <Promise<Array<ContributionValidity>>> - a list of contributor contributions together with contribution validity (based on coordinator verification).
404
+ */
405
+ export const getContributionsValidityForContributor = async (
406
+ firestoreDatabase: Firestore,
407
+ circuits: Array<FirebaseDocumentInfo>,
408
+ ceremonyId: string,
409
+ participantId: string,
410
+ isFinalizing: boolean
411
+ ): Promise<Array<ContributionValidity>> => {
412
+ const contributionsValidity: Array<ContributionValidity> = []
413
+
414
+ for await (const circuit of circuits) {
415
+ // Get circuit contribution from contributor.
416
+ const circuitContributionsFromContributor = await getCircuitContributionsFromContributor(
417
+ firestoreDatabase,
418
+ ceremonyId,
419
+ circuit.id,
420
+ participantId
421
+ )
422
+
423
+ // Check for ceremony finalization (= there could be more than one contribution).
424
+ const contribution = isFinalizing
425
+ ? circuitContributionsFromContributor
426
+ .filter(
427
+ (contributionDocument: FirebaseDocumentInfo) =>
428
+ contributionDocument.data.zkeyIndex === finalContributionIndex
429
+ )
430
+ .at(0)
431
+ : circuitContributionsFromContributor.at(0)
432
+
433
+ if (!contribution)
434
+ throw new Error(
435
+ "Unable to retrieve contributions for the participant. There may have occurred a database-side error. Please, we kindly ask you to terminate the current session and repeat the process"
436
+ )
437
+
438
+ contributionsValidity.push({
439
+ contributionId: contribution?.id,
440
+ circuitId: circuit.id,
441
+ valid: contribution?.data.valid
442
+ })
443
+ }
444
+
445
+ return contributionsValidity
446
+ }
447
+
448
+ /**
449
+ * Return the public attestation preamble for given contributor.
450
+ * @param contributorIdentifier <string> - the identifier of the contributor (handle, name, uid).
451
+ * @param ceremonyName <string> - the name of the ceremony.
452
+ * @param isFinalizing <boolean> - true when the coordinator is finalizing the ceremony, otherwise false.
453
+ * @returns <string> - the public attestation preamble.
454
+ */
455
+ export const getPublicAttestationPreambleForContributor = (
456
+ contributorIdentifier: string,
457
+ ceremonyName: string,
458
+ isFinalizing: boolean
459
+ ) =>
460
+ `Hey, I'm ${contributorIdentifier} and I have ${
461
+ isFinalizing ? "finalized" : "contributed to"
462
+ } the ${ceremonyName} MPC Phase2 Trusted Setup ceremony.\nThe following are my contribution signatures:`
463
+
464
+ /**
465
+ * Check and prepare public attestation for the contributor made only of its valid contributions.
466
+ * @param firestoreDatabase <Firestore> - the Firestore service instance associated to the current Firebase application.
467
+ * @param circuits <Array<FirebaseDocumentInfo>> - the array of ceremony circuits documents.
468
+ * @param ceremonyId <string> - the unique identifier of the ceremony.
469
+ * @param participantId <string> - the unique identifier of the contributor.
470
+ * @param participantContributions <Array<Co> - the document data of the participant.
471
+ * @param contributorIdentifier <string> - the identifier of the contributor (handle, name, uid).
472
+ * @param ceremonyName <string> - the name of the ceremony.
473
+ * @param isFinalizing <boolean> - true when the coordinator is finalizing the ceremony, otherwise false.
474
+ * @returns <Promise<string>> - the public attestation for the contributor.
475
+ */
476
+ export const generateValidContributionsAttestation = async (
477
+ firestoreDatabase: Firestore,
478
+ circuits: Array<FirebaseDocumentInfo>,
479
+ ceremonyId: string,
480
+ participantId: string,
481
+ participantContributions: Array<Contribution>,
482
+ contributorIdentifier: string,
483
+ ceremonyName: string,
484
+ isFinalizing: boolean
485
+ ): Promise<string> => {
486
+ // Generate the attestation preamble for the contributor.
487
+ let publicAttestation = getPublicAttestationPreambleForContributor(
488
+ contributorIdentifier,
489
+ ceremonyName,
490
+ isFinalizing
491
+ )
492
+
493
+ // Get contributors' contributions validity.
494
+ const contributionsWithValidity = await getContributionsValidityForContributor(
495
+ firestoreDatabase,
496
+ circuits,
497
+ ceremonyId,
498
+ participantId,
499
+ isFinalizing
500
+ )
501
+
502
+ for await (const contributionWithValidity of contributionsWithValidity) {
503
+ // Filter for the related contribution document info.
504
+ const matchedContributions = participantContributions.filter(
505
+ (contribution: Contribution) => contribution.doc === contributionWithValidity.contributionId
506
+ )
507
+
508
+ if (matchedContributions.length === 0)
509
+ throw new Error(
510
+ `Unable to retrieve given circuit contribution information. This could happen due to some errors while writing the information on the database.`
511
+ )
512
+
513
+ if (matchedContributions.length > 1)
514
+ throw new Error(`Duplicated circuit contribution information. Please, contact the coordinator.`)
515
+
516
+ const participantContribution = matchedContributions.at(0)!
517
+
518
+ // Get circuit document (the one for which the contribution was calculated).
519
+ const circuitDocument = await getDocumentById(
520
+ firestoreDatabase,
521
+ getCircuitsCollectionPath(ceremonyId),
522
+ contributionWithValidity.circuitId
523
+ )
524
+ const contributionDocument = await getDocumentById(
525
+ firestoreDatabase,
526
+ getContributionsCollectionPath(ceremonyId, contributionWithValidity.circuitId),
527
+ participantContribution.doc
528
+ )
529
+
530
+ if (!contributionDocument.data() || !circuitDocument.data())
531
+ throw new Error(`Something went wrong when retrieving the data from the database`)
532
+
533
+ // Extract data.
534
+ const { sequencePosition, prefix } = circuitDocument.data()!
535
+ const { zkeyIndex } = contributionDocument.data()!
536
+
537
+ // Update public attestation.
538
+ publicAttestation = `${publicAttestation}\n\nCircuit # ${sequencePosition} (${prefix})\nContributor # ${
539
+ zkeyIndex > 0 ? Number(zkeyIndex) : zkeyIndex
540
+ }\n${participantContribution.hash}`
541
+ }
542
+
543
+ return publicAttestation
544
+ }
545
+
546
+ /**
547
+ * Create a custom logger to write logs on a local file.
548
+ * @param filename <string> - the name of the output file (where the logs are going to be written).
549
+ * @param level <winston.LoggerOptions["level"]> - the option for the logger level (e.g., info, error).
550
+ * @returns <Logger> - a customized winston logger for files.
551
+ */
552
+ export const createCustomLoggerForFile = (filename: string, level: winston.LoggerOptions["level"] = "info"): Logger =>
553
+ winston.createLogger({
554
+ level,
555
+ transports: new winston.transports.File({
556
+ filename,
557
+ format: winston.format.printf((log) => log.message),
558
+ level
559
+ })
560
+ })
561
+
562
+ /**
563
+ * Return an amount of bytes read from a file to a particular location in the form of a buffer.
564
+ * @param localFilePath <string> - the local path where the artifact will be downloaded.
565
+ * @param offset <number> - the index of the line to be read (0 from the start).
566
+ * @param length <number> - the length of the line to be read.
567
+ * @param position <ReadPosition> - the position inside the file.
568
+ * @returns <Buffer> - the buffer w/ the read bytes.
569
+ */
570
+ export const readBytesFromFile = (
571
+ localFilePath: string,
572
+ offset: number,
573
+ length: number,
574
+ position: ReadPosition
575
+ ): Buffer => {
576
+ // Open the file (read mode).
577
+ const fileDescriptor = fs.openSync(localFilePath, "r")
578
+
579
+ // Prepare buffer.
580
+ const buffer = Buffer.alloc(length)
581
+
582
+ // Read bytes.
583
+ fs.readSync(fileDescriptor, buffer, offset, length, position)
584
+
585
+ // Return the read bytes.
586
+ return buffer
587
+ }
588
+
589
+ /**
590
+ * Return the info about the R1CS file.ù
591
+ * @dev this method was built taking inspiration from
592
+ * https://github.com/weijiekoh/circom-helper/blob/master/ts/read_num_inputs.ts#L5.
593
+ * You can find the specs of R1CS file here
594
+ * https://github.com/iden3/r1csfile/blob/master/doc/r1cs_bin_format.md
595
+ * @param localR1CSFilePath <string> - the local path to the R1CS file.
596
+ * @returns <CircuitMetadata> - the info about the R1CS file.
597
+ */
598
+ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
599
+ /**
600
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
601
+ * ┃ 4 │ 72 31 63 73 ┃ Magic "r1cs"
602
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
603
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
604
+ * ┃ 4 │ 01 00 00 00 ┃ Version 1
605
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
606
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
607
+ * ┃ 4 │ 03 00 00 00 ┃ Number of Sections
608
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
609
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┓
610
+ * ┃ 4 │ sectionType ┃ 8 │ SectionSize ┃
611
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┻━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━┛
612
+ * ┏━━━━━━━━━━━━━━━━━━━━━┓
613
+ * ┃ ┃
614
+ * ┃ ┃
615
+ * ┃ ┃
616
+ * ┃ Section Content ┃
617
+ * ┃ ┃
618
+ * ┃ ┃
619
+ * ┃ ┃
620
+ * ┗━━━━━━━━━━━━━━━━━━━━━┛
621
+ *
622
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┓
623
+ * ┃ 4 │ sectionType ┃ 8 │ SectionSize ┃
624
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┻━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━┛
625
+ * ┏━━━━━━━━━━━━━━━━━━━━━┓
626
+ * ┃ ┃
627
+ * ┃ ┃
628
+ * ┃ ┃
629
+ * ┃ Section Content ┃
630
+ * ┃ ┃
631
+ * ┃ ┃
632
+ * ┃ ┃
633
+ * ┗━━━━━━━━━━━━━━━━━━━━━┛
634
+ *
635
+ * ...
636
+ * ...
637
+ * ...
638
+ */
639
+
640
+ // Prepare state.
641
+ let pointer = 0 // selector to particular file data position in order to read data.
642
+ let wires = 0
643
+ let publicOutputs = 0
644
+ let publicInputs = 0
645
+ let privateInputs = 0
646
+ let labels = 0
647
+ let constraints = 0
648
+
649
+ try {
650
+ // Get 'number of section' (jump magic r1cs and version1 data).
651
+ const numberOfSections = ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, 8))
652
+
653
+ // Jump to first section.
654
+ pointer = 12
655
+
656
+ // For each section
657
+ for (let i = 0; i < numberOfSections; i++) {
658
+ // Read section type.
659
+ const sectionType = ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer))
660
+
661
+ // Jump to section size.
662
+ pointer += 4
663
+
664
+ // Read section size
665
+ const sectionSize = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
666
+
667
+ // If at header section (0x00000001 : Header Section).
668
+ if (sectionType === BigInt(1)) {
669
+ // Read info from header section.
670
+ /**
671
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
672
+ * ┃ 4 │ 20 00 00 00 ┃ Field Size in bytes (fs)
673
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
674
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
675
+ * ┃ fs │ 010000f0 93f5e143 9170b979 48e83328 5d588181 b64550b8 29a031e1 724e6430 ┃ Prime size
676
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
677
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
678
+ * ┃ 32 │ 01 00 00 00 ┃ nWires
679
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
680
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
681
+ * ┃ 32 │ 01 00 00 00 ┃ nPubOut
682
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
683
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
684
+ * ┃ 32 │ 01 00 00 00 ┃ nPubIn
685
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
686
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
687
+ * ┃ 32 │ 01 00 00 00 ┃ nPrvIn
688
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
689
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
690
+ * ┃ 64 │ 01 00 00 00 00 00 00 00 ┃ nLabels
691
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
692
+ * ┏━━━━┳━━━━━━━━━━━━━━━━━┓
693
+ * ┃ 32 │ 01 00 00 00 ┃ mConstraints
694
+ * ┗━━━━┻━━━━━━━━━━━━━━━━━┛
695
+ */
696
+
697
+ pointer += sectionSize - 20
698
+
699
+ // Read R1CS info.
700
+ wires = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
701
+ pointer += 4
702
+
703
+ publicOutputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
704
+ pointer += 4
705
+
706
+ publicInputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
707
+ pointer += 4
708
+
709
+ privateInputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
710
+ pointer += 4
711
+
712
+ labels = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
713
+ pointer += 8
714
+
715
+ constraints = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
716
+ }
717
+
718
+ pointer += 8 + Number(sectionSize)
719
+ }
720
+
721
+ return {
722
+ curve: "bn-128", /// @note currently default to bn-128 as we support only Groth16 proving system.
723
+ wires,
724
+ constraints,
725
+ privateInputs,
726
+ publicInputs,
727
+ labels,
728
+ outputs: publicOutputs,
729
+ pot: computeSmallestPowersOfTauForCircuit(constraints, publicOutputs)
730
+ }
731
+ } catch (err: any) {
732
+ throw new Error(
733
+ `The R1CS file you provided would not appear to be correct. Please, check that you have provided a valid R1CS file and repeat the process.`
734
+ )
735
+ }
736
+ }
737
+
738
+ /**
739
+ * Return a string with double digits if the provided input is one digit only.
740
+ * @param in <number> - the input number to be converted.
741
+ * @returns <string> - the two digits stringified number derived from the conversion.
742
+ */
743
+ export const convertToDoubleDigits = (amount: number): string => (amount < 10 ? `0${amount}` : amount.toString())