@devtion/actions 0.0.0-92056fa → 0.0.0-9239207

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 (36) hide show
  1. package/README.md +1 -1
  2. package/dist/index.mjs +346 -277
  3. package/dist/index.node.js +345 -274
  4. package/dist/types/src/helpers/constants.d.ts +5 -2
  5. package/dist/types/src/helpers/constants.d.ts.map +1 -1
  6. package/dist/types/src/helpers/contracts.d.ts.map +1 -1
  7. package/dist/types/src/helpers/crypto.d.ts +1 -0
  8. package/dist/types/src/helpers/crypto.d.ts.map +1 -1
  9. package/dist/types/src/helpers/database.d.ts +8 -0
  10. package/dist/types/src/helpers/database.d.ts.map +1 -1
  11. package/dist/types/src/helpers/security.d.ts +1 -1
  12. package/dist/types/src/helpers/security.d.ts.map +1 -1
  13. package/dist/types/src/helpers/storage.d.ts +5 -2
  14. package/dist/types/src/helpers/storage.d.ts.map +1 -1
  15. package/dist/types/src/helpers/utils.d.ts +34 -20
  16. package/dist/types/src/helpers/utils.d.ts.map +1 -1
  17. package/dist/types/src/helpers/verification.d.ts +3 -2
  18. package/dist/types/src/helpers/verification.d.ts.map +1 -1
  19. package/dist/types/src/helpers/vm.d.ts.map +1 -1
  20. package/dist/types/src/index.d.ts +2 -2
  21. package/dist/types/src/index.d.ts.map +1 -1
  22. package/dist/types/src/types/index.d.ts +9 -3
  23. package/dist/types/src/types/index.d.ts.map +1 -1
  24. package/package.json +3 -8
  25. package/src/helpers/constants.ts +39 -31
  26. package/src/helpers/contracts.ts +3 -3
  27. package/src/helpers/database.ts +13 -0
  28. package/src/helpers/functions.ts +1 -1
  29. package/src/helpers/security.ts +11 -10
  30. package/src/helpers/services.ts +3 -3
  31. package/src/helpers/storage.ts +15 -3
  32. package/src/helpers/utils.ts +316 -272
  33. package/src/helpers/verification.ts +6 -6
  34. package/src/helpers/vm.ts +18 -7
  35. package/src/index.ts +5 -3
  36. package/src/types/index.ts +32 -8
@@ -1,18 +1,21 @@
1
1
  import { Firestore } from "firebase/firestore"
2
- import fs, { ReadPosition } from "fs"
3
- import { utils as ffUtils } from "ffjavascript"
2
+ import fs, { ReadPosition, createWriteStream } from "fs"
4
3
  import winston, { Logger } from "winston"
5
- import { S3Client, GetObjectCommand, HeadObjectCommand } from "@aws-sdk/client-s3"
6
- import {
7
- CircuitMetadata,
8
- Contribution,
9
- CircuitDocument,
4
+ import fetch from "@adobe/node-fetch-retry"
5
+ import { pipeline } from "stream"
6
+ import { promisify } from "util"
7
+ import {
8
+ CircuitMetadata,
9
+ Contribution,
10
+ CircuitDocument,
10
11
  CircuitInputData,
11
- ContributionValidity,
12
- FirebaseDocumentInfo,
13
- SetupCeremonyData,
12
+ ContributionValidity,
13
+ FirebaseDocumentInfo,
14
+ SetupCeremonyData,
14
15
  CeremonySetupTemplate,
15
16
  CeremonySetupTemplateCircuitArtifacts,
17
+ StringifiedBigInts,
18
+ BigIntVariants
16
19
  } from "../types/index"
17
20
  import { finalContributionIndex, genesisZkeyIndex, potFilenameTemplate } from "./constants"
18
21
  import {
@@ -22,247 +25,32 @@ import {
22
25
  getContributionsCollectionPath
23
26
  } from "./database"
24
27
  import { CeremonyTimeoutType } from "../types/enums"
25
- import {
26
- getPotStorageFilePath,
27
- getR1csStorageFilePath,
28
- getWasmStorageFilePath,
28
+ import {
29
+ getPotStorageFilePath,
30
+ getR1csStorageFilePath,
31
+ getWasmStorageFilePath,
29
32
  getZkeyStorageFilePath
30
33
  } from "./storage"
31
34
  import { blake512FromPath } from "./crypto"
32
- import { Readable, pipeline } from "stream"
33
- import { promisify } from "util"
34
35
 
35
36
  /**
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
37
+ * Return a string with double digits if the provided input is one digit only.
38
+ * @param in <number> - the input number to be converted.
39
+ * @returns <string> - the two digits stringified number derived from the conversion.
41
40
  */
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
-
91
- // where we storing the r1cs downloaded
92
- const localR1csPath = `./${circuitData.name}.r1cs`
93
- // where we storing the wasm downloaded
94
- const localWasmPath = `./${circuitData.name}.wasm`
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({
100
- region: artifacts.region,
101
- credentials: undefined
102
- })
103
-
104
- // download the r1cs to extract the metadata
105
- const command = new GetObjectCommand({ Bucket: artifacts.bucket, Key: artifacts.r1csStoragePath })
106
- const response = await s3.send(command)
107
- const streamPipeline = promisify(pipeline)
108
-
109
- if (response.$metadata.httpStatusCode !== 200)
110
- throw new Error(`There was an error while trying to download the r1cs file for circuit ${circuitData.name}. Please check that the file has the correct permissions (public) set.`)
41
+ export const convertToDoubleDigits = (amount: number): string => (amount < 10 ? `0${amount}` : amount.toString())
111
42
 
112
- if (response.Body instanceof Readable)
113
- await streamPipeline(response.Body, fs.createWriteStream(localR1csPath))
114
-
115
- // extract the metadata from the r1cs
116
- const metadata = getR1CSInfo(localR1csPath)
117
-
118
- // download wasm too to ensure it's available
119
- const wasmCommand = new GetObjectCommand({ Bucket: artifacts.bucket, Key: artifacts.wasmStoragePath })
120
- const wasmResponse = await s3.send(wasmCommand)
121
-
122
- if (wasmResponse.$metadata.httpStatusCode !== 200)
123
- throw new Error(`There was an error while trying to download the wasm file for circuit ${circuitData.name}. Please check that the file has the correct permissions (public) set.`)
124
-
125
- if (wasmResponse.Body instanceof Readable)
126
- await streamPipeline(wasmResponse.Body, fs.createWriteStream(localWasmPath))
127
-
128
- // validate that the circuit hash and template links are valid
129
- const template = circuitData.template
130
-
131
- const URLMatch = template.source.match(urlPattern)
132
- if (!URLMatch || URLMatch.length === 0 || URLMatch.length > 1) throw new Error("You should provide the URL to the circuits templates on GitHub.")
133
-
134
- const hashMatch = template.commitHash.match(commitHashPattern)
135
- if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1) throw new Error("You should provide a valid commit hash of the circuit templates.")
136
-
137
- // calculate the hash of the r1cs file
138
- const r1csBlake2bHash = await blake512FromPath(localR1csPath)
139
-
140
- const circuitPrefix = extractPrefix(circuitData.name)
141
-
142
- // filenames
143
- const doubleDigitsPowers = convertToDoubleDigits(metadata.pot!)
144
- const r1csCompleteFilename = `${circuitData.name}.r1cs`
145
- const wasmCompleteFilename = `${circuitData.name}.wasm`
146
- const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`
147
- const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`
148
-
149
- // storage paths
150
- const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename)
151
- const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename)
152
- const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit)
153
- const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename)
154
-
155
- const files: any = {
156
- potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
157
- r1csFilename: r1csCompleteFilename,
158
- wasmFilename: wasmCompleteFilename,
159
- initialZkeyFilename: firstZkeyCompleteFilename,
160
- potStoragePath: potStorageFilePath,
161
- r1csStoragePath: r1csStorageFilePath,
162
- wasmStoragePath: wasmStorageFilePath,
163
- initialZkeyStoragePath: zkeyStorageFilePath,
164
- r1csBlake2bHash: r1csBlake2bHash
165
- }
166
-
167
- // validate that the compiler hash is a valid hash
168
- const compiler = circuitData.compiler
169
- const compilerHashMatch = compiler.commitHash.match(commitHashPattern)
170
- if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1) throw new Error("You should provide a valid commit hash of the circuit compiler.")
171
-
172
- // validate that the verification options are valid
173
- const verification = circuitData.verification
174
- if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
175
- throw new Error("Please enter a valid verification mechanism: either CF or VM")
176
-
177
- // @todo VM parameters verification
178
- // if (verification['cfOrVM'] === "VM") {}
179
-
180
- // check that the timeout is provided for the correct configuration
181
- let dynamicThreshold: number | undefined
182
- let fixedTimeWindow: number | undefined
183
-
184
- let circuit: CircuitDocument | CircuitInputData = {} as CircuitDocument | CircuitInputData
185
-
186
- if (data.timeoutMechanismType === CeremonyTimeoutType.DYNAMIC) {
187
- if (circuitData.dynamicThreshold <= 0)
188
- throw new Error("The dynamic threshold should be > 0.")
189
- dynamicThreshold = circuitData.dynamicThreshold
190
-
191
- // the Circuit data for the ceremony setup
192
- circuit = {
193
- name: circuitData.name,
194
- description: circuitData.description,
195
- prefix: circuitPrefix,
196
- sequencePosition: i+1,
197
- metadata: metadata,
198
- files: files,
199
- template: template,
200
- compiler: compiler,
201
- verification: verification,
202
- dynamicThreshold: dynamicThreshold,
203
- avgTimings: {
204
- contributionComputation: 0,
205
- fullContribution: 0,
206
- verifyCloudFunction: 0
207
- },
208
-
209
- }
210
- }
211
-
212
- if (data.timeoutMechanismType === CeremonyTimeoutType.FIXED) {
213
- if (circuitData.fixedTimeWindow <= 0)
214
- throw new Error("The fixed time window threshold should be > 0.")
215
- fixedTimeWindow = circuitData.fixedTimeWindow
216
-
217
-
218
- // the Circuit data for the ceremony setup
219
- circuit = {
220
- name: circuitData.name,
221
- description: circuitData.description,
222
- prefix: circuitPrefix,
223
- sequencePosition: i+1,
224
- metadata: metadata,
225
- files: files,
226
- template: template,
227
- compiler: compiler,
228
- verification: verification,
229
- fixedTimeWindow: fixedTimeWindow,
230
- avgTimings: {
231
- contributionComputation: 0,
232
- fullContribution: 0,
233
- verifyCloudFunction: 0
234
- },
235
-
236
- }
237
- }
238
-
239
-
240
- circuits.push(circuit)
241
-
242
- // remove the local r1cs download (if used for verifying the config only vs setup)
243
- if (cleanup) fs.unlinkSync(localR1csPath)
244
- }
245
-
246
- const setupData: SetupCeremonyData = {
247
- ceremonyInputData: {
248
- title: data.title,
249
- description: data.description,
250
- startDate: startDate.valueOf(),
251
- endDate: endDate.valueOf(),
252
- timeoutMechanismType: data.timeoutMechanismType,
253
- penalty: data.penalty
254
- },
255
- ceremonyPrefix: extractPrefix(data.title),
256
- circuits: circuits,
257
- circuitArtifacts: circuitArtifacts
258
- }
259
-
260
- return setupData
261
-
262
- } catch (error: any) {
263
- throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`)
264
- }
265
- }
43
+ /**
44
+ * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
45
+ * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
46
+ * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
47
+ * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
48
+ * @param str <string> - the arbitrary string from which to extract the prefix.
49
+ * @returns <string> - the resulting prefix.
50
+ */
51
+ export const extractPrefix = (str: string): string =>
52
+ // eslint-disable-next-line no-useless-escape
53
+ str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase()
266
54
 
267
55
  /**
268
56
  * Extract data from a R1CS metadata file generated with a custom file-based logger.
@@ -334,18 +122,6 @@ export const formatZkeyIndex = (progress: number): string => {
334
122
  export const extractPoTFromFilename = (potCompleteFilename: string): number =>
335
123
  Number(potCompleteFilename.split("_").pop()?.split(".").at(0))
336
124
 
337
- /**
338
- * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
339
- * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
340
- * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
341
- * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
342
- * @param str <string> - the arbitrary string from which to extract the prefix.
343
- * @returns <string> - the resulting prefix.
344
- */
345
- export const extractPrefix = (str: string): string =>
346
- // eslint-disable-next-line no-useless-escape
347
- str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase()
348
-
349
125
  /**
350
126
  * Automate the generation of an entropy for a contribution.
351
127
  * @dev Took inspiration from here https://github.com/glamperd/setup-mpc-ui/blob/master/client/src/state/Compute.tsx#L112.
@@ -452,9 +228,11 @@ export const getPublicAttestationPreambleForContributor = (
452
228
  ceremonyName: string,
453
229
  isFinalizing: boolean
454
230
  ) =>
455
- `Hey, I'm ${contributorIdentifier} and I have ${
456
- isFinalizing ? "finalized" : "contributed to"
457
- } the ${ceremonyName} MPC Phase2 Trusted Setup ceremony.\nThe following are my contribution signatures:`
231
+ `Hey, I'm ${contributorIdentifier} and I have ${isFinalizing ? "finalized" : "contributed to"} the ${ceremonyName}${
232
+ ceremonyName.toLowerCase().includes("trusted setup") || ceremonyName.toLowerCase().includes("ceremony")
233
+ ? "."
234
+ : " MPC Phase2 Trusted Setup ceremony."
235
+ }\nThe following are my contribution signatures:`
458
236
 
459
237
  /**
460
238
  * Check and prepare public attestation for the contributor made only of its valid contributions.
@@ -581,6 +359,48 @@ export const readBytesFromFile = (
581
359
  return buffer
582
360
  }
583
361
 
362
+ /**
363
+ * Given a buffer in little endian format, convert it to bigint
364
+ * @param buffer
365
+ * @returns
366
+ */
367
+ export function leBufferToBigint(buffer: Buffer): bigint {
368
+ return BigInt(`0x${buffer.reverse().toString("hex")}`)
369
+ }
370
+
371
+ /**
372
+ * Given an input containing string values, convert them
373
+ * to bigint
374
+ * @param input - The input to convert
375
+ * @returns the input with string values converted to bigint
376
+ */
377
+ export const unstringifyBigInts = (input: StringifiedBigInts): BigIntVariants => {
378
+ if (typeof input === "string" && /^[0-9]+$/.test(input)) {
379
+ return BigInt(input)
380
+ }
381
+
382
+ if (typeof input === "string" && /^0x[0-9a-fA-F]+$/.test(input)) {
383
+ return BigInt(input)
384
+ }
385
+
386
+ if (Array.isArray(input)) {
387
+ return input.map(unstringifyBigInts)
388
+ }
389
+
390
+ if (input === null) {
391
+ return null
392
+ }
393
+
394
+ if (typeof input === "object") {
395
+ return Object.entries(input).reduce<Record<string, bigint>>((acc, [key, value]) => {
396
+ acc[key] = unstringifyBigInts(value) as bigint
397
+ return acc
398
+ }, {})
399
+ }
400
+
401
+ return input
402
+ }
403
+
584
404
  /**
585
405
  * Return the info about the R1CS file.ù
586
406
  * @dev this method was built taking inspiration from
@@ -643,7 +463,7 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
643
463
 
644
464
  try {
645
465
  // Get 'number of section' (jump magic r1cs and version1 data).
646
- const numberOfSections = ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, 8))
466
+ const numberOfSections = leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, 8))
647
467
 
648
468
  // Jump to first section.
649
469
  pointer = 12
@@ -651,13 +471,13 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
651
471
  // For each section
652
472
  for (let i = 0; i < numberOfSections; i++) {
653
473
  // Read section type.
654
- const sectionType = ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer))
474
+ const sectionType = leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer))
655
475
 
656
476
  // Jump to section size.
657
477
  pointer += 4
658
478
 
659
479
  // Read section size
660
- const sectionSize = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
480
+ const sectionSize = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
661
481
 
662
482
  // If at header section (0x00000001 : Header Section).
663
483
  if (sectionType === BigInt(1)) {
@@ -692,22 +512,22 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
692
512
  pointer += sectionSize - 20
693
513
 
694
514
  // Read R1CS info.
695
- wires = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
515
+ wires = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
696
516
  pointer += 4
697
517
 
698
- publicOutputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
518
+ publicOutputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
699
519
  pointer += 4
700
520
 
701
- publicInputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
521
+ publicInputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
702
522
  pointer += 4
703
523
 
704
- privateInputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
524
+ privateInputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
705
525
  pointer += 4
706
526
 
707
- labels = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
527
+ labels = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
708
528
  pointer += 8
709
529
 
710
- constraints = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
530
+ constraints = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
711
531
  }
712
532
 
713
533
  pointer += 8 + Number(sectionSize)
@@ -731,8 +551,232 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
731
551
  }
732
552
 
733
553
  /**
734
- * Return a string with double digits if the provided input is one digit only.
735
- * @param in <number> - the input number to be converted.
736
- * @returns <string> - the two digits stringified number derived from the conversion.
554
+ * Parse and validate that the ceremony configuration is correct
555
+ * @notice this does not upload any files to storage
556
+ * @param path <string> - the path to the configuration file
557
+ * @param cleanup <boolean> - whether to delete the r1cs file after parsing
558
+ * @returns any - the data to pass to the cloud function for setup and the circuit artifacts
737
559
  */
738
- export const convertToDoubleDigits = (amount: number): string => (amount < 10 ? `0${amount}` : amount.toString())
560
+ export const parseCeremonyFile = async (path: string, cleanup: boolean = false): Promise<SetupCeremonyData> => {
561
+ // check that the path exists
562
+ if (!fs.existsSync(path))
563
+ throw new Error(
564
+ "The provided path to the configuration file does not exist. Please provide an absolute path and try again."
565
+ )
566
+
567
+ try {
568
+ // read the data
569
+ const data: CeremonySetupTemplate = JSON.parse(fs.readFileSync(path).toString())
570
+
571
+ // verify that the data is correct
572
+ if (
573
+ data.timeoutMechanismType !== CeremonyTimeoutType.DYNAMIC &&
574
+ data.timeoutMechanismType !== CeremonyTimeoutType.FIXED
575
+ )
576
+ throw new Error("Invalid timeout type. Please choose between DYNAMIC and FIXED.")
577
+
578
+ // validate that we have at least 1 circuit input data
579
+ if (!data.circuits || data.circuits.length === 0)
580
+ throw new Error("You need to provide the data for at least 1 circuit.")
581
+
582
+ // validate that the end date is in the future
583
+ let endDate: Date
584
+ let startDate: Date
585
+ try {
586
+ endDate = new Date(data.endDate)
587
+ startDate = new Date(data.startDate)
588
+ } catch (error: any) {
589
+ throw new Error("The dates should follow this format: 2023-07-04T00:00:00.")
590
+ }
591
+
592
+ if (endDate <= startDate) throw new Error("The end date should be greater than the start date.")
593
+
594
+ const currentDate = new Date()
595
+
596
+ if (endDate <= currentDate || startDate <= currentDate)
597
+ throw new Error("The start and end dates should be in the future.")
598
+
599
+ // validate penalty
600
+ if (data.penalty <= 0) throw new Error("The penalty should be greater than zero.")
601
+
602
+ const circuits: CircuitDocument[] = []
603
+ const urlPattern = /(https?:\/\/[^\s]+)/g
604
+ const commitHashPattern = /^[a-f0-9]{40}$/i
605
+
606
+ const circuitArtifacts: CeremonySetupTemplateCircuitArtifacts[] = []
607
+
608
+ for (let i = 0; i < data.circuits.length; i++) {
609
+ const circuitData = data.circuits[i]
610
+ const { artifacts } = circuitData
611
+ circuitArtifacts.push({
612
+ artifacts
613
+ })
614
+
615
+ // where we storing the r1cs downloaded
616
+ const localR1csPath = `./${circuitData.name}.r1cs`
617
+ // where we storing the wasm downloaded
618
+ const localWasmPath = `./${circuitData.name}.wasm`
619
+
620
+ // download the r1cs to extract the metadata
621
+ const streamPipeline = promisify(pipeline)
622
+
623
+ // Make the call.
624
+ const responseR1CS = await fetch(artifacts.r1csStoragePath)
625
+
626
+ // Handle errors.
627
+ if (!responseR1CS.ok && responseR1CS.status !== 200)
628
+ throw new Error(
629
+ `There was an error while trying to download the r1cs file for circuit ${circuitData.name}. Please check that the file has the correct permissions (public) set.`
630
+ )
631
+
632
+ await streamPipeline(responseR1CS.body!, createWriteStream(localR1csPath))
633
+ // Write the file locally
634
+
635
+ // extract the metadata from the r1cs
636
+ const metadata = getR1CSInfo(localR1csPath)
637
+
638
+ // download wasm too to ensure it's available
639
+ const responseWASM = await fetch(artifacts.wasmStoragePath)
640
+ if (!responseWASM.ok && responseWASM.status !== 200)
641
+ throw new Error(
642
+ `There was an error while trying to download the WASM file for circuit ${circuitData.name}. Please check that the file has the correct permissions (public) set.`
643
+ )
644
+ await streamPipeline(responseWASM.body!, createWriteStream(localWasmPath))
645
+
646
+ // validate that the circuit hash and template links are valid
647
+ const { template } = circuitData
648
+
649
+ const URLMatch = template.source.match(urlPattern)
650
+ if (!URLMatch || URLMatch.length === 0 || URLMatch.length > 1)
651
+ throw new Error("You should provide the URL to the circuits templates on GitHub.")
652
+
653
+ const hashMatch = template.commitHash.match(commitHashPattern)
654
+ if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1)
655
+ throw new Error("You should provide a valid commit hash of the circuit templates.")
656
+
657
+ // calculate the hash of the r1cs file
658
+ const r1csBlake2bHash = await blake512FromPath(localR1csPath)
659
+
660
+ const circuitPrefix = extractPrefix(circuitData.name)
661
+
662
+ // filenames
663
+ const doubleDigitsPowers = convertToDoubleDigits(metadata.pot!)
664
+ const r1csCompleteFilename = `${circuitData.name}.r1cs`
665
+ const wasmCompleteFilename = `${circuitData.name}.wasm`
666
+ const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`
667
+ const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`
668
+
669
+ // storage paths
670
+ const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename)
671
+ const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename)
672
+ const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit)
673
+ const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename)
674
+
675
+ const files: any = {
676
+ potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
677
+ r1csFilename: r1csCompleteFilename,
678
+ wasmFilename: wasmCompleteFilename,
679
+ initialZkeyFilename: firstZkeyCompleteFilename,
680
+ potStoragePath: potStorageFilePath,
681
+ r1csStoragePath: r1csStorageFilePath,
682
+ wasmStoragePath: wasmStorageFilePath,
683
+ initialZkeyStoragePath: zkeyStorageFilePath,
684
+ r1csBlake2bHash
685
+ }
686
+
687
+ // validate that the compiler hash is a valid hash
688
+ const { compiler } = circuitData
689
+ const compilerHashMatch = compiler.commitHash.match(commitHashPattern)
690
+ if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1)
691
+ throw new Error("You should provide a valid commit hash of the circuit compiler.")
692
+
693
+ // validate that the verification options are valid
694
+ const { verification } = circuitData
695
+ if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
696
+ throw new Error("Please enter a valid verification mechanism: either CF or VM")
697
+
698
+ // @todo VM parameters verification
699
+ // if (verification['cfOrVM'] === "VM") {}
700
+
701
+ // check that the timeout is provided for the correct configuration
702
+ let dynamicThreshold: number | undefined
703
+ let fixedTimeWindow: number | undefined
704
+
705
+ let circuit: CircuitDocument | CircuitInputData = {} as CircuitDocument | CircuitInputData
706
+
707
+ if (data.timeoutMechanismType === CeremonyTimeoutType.DYNAMIC) {
708
+ if (circuitData.dynamicThreshold <= 0) throw new Error("The dynamic threshold should be > 0.")
709
+ dynamicThreshold = circuitData.dynamicThreshold
710
+
711
+ // the Circuit data for the ceremony setup
712
+ circuit = {
713
+ name: circuitData.name,
714
+ description: circuitData.description,
715
+ prefix: circuitPrefix,
716
+ sequencePosition: i + 1,
717
+ metadata,
718
+ files,
719
+ template,
720
+ compiler,
721
+ verification,
722
+ dynamicThreshold,
723
+ avgTimings: {
724
+ contributionComputation: 0,
725
+ fullContribution: 0,
726
+ verifyCloudFunction: 0
727
+ }
728
+ }
729
+ }
730
+
731
+ if (data.timeoutMechanismType === CeremonyTimeoutType.FIXED) {
732
+ if (circuitData.fixedTimeWindow <= 0) throw new Error("The fixed time window threshold should be > 0.")
733
+ fixedTimeWindow = circuitData.fixedTimeWindow
734
+
735
+ // the Circuit data for the ceremony setup
736
+ circuit = {
737
+ name: circuitData.name,
738
+ description: circuitData.description,
739
+ prefix: circuitPrefix,
740
+ sequencePosition: i + 1,
741
+ metadata,
742
+ files,
743
+ template,
744
+ compiler,
745
+ verification,
746
+ fixedTimeWindow,
747
+ avgTimings: {
748
+ contributionComputation: 0,
749
+ fullContribution: 0,
750
+ verifyCloudFunction: 0
751
+ }
752
+ }
753
+ }
754
+
755
+ circuits.push(circuit)
756
+
757
+ // remove the local r1cs and wasm downloads (if used for verifying the config only vs setup)
758
+ if (cleanup) {
759
+ fs.unlinkSync(localR1csPath)
760
+ fs.unlinkSync(localWasmPath)
761
+ }
762
+ }
763
+
764
+ const setupData: SetupCeremonyData = {
765
+ ceremonyInputData: {
766
+ title: data.title,
767
+ description: data.description,
768
+ startDate: startDate.valueOf(),
769
+ endDate: endDate.valueOf(),
770
+ timeoutMechanismType: data.timeoutMechanismType,
771
+ penalty: data.penalty
772
+ },
773
+ ceremonyPrefix: extractPrefix(data.title),
774
+ circuits,
775
+ circuitArtifacts
776
+ }
777
+
778
+ return setupData
779
+ } catch (error: any) {
780
+ throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`)
781
+ }
782
+ }