@devtion/actions 0.0.0-8bb9489 → 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 (34) hide show
  1. package/dist/index.mjs +322 -262
  2. package/dist/index.node.js +323 -261
  3. package/dist/types/src/helpers/constants.d.ts +5 -2
  4. package/dist/types/src/helpers/constants.d.ts.map +1 -1
  5. package/dist/types/src/helpers/contracts.d.ts.map +1 -1
  6. package/dist/types/src/helpers/crypto.d.ts +1 -0
  7. package/dist/types/src/helpers/crypto.d.ts.map +1 -1
  8. package/dist/types/src/helpers/database.d.ts +8 -0
  9. package/dist/types/src/helpers/database.d.ts.map +1 -1
  10. package/dist/types/src/helpers/security.d.ts +1 -1
  11. package/dist/types/src/helpers/security.d.ts.map +1 -1
  12. package/dist/types/src/helpers/storage.d.ts +1 -1
  13. package/dist/types/src/helpers/storage.d.ts.map +1 -1
  14. package/dist/types/src/helpers/utils.d.ts +34 -20
  15. package/dist/types/src/helpers/utils.d.ts.map +1 -1
  16. package/dist/types/src/helpers/verification.d.ts +3 -2
  17. package/dist/types/src/helpers/verification.d.ts.map +1 -1
  18. package/dist/types/src/helpers/vm.d.ts.map +1 -1
  19. package/dist/types/src/index.d.ts +2 -2
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/types/index.d.ts +9 -3
  22. package/dist/types/src/types/index.d.ts.map +1 -1
  23. package/package.json +3 -4
  24. package/src/helpers/constants.ts +40 -32
  25. package/src/helpers/contracts.ts +3 -3
  26. package/src/helpers/database.ts +13 -0
  27. package/src/helpers/security.ts +8 -5
  28. package/src/helpers/services.ts +2 -2
  29. package/src/helpers/storage.ts +3 -3
  30. package/src/helpers/utils.ts +299 -254
  31. package/src/helpers/verification.ts +6 -6
  32. package/src/helpers/vm.ts +9 -4
  33. package/src/index.ts +3 -1
  34. package/src/types/index.ts +23 -3
@@ -1,8 +1,9 @@
1
1
  import { Firestore } from "firebase/firestore"
2
2
  import fs, { ReadPosition, createWriteStream } from "fs"
3
- import { utils as ffUtils } from "ffjavascript"
4
3
  import winston, { Logger } from "winston"
5
4
  import fetch from "@adobe/node-fetch-retry"
5
+ import { pipeline } from "stream"
6
+ import { promisify } from "util"
6
7
  import {
7
8
  CircuitMetadata,
8
9
  Contribution,
@@ -12,7 +13,9 @@ import {
12
13
  FirebaseDocumentInfo,
13
14
  SetupCeremonyData,
14
15
  CeremonySetupTemplate,
15
- CeremonySetupTemplateCircuitArtifacts
16
+ CeremonySetupTemplateCircuitArtifacts,
17
+ StringifiedBigInts,
18
+ BigIntVariants
16
19
  } from "../types/index"
17
20
  import { finalContributionIndex, genesisZkeyIndex, potFilenameTemplate } from "./constants"
18
21
  import {
@@ -29,237 +32,25 @@ import {
29
32
  getZkeyStorageFilePath
30
33
  } from "./storage"
31
34
  import { blake512FromPath } from "./crypto"
32
- import { 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))
45
- throw new Error(
46
- "The provided path to the configuration file does not exist. Please provide an absolute path and try again."
47
- )
48
-
49
- try {
50
- // read the data
51
- const data: CeremonySetupTemplate = JSON.parse(fs.readFileSync(path).toString())
52
-
53
- // verify that the data is correct
54
- if (
55
- data["timeoutMechanismType"] !== CeremonyTimeoutType.DYNAMIC &&
56
- data["timeoutMechanismType"] !== CeremonyTimeoutType.FIXED
57
- )
58
- throw new Error("Invalid timeout type. Please choose between DYNAMIC and FIXED.")
59
-
60
- // validate that we have at least 1 circuit input data
61
- if (!data.circuits || data.circuits.length === 0)
62
- throw new Error("You need to provide the data for at least 1 circuit.")
63
-
64
- // validate that the end date is in the future
65
- let endDate: Date
66
- let startDate: Date
67
- try {
68
- endDate = new Date(data.endDate)
69
- startDate = new Date(data.startDate)
70
- } catch (error: any) {
71
- throw new Error("The dates should follow this format: 2023-07-04T00:00:00.")
72
- }
73
-
74
- if (endDate <= startDate) throw new Error("The end date should be greater than the start date.")
75
-
76
- const currentDate = new Date()
77
-
78
- if (endDate <= currentDate || startDate <= currentDate)
79
- throw new Error("The start and end dates should be in the future.")
80
-
81
- // validate penalty
82
- if (data.penalty <= 0) throw new Error("The penalty should be greater than zero.")
83
-
84
- const circuits: CircuitDocument[] = []
85
- const urlPattern = /(https?:\/\/[^\s]+)/g
86
- const commitHashPattern = /^[a-f0-9]{40}$/i
87
-
88
- const circuitArtifacts: CeremonySetupTemplateCircuitArtifacts[] = []
89
-
90
- for (let i = 0; i < data.circuits.length; i++) {
91
- const circuitData = data.circuits[i]
92
- const artifacts = circuitData.artifacts
93
- circuitArtifacts.push({
94
- artifacts: artifacts
95
- })
96
-
97
- // where we storing the r1cs downloaded
98
- const localR1csPath = `./${circuitData.name}.r1cs`
99
- // where we storing the wasm downloaded
100
- const localWasmPath = `./${circuitData.name}.wasm`
101
-
102
- // download the r1cs to extract the metadata
103
- const streamPipeline = promisify(pipeline)
104
-
105
- // Make the call.
106
- const responseR1CS = await fetch(artifacts.r1csStoragePath)
107
-
108
- // Handle errors.
109
- if (!responseR1CS.ok && responseR1CS.status !== 200)
110
- throw new Error(
111
- `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.`
112
- )
113
-
114
- await streamPipeline(responseR1CS.body!, createWriteStream(localR1csPath))
115
- // Write the file locally
116
-
117
- // extract the metadata from the r1cs
118
- const metadata = getR1CSInfo(localR1csPath)
119
-
120
- // download wasm too to ensure it's available
121
- const responseWASM = await fetch(artifacts.wasmStoragePath)
122
- if (!responseWASM.ok && responseWASM.status !== 200)
123
- throw new Error(
124
- `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.`
125
- )
126
- await streamPipeline(responseWASM.body!, 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)
133
- throw new Error("You should provide the URL to the circuits templates on GitHub.")
134
-
135
- const hashMatch = template.commitHash.match(commitHashPattern)
136
- if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1)
137
- throw new Error("You should provide a valid commit hash of the circuit templates.")
138
-
139
- // calculate the hash of the r1cs file
140
- const r1csBlake2bHash = await blake512FromPath(localR1csPath)
141
-
142
- const circuitPrefix = extractPrefix(circuitData.name)
143
-
144
- // filenames
145
- const doubleDigitsPowers = convertToDoubleDigits(metadata.pot!)
146
- const r1csCompleteFilename = `${circuitData.name}.r1cs`
147
- const wasmCompleteFilename = `${circuitData.name}.wasm`
148
- const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`
149
- const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`
150
-
151
- // storage paths
152
- const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename)
153
- const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename)
154
- const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit)
155
- const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename)
156
-
157
- const files: any = {
158
- potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
159
- r1csFilename: r1csCompleteFilename,
160
- wasmFilename: wasmCompleteFilename,
161
- initialZkeyFilename: firstZkeyCompleteFilename,
162
- potStoragePath: potStorageFilePath,
163
- r1csStoragePath: r1csStorageFilePath,
164
- wasmStoragePath: wasmStorageFilePath,
165
- initialZkeyStoragePath: zkeyStorageFilePath,
166
- r1csBlake2bHash: r1csBlake2bHash
167
- }
168
-
169
- // validate that the compiler hash is a valid hash
170
- const compiler = circuitData.compiler
171
- const compilerHashMatch = compiler.commitHash.match(commitHashPattern)
172
- if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1)
173
- throw new Error("You should provide a valid commit hash of the circuit compiler.")
174
-
175
- // validate that the verification options are valid
176
- const verification = circuitData.verification
177
- if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
178
- throw new Error("Please enter a valid verification mechanism: either CF or VM")
179
-
180
- // @todo VM parameters verification
181
- // if (verification['cfOrVM'] === "VM") {}
182
-
183
- // check that the timeout is provided for the correct configuration
184
- let dynamicThreshold: number | undefined
185
- let fixedTimeWindow: number | undefined
186
-
187
- let circuit: CircuitDocument | CircuitInputData = {} as CircuitDocument | CircuitInputData
188
-
189
- if (data.timeoutMechanismType === CeremonyTimeoutType.DYNAMIC) {
190
- if (circuitData.dynamicThreshold <= 0) throw new Error("The dynamic threshold should be > 0.")
191
- dynamicThreshold = circuitData.dynamicThreshold
192
-
193
- // the Circuit data for the ceremony setup
194
- circuit = {
195
- name: circuitData.name,
196
- description: circuitData.description,
197
- prefix: circuitPrefix,
198
- sequencePosition: i + 1,
199
- metadata: metadata,
200
- files: files,
201
- template: template,
202
- compiler: compiler,
203
- verification: verification,
204
- dynamicThreshold: dynamicThreshold,
205
- avgTimings: {
206
- contributionComputation: 0,
207
- fullContribution: 0,
208
- verifyCloudFunction: 0
209
- }
210
- }
211
- }
212
-
213
- if (data.timeoutMechanismType === CeremonyTimeoutType.FIXED) {
214
- if (circuitData.fixedTimeWindow <= 0) throw new Error("The fixed time window threshold should be > 0.")
215
- fixedTimeWindow = circuitData.fixedTimeWindow
216
-
217
- // the Circuit data for the ceremony setup
218
- circuit = {
219
- name: circuitData.name,
220
- description: circuitData.description,
221
- prefix: circuitPrefix,
222
- sequencePosition: i + 1,
223
- metadata: metadata,
224
- files: files,
225
- template: template,
226
- compiler: compiler,
227
- verification: verification,
228
- fixedTimeWindow: fixedTimeWindow,
229
- avgTimings: {
230
- contributionComputation: 0,
231
- fullContribution: 0,
232
- verifyCloudFunction: 0
233
- }
234
- }
235
- }
236
-
237
- circuits.push(circuit)
238
-
239
- // remove the local r1cs and wasm downloads (if used for verifying the config only vs setup)
240
- if (cleanup) fs.unlinkSync(localR1csPath)
241
- fs.unlinkSync(localWasmPath)
242
- }
243
-
244
- const setupData: SetupCeremonyData = {
245
- ceremonyInputData: {
246
- title: data.title,
247
- description: data.description,
248
- startDate: startDate.valueOf(),
249
- endDate: endDate.valueOf(),
250
- timeoutMechanismType: data.timeoutMechanismType,
251
- penalty: data.penalty
252
- },
253
- ceremonyPrefix: extractPrefix(data.title),
254
- circuits: circuits,
255
- circuitArtifacts: circuitArtifacts
256
- }
41
+ export const convertToDoubleDigits = (amount: number): string => (amount < 10 ? `0${amount}` : amount.toString())
257
42
 
258
- return setupData
259
- } catch (error: any) {
260
- throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`)
261
- }
262
- }
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()
263
54
 
264
55
  /**
265
56
  * Extract data from a R1CS metadata file generated with a custom file-based logger.
@@ -331,18 +122,6 @@ export const formatZkeyIndex = (progress: number): string => {
331
122
  export const extractPoTFromFilename = (potCompleteFilename: string): number =>
332
123
  Number(potCompleteFilename.split("_").pop()?.split(".").at(0))
333
124
 
334
- /**
335
- * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
336
- * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
337
- * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
338
- * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
339
- * @param str <string> - the arbitrary string from which to extract the prefix.
340
- * @returns <string> - the resulting prefix.
341
- */
342
- export const extractPrefix = (str: string): string =>
343
- // eslint-disable-next-line no-useless-escape
344
- str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase()
345
-
346
125
  /**
347
126
  * Automate the generation of an entropy for a contribution.
348
127
  * @dev Took inspiration from here https://github.com/glamperd/setup-mpc-ui/blob/master/client/src/state/Compute.tsx#L112.
@@ -580,6 +359,48 @@ export const readBytesFromFile = (
580
359
  return buffer
581
360
  }
582
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
+
583
404
  /**
584
405
  * Return the info about the R1CS file.ù
585
406
  * @dev this method was built taking inspiration from
@@ -642,7 +463,7 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
642
463
 
643
464
  try {
644
465
  // Get 'number of section' (jump magic r1cs and version1 data).
645
- const numberOfSections = ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, 8))
466
+ const numberOfSections = leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, 8))
646
467
 
647
468
  // Jump to first section.
648
469
  pointer = 12
@@ -650,13 +471,13 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
650
471
  // For each section
651
472
  for (let i = 0; i < numberOfSections; i++) {
652
473
  // Read section type.
653
- const sectionType = ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer))
474
+ const sectionType = leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer))
654
475
 
655
476
  // Jump to section size.
656
477
  pointer += 4
657
478
 
658
479
  // Read section size
659
- const sectionSize = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
480
+ const sectionSize = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
660
481
 
661
482
  // If at header section (0x00000001 : Header Section).
662
483
  if (sectionType === BigInt(1)) {
@@ -691,22 +512,22 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
691
512
  pointer += sectionSize - 20
692
513
 
693
514
  // Read R1CS info.
694
- wires = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
515
+ wires = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
695
516
  pointer += 4
696
517
 
697
- publicOutputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
518
+ publicOutputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
698
519
  pointer += 4
699
520
 
700
- publicInputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
521
+ publicInputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
701
522
  pointer += 4
702
523
 
703
- privateInputs = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
524
+ privateInputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
704
525
  pointer += 4
705
526
 
706
- labels = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
527
+ labels = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)))
707
528
  pointer += 8
708
529
 
709
- constraints = Number(ffUtils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
530
+ constraints = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)))
710
531
  }
711
532
 
712
533
  pointer += 8 + Number(sectionSize)
@@ -730,8 +551,232 @@ export const getR1CSInfo = (localR1CSFilePath: string): CircuitMetadata => {
730
551
  }
731
552
 
732
553
  /**
733
- * Return a string with double digits if the provided input is one digit only.
734
- * @param in <number> - the input number to be converted.
735
- * @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
736
559
  */
737
- 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
+ }
@@ -1,4 +1,4 @@
1
- import { groth16, zKey } from "snarkjs"
1
+ import { CircuitSignals, Groth16Proof, PublicSignals, groth16, zKey } from "snarkjs"
2
2
  import fs from "fs"
3
3
  import { Firestore, where } from "firebase/firestore"
4
4
  import { Functions } from "firebase/functions"
@@ -61,7 +61,7 @@ export const verifyZKey = async (
61
61
  * @returns <Promise<object>> The proof
62
62
  */
63
63
  export const generateGROTH16Proof = async (
64
- circuitInput: object,
64
+ circuitInput: CircuitSignals,
65
65
  zkeyFilePath: string,
66
66
  wasmFilePath: string,
67
67
  logger?: any
@@ -88,8 +88,8 @@ export const generateGROTH16Proof = async (
88
88
  */
89
89
  export const verifyGROTH16Proof = async (
90
90
  verificationKeyPath: string,
91
- publicSignals: object,
92
- proof: object
91
+ publicSignals: PublicSignals,
92
+ proof: Groth16Proof
93
93
  ): Promise<boolean> => {
94
94
  const verificationKey = JSON.parse(fs.readFileSync(verificationKeyPath).toString())
95
95
  const success = await groth16.verify(verificationKey, publicSignals, proof)
@@ -182,8 +182,8 @@ export const generateZkeyFromScratch = async (
182
182
  await zKey.beacon(
183
183
  finalContributionZKeyLocalPath,
184
184
  zkeyLocalPath,
185
- coordinatorIdentifier,
186
- beacon,
185
+ coordinatorIdentifier!,
186
+ beacon!,
187
187
  numExpIterations,
188
188
  logger
189
189
  )