@devtion/actions 0.0.0-9c50f66 → 0.0.0-a9e4cd4

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.
@@ -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
@@ -19,7 +19,6 @@ var crypto = require('crypto');
19
19
  var blake = require('blakejs');
20
20
  var ffjavascript = require('ffjavascript');
21
21
  var winston = require('winston');
22
- var clientS3 = require('@aws-sdk/client-s3');
23
22
  var stream = require('stream');
24
23
  var util = require('util');
25
24
  var app = require('firebase/app');
@@ -342,7 +341,7 @@ const commonTerms = {
342
341
  finalizeCircuit: "finalizeCircuit",
343
342
  finalizeCeremony: "finalizeCeremony",
344
343
  downloadCircuitArtifacts: "downloadCircuitArtifacts",
345
- transferObject: "transferObject",
344
+ transferObject: "transferObject"
346
345
  }
347
346
  };
348
347
 
@@ -693,11 +692,15 @@ const getChunksAndPreSignedUrls = async (cloudFunctions, bucketName, objectKey,
693
692
  * @param cloudFunctions <Functions> - the Firebase Cloud Functions service instance.
694
693
  * @param ceremonyId <string> - the unique identifier of the ceremony.
695
694
  * @param alreadyUploadedChunks Array<ETagWithPartNumber> - the temporary information about the already uploaded chunks.
695
+ * @param logger <GenericBar> - an optional logger to show progress.
696
696
  * @returns <Promise<Array<ETagWithPartNumber>>> - the completed (uploaded) chunks information.
697
697
  */
698
- const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremonyId, alreadyUploadedChunks) => {
698
+ const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremonyId, alreadyUploadedChunks, logger) => {
699
699
  // Keep track of uploaded chunks.
700
700
  const uploadedChunks = alreadyUploadedChunks || [];
701
+ // if we were passed a logger, start it
702
+ if (logger)
703
+ logger.start(chunksWithUrls.length, 0);
701
704
  // Loop through remaining chunks.
702
705
  for (let i = alreadyUploadedChunks ? alreadyUploadedChunks.length : 0; i < chunksWithUrls.length; i += 1) {
703
706
  // Consume the pre-signed url to upload the chunk.
@@ -729,6 +732,9 @@ const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremony
729
732
  // nb. this must be done only when contributing (not finalizing).
730
733
  if (!!ceremonyId && !!cloudFunctions)
731
734
  await temporaryStoreCurrentContributionUploadedChunkData(cloudFunctions, ceremonyId, chunk);
735
+ // increment the count on the logger
736
+ if (logger)
737
+ logger.increment();
732
738
  }
733
739
  return uploadedChunks;
734
740
  };
@@ -749,8 +755,9 @@ const uploadParts = async (chunksWithUrls, contentType, cloudFunctions, ceremony
749
755
  * @param configStreamChunkSize <number> - size of each chunk into which the artifact is going to be splitted (nb. will be converted in MB).
750
756
  * @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).
751
757
  * @param [temporaryDataToResumeMultiPartUpload] <TemporaryParticipantContributionData> - the temporary information necessary to resume an already started multi-part upload.
758
+ * @param logger <GenericBar> - an optional logger to show progress.
752
759
  */
753
- const multiPartUpload = async (cloudFunctions, bucketName, objectKey, localFilePath, configStreamChunkSize, ceremonyId, temporaryDataToResumeMultiPartUpload) => {
760
+ const multiPartUpload = async (cloudFunctions, bucketName, objectKey, localFilePath, configStreamChunkSize, ceremonyId, temporaryDataToResumeMultiPartUpload, logger) => {
754
761
  // The unique identifier of the multi-part upload.
755
762
  let multiPartUploadId = "";
756
763
  // The list of already uploaded chunks.
@@ -774,7 +781,7 @@ const multiPartUpload = async (cloudFunctions, bucketName, objectKey, localFileP
774
781
  const chunksWithUrlsZkey = await getChunksAndPreSignedUrls(cloudFunctions, bucketName, objectKey, localFilePath, multiPartUploadId, configStreamChunkSize, ceremonyId);
775
782
  // Step (2).
776
783
  const partNumbersAndETagsZkey = await uploadParts(chunksWithUrlsZkey, mime.lookup(localFilePath), // content-type.
777
- cloudFunctions, ceremonyId, alreadyUploadedChunks);
784
+ cloudFunctions, ceremonyId, alreadyUploadedChunks, logger);
778
785
  // Step (3).
779
786
  await completeMultiPartUpload(cloudFunctions, bucketName, objectKey, multiPartUploadId, partNumbersAndETagsZkey, ceremonyId);
780
787
  };
@@ -1046,207 +1053,22 @@ const compareHashes = async (path1, path2) => {
1046
1053
  };
1047
1054
 
1048
1055
  /**
1049
- * Parse and validate that the ceremony configuration is correct
1050
- * @notice this does not upload any files to storage
1051
- * @param path <string> - the path to the configuration file
1052
- * @param cleanup <boolean> - whether to delete the r1cs file after parsing
1053
- * @returns any - the data to pass to the cloud function for setup and the circuit artifacts
1056
+ * Return a string with double digits if the provided input is one digit only.
1057
+ * @param in <number> - the input number to be converted.
1058
+ * @returns <string> - the two digits stringified number derived from the conversion.
1054
1059
  */
1055
- const parseCeremonyFile = async (path, cleanup = false) => {
1056
- // check that the path exists
1057
- if (!fs.existsSync(path))
1058
- throw new Error("The provided path to the configuration file does not exist. Please provide an absolute path and try again.");
1059
- try {
1060
- // read the data
1061
- const data = JSON.parse(fs.readFileSync(path).toString());
1062
- // verify that the data is correct
1063
- if (data['timeoutMechanismType'] !== "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */ && data['timeoutMechanismType'] !== "FIXED" /* CeremonyTimeoutType.FIXED */)
1064
- throw new Error("Invalid timeout type. Please choose between DYNAMIC and FIXED.");
1065
- // validate that we have at least 1 circuit input data
1066
- if (!data.circuits || data.circuits.length === 0)
1067
- throw new Error("You need to provide the data for at least 1 circuit.");
1068
- // validate that the end date is in the future
1069
- let endDate;
1070
- let startDate;
1071
- try {
1072
- endDate = new Date(data.endDate);
1073
- startDate = new Date(data.startDate);
1074
- }
1075
- catch (error) {
1076
- throw new Error("The dates should follow this format: 2023-07-04T00:00:00.");
1077
- }
1078
- if (endDate <= startDate)
1079
- throw new Error("The end date should be greater than the start date.");
1080
- const currentDate = new Date();
1081
- if (endDate <= currentDate || startDate <= currentDate)
1082
- throw new Error("The start and end dates should be in the future.");
1083
- // validate penalty
1084
- if (data.penalty <= 0)
1085
- throw new Error("The penalty should be greater than zero.");
1086
- const circuits = [];
1087
- const urlPattern = /(https?:\/\/[^\s]+)/g;
1088
- const commitHashPattern = /^[a-f0-9]{40}$/i;
1089
- const circuitArtifacts = [];
1090
- for (let i = 0; i < data.circuits.length; i++) {
1091
- const circuitData = data.circuits[i];
1092
- const artifacts = circuitData.artifacts;
1093
- circuitArtifacts.push({
1094
- artifacts: artifacts
1095
- });
1096
- const r1csPath = artifacts.r1csStoragePath;
1097
- const wasmPath = artifacts.wasmStoragePath;
1098
- // where we storing the r1cs downloaded
1099
- const localR1csPath = `./${circuitData.name}.r1cs`;
1100
- // check that the artifacts exist in S3
1101
- // we don't need any privileges to download this
1102
- // just the correct region
1103
- const s3 = new clientS3.S3Client({ region: artifacts.region });
1104
- try {
1105
- await s3.send(new clientS3.HeadObjectCommand({
1106
- Bucket: artifacts.bucket,
1107
- Key: r1csPath
1108
- }));
1109
- }
1110
- catch (error) {
1111
- throw new Error(`The r1cs file (${r1csPath}) seems to not exist. Please ensure this is correct and that the object is publicly available.`);
1112
- }
1113
- try {
1114
- await s3.send(new clientS3.HeadObjectCommand({
1115
- Bucket: artifacts.bucket,
1116
- Key: wasmPath
1117
- }));
1118
- }
1119
- catch (error) {
1120
- throw new Error(`The wasm file (${wasmPath}) seems to not exist. Please ensure this is correct and that the object is publicly available.`);
1121
- }
1122
- // download the r1cs to extract the metadata
1123
- const command = new clientS3.GetObjectCommand({ Bucket: artifacts.bucket, Key: artifacts.r1csStoragePath });
1124
- const response = await s3.send(command);
1125
- const streamPipeline = util.promisify(stream.pipeline);
1126
- if (response.$metadata.httpStatusCode !== 200)
1127
- 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.");
1128
- if (response.Body instanceof stream.Readable)
1129
- await streamPipeline(response.Body, fs.createWriteStream(localR1csPath));
1130
- // extract the metadata from the r1cs
1131
- const metadata = getR1CSInfo(localR1csPath);
1132
- // validate that the circuit hash and template links are valid
1133
- const template = circuitData.template;
1134
- const URLMatch = template.source.match(urlPattern);
1135
- if (!URLMatch || URLMatch.length === 0 || URLMatch.length > 1)
1136
- throw new Error("You should provide the URL to the circuits templates on GitHub.");
1137
- const hashMatch = template.commitHash.match(commitHashPattern);
1138
- if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1)
1139
- throw new Error("You should provide a valid commit hash of the circuit templates.");
1140
- // calculate the hash of the r1cs file
1141
- const r1csBlake2bHash = await blake512FromPath(localR1csPath);
1142
- const circuitPrefix = extractPrefix(circuitData.name);
1143
- // filenames
1144
- const doubleDigitsPowers = convertToDoubleDigits(metadata.pot);
1145
- const r1csCompleteFilename = `${circuitData.name}.r1cs`;
1146
- const wasmCompleteFilename = `${circuitData.name}.wasm`;
1147
- const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`;
1148
- const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`;
1149
- // storage paths
1150
- const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename);
1151
- const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename);
1152
- const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit);
1153
- const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename);
1154
- const files = {
1155
- potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
1156
- r1csFilename: r1csCompleteFilename,
1157
- wasmFilename: wasmCompleteFilename,
1158
- initialZkeyFilename: firstZkeyCompleteFilename,
1159
- potStoragePath: potStorageFilePath,
1160
- r1csStoragePath: r1csStorageFilePath,
1161
- wasmStoragePath: wasmStorageFilePath,
1162
- initialZkeyStoragePath: zkeyStorageFilePath,
1163
- r1csBlake2bHash: r1csBlake2bHash
1164
- };
1165
- // validate that the compiler hash is a valid hash
1166
- const compiler = circuitData.compiler;
1167
- const compilerHashMatch = compiler.commitHash.match(commitHashPattern);
1168
- if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1)
1169
- throw new Error("You should provide a valid commit hash of the circuit compiler.");
1170
- // validate that the verification options are valid
1171
- const verification = circuitData.verification;
1172
- if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
1173
- throw new Error("Please enter a valid verification mechanism: either CF or VM");
1174
- // @todo VM parameters verification
1175
- // if (verification['cfOrVM'] === "VM") {}
1176
- // check that the timeout is provided for the correct configuration
1177
- let dynamicThreshold;
1178
- let fixedTimeWindow;
1179
- let circuit = {};
1180
- if (data.timeoutMechanismType === "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */) {
1181
- if (circuitData.dynamicThreshold <= 0)
1182
- throw new Error("The dynamic threshold should be > 0.");
1183
- dynamicThreshold = circuitData.dynamicThreshold;
1184
- // the Circuit data for the ceremony setup
1185
- circuit = {
1186
- name: circuitData.name,
1187
- description: circuitData.description,
1188
- prefix: circuitPrefix,
1189
- sequencePosition: i + 1,
1190
- metadata: metadata,
1191
- files: files,
1192
- template: template,
1193
- compiler: compiler,
1194
- verification: verification,
1195
- dynamicThreshold: dynamicThreshold,
1196
- avgTimings: {
1197
- contributionComputation: 0,
1198
- fullContribution: 0,
1199
- verifyCloudFunction: 0
1200
- },
1201
- };
1202
- }
1203
- if (data.timeoutMechanismType === "FIXED" /* CeremonyTimeoutType.FIXED */) {
1204
- if (circuitData.fixedTimeWindow <= 0)
1205
- throw new Error("The fixed time window threshold should be > 0.");
1206
- fixedTimeWindow = circuitData.fixedTimeWindow;
1207
- // the Circuit data for the ceremony setup
1208
- circuit = {
1209
- name: circuitData.name,
1210
- description: circuitData.description,
1211
- prefix: circuitPrefix,
1212
- sequencePosition: i + 1,
1213
- metadata: metadata,
1214
- files: files,
1215
- template: template,
1216
- compiler: compiler,
1217
- verification: verification,
1218
- fixedTimeWindow: fixedTimeWindow,
1219
- avgTimings: {
1220
- contributionComputation: 0,
1221
- fullContribution: 0,
1222
- verifyCloudFunction: 0
1223
- },
1224
- };
1225
- }
1226
- circuits.push(circuit);
1227
- // remove the local r1cs download (if used for verifying the config only vs setup)
1228
- if (cleanup)
1229
- fs.unlinkSync(localR1csPath);
1230
- }
1231
- const setupData = {
1232
- ceremonyInputData: {
1233
- title: data.title,
1234
- description: data.description,
1235
- startDate: startDate.valueOf(),
1236
- endDate: endDate.valueOf(),
1237
- timeoutMechanismType: data.timeoutMechanismType,
1238
- penalty: data.penalty
1239
- },
1240
- ceremonyPrefix: extractPrefix(data.title),
1241
- circuits: circuits,
1242
- circuitArtifacts: circuitArtifacts
1243
- };
1244
- return setupData;
1245
- }
1246
- catch (error) {
1247
- throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`);
1248
- }
1249
- };
1060
+ const convertToDoubleDigits = (amount) => (amount < 10 ? `0${amount}` : amount.toString());
1061
+ /**
1062
+ * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
1063
+ * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
1064
+ * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
1065
+ * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
1066
+ * @param str <string> - the arbitrary string from which to extract the prefix.
1067
+ * @returns <string> - the resulting prefix.
1068
+ */
1069
+ const extractPrefix = (str) =>
1070
+ // eslint-disable-next-line no-useless-escape
1071
+ str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase();
1250
1072
  /**
1251
1073
  * Extract data from a R1CS metadata file generated with a custom file-based logger.
1252
1074
  * @notice useful for extracting metadata circuits contained in the generated file using a logger
@@ -1303,17 +1125,6 @@ const formatZkeyIndex = (progress) => {
1303
1125
  * @returns <number> - the amount of powers.
1304
1126
  */
1305
1127
  const extractPoTFromFilename = (potCompleteFilename) => Number(potCompleteFilename.split("_").pop()?.split(".").at(0));
1306
- /**
1307
- * Extract a prefix consisting of alphanumeric and underscore characters from a string with arbitrary characters.
1308
- * @dev replaces all special symbols and whitespaces with an underscore char ('_'). Convert all uppercase chars to lowercase.
1309
- * @notice example: str = 'Multiplier-2!2.4.zkey'; output prefix = 'multiplier_2_2_4.zkey'.
1310
- * NB. Prefix extraction is a key process that conditions the name of the ceremony artifacts, download/upload from/to storage, collections paths.
1311
- * @param str <string> - the arbitrary string from which to extract the prefix.
1312
- * @returns <string> - the resulting prefix.
1313
- */
1314
- const extractPrefix = (str) =>
1315
- // eslint-disable-next-line no-useless-escape
1316
- str.replace(/[`\s~!@#$%^&*()|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").toLowerCase();
1317
1128
  /**
1318
1129
  * Automate the generation of an entropy for a contribution.
1319
1130
  * @dev Took inspiration from here https://github.com/glamperd/setup-mpc-ui/blob/master/client/src/state/Compute.tsx#L112.
@@ -1380,7 +1191,9 @@ const getContributionsValidityForContributor = async (firestoreDatabase, circuit
1380
1191
  * @param isFinalizing <boolean> - true when the coordinator is finalizing the ceremony, otherwise false.
1381
1192
  * @returns <string> - the public attestation preamble.
1382
1193
  */
1383
- 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:`;
1194
+ 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")
1195
+ ? "."
1196
+ : " MPC Phase2 Trusted Setup ceremony."}\nThe following are my contribution signatures:`;
1384
1197
  /**
1385
1198
  * Check and prepare public attestation for the contributor made only of its valid contributions.
1386
1199
  * @param firestoreDatabase <Firestore> - the Firestore service instance associated to the current Firebase application.
@@ -1514,8 +1327,9 @@ const getR1CSInfo = (localR1CSFilePath) => {
1514
1327
  const numberOfSections = ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, 8));
1515
1328
  // Jump to first section.
1516
1329
  pointer = 12;
1330
+ let found = false;
1517
1331
  // For each section
1518
- for (let i = 0; i < numberOfSections; i++) {
1332
+ for (let i = 0; i < numberOfSections && !found; i++) {
1519
1333
  // Read section type.
1520
1334
  const sectionType = ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer));
1521
1335
  // Jump to section size.
@@ -1564,6 +1378,7 @@ const getR1CSInfo = (localR1CSFilePath) => {
1564
1378
  labels = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 8, pointer)));
1565
1379
  pointer += 8;
1566
1380
  constraints = Number(ffjavascript.utils.leBuff2int(readBytesFromFile(localR1CSFilePath, 0, 4, pointer)));
1381
+ found = true;
1567
1382
  }
1568
1383
  pointer += 8 + Number(sectionSize);
1569
1384
  }
@@ -1583,11 +1398,194 @@ const getR1CSInfo = (localR1CSFilePath) => {
1583
1398
  }
1584
1399
  };
1585
1400
  /**
1586
- * Return a string with double digits if the provided input is one digit only.
1587
- * @param in <number> - the input number to be converted.
1588
- * @returns <string> - the two digits stringified number derived from the conversion.
1401
+ * Parse and validate that the ceremony configuration is correct
1402
+ * @notice this does not upload any files to storage
1403
+ * @param path <string> - the path to the configuration file
1404
+ * @param cleanup <boolean> - whether to delete the r1cs file after parsing
1405
+ * @returns any - the data to pass to the cloud function for setup and the circuit artifacts
1589
1406
  */
1590
- const convertToDoubleDigits = (amount) => (amount < 10 ? `0${amount}` : amount.toString());
1407
+ const parseCeremonyFile = async (path, cleanup = false) => {
1408
+ // check that the path exists
1409
+ if (!fs.existsSync(path))
1410
+ throw new Error("The provided path to the configuration file does not exist. Please provide an absolute path and try again.");
1411
+ try {
1412
+ // read the data
1413
+ const data = JSON.parse(fs.readFileSync(path).toString());
1414
+ // verify that the data is correct
1415
+ if (data.timeoutMechanismType !== "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */ &&
1416
+ data.timeoutMechanismType !== "FIXED" /* CeremonyTimeoutType.FIXED */)
1417
+ throw new Error("Invalid timeout type. Please choose between DYNAMIC and FIXED.");
1418
+ // validate that we have at least 1 circuit input data
1419
+ if (!data.circuits || data.circuits.length === 0)
1420
+ throw new Error("You need to provide the data for at least 1 circuit.");
1421
+ // validate that the end date is in the future
1422
+ let endDate;
1423
+ let startDate;
1424
+ try {
1425
+ endDate = new Date(data.endDate);
1426
+ startDate = new Date(data.startDate);
1427
+ }
1428
+ catch (error) {
1429
+ throw new Error("The dates should follow this format: 2023-07-04T00:00:00.");
1430
+ }
1431
+ if (endDate <= startDate)
1432
+ throw new Error("The end date should be greater than the start date.");
1433
+ const currentDate = new Date();
1434
+ if (endDate <= currentDate || startDate <= currentDate)
1435
+ throw new Error("The start and end dates should be in the future.");
1436
+ // validate penalty
1437
+ if (data.penalty <= 0)
1438
+ throw new Error("The penalty should be greater than zero.");
1439
+ const circuits = [];
1440
+ const urlPattern = /(https?:\/\/[^\s]+)/g;
1441
+ const commitHashPattern = /^[a-f0-9]{40}$/i;
1442
+ const circuitArtifacts = [];
1443
+ for (let i = 0; i < data.circuits.length; i++) {
1444
+ const circuitData = data.circuits[i];
1445
+ const { artifacts } = circuitData;
1446
+ circuitArtifacts.push({
1447
+ artifacts
1448
+ });
1449
+ // where we storing the r1cs downloaded
1450
+ const localR1csPath = `./${circuitData.name}.r1cs`;
1451
+ // where we storing the wasm downloaded
1452
+ const localWasmPath = `./${circuitData.name}.wasm`;
1453
+ // download the r1cs to extract the metadata
1454
+ const streamPipeline = util.promisify(stream.pipeline);
1455
+ // Make the call.
1456
+ const responseR1CS = await fetch(artifacts.r1csStoragePath);
1457
+ // Handle errors.
1458
+ if (!responseR1CS.ok && responseR1CS.status !== 200)
1459
+ 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.`);
1460
+ await streamPipeline(responseR1CS.body, fs.createWriteStream(localR1csPath));
1461
+ // Write the file locally
1462
+ // extract the metadata from the r1cs
1463
+ const metadata = getR1CSInfo(localR1csPath);
1464
+ // download wasm too to ensure it's available
1465
+ const responseWASM = await fetch(artifacts.wasmStoragePath);
1466
+ if (!responseWASM.ok && responseWASM.status !== 200)
1467
+ 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.`);
1468
+ await streamPipeline(responseWASM.body, fs.createWriteStream(localWasmPath));
1469
+ // validate that the circuit hash and template links are valid
1470
+ const { template } = circuitData;
1471
+ const URLMatch = template.source.match(urlPattern);
1472
+ if (!URLMatch || URLMatch.length === 0 || URLMatch.length > 1)
1473
+ throw new Error("You should provide the URL to the circuits templates on GitHub.");
1474
+ const hashMatch = template.commitHash.match(commitHashPattern);
1475
+ if (!hashMatch || hashMatch.length === 0 || hashMatch.length > 1)
1476
+ throw new Error("You should provide a valid commit hash of the circuit templates.");
1477
+ // calculate the hash of the r1cs file
1478
+ const r1csBlake2bHash = await blake512FromPath(localR1csPath);
1479
+ const circuitPrefix = extractPrefix(circuitData.name);
1480
+ // filenames
1481
+ const doubleDigitsPowers = convertToDoubleDigits(metadata.pot);
1482
+ const r1csCompleteFilename = `${circuitData.name}.r1cs`;
1483
+ const wasmCompleteFilename = `${circuitData.name}.wasm`;
1484
+ const smallestPowersOfTauCompleteFilenameForCircuit = `${potFilenameTemplate}${doubleDigitsPowers}.ptau`;
1485
+ const firstZkeyCompleteFilename = `${circuitPrefix}_${genesisZkeyIndex}.zkey`;
1486
+ // storage paths
1487
+ const r1csStorageFilePath = getR1csStorageFilePath(circuitPrefix, r1csCompleteFilename);
1488
+ const wasmStorageFilePath = getWasmStorageFilePath(circuitPrefix, wasmCompleteFilename);
1489
+ const potStorageFilePath = getPotStorageFilePath(smallestPowersOfTauCompleteFilenameForCircuit);
1490
+ const zkeyStorageFilePath = getZkeyStorageFilePath(circuitPrefix, firstZkeyCompleteFilename);
1491
+ const files = {
1492
+ potFilename: smallestPowersOfTauCompleteFilenameForCircuit,
1493
+ r1csFilename: r1csCompleteFilename,
1494
+ wasmFilename: wasmCompleteFilename,
1495
+ initialZkeyFilename: firstZkeyCompleteFilename,
1496
+ potStoragePath: potStorageFilePath,
1497
+ r1csStoragePath: r1csStorageFilePath,
1498
+ wasmStoragePath: wasmStorageFilePath,
1499
+ initialZkeyStoragePath: zkeyStorageFilePath,
1500
+ r1csBlake2bHash
1501
+ };
1502
+ // validate that the compiler hash is a valid hash
1503
+ const { compiler } = circuitData;
1504
+ const compilerHashMatch = compiler.commitHash.match(commitHashPattern);
1505
+ if (!compilerHashMatch || compilerHashMatch.length === 0 || compilerHashMatch.length > 1)
1506
+ throw new Error("You should provide a valid commit hash of the circuit compiler.");
1507
+ // validate that the verification options are valid
1508
+ const { verification } = circuitData;
1509
+ if (verification.cfOrVm !== "CF" && verification.cfOrVm !== "VM")
1510
+ throw new Error("Please enter a valid verification mechanism: either CF or VM");
1511
+ // @todo VM parameters verification
1512
+ // if (verification['cfOrVM'] === "VM") {}
1513
+ // check that the timeout is provided for the correct configuration
1514
+ let dynamicThreshold;
1515
+ let fixedTimeWindow;
1516
+ let circuit = {};
1517
+ if (data.timeoutMechanismType === "DYNAMIC" /* CeremonyTimeoutType.DYNAMIC */) {
1518
+ if (circuitData.dynamicThreshold <= 0)
1519
+ throw new Error("The dynamic threshold should be > 0.");
1520
+ dynamicThreshold = circuitData.dynamicThreshold;
1521
+ // the Circuit data for the ceremony setup
1522
+ circuit = {
1523
+ name: circuitData.name,
1524
+ description: circuitData.description,
1525
+ prefix: circuitPrefix,
1526
+ sequencePosition: i + 1,
1527
+ metadata,
1528
+ files,
1529
+ template,
1530
+ compiler,
1531
+ verification,
1532
+ dynamicThreshold,
1533
+ avgTimings: {
1534
+ contributionComputation: 0,
1535
+ fullContribution: 0,
1536
+ verifyCloudFunction: 0
1537
+ }
1538
+ };
1539
+ }
1540
+ if (data.timeoutMechanismType === "FIXED" /* CeremonyTimeoutType.FIXED */) {
1541
+ if (circuitData.fixedTimeWindow <= 0)
1542
+ throw new Error("The fixed time window threshold should be > 0.");
1543
+ fixedTimeWindow = circuitData.fixedTimeWindow;
1544
+ // the Circuit data for the ceremony setup
1545
+ circuit = {
1546
+ name: circuitData.name,
1547
+ description: circuitData.description,
1548
+ prefix: circuitPrefix,
1549
+ sequencePosition: i + 1,
1550
+ metadata,
1551
+ files,
1552
+ template,
1553
+ compiler,
1554
+ verification,
1555
+ fixedTimeWindow,
1556
+ avgTimings: {
1557
+ contributionComputation: 0,
1558
+ fullContribution: 0,
1559
+ verifyCloudFunction: 0
1560
+ }
1561
+ };
1562
+ }
1563
+ circuits.push(circuit);
1564
+ // remove the local r1cs and wasm downloads (if used for verifying the config only vs setup)
1565
+ if (cleanup) {
1566
+ fs.unlinkSync(localR1csPath);
1567
+ fs.unlinkSync(localWasmPath);
1568
+ }
1569
+ }
1570
+ const setupData = {
1571
+ ceremonyInputData: {
1572
+ title: data.title,
1573
+ description: data.description,
1574
+ startDate: startDate.valueOf(),
1575
+ endDate: endDate.valueOf(),
1576
+ timeoutMechanismType: data.timeoutMechanismType,
1577
+ penalty: data.penalty
1578
+ },
1579
+ ceremonyPrefix: extractPrefix(data.title),
1580
+ circuits,
1581
+ circuitArtifacts
1582
+ };
1583
+ return setupData;
1584
+ }
1585
+ catch (error) {
1586
+ throw new Error(`Error while parsing up the ceremony setup file. ${error.message}`);
1587
+ }
1588
+ };
1591
1589
 
1592
1590
  /**
1593
1591
  * Verify that a zKey is valid
@@ -1836,7 +1834,7 @@ const getFirestoreDatabase = (app) => firestore.getFirestore(app);
1836
1834
  * @param app <FirebaseApp> - the Firebase application.
1837
1835
  * @returns <Functions> - the Cloud Functions associated to the application.
1838
1836
  */
1839
- const getFirebaseFunctions = (app) => functions.getFunctions(app, 'europe-west1');
1837
+ const getFirebaseFunctions = (app) => functions.getFunctions(app, "europe-west1");
1840
1838
  /**
1841
1839
  * Retrieve the configuration variables for the AWS services (S3, EC2).
1842
1840
  * @returns <AWSVariables> - the values of the AWS services configuration variables.
@@ -1845,14 +1843,14 @@ const getAWSVariables = () => {
1845
1843
  if (!process.env.AWS_ACCESS_KEY_ID ||
1846
1844
  !process.env.AWS_SECRET_ACCESS_KEY ||
1847
1845
  !process.env.AWS_REGION ||
1848
- !process.env.AWS_ROLE_ARN ||
1846
+ !process.env.AWS_INSTANCE_PROFILE_ARN ||
1849
1847
  !process.env.AWS_AMI_ID)
1850
1848
  throw new Error("Could not retrieve the AWS environment variables. Please, verify your environment configuration and retry");
1851
1849
  return {
1852
1850
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
1853
1851
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
1854
1852
  region: process.env.AWS_REGION || "us-east-1",
1855
- roleArn: process.env.AWS_ROLE_ARN,
1853
+ instanceProfileArn: process.env.AWS_INSTANCE_PROFILE_ARN,
1856
1854
  amiId: process.env.AWS_AMI_ID
1857
1855
  };
1858
1856
  };
@@ -2105,7 +2103,8 @@ const getGitHubStats = async (user) => {
2105
2103
  following: jsonData.following,
2106
2104
  followers: jsonData.followers,
2107
2105
  publicRepos: jsonData.public_repos,
2108
- avatarUrl: jsonData.avatar_url
2106
+ avatarUrl: jsonData.avatar_url,
2107
+ age: jsonData.created_at
2109
2108
  };
2110
2109
  return data;
2111
2110
  };
@@ -2117,20 +2116,21 @@ const getGitHubStats = async (user) => {
2117
2116
  * @param minimumAmountOfPublicRepos <number> The minimum amount of public repos the user should have
2118
2117
  * @returns <any> Return the avatar URL of the user if the user is reputable, false otherwise
2119
2118
  */
2120
- const githubReputation = async (userLogin, minimumAmountOfFollowing, minimumAmountOfFollowers, minimumAmountOfPublicRepos) => {
2119
+ const githubReputation = async (userLogin, minimumAmountOfFollowing, minimumAmountOfFollowers, minimumAmountOfPublicRepos, minimumAge) => {
2121
2120
  if (!process.env.GITHUB_ACCESS_TOKEN)
2122
2121
  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.");
2123
- const { following, followers, publicRepos, avatarUrl } = await getGitHubStats(userLogin);
2122
+ const { following, followers, publicRepos, avatarUrl, age } = await getGitHubStats(userLogin);
2124
2123
  if (following < minimumAmountOfFollowing ||
2125
2124
  publicRepos < minimumAmountOfPublicRepos ||
2126
- followers < minimumAmountOfFollowers)
2125
+ followers < minimumAmountOfFollowers ||
2126
+ new Date(age) > new Date(Date.now() - minimumAge))
2127
2127
  return {
2128
2128
  reputable: false,
2129
2129
  avatarUrl: ""
2130
2130
  };
2131
2131
  return {
2132
2132
  reputable: true,
2133
- avatarUrl: avatarUrl
2133
+ avatarUrl
2134
2134
  };
2135
2135
  };
2136
2136
 
@@ -2339,8 +2339,13 @@ const vmDependenciesAndCacheArtifactsCommand = (zKeyPath, potPath, snsTopic, reg
2339
2339
  // eslint-disable-next-line no-template-curly-in-string
2340
2340
  "touch ${MARKER_FILE}",
2341
2341
  "sudo yum update -y",
2342
- "curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash - ",
2343
- "sudo yum install -y nodejs",
2342
+ "curl -O https://nodejs.org/dist/v16.13.0/node-v16.13.0-linux-x64.tar.xz",
2343
+ "tar -xf node-v16.13.0-linux-x64.tar.xz",
2344
+ "mv node-v16.13.0-linux-x64 nodejs",
2345
+ "sudo mv nodejs /opt/",
2346
+ "echo 'export NODEJS_HOME=/opt/nodejs' >> /etc/profile",
2347
+ "echo 'export PATH=$NODEJS_HOME/bin:$PATH' >> /etc/profile",
2348
+ "source /etc/profile",
2344
2349
  "npm install -g snarkjs",
2345
2350
  `aws s3 cp s3://${zKeyPath} /var/tmp/genesisZkey.zkey`,
2346
2351
  `aws s3 cp s3://${potPath} /var/tmp/pot.ptau`,
@@ -2359,6 +2364,7 @@ const vmDependenciesAndCacheArtifactsCommand = (zKeyPath, potPath, snsTopic, reg
2359
2364
  * @returns Array<string> - the list of commands for contribution verification.
2360
2365
  */
2361
2366
  const vmContributionVerificationCommand = (bucketName, lastZkeyStoragePath, verificationTranscriptStoragePathAndFilename) => [
2367
+ `source /etc/profile`,
2362
2368
  `aws s3 cp s3://${bucketName}/${lastZkeyStoragePath} /var/tmp/lastZKey.zkey > /var/tmp/log.txt`,
2363
2369
  `snarkjs zkvi /var/tmp/genesisZkey.zkey /var/tmp/pot.ptau /var/tmp/lastZKey.zkey > /var/tmp/verification_transcript.log`,
2364
2370
  `aws s3 cp /var/tmp/verification_transcript.log s3://${bucketName}/${verificationTranscriptStoragePathAndFilename} &>/dev/null`,
@@ -2385,7 +2391,7 @@ const computeDiskSizeForVM = (zKeySizeInBytes, pot) => Math.ceil(2 * convertByte
2385
2391
  */
2386
2392
  const createEC2Instance = async (ec2, commands, instanceType, volumeSize, diskType) => {
2387
2393
  // Get the AWS variables.
2388
- const { amiId, roleArn } = getAWSVariables();
2394
+ const { amiId, instanceProfileArn } = getAWSVariables();
2389
2395
  // Parametrize the VM EC2 instance.
2390
2396
  const params = {
2391
2397
  ImageId: amiId,
@@ -2394,7 +2400,7 @@ const createEC2Instance = async (ec2, commands, instanceType, volumeSize, diskTy
2394
2400
  MinCount: 1,
2395
2401
  // nb. to find this: iam -> roles -> role_name.
2396
2402
  IamInstanceProfile: {
2397
- Arn: roleArn
2403
+ Arn: instanceProfileArn
2398
2404
  },
2399
2405
  // nb. for running commands at the startup.
2400
2406
  UserData: Buffer.from(commands.join("\n")).toString("base64"),
@@ -6,5 +6,5 @@
6
6
  * @param minimumAmountOfPublicRepos <number> The minimum amount of public repos the user should have
7
7
  * @returns <any> Return the avatar URL of the user if the user is reputable, false otherwise
8
8
  */
9
- export declare const githubReputation: (userLogin: string, minimumAmountOfFollowing: number, minimumAmountOfFollowers: number, minimumAmountOfPublicRepos: number) => Promise<any>;
9
+ export declare const githubReputation: (userLogin: string, minimumAmountOfFollowing: number, minimumAmountOfFollowers: number, minimumAmountOfPublicRepos: number, minimumAge: number) => Promise<any>;
10
10
  //# sourceMappingURL=security.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"security.d.ts","sourceRoot":"","sources":["../../../../src/helpers/security.ts"],"names":[],"mappings":"AA8BA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,cACd,MAAM,4BACS,MAAM,4BACN,MAAM,8BACJ,MAAM,KACnC,QAAQ,GAAG,CAsBb,CAAA"}
1
+ {"version":3,"file":"security.d.ts","sourceRoot":"","sources":["../../../../src/helpers/security.ts"],"names":[],"mappings":"AA6BA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,cACd,MAAM,4BACS,MAAM,4BACN,MAAM,8BACJ,MAAM,cACtB,MAAM,KACnB,QAAQ,GAAG,CAuBb,CAAA"}