@devtion/actions 0.0.0-bfc9ee4 → 0.0.0-c1f4cbe

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 +331 -298
  3. package/dist/index.node.js +331 -297
  4. package/dist/types/src/helpers/constants.d.ts +8 -0
  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 +2 -2
  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 +1 -1
  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 +8 -0
  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 +33 -52
  30. package/src/helpers/services.ts +3 -3
  31. package/src/helpers/storage.ts +15 -3
  32. package/src/helpers/utils.ts +316 -277
  33. package/src/helpers/verification.ts +6 -6
  34. package/src/helpers/vm.ts +14 -7
  35. package/src/index.ts +3 -2
  36. package/src/types/index.ts +32 -8
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @module @p0tion/actions
3
- * @version 1.0.5
2
+ * @module @devtion/actions
3
+ * @version 1.1.1
4
4
  * @file A set of actions and helpers for CLI commands
5
5
  * @copyright Ethereum Foundation 2022
6
6
  * @license MIT
@@ -17,9 +17,7 @@ var firestore = require('firebase/firestore');
17
17
  var snarkjs = require('snarkjs');
18
18
  var crypto = require('crypto');
19
19
  var blake = require('blakejs');
20
- var ffjavascript = require('ffjavascript');
21
20
  var winston = require('winston');
22
- var clientS3 = require('@aws-sdk/client-s3');
23
21
  var stream = require('stream');
24
22
  var util = require('util');
25
23
  var app = require('firebase/app');
@@ -246,6 +244,12 @@ const commonTerms = {
246
244
  verificationStartedAt: "verificationStartedAt"
247
245
  }
248
246
  },
247
+ avatars: {
248
+ name: "avatars",
249
+ fields: {
250
+ avatarUrl: "avatarUrl"
251
+ }
252
+ },
249
253
  ceremonies: {
250
254
  name: "ceremonies",
251
255
  fields: {
@@ -337,6 +341,8 @@ const commonTerms = {
337
341
  finalizeCeremony: "finalizeCeremony",
338
342
  downloadCircuitArtifacts: "downloadCircuitArtifacts",
339
343
  transferObject: "transferObject",
344
+ bandadaValidateProof: "bandadaValidateProof",
345
+ checkNonceOfSIWEAddress: "checkNonceOfSIWEAddress"
340
346
  }
341
347
  };
342
348
 
@@ -687,19 +693,23 @@ const getChunksAndPreSignedUrls = async (cloudFunctions, bucketName, objectKey,
687
693
  * @param cloudFunctions <Functions> - the Firebase Cloud Functions service instance.
688
694
  * @param ceremonyId <string> - the unique identifier of the ceremony.
689
695
  * @param alreadyUploadedChunks Array<ETagWithPartNumber> - the temporary information about the already uploaded chunks.
696
+ * @param logger <GenericBar> - an optional logger to show progress.
690
697
  * @returns <Promise<Array<ETagWithPartNumber>>> - the completed (uploaded) chunks information.
691
698
  */
692
- const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremonyId, alreadyUploadedChunks) => {
699
+ const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremonyId, alreadyUploadedChunks, logger) => {
693
700
  // Keep track of uploaded chunks.
694
701
  const uploadedChunks = alreadyUploadedChunks || [];
702
+ // if we were passed a logger, start it
703
+ if (logger)
704
+ logger.start(chunksWithUrls.length, 0);
695
705
  // Loop through remaining chunks.
696
706
  for (let i = alreadyUploadedChunks ? alreadyUploadedChunks.length : 0; i < chunksWithUrls.length; i += 1) {
697
707
  // Consume the pre-signed url to upload the chunk.
698
708
  // @ts-ignore
699
709
  const response = await fetch(chunksWithUrls[i].preSignedUrl, {
700
710
  retryOptions: {
701
- retryInitialDelay: 500,
702
- socketTimeout: 60000,
711
+ retryInitialDelay: 500, // 500 ms.
712
+ socketTimeout: 60000, // 60 seconds.
703
713
  retryMaxDuration: 300000 // 5 minutes.
704
714
  },
705
715
  method: "PUT",
@@ -723,6 +733,9 @@ const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremony
723
733
  // nb. this must be done only when contributing (not finalizing).
724
734
  if (!!ceremonyId && !!cloudFunctions)
725
735
  await temporaryStoreCurrentContributionUploadedChunkData(cloudFunctions, ceremonyId, chunk);
736
+ // increment the count on the logger
737
+ if (logger)
738
+ logger.increment();
726
739
  }
727
740
  return uploadedChunks;
728
741
  };
@@ -743,8 +756,9 @@ const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremony
743
756
  * @param configStreamChunkSize <number> - size of each chunk into which the artifact is going to be splitted (nb. will be converted in MB).
744
757
  * @param [ceremonyId] <string> - the unique identifier of the ceremony (used as a double-edge sword - as identifier and as a check if current contributor is the coordinator finalizing the ceremony).
745
758
  * @param [temporaryDataToResumeMultiPartUpload] <TemporaryParticipantContributionData> - the temporary information necessary to resume an already started multi-part upload.
759
+ * @param logger <GenericBar> - an optional logger to show progress.
746
760
  */
747
- const multiPartUpload = async (cloudFunctions, bucketName, objectKey, localFilePath, configStreamChunkSize, ceremonyId, temporaryDataToResumeMultiPartUpload) => {
761
+ const multiPartUpload = async (cloudFunctions, bucketName, objectKey, localFilePath, configStreamChunkSize, ceremonyId, temporaryDataToResumeMultiPartUpload, logger) => {
748
762
  // The unique identifier of the multi-part upload.
749
763
  let multiPartUploadId = "";
750
764
  // The list of already uploaded chunks.
@@ -768,7 +782,7 @@ const multiPartUpload = async (cloudFunctions, bucketName, objectKey, localFileP
768
782
  const chunksWithUrlsZkey = await getChunksAndPreSignedUrls(cloudFunctions, bucketName, objectKey, localFilePath, multiPartUploadId, configStreamChunkSize, ceremonyId);
769
783
  // Step (2).
770
784
  const partNumbersAndETagsZkey = await uploadParts(chunksWithUrlsZkey, mime.lookup(localFilePath), // content-type.
771
- cloudFunctions, ceremonyId, alreadyUploadedChunks);
785
+ cloudFunctions, ceremonyId, alreadyUploadedChunks, logger);
772
786
  // Step (3).
773
787
  await completeMultiPartUpload(cloudFunctions, bucketName, objectKey, multiPartUploadId, partNumbersAndETagsZkey, ceremonyId);
774
788
  };
@@ -992,6 +1006,17 @@ const getClosedCeremonies = async (firestoreDatabase) => {
992
1006
  ]);
993
1007
  return fromQueryToFirebaseDocumentInfo(closedCeremoniesQuerySnap.docs);
994
1008
  };
1009
+ /**
1010
+ * Query all ceremonies
1011
+ * @notice get all ceremonies from the database.
1012
+ * @dev this is a helper for the CLI ceremony methods.
1013
+ * @param firestoreDatabase <Firestore> - the Firestore service instance associated to the current Firebase application.
1014
+ * @returns <Promise<Array<FirebaseDocumentInfo>>> - the list of all ceremonies.
1015
+ */
1016
+ const getAllCeremonies = async (firestoreDatabase) => {
1017
+ const ceremoniesQuerySnap = await queryCollection(firestoreDatabase, commonTerms.collections.ceremonies.name, []);
1018
+ return fromQueryToFirebaseDocumentInfo(ceremoniesQuerySnap.docs);
1019
+ };
995
1020
 
996
1021
  /**
997
1022
  * @hidden
@@ -1040,207 +1065,22 @@ const compareHashes = async (path1, path2) => {
1040
1065
  };
1041
1066
 
1042
1067
  /**
1043
- * Parse and validate that the ceremony configuration is correct
1044
- * @notice this does not upload any files to storage
1045
- * @param path <string> - the path to the configuration file
1046
- * @param cleanup <boolean> - whether to delete the r1cs file after parsing
1047
- * @returns any - the data to pass to the cloud function for setup and the circuit artifacts
1068
+ * Return a string with double digits if the provided input is one digit only.
1069
+ * @param in <number> - the input number to be converted.
1070
+ * @returns <string> - the two digits stringified number derived from the conversion.
1048
1071
  */
1049
- const parseCeremonyFile = async (path, cleanup = false) => {
1050
- // check that the path exists
1051
- if (!fs.existsSync(path))
1052
- throw new Error("The provided path to the configuration file does not exist. Please provide an absolute path and try again.");
1053
- try {
1054
- // read the data
1055
- const data = JSON.parse(fs.readFileSync(path).toString());
1056
- // verify that the data is correct
1057
- if (data['timeoutMechanismType'] !== "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */ && data['timeoutMechanismType'] !== "FIXED" /* CeremonyTimeoutType.FIXED */)
1058
- throw new Error("Invalid timeout type. Please choose between DYNAMIC and FIXED.");
1059
- // validate that we have at least 1 circuit input data
1060
- if (!data.circuits || data.circuits.length === 0)
1061
- throw new Error("You need to provide the data for at least 1 circuit.");
1062
- // validate that the end date is in the future
1063
- let endDate;
1064
- let startDate;
1065
- try {
1066
- endDate = new Date(data.endDate);
1067
- startDate = new Date(data.startDate);
1068
- }
1069
- catch (error) {
1070
- throw new Error("The dates should follow this format: 2023-07-04T00:00:00.");
1071
- }
1072
- if (endDate <= startDate)
1073
- throw new Error("The end date should be greater than the start date.");
1074
- const currentDate = new Date();
1075
- if (endDate <= currentDate || startDate <= currentDate)
1076
- throw new Error("The start and end dates should be in the future.");
1077
- // validate penalty
1078
- if (data.penalty <= 0)
1079
- throw new Error("The penalty should be greater than zero.");
1080
- const circuits = [];
1081
- const urlPattern = /(https?:\/\/[^\s]+)/g;
1082
- const commitHashPattern = /^[a-f0-9]{40}$/i;
1083
- const circuitArtifacts = [];
1084
- for (let i = 0; i < data.circuits.length; i++) {
1085
- const circuitData = data.circuits[i];
1086
- const artifacts = circuitData.artifacts;
1087
- circuitArtifacts.push({
1088
- artifacts: artifacts
1089
- });
1090
- const r1csPath = artifacts.r1csStoragePath;
1091
- const wasmPath = artifacts.wasmStoragePath;
1092
- // where we storing the r1cs downloaded
1093
- const localR1csPath = `./${circuitData.name}.r1cs`;
1094
- // check that the artifacts exist in S3
1095
- // we don't need any privileges to download this
1096
- // just the correct region
1097
- const s3 = new clientS3.S3Client({ region: artifacts.region });
1098
- try {
1099
- await s3.send(new clientS3.HeadObjectCommand({
1100
- Bucket: artifacts.bucket,
1101
- Key: r1csPath
1102
- }));
1103
- }
1104
- catch (error) {
1105
- throw new Error(`The r1cs file (${r1csPath}) seems to not exist. Please ensure this is correct and that the object is publicly available.`);
1106
- }
1107
- try {
1108
- await s3.send(new clientS3.HeadObjectCommand({
1109
- Bucket: artifacts.bucket,
1110
- Key: wasmPath
1111
- }));
1112
- }
1113
- catch (error) {
1114
- throw new Error(`The wasm file (${wasmPath}) seems to not exist. Please ensure this is correct and that the object is publicly available.`);
1115
- }
1116
- // download the r1cs to extract the metadata
1117
- const command = new clientS3.GetObjectCommand({ Bucket: artifacts.bucket, Key: artifacts.r1csStoragePath });
1118
- const response = await s3.send(command);
1119
- const streamPipeline = util.promisify(stream.pipeline);
1120
- if (response.$metadata.httpStatusCode !== 200)
1121
- 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.");
1122
- if (response.Body instanceof stream.Readable)
1123
- await streamPipeline(response.Body, fs.createWriteStream(localR1csPath));
1124
- // extract the metadata from the r1cs
1125
- const metadata = getR1CSInfo(localR1csPath);
1126
- // validate that the circuit hash and template links are valid
1127
- const template = circuitData.template;
1128
- const URLMatch = template.source.match(urlPattern);
1129
- if (!URLMatch || URLMatch.length === 0 || URLMatch.length > 1)
1130
- throw new Error("You should provide the URL to the circuits templates on GitHub.");
1131
- const hashMatch = template.commitHash.match(commitHashPattern);
1132
- if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1)
1133
- throw new Error("You should provide a valid commit hash of the circuit templates.");
1134
- // calculate the hash of the r1cs file
1135
- const r1csBlake2bHash = await blake512FromPath(localR1csPath);
1136
- const circuitPrefix = extractPrefix(circuitData.name);
1137
- // filenames
1138
- const doubleDigitsPowers = convertToDoubleDigits(metadata.pot);
1139
- const r1csCompleteFilename = `${circuitData.name}.r1cs`;
1140
- const wasmCompleteFilename = `${circuitData.name}.wasm`;
1141
- const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`;
1142
- const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`;
1143
- // storage paths
1144
- const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename);
1145
- const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename);
1146
- const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit);
1147
- const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename);
1148
- const files = {
1149
- potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
1150
- r1csFilename: r1csCompleteFilename,
1151
- wasmFilename: wasmCompleteFilename,
1152
- initialZkeyFilename: firstZkeyCompleteFilename,
1153
- potStoragePath: potStorageFilePath,
1154
- r1csStoragePath: r1csStorageFilePath,
1155
- wasmStoragePath: wasmStorageFilePath,
1156
- initialZkeyStoragePath: zkeyStorageFilePath,
1157
- r1csBlake2bHash: r1csBlake2bHash
1158
- };
1159
- // validate that the compiler hash is a valid hash
1160
- const compiler = circuitData.compiler;
1161
- const compilerHashMatch = compiler.commitHash.match(commitHashPattern);
1162
- if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1)
1163
- throw new Error("You should provide a valid commit hash of the circuit compiler.");
1164
- // validate that the verification options are valid
1165
- const verification = circuitData.verification;
1166
- if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
1167
- throw new Error("Please enter a valid verification mechanism: either CF or VM");
1168
- // @todo VM parameters verification
1169
- // if (verification['cfOrVM'] === "VM") {}
1170
- // check that the timeout is provided for the correct configuration
1171
- let dynamicThreshold;
1172
- let fixedTimeWindow;
1173
- let circuit = {};
1174
- if (data.timeoutMechanismType === "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */) {
1175
- if (circuitData.dynamicThreshold <= 0)
1176
- throw new Error("The dynamic threshold should be > 0.");
1177
- dynamicThreshold = circuitData.dynamicThreshold;
1178
- // the Circuit data for the ceremony setup
1179
- circuit = {
1180
- name: circuitData.name,
1181
- description: circuitData.description,
1182
- prefix: circuitPrefix,
1183
- sequencePosition: i + 1,
1184
- metadata: metadata,
1185
- files: files,
1186
- template: template,
1187
- compiler: compiler,
1188
- verification: verification,
1189
- dynamicThreshold: dynamicThreshold,
1190
- avgTimings: {
1191
- contributionComputation: 0,
1192
- fullContribution: 0,
1193
- verifyCloudFunction: 0
1194
- },
1195
- };
1196
- }
1197
- if (data.timeoutMechanismType === "FIXED" /* CeremonyTimeoutType.FIXED */) {
1198
- if (circuitData.fixedTimeWindow <= 0)
1199
- throw new Error("The fixed time window threshold should be > 0.");
1200
- fixedTimeWindow = circuitData.fixedTimeWindow;
1201
- // the Circuit data for the ceremony setup
1202
- circuit = {
1203
- name: circuitData.name,
1204
- description: circuitData.description,
1205
- prefix: circuitPrefix,
1206
- sequencePosition: i + 1,
1207
- metadata: metadata,
1208
- files: files,
1209
- template: template,
1210
- compiler: compiler,
1211
- verification: verification,
1212
- fixedTimeWindow: fixedTimeWindow,
1213
- avgTimings: {
1214
- contributionComputation: 0,
1215
- fullContribution: 0,
1216
- verifyCloudFunction: 0
1217
- },
1218
- };
1219
- }
1220
- circuits.push(circuit);
1221
- // remove the local r1cs download (if used for verifying the config only vs setup)
1222
- if (cleanup)
1223
- fs.unlinkSync(localR1csPath);
1224
- }
1225
- const setupData = {
1226
- ceremonyInputData: {
1227
- title: data.title,
1228
- description: data.description,
1229
- startDate: startDate.valueOf(),
1230
- endDate: endDate.valueOf(),
1231
- timeoutMechanismType: data.timeoutMechanismType,
1232
- penalty: data.penalty
1233
- },
1234
- ceremonyPrefix: extractPrefix(data.title),
1235
- circuits: circuits,
1236
- circuitArtifacts: circuitArtifacts
1237
- };
1238
- return setupData;
1239
- }
1240
- catch (error) {
1241
- throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`);
1242
- }
1243
- };
1072
+ const convertToDoubleDigits = (amount) => (amount < 10 ? `0${amount}` : amount.toString());
1073
+ /**
1074
+ * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
1075
+ * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
1076
+ * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
1077
+ * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
1078
+ * @param str <string> - the arbitrary string from which to extract the prefix.
1079
+ * @returns <string> - the resulting prefix.
1080
+ */
1081
+ const extractPrefix = (str) =>
1082
+ // eslint-disable-next-line no-useless-escape
1083
+ str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase();
1244
1084
  /**
1245
1085
  * Extract data from a R1CS metadata file generated with a custom file-based logger.
1246
1086
  * @notice useful for extracting metadata circuits contained in the generated file using a logger
@@ -1297,17 +1137,6 @@ const formatZkeyIndex = (progress) => {
1297
1137
  * @returns <number> - the amount of powers.
1298
1138
  */
1299
1139
  const extractPoTFromFilename = (potCompleteFilename) => Number(potCompleteFilename.split("_").pop()?.split(".").at(0));
1300
- /**
1301
- * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
1302
- * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
1303
- * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
1304
- * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
1305
- * @param str <string> - the arbitrary string from which to extract the prefix.
1306
- * @returns <string> - the resulting prefix.
1307
- */
1308
- const extractPrefix = (str) =>
1309
- // eslint-disable-next-line no-useless-escape
1310
- str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase();
1311
1140
  /**
1312
1141
  * Automate the generation of an entropy for a contribution.
1313
1142
  * @dev Took inspiration from here https://github.com/glamperd/setup-mpc-ui/blob/master/client/src/state/Compute.tsx#L112.
@@ -1374,7 +1203,9 @@ const getContributionsValidityForContributor = async (firestoreDatabase, circuit
1374
1203
  * @param isFinalizing <boolean> - true when the coordinator is finalizing the ceremony, otherwise false.
1375
1204
  * @returns <string> - the public attestation preamble.
1376
1205
  */
1377
- const getPublicAttestationPreambleForContributor = (contributorIdentifier, ceremonyName, isFinalizing) => `Hey, I'm ${contributorIdentifier} and I have ${isFinalizing ? "finalized" : "contributed to"} the ${ceremonyName} MPC Phase2 Trusted Setup ceremony.\nThe following are my contribution signatures:`;
1206
+ const getPublicAttestationPreambleForContributor = (contributorIdentifier, ceremonyName, isFinalizing) => `Hey, I'm ${contributorIdentifier} and I have ${isFinalizing ? "finalized" : "contributed to"} the ${ceremonyName}${ceremonyName.toLowerCase().includes("trusted setup") || ceremonyName.toLowerCase().includes("ceremony")
1207
+ ? "."
1208
+ : " MPC Phase2 Trusted Setup ceremony."}\nThe following are my contribution signatures:`;
1378
1209
  /**
1379
1210
  * Check and prepare public attestation for the contributor made only of its valid contributions.
1380
1211
  * @param firestoreDatabase <Firestore> - the Firestore service instance associated to the current Firebase application.
@@ -1445,6 +1276,41 @@ const readBytesFromFile = (localFilePath, offset, length, position) => {
1445
1276
  // Return the read bytes.
1446
1277
  return buffer;
1447
1278
  };
1279
+ /**
1280
+ * Given a buffer in little endian format, convert it to bigint
1281
+ * @param buffer
1282
+ * @returns
1283
+ */
1284
+ function leBufferToBigint(buffer) {
1285
+ return BigInt(`0x${buffer.reverse().toString("hex")}`);
1286
+ }
1287
+ /**
1288
+ * Given an input containing string values, convert them
1289
+ * to bigint
1290
+ * @param input - The input to convert
1291
+ * @returns the input with string values converted to bigint
1292
+ */
1293
+ const unstringifyBigInts = (input) => {
1294
+ if (typeof input === "string" && /^[0-9]+$/.test(input)) {
1295
+ return BigInt(input);
1296
+ }
1297
+ if (typeof input === "string" && /^0x[0-9a-fA-F]+$/.test(input)) {
1298
+ return BigInt(input);
1299
+ }
1300
+ if (Array.isArray(input)) {
1301
+ return input.map(unstringifyBigInts);
1302
+ }
1303
+ if (input === null) {
1304
+ return null;
1305
+ }
1306
+ if (typeof input === "object") {
1307
+ return Object.entries(input).reduce((acc, [key, value]) => {
1308
+ acc[key] = unstringifyBigInts(value);
1309
+ return acc;
1310
+ }, {});
1311
+ }
1312
+ return input;
1313
+ };
1448
1314
  /**
1449
1315
  * Return the info about the R1CS file.ù
1450
1316
  * @dev this method was built taking inspiration from
@@ -1505,17 +1371,17 @@ const getR1CSInfo = (localR1CSFilePath) => {
1505
1371
  let constraints = 0;
1506
1372
  try {
1507
1373
  // Get 'number of section' (jump magic r1cs and version1 data).
1508
- const numberOfSections = ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, 8));
1374
+ const numberOfSections = leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, 8));
1509
1375
  // Jump to first section.
1510
1376
  pointer = 12;
1511
1377
  // For each section
1512
1378
  for (let i = 0; i < numberOfSections; i++) {
1513
1379
  // Read section type.
1514
- const sectionType = ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer));
1380
+ const sectionType = leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer));
1515
1381
  // Jump to section size.
1516
1382
  pointer += 4;
1517
1383
  // Read section size
1518
- const sectionSize = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)));
1384
+ const sectionSize = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)));
1519
1385
  // If at header section (0x00000001 : Header Section).
1520
1386
  if (sectionType === BigInt(1)) {
1521
1387
  // Read info from header section.
@@ -1547,22 +1413,22 @@ const getR1CSInfo = (localR1CSFilePath) => {
1547
1413
  */
1548
1414
  pointer += sectionSize - 20;
1549
1415
  // Read R1CS info.
1550
- wires = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1416
+ wires = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1551
1417
  pointer += 4;
1552
- publicOutputs = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1418
+ publicOutputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1553
1419
  pointer += 4;
1554
- publicInputs = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1420
+ publicInputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1555
1421
  pointer += 4;
1556
- privateInputs = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1422
+ privateInputs = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1557
1423
  pointer += 4;
1558
- labels = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)));
1424
+ labels = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)));
1559
1425
  pointer += 8;
1560
- constraints = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1426
+ constraints = Number(leBufferToBigint(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1561
1427
  }
1562
1428
  pointer += 8 + Number(sectionSize);
1563
1429
  }
1564
1430
  return {
1565
- curve: "bn-128",
1431
+ curve: "bn-128", /// @note currently default to bn-128 as we support only Groth16 proving system.
1566
1432
  wires,
1567
1433
  constraints,
1568
1434
  privateInputs,
@@ -1577,11 +1443,194 @@ const getR1CSInfo = (localR1CSFilePath) => {
1577
1443
  }
1578
1444
  };
1579
1445
  /**
1580
- * Return a string with double digits if the provided input is one digit only.
1581
- * @param in <number> - the input number to be converted.
1582
- * @returns <string> - the two digits stringified number derived from the conversion.
1446
+ * Parse and validate that the ceremony configuration is correct
1447
+ * @notice this does not upload any files to storage
1448
+ * @param path <string> - the path to the configuration file
1449
+ * @param cleanup <boolean> - whether to delete the r1cs file after parsing
1450
+ * @returns any - the data to pass to the cloud function for setup and the circuit artifacts
1583
1451
  */
1584
- const convertToDoubleDigits = (amount) => (amount < 10 ? `0${amount}` : amount.toString());
1452
+ const parseCeremonyFile = async (path, cleanup = false) => {
1453
+ // check that the path exists
1454
+ if (!fs.existsSync(path))
1455
+ throw new Error("The provided path to the configuration file does not exist. Please provide an absolute path and try again.");
1456
+ try {
1457
+ // read the data
1458
+ const data = JSON.parse(fs.readFileSync(path).toString());
1459
+ // verify that the data is correct
1460
+ if (data.timeoutMechanismType !== "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */ &&
1461
+ data.timeoutMechanismType !== "FIXED" /* CeremonyTimeoutType.FIXED */)
1462
+ throw new Error("Invalid timeout type. Please choose between DYNAMIC and FIXED.");
1463
+ // validate that we have at least 1 circuit input data
1464
+ if (!data.circuits || data.circuits.length === 0)
1465
+ throw new Error("You need to provide the data for at least 1 circuit.");
1466
+ // validate that the end date is in the future
1467
+ let endDate;
1468
+ let startDate;
1469
+ try {
1470
+ endDate = new Date(data.endDate);
1471
+ startDate = new Date(data.startDate);
1472
+ }
1473
+ catch (error) {
1474
+ throw new Error("The dates should follow this format: 2023-07-04T00:00:00.");
1475
+ }
1476
+ if (endDate <= startDate)
1477
+ throw new Error("The end date should be greater than the start date.");
1478
+ const currentDate = new Date();
1479
+ if (endDate <= currentDate || startDate <= currentDate)
1480
+ throw new Error("The start and end dates should be in the future.");
1481
+ // validate penalty
1482
+ if (data.penalty <= 0)
1483
+ throw new Error("The penalty should be greater than zero.");
1484
+ const circuits = [];
1485
+ const urlPattern = /(https?:\/\/[^\s]+)/g;
1486
+ const commitHashPattern = /^[a-f0-9]{40}$/i;
1487
+ const circuitArtifacts = [];
1488
+ for (let i = 0; i < data.circuits.length; i++) {
1489
+ const circuitData = data.circuits[i];
1490
+ const { artifacts } = circuitData;
1491
+ circuitArtifacts.push({
1492
+ artifacts
1493
+ });
1494
+ // where we storing the r1cs downloaded
1495
+ const localR1csPath = `./${circuitData.name}.r1cs`;
1496
+ // where we storing the wasm downloaded
1497
+ const localWasmPath = `./${circuitData.name}.wasm`;
1498
+ // download the r1cs to extract the metadata
1499
+ const streamPipeline = util.promisify(stream.pipeline);
1500
+ // Make the call.
1501
+ const responseR1CS = await fetch(artifacts.r1csStoragePath);
1502
+ // Handle errors.
1503
+ if (!responseR1CS.ok && responseR1CS.status !== 200)
1504
+ 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.`);
1505
+ await streamPipeline(responseR1CS.body, fs.createWriteStream(localR1csPath));
1506
+ // Write the file locally
1507
+ // extract the metadata from the r1cs
1508
+ const metadata = getR1CSInfo(localR1csPath);
1509
+ // download wasm too to ensure it's available
1510
+ const responseWASM = await fetch(artifacts.wasmStoragePath);
1511
+ if (!responseWASM.ok && responseWASM.status !== 200)
1512
+ 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.`);
1513
+ await streamPipeline(responseWASM.body, fs.createWriteStream(localWasmPath));
1514
+ // validate that the circuit hash and template links are valid
1515
+ const { template } = circuitData;
1516
+ const URLMatch = template.source.match(urlPattern);
1517
+ if (!URLMatch || URLMatch.length === 0 || URLMatch.length > 1)
1518
+ throw new Error("You should provide the URL to the circuits templates on GitHub.");
1519
+ const hashMatch = template.commitHash.match(commitHashPattern);
1520
+ if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1)
1521
+ throw new Error("You should provide a valid commit hash of the circuit templates.");
1522
+ // calculate the hash of the r1cs file
1523
+ const r1csBlake2bHash = await blake512FromPath(localR1csPath);
1524
+ const circuitPrefix = extractPrefix(circuitData.name);
1525
+ // filenames
1526
+ const doubleDigitsPowers = convertToDoubleDigits(metadata.pot);
1527
+ const r1csCompleteFilename = `${circuitData.name}.r1cs`;
1528
+ const wasmCompleteFilename = `${circuitData.name}.wasm`;
1529
+ const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`;
1530
+ const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`;
1531
+ // storage paths
1532
+ const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename);
1533
+ const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename);
1534
+ const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit);
1535
+ const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename);
1536
+ const files = {
1537
+ potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
1538
+ r1csFilename: r1csCompleteFilename,
1539
+ wasmFilename: wasmCompleteFilename,
1540
+ initialZkeyFilename: firstZkeyCompleteFilename,
1541
+ potStoragePath: potStorageFilePath,
1542
+ r1csStoragePath: r1csStorageFilePath,
1543
+ wasmStoragePath: wasmStorageFilePath,
1544
+ initialZkeyStoragePath: zkeyStorageFilePath,
1545
+ r1csBlake2bHash
1546
+ };
1547
+ // validate that the compiler hash is a valid hash
1548
+ const { compiler } = circuitData;
1549
+ const compilerHashMatch = compiler.commitHash.match(commitHashPattern);
1550
+ if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1)
1551
+ throw new Error("You should provide a valid commit hash of the circuit compiler.");
1552
+ // validate that the verification options are valid
1553
+ const { verification } = circuitData;
1554
+ if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
1555
+ throw new Error("Please enter a valid verification mechanism: either CF or VM");
1556
+ // @todo VM parameters verification
1557
+ // if (verification['cfOrVM'] === "VM") {}
1558
+ // check that the timeout is provided for the correct configuration
1559
+ let dynamicThreshold;
1560
+ let fixedTimeWindow;
1561
+ let circuit = {};
1562
+ if (data.timeoutMechanismType === "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */) {
1563
+ if (circuitData.dynamicThreshold <= 0)
1564
+ throw new Error("The dynamic threshold should be > 0.");
1565
+ dynamicThreshold = circuitData.dynamicThreshold;
1566
+ // the Circuit data for the ceremony setup
1567
+ circuit = {
1568
+ name: circuitData.name,
1569
+ description: circuitData.description,
1570
+ prefix: circuitPrefix,
1571
+ sequencePosition: i + 1,
1572
+ metadata,
1573
+ files,
1574
+ template,
1575
+ compiler,
1576
+ verification,
1577
+ dynamicThreshold,
1578
+ avgTimings: {
1579
+ contributionComputation: 0,
1580
+ fullContribution: 0,
1581
+ verifyCloudFunction: 0
1582
+ }
1583
+ };
1584
+ }
1585
+ if (data.timeoutMechanismType === "FIXED" /* CeremonyTimeoutType.FIXED */) {
1586
+ if (circuitData.fixedTimeWindow <= 0)
1587
+ throw new Error("The fixed time window threshold should be > 0.");
1588
+ fixedTimeWindow = circuitData.fixedTimeWindow;
1589
+ // the Circuit data for the ceremony setup
1590
+ circuit = {
1591
+ name: circuitData.name,
1592
+ description: circuitData.description,
1593
+ prefix: circuitPrefix,
1594
+ sequencePosition: i + 1,
1595
+ metadata,
1596
+ files,
1597
+ template,
1598
+ compiler,
1599
+ verification,
1600
+ fixedTimeWindow,
1601
+ avgTimings: {
1602
+ contributionComputation: 0,
1603
+ fullContribution: 0,
1604
+ verifyCloudFunction: 0
1605
+ }
1606
+ };
1607
+ }
1608
+ circuits.push(circuit);
1609
+ // remove the local r1cs and wasm downloads (if used for verifying the config only vs setup)
1610
+ if (cleanup) {
1611
+ fs.unlinkSync(localR1csPath);
1612
+ fs.unlinkSync(localWasmPath);
1613
+ }
1614
+ }
1615
+ const setupData = {
1616
+ ceremonyInputData: {
1617
+ title: data.title,
1618
+ description: data.description,
1619
+ startDate: startDate.valueOf(),
1620
+ endDate: endDate.valueOf(),
1621
+ timeoutMechanismType: data.timeoutMechanismType,
1622
+ penalty: data.penalty
1623
+ },
1624
+ ceremonyPrefix: extractPrefix(data.title),
1625
+ circuits,
1626
+ circuitArtifacts
1627
+ };
1628
+ return setupData;
1629
+ }
1630
+ catch (error) {
1631
+ throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`);
1632
+ }
1633
+ };
1585
1634
 
1586
1635
  /**
1587
1636
  * Verify that a zKey is valid
@@ -1830,7 +1879,7 @@ const getFirestoreDatabase = (app) => firestore.getFirestore(app);
1830
1879
  * @param app <FirebaseApp> - the Firebase application.
1831
1880
  * @returns <Functions> - the Cloud Functions associated to the application.
1832
1881
  */
1833
- const getFirebaseFunctions = (app) => functions.getFunctions(app, 'europe-west1');
1882
+ const getFirebaseFunctions = (app) => functions.getFunctions(app, "europe-west1");
1834
1883
  /**
1835
1884
  * Retrieve the configuration variables for the AWS services (S3, EC2).
1836
1885
  * @returns <AWSVariables> - the values of the AWS services configuration variables.
@@ -1839,14 +1888,14 @@ const getAWSVariables = () => {
1839
1888
  if (!process.env.AWS_ACCESS_KEY_ID ||
1840
1889
  !process.env.AWS_SECRET_ACCESS_KEY ||
1841
1890
  !process.env.AWS_REGION ||
1842
- !process.env.AWS_ROLE_ARN ||
1891
+ !process.env.AWS_INSTANCE_PROFILE_ARN ||
1843
1892
  !process.env.AWS_AMI_ID)
1844
1893
  throw new Error("Could not retrieve the AWS environment variables. Please, verify your environment configuration and retry");
1845
1894
  return {
1846
1895
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
1847
1896
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
1848
1897
  region: process.env.AWS_REGION || "us-east-1",
1849
- roleArn: process.env.AWS_ROLE_ARN,
1898
+ instanceProfileArn: process.env.AWS_INSTANCE_PROFILE_ARN,
1850
1899
  amiId: process.env.AWS_AMI_ID
1851
1900
  };
1852
1901
  };
@@ -1927,11 +1976,11 @@ const p256 = (proofPart) => {
1927
1976
  */
1928
1977
  const formatSolidityCalldata = (circuitInput, _proof) => {
1929
1978
  try {
1930
- const proof = ffjavascript.utils.unstringifyBigInts(_proof);
1979
+ const proof = unstringifyBigInts(_proof);
1931
1980
  // format the public inputs to the circuit
1932
1981
  const formattedCircuitInput = [];
1933
1982
  for (const cInput of circuitInput) {
1934
- formattedCircuitInput.push(p256(ffjavascript.utils.unstringifyBigInts(cInput)));
1983
+ formattedCircuitInput.push(p256(unstringifyBigInts(cInput)));
1935
1984
  }
1936
1985
  // construct calldata
1937
1986
  const calldata = {
@@ -2081,55 +2130,28 @@ const verifyCeremony = async (functions, firestore$1, ceremonyPrefix, outputDire
2081
2130
  };
2082
2131
 
2083
2132
  /**
2084
- * This function will return the number of public repos of a user
2085
- * @param user <string> The username of the user
2086
- * @returns <number> The number of public repos
2087
- */
2088
- const getNumberOfPublicReposGitHub = async (user) => {
2089
- const response = await fetch(`https://api.github.com/user/${user}/repos`, {
2090
- method: "GET",
2091
- headers: {
2092
- Authorization: `token ${process.env.GITHUB_ACCESS_TOKEN}`
2093
- }
2094
- });
2095
- if (response.status !== 200)
2096
- throw new Error("It was not possible to retrieve the number of public repositories. Please try again.");
2097
- const jsonData = await response.json();
2098
- return jsonData.length;
2099
- };
2100
- /**
2101
- * This function will return the number of followers of a user
2102
- * @param user <string> The username of the user
2103
- * @returns <number> The number of followers
2133
+ * This function queries the GitHub API to fetch users statistics
2134
+ * @param user {string} the user uid
2135
+ * @returns {any} the stats from the GitHub API
2104
2136
  */
2105
- const getNumberOfFollowersGitHub = async (user) => {
2106
- const response = await fetch(`https://api.github.com/user/${user}/followers`, {
2137
+ const getGitHubStats = async (user) => {
2138
+ const response = await fetch(`https://api.github.com/user/${user}`, {
2107
2139
  method: "GET",
2108
2140
  headers: {
2109
2141
  Authorization: `token ${process.env.GITHUB_ACCESS_TOKEN}`
2110
2142
  }
2111
2143
  });
2112
2144
  if (response.status !== 200)
2113
- throw new Error("It was not possible to retrieve the number of followers. Please try again.");
2145
+ throw new Error("It was not possible to retrieve the user's statistic. Please try again.");
2114
2146
  const jsonData = await response.json();
2115
- return jsonData.length;
2116
- };
2117
- /**
2118
- * This function will return the number of following of a user
2119
- * @param user <string> The username of the user
2120
- * @returns <number> The number of following users
2121
- */
2122
- const getNumberOfFollowingGitHub = async (user) => {
2123
- const response = await fetch(`https://api.github.com/user/${user}/following`, {
2124
- method: "GET",
2125
- headers: {
2126
- Authorization: `token ${process.env.GITHUB_ACCESS_TOKEN}`
2127
- }
2128
- });
2129
- if (response.status !== 200)
2130
- throw new Error("It was not possible to retrieve the number of following. Please try again.");
2131
- const jsonData = await response.json();
2132
- return jsonData.length;
2147
+ const data = {
2148
+ following: jsonData.following,
2149
+ followers: jsonData.followers,
2150
+ publicRepos: jsonData.public_repos,
2151
+ avatarUrl: jsonData.avatar_url,
2152
+ age: jsonData.created_at
2153
+ };
2154
+ return data;
2133
2155
  };
2134
2156
  /**
2135
2157
  * This function will check if the user is reputable enough to be able to use the app
@@ -2137,19 +2159,24 @@ const getNumberOfFollowingGitHub = async (user) => {
2137
2159
  * @param minimumAmountOfFollowing <number> The minimum amount of following the user should have
2138
2160
  * @param minimumAmountOfFollowers <number> The minimum amount of followers the user should have
2139
2161
  * @param minimumAmountOfPublicRepos <number> The minimum amount of public repos the user should have
2140
- * @returns <boolean> True if the user is reputable enough, false otherwise
2162
+ * @returns <any> Return the avatar URL of the user if the user is reputable, false otherwise
2141
2163
  */
2142
- const githubReputation = async (userLogin, minimumAmountOfFollowing, minimumAmountOfFollowers, minimumAmountOfPublicRepos) => {
2164
+ const githubReputation = async (userLogin, minimumAmountOfFollowing, minimumAmountOfFollowers, minimumAmountOfPublicRepos, minimumAge) => {
2143
2165
  if (!process.env.GITHUB_ACCESS_TOKEN)
2144
2166
  throw new Error("The GitHub access token is missing. Please insert a valid token to be used for anti-sybil checks on user registation, and then try again.");
2145
- const following = await getNumberOfFollowingGitHub(userLogin);
2146
- const repos = await getNumberOfPublicReposGitHub(userLogin);
2147
- const followers = await getNumberOfFollowersGitHub(userLogin);
2167
+ const { following, followers, publicRepos, avatarUrl, age } = await getGitHubStats(userLogin);
2148
2168
  if (following < minimumAmountOfFollowing ||
2149
- repos < minimumAmountOfPublicRepos ||
2150
- followers < minimumAmountOfFollowers)
2151
- return false;
2152
- return true;
2169
+ publicRepos < minimumAmountOfPublicRepos ||
2170
+ followers < minimumAmountOfFollowers ||
2171
+ new Date(age) > new Date(Date.now() - minimumAge))
2172
+ return {
2173
+ reputable: false,
2174
+ avatarUrl: ""
2175
+ };
2176
+ return {
2177
+ reputable: true,
2178
+ avatarUrl
2179
+ };
2153
2180
  };
2154
2181
 
2155
2182
  /**
@@ -2335,8 +2362,8 @@ const createSSMClient = async () => {
2335
2362
  * @returns <Array<string>> - the list of startup commands to be executed.
2336
2363
  */
2337
2364
  const vmBootstrapCommand = (bucketName) => [
2338
- "#!/bin/bash",
2339
- `aws s3 cp s3://${bucketName}/${vmBootstrapScriptFilename} ${vmBootstrapScriptFilename}`,
2365
+ "#!/bin/bash", // shabang.
2366
+ `aws s3 cp s3://${bucketName}/${vmBootstrapScriptFilename} ${vmBootstrapScriptFilename}`, // copy file from S3 bucket to VM.
2340
2367
  `chmod +x ${vmBootstrapScriptFilename} && bash ${vmBootstrapScriptFilename}` // grant permission and execute.
2341
2368
  ];
2342
2369
  /**
@@ -2357,8 +2384,13 @@ const vmDependenciesAndCacheArtifactsCommand = (zKeyPath, potPath, snsTopic, reg
2357
2384
  // eslint-disable-next-line no-template-curly-in-string
2358
2385
  "touch ${MARKER_FILE}",
2359
2386
  "sudo yum update -y",
2360
- "curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash - ",
2361
- "sudo yum install -y nodejs",
2387
+ "curl -O https://nodejs.org/dist/v16.13.0/node-v16.13.0-linux-x64.tar.xz",
2388
+ "tar -xf node-v16.13.0-linux-x64.tar.xz",
2389
+ "mv node-v16.13.0-linux-x64 nodejs",
2390
+ "sudo mv nodejs /opt/",
2391
+ "echo 'export NODEJS_HOME=/opt/nodejs' >> /etc/profile",
2392
+ "echo 'export PATH=$NODEJS_HOME/bin:$PATH' >> /etc/profile",
2393
+ "source /etc/profile",
2362
2394
  "npm install -g snarkjs",
2363
2395
  `aws s3 cp s3://${zKeyPath} /var/tmp/genesisZkey.zkey`,
2364
2396
  `aws s3 cp s3://${potPath} /var/tmp/pot.ptau`,
@@ -2377,6 +2409,7 @@ const vmDependenciesAndCacheArtifactsCommand = (zKeyPath, potPath, snsTopic, reg
2377
2409
  * @returns Array<string> - the list of commands for contribution verification.
2378
2410
  */
2379
2411
  const vmContributionVerificationCommand = (bucketName, lastZkeyStoragePath, verificationTranscriptStoragePathAndFilename) => [
2412
+ `source /etc/profile`,
2380
2413
  `aws s3 cp s3://${bucketName}/${lastZkeyStoragePath} /var/tmp/lastZKey.zkey > /var/tmp/log.txt`,
2381
2414
  `snarkjs zkvi /var/tmp/genesisZkey.zkey /var/tmp/pot.ptau /var/tmp/lastZKey.zkey > /var/tmp/verification_transcript.log`,
2382
2415
  `aws s3 cp /var/tmp/verification_transcript.log s3://${bucketName}/${verificationTranscriptStoragePathAndFilename} &>/dev/null`,
@@ -2403,7 +2436,7 @@ const computeDiskSizeForVM = (zKeySizeInBytes, pot) => Math.ceil(2 * convertByte
2403
2436
  */
2404
2437
  const createEC2Instance = async (ec2, commands, instanceType, volumeSize, diskType) => {
2405
2438
  // Get the AWS variables.
2406
- const { amiId, roleArn } = getAWSVariables();
2439
+ const { amiId, instanceProfileArn } = getAWSVariables();
2407
2440
  // Parametrize the VM EC2 instance.
2408
2441
  const params = {
2409
2442
  ImageId: amiId,
@@ -2412,7 +2445,7 @@ const createEC2Instance = async (ec2, commands, instanceType, volumeSize, diskTy
2412
2445
  MinCount: 1,
2413
2446
  // nb. to find this: iam -> roles -> role_name.
2414
2447
  IamInstanceProfile: {
2415
- Arn: roleArn
2448
+ Arn: instanceProfileArn
2416
2449
  },
2417
2450
  // nb. for running commands at the startup.
2418
2451
  UserData: Buffer.from(commands.join("\n")).toString("base64"),
@@ -2421,7 +2454,7 @@ const createEC2Instance = async (ec2, commands, instanceType, volumeSize, diskTy
2421
2454
  DeviceName: "/dev/xvda",
2422
2455
  Ebs: {
2423
2456
  DeleteOnTermination: true,
2424
- VolumeSize: volumeSize,
2457
+ VolumeSize: volumeSize, // disk size in GB.
2425
2458
  VolumeType: diskType
2426
2459
  }
2427
2460
  }
@@ -2649,6 +2682,7 @@ exports.generatePreSignedUrlsParts = generatePreSignedUrlsParts;
2649
2682
  exports.generateValidContributionsAttestation = generateValidContributionsAttestation;
2650
2683
  exports.generateZkeyFromScratch = generateZkeyFromScratch;
2651
2684
  exports.genesisZkeyIndex = genesisZkeyIndex;
2685
+ exports.getAllCeremonies = getAllCeremonies;
2652
2686
  exports.getAllCollectionDocs = getAllCollectionDocs;
2653
2687
  exports.getBucketName = getBucketName;
2654
2688
  exports.getCeremonyCircuits = getCeremonyCircuits;