@devtion/devcli 0.0.0-5d170d3 → 0.0.0-671e653

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 (42) hide show
  1. package/README.md +3 -1
  2. package/dist/.env +17 -3
  3. package/dist/index.js +516 -108
  4. package/dist/public/mini-semaphore.wasm +0 -0
  5. package/dist/public/mini-semaphore.zkey +0 -0
  6. package/dist/types/commands/authBandada.d.ts +2 -0
  7. package/dist/types/commands/authSIWE.d.ts +7 -0
  8. package/dist/types/commands/ceremony/index.d.ts +3 -0
  9. package/dist/types/commands/ceremony/listParticipants.d.ts +2 -0
  10. package/dist/types/commands/contribute.d.ts +1 -1
  11. package/dist/types/commands/finalize.d.ts +4 -3
  12. package/dist/types/commands/index.d.ts +2 -0
  13. package/dist/types/commands/observe.d.ts +1 -1
  14. package/dist/types/commands/setup.d.ts +2 -2
  15. package/dist/types/lib/bandada.d.ts +6 -0
  16. package/dist/types/lib/files.d.ts +1 -0
  17. package/dist/types/lib/localConfigs.d.ts +38 -0
  18. package/dist/types/lib/prompts.d.ts +6 -6
  19. package/dist/types/lib/utils.d.ts +3 -2
  20. package/dist/types/types/index.d.ts +63 -0
  21. package/package.json +12 -4
  22. package/src/commands/auth.ts +28 -8
  23. package/src/commands/authBandada.ts +120 -0
  24. package/src/commands/authSIWE.ts +178 -0
  25. package/src/commands/ceremony/index.ts +20 -0
  26. package/src/commands/ceremony/listParticipants.ts +30 -0
  27. package/src/commands/contribute.ts +51 -29
  28. package/src/commands/finalize.ts +22 -13
  29. package/src/commands/index.ts +3 -1
  30. package/src/commands/listCeremonies.ts +2 -3
  31. package/src/commands/logout.ts +3 -1
  32. package/src/commands/observe.ts +3 -3
  33. package/src/commands/setup.ts +56 -45
  34. package/src/commands/validate.ts +2 -3
  35. package/src/index.ts +35 -13
  36. package/src/lib/bandada.ts +51 -0
  37. package/src/lib/errors.ts +1 -1
  38. package/src/lib/localConfigs.ts +55 -1
  39. package/src/lib/prompts.ts +20 -20
  40. package/src/lib/services.ts +39 -16
  41. package/src/lib/utils.ts +45 -10
  42. package/src/types/index.ts +68 -0
package/dist/index.js CHANGED
@@ -2,28 +2,27 @@
2
2
 
3
3
  /**
4
4
  * @module @p0tion/phase2cli
5
- * @version 1.0.5
5
+ * @version 1.1.1
6
6
  * @file All-in-one interactive command-line for interfacing with zkSNARK Phase 2 Trusted Setup ceremonies
7
7
  * @copyright Ethereum Foundation 2022
8
8
  * @license MIT
9
9
  * @see [Github]{@link https://github.com/privacy-scaling-explorations/p0tion}
10
10
  */
11
11
  import { createCommand } from 'commander';
12
- import fs, { readFileSync, createWriteStream, renameSync } from 'fs';
13
- import { dirname } from 'path';
12
+ import fs, { readFileSync, createWriteStream, existsSync, renameSync } from 'fs';
13
+ import path, { dirname } from 'path';
14
14
  import { fileURLToPath } from 'url';
15
- import { zKey } from 'snarkjs';
15
+ import { zKey, groth16 } from 'snarkjs';
16
16
  import boxen from 'boxen';
17
17
  import { pipeline } from 'node:stream';
18
18
  import { promisify } from 'node:util';
19
19
  import fetch$1 from 'node-fetch';
20
- import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
21
- import { commonTerms, formatZkeyIndex, getZkeyStorageFilePath, finalContributionIndex, createCustomLoggerForFile, getBucketName, progressToNextContributionStep, permanentlyStoreCurrentContributionTimeAndHash, convertToDoubleDigits, multiPartUpload, verifyContribution, generateGetObjectPreSignedUrl, convertBytesOrKbToGb, numExpIterations, getDocumentById, getParticipantsCollectionPath, fromQueryToFirebaseDocumentInfo, getAllCollectionDocs, extractPrefix, autoGenerateEntropy, vmConfigurationTypes, initializeFirebaseCoreServices, signInToFirebaseWithCredentials, getCurrentFirebaseAuthUser, isCoordinator, parseCeremonyFile, blake512FromPath, checkIfObjectExist, setupCeremony, genesisZkeyIndex, getR1csStorageFilePath, getWasmStorageFilePath, getPotStorageFilePath, extractPoTFromFilename, potFileDownloadMainUrl, createS3Bucket, potFilenameTemplate, getR1CSInfo, getOpenedCeremonies, getCeremonyCircuits, checkParticipantForCeremony, getCurrentActiveParticipantTimeout, getCircuitBySequencePosition, getCircuitContributionsFromContributor, progressToNextCircuitForContribution, resumeContributionAfterTimeoutExpiration, generateValidContributionsAttestation, getContributionsValidityForContributor, getClosedCeremonies, checkAndPrepareCoordinatorForFinalization, computeSHA256ToHex, finalizeCeremony, getVerificationKeyStorageFilePath, verificationKeyAcronym, getVerifierContractStorageFilePath, verifierSmartContractAcronym, finalizeCircuit, exportVkey, exportVerifierContract } from '@p0tion/actions';
20
+ import { commonTerms, formatZkeyIndex, getZkeyStorageFilePath, finalContributionIndex, createCustomLoggerForFile, getBucketName, progressToNextContributionStep, permanentlyStoreCurrentContributionTimeAndHash, convertToDoubleDigits, multiPartUpload, verifyContribution, generateGetObjectPreSignedUrl, convertBytesOrKbToGb, numExpIterations, getDocumentById, getParticipantsCollectionPath, fromQueryToFirebaseDocumentInfo, getAllCollectionDocs, extractPrefix, autoGenerateEntropy, vmConfigurationTypes, initializeFirebaseCoreServices, signInToFirebaseWithCredentials, getCurrentFirebaseAuthUser, isCoordinator, parseCeremonyFile, blake512FromPath, checkIfObjectExist, setupCeremony, genesisZkeyIndex, getR1csStorageFilePath, getWasmStorageFilePath, getPotStorageFilePath, extractPoTFromFilename, potFileDownloadMainUrl, createS3Bucket, potFilenameTemplate, getR1CSInfo, getOpenedCeremonies, getCeremonyCircuits, checkParticipantForCeremony, getCurrentActiveParticipantTimeout, getCircuitBySequencePosition, getCircuitContributionsFromContributor, progressToNextCircuitForContribution, resumeContributionAfterTimeoutExpiration, generateValidContributionsAttestation, getContributionsValidityForContributor, getClosedCeremonies, checkAndPrepareCoordinatorForFinalization, computeSHA256ToHex, finalizeCeremony, getVerificationKeyStorageFilePath, verificationKeyAcronym, getVerifierContractStorageFilePath, verifierSmartContractAcronym, finalizeCircuit, exportVkey, exportVerifierContract, getAllCeremonies } from '@devtion/actions';
22
21
  import fetch from '@adobe/node-fetch-retry';
23
22
  import { request } from '@octokit/request';
24
23
  import { SingleBar, Presets } from 'cli-progress';
25
24
  import dotenv from 'dotenv';
26
- import { GithubAuthProvider, getAuth, signOut } from 'firebase/auth';
25
+ import { GithubAuthProvider, signInWithCustomToken, getAuth, signOut } from 'firebase/auth';
27
26
  import { getDiskInfoSync } from 'node-disk-info';
28
27
  import ora from 'ora';
29
28
  import { Timer } from 'timer-node';
@@ -34,11 +33,13 @@ import Conf from 'conf';
34
33
  import prompts from 'prompts';
35
34
  import clear from 'clear';
36
35
  import figlet from 'figlet';
37
- import { Readable } from 'stream';
38
36
  import { createOAuthDeviceAuth } from '@octokit/auth-oauth-device';
39
37
  import clipboard from 'clipboardy';
40
38
  import open from 'open';
41
- import { Timestamp, onSnapshot } from 'firebase/firestore';
39
+ import { Identity } from '@semaphore-protocol/identity';
40
+ import { httpsCallable } from 'firebase/functions';
41
+ import { ApiSdk } from '@bandada/api-sdk';
42
+ import { Timestamp, onSnapshot, doc, collection, getDocs } from 'firebase/firestore';
42
43
  import readline from 'readline';
43
44
 
44
45
  /**
@@ -99,7 +100,7 @@ const CORE_SERVICES_ERRORS = {
99
100
  FIREBASE_TOKEN_EXPIRED_REMOVED_PERMISSIONS: `The Github authorization has failed due to lack of association between your account and the CLI`,
100
101
  FIREBASE_USER_DISABLED: `The Github account has been suspended by the ceremony coordinator(s), blocking the possibility of contribution. Please, contact them to understand the motivation behind it.`,
101
102
  FIREBASE_FAILED_CREDENTIALS_VERIFICATION: `Firebase cannot verify your Github credentials due to network errors. Please, try once again later.`,
102
- FIREBASE_NETWORK_ERROR: `Unable to reach Firebase due to network erros. Please, try once again later and make sure your Internet connection is stable.`,
103
+ FIREBASE_NETWORK_ERROR: `Unable to reach Firebase due to network errors. Please, try once again later and make sure your Internet connection is stable.`,
103
104
  FIREBASE_CEREMONY_NOT_OPENED: `There are no ceremonies opened to contributions`,
104
105
  FIREBASE_CEREMONY_NOT_CLOSED: `There are no ceremonies ready to finalization`,
105
106
  AWS_CEREMONY_BUCKET_CREATION: `Unable to create a new bucket for the ceremony. Something went wrong during the creation. Please, repeat the process by providing a new ceremony name of the ceremony.`,
@@ -237,6 +238,14 @@ const checkAndMakeNewDirectoryIfNonexistent = (directoryLocalPath) => {
237
238
  const writeLocalJsonFile = (filePath, data) => {
238
239
  fs.writeFileSync(filePath, JSON.stringify(data), "utf-8");
239
240
  };
241
+ /**
242
+ * Return the local current project directory name.
243
+ * @returns <string> - the local project (e.g., dist/) directory name.
244
+ */
245
+ const getLocalDirname = () => {
246
+ const filename = fileURLToPath(import.meta.url);
247
+ return path.dirname(filename);
248
+ };
240
249
 
241
250
  // Get npm package name.
242
251
  const packagePath$4 = `${dirname(fileURLToPath(import.meta.url))}/..`;
@@ -252,6 +261,14 @@ const config = new Conf({
252
261
  accessToken: {
253
262
  type: "string",
254
263
  default: ""
264
+ },
265
+ bandadaIdentity: {
266
+ type: "string",
267
+ default: ""
268
+ },
269
+ authMethod: {
270
+ type: "string",
271
+ default: ""
255
272
  }
256
273
  }
257
274
  });
@@ -312,6 +329,39 @@ const setLocalAccessToken = (token) => config.set("accessToken", token);
312
329
  * Delete the stored access token.
313
330
  */
314
331
  const deleteLocalAccessToken = () => config.delete("accessToken");
332
+ /**
333
+ * Return the Bandada identity, if present.
334
+ * @returns <string | undefined> - the Bandada identity if present, otherwise undefined.
335
+ */
336
+ const getLocalBandadaIdentity = () => config.get("bandadaIdentity");
337
+ /**
338
+ * Check if the Bandada identity exists in the local storage.
339
+ * @returns <boolean>
340
+ */
341
+ const checkLocalBandadaIdentity = () => config.has("bandadaIdentity") && !!config.get("bandadaIdentity");
342
+ /**
343
+ * Set the Bandada identity.
344
+ * @param identity <string> - the Bandada identity to be stored.
345
+ */
346
+ const setLocalBandadaIdentity = (identity) => config.set("bandadaIdentity", identity);
347
+ /**
348
+ * Delete the stored Bandada identity.
349
+ */
350
+ const deleteLocalBandadaIdentity = () => config.delete("bandadaIdentity");
351
+ /**
352
+ * Return the authentication method, if present.
353
+ * @returns <string | undefined> - the authentication method if present, otherwise undefined.
354
+ */
355
+ const getLocalAuthMethod = () => config.get("authMethod");
356
+ /**
357
+ * Set the authentication method.
358
+ * @param method <string> - the authentication method to be stored.
359
+ */
360
+ const setLocalAuthMethod = (method) => config.set("authMethod", method);
361
+ /**
362
+ * Delete the stored authentication method.
363
+ */
364
+ const deleteLocalAuthMethod = () => config.delete("authMethod");
315
365
  /**
316
366
  * Get the complete local file path.
317
367
  * @param cwd <string> - the current working directory path.
@@ -367,6 +417,12 @@ const getVerificationKeyLocalFilePath = (completeFilename) => `${verificationKey
367
417
  * @returns <string> - the complete final verifier contract path to the file.
368
418
  */
369
419
  const getVerifierContractLocalFilePath = (completeFilename) => `${verifierContractsLocalFolderPath}/${completeFilename}`;
420
+ /**
421
+ * Get the complete final attestation file path.
422
+ * @param completeFilename <string> - the complete filename of the file (name.ext).
423
+ * @returns <string> - the complete final final attestation path to the file.
424
+ */
425
+ const getFinalAttestationLocalFilePath = (completeFilename) => `${finalAttestationsLocalFolderPath}/${completeFilename}`;
370
426
  /**
371
427
  * Get the final transcript file path.
372
428
  * @param completeFilename <string> - the complete filename of the file (name.ext).
@@ -416,7 +472,7 @@ const getGithubAuthenticatedUserGists = async (githubToken, params) => {
416
472
  headers: {
417
473
  authorization: `token ${githubToken}`
418
474
  },
419
- per_page: params.perPage,
475
+ per_page: params.perPage, // max items per page = 100.
420
476
  page: params.page
421
477
  });
422
478
  if (response && response.status === 200)
@@ -464,8 +520,9 @@ const getPublicAttestationGist = async (githubToken, publicAttestationFilename)
464
520
  * @returns <string> - the third-party provider handle of the user.
465
521
  */
466
522
  const getUserHandleFromProviderUserId = (providerUserId) => {
467
- if (providerUserId.indexOf("-") === -1)
468
- showError(THIRD_PARTY_SERVICES_ERRORS.GITHUB_GET_GITHUB_ACCOUNT_INFO, true);
523
+ if (providerUserId.indexOf("-") === -1) {
524
+ return providerUserId;
525
+ }
469
526
  return providerUserId.split("-")[0];
470
527
  };
471
528
  /**
@@ -581,8 +638,18 @@ const publishGist = async (token, content, ceremonyTitle, ceremonyPrefix) => {
581
638
  * @returns <string> - the ready to share tweet url.
582
639
  */
583
640
  const generateCustomUrlToTweetAboutParticipation = (ceremonyName, gistUrl, isFinalizing) => isFinalizing
584
- ? `https://twitter.com/intent/tweet?text=I%20have%20finalized%20the%20${ceremonyName}%20Phase%202%20Trusted%20Setup%20ceremony!%20You%20can%20view%20my%20final%20attestation%20here:%20${gistUrl}%20#Ethereum%20#ZKP%20#PSE`
585
- : `https://twitter.com/intent/tweet?text=I%20contributed%20to%20the%20${ceremonyName}%20Phase%202%20Trusted%20Setup%20ceremony!%20You%20can%20contribute%20here:%20https://github.com/privacy-scaling-explorations/p0tion%20You%20can%20view%20my%20attestation%20here:%20${gistUrl}%20#Ethereum%20#ZKP`;
641
+ ? `https://twitter.com/intent/tweet?text=I%20have%20finalized%20the%20${ceremonyName}${ceremonyName.toLowerCase().includes("trusted") ||
642
+ ceremonyName.toLowerCase().includes("setup") ||
643
+ ceremonyName.toLowerCase().includes("phase2") ||
644
+ ceremonyName.toLowerCase().includes("ceremony")
645
+ ? "!"
646
+ : "%20Phase%202%20Trusted%20Setup%20ceremony!"}%20You%20can%20view%20my%20final%20attestation%20here:%20${gistUrl}%20#Ethereum%20#ZKP%20#PSE`
647
+ : `https://twitter.com/intent/tweet?text=I%20contributed%20to%20the%20${ceremonyName}${ceremonyName.toLowerCase().includes("trusted") ||
648
+ ceremonyName.toLowerCase().includes("setup") ||
649
+ ceremonyName.toLowerCase().includes("phase2") ||
650
+ ceremonyName.toLowerCase().includes("ceremony")
651
+ ? "!"
652
+ : "%20Phase%202%20Trusted%20Setup%20ceremony!"}%20You%20can%20view%20the%20steps%20to%20contribute%20here:%20https://ceremony.pse.dev%20You%20can%20view%20my%20attestation%20here:%20${gistUrl}%20#Ethereum%20#ZKP`;
586
653
  /**
587
654
  * Return a custom progress bar.
588
655
  * @param type <ProgressBarType> - the type of the progress bar.
@@ -710,13 +777,14 @@ const getLatestUpdatesFromParticipant = async (firestoreDatabase, ceremonyId, pa
710
777
  * @param entropyOrBeaconHash <string> - the entropy or beacon hash (only when finalizing) for the contribution.
711
778
  * @param contributorOrCoordinatorIdentifier <string> - the identifier of the contributor or coordinator (only when finalizing).
712
779
  * @param isFinalizing <boolean> - flag to discriminate between ceremony finalization (true) and contribution (false).
780
+ * @param circuitsLength <number> - the total number of circuits in the ceremony.
713
781
  */
714
- const handleStartOrResumeContribution = async (cloudFunctions, firestoreDatabase, ceremony, circuit, participant, entropyOrBeaconHash, contributorOrCoordinatorIdentifier, isFinalizing) => {
782
+ const handleStartOrResumeContribution = async (cloudFunctions, firestoreDatabase, ceremony, circuit, participant, entropyOrBeaconHash, contributorOrCoordinatorIdentifier, isFinalizing, circuitsLength) => {
715
783
  // Extract data.
716
784
  const { prefix: ceremonyPrefix } = ceremony.data;
717
785
  const { waitingQueue, avgTimings, prefix: circuitPrefix, sequencePosition } = circuit.data;
718
786
  const { completedContributions } = waitingQueue; // = current progress.
719
- console.log(`${theme.text.bold(`\n- Circuit # ${theme.colors.magenta(`${sequencePosition}`)}`)} (Contribution Steps)`);
787
+ console.log(`${theme.text.bold(`\n- Circuit # ${theme.colors.magenta(`${sequencePosition}/${circuitsLength}`)}`)} (Contribution Steps)`);
720
788
  // Get most up-to-date data from the participant document.
721
789
  let participantData = await getLatestUpdatesFromParticipant(firestoreDatabase, ceremony.id, participant.id);
722
790
  const spinner = customSpinner(`${participantData.contributionStep === "DOWNLOADING" /* ParticipantContributionStep.DOWNLOADING */
@@ -762,6 +830,7 @@ const handleStartOrResumeContribution = async (cloudFunctions, firestoreDatabase
762
830
  // Download the latest contribution from bucket.
763
831
  await downloadCeremonyArtifact(cloudFunctions, bucketName, lastZkeyStorageFilePath, lastZkeyLocalFilePath);
764
832
  console.log(`${theme.symbols.success} Contribution ${theme.text.bold(`#${lastZkeyIndex}`)} correctly downloaded`);
833
+ await sleep(3000);
765
834
  // Advance to next contribution step (COMPUTING) if not finalizing.
766
835
  if (!isFinalizing) {
767
836
  spinner.text = `Preparing for contribution computation...`;
@@ -789,11 +858,14 @@ const handleStartOrResumeContribution = async (cloudFunctions, firestoreDatabase
789
858
  showError(COMMAND_ERRORS.COMMAND_CONTRIBUTE_FINALIZE_NO_TRANSCRIPT_CONTRIBUTION_HASH_MATCH, true);
790
859
  // Format contribution hash.
791
860
  const contributionHash = matchContributionHash?.at(0)?.replace("\n\t\t", "");
861
+ await sleep(500);
792
862
  // Make request to cloud functions to permanently store the information.
793
863
  await permanentlyStoreCurrentContributionTimeAndHash(cloudFunctions, ceremony.id, computingTime, contributionHash);
794
864
  // Format computing time.
795
865
  const { seconds: computationSeconds, minutes: computationMinutes, hours: computationHours } = getSecondsMinutesHoursFromMillis(computingTime);
796
866
  spinner.succeed(`${isFinalizing ? "Contribution" : `Contribution ${theme.text.bold(`#${nextZkeyIndex}`)}`} computation took ${theme.text.bold(`${convertToDoubleDigits(computationHours)}:${convertToDoubleDigits(computationMinutes)}:${convertToDoubleDigits(computationSeconds)}`)}`);
867
+ // ensure the previous step is completed
868
+ await sleep(5000);
797
869
  // Advance to next contribution step (UPLOADING) if not finalizing.
798
870
  if (!isFinalizing) {
799
871
  spinner.text = `Preparing for uploading the contribution...`;
@@ -809,12 +881,17 @@ const handleStartOrResumeContribution = async (cloudFunctions, firestoreDatabase
809
881
  console.log(`${theme.symbols.success} Contribution ${theme.text.bold(`#${nextZkeyIndex}`)} already computed`);
810
882
  // Contribution step = UPLOADING.
811
883
  if (isFinalizing || participantData.contributionStep === "UPLOADING" /* ParticipantContributionStep.UPLOADING */) {
812
- spinner.text = `Uploading ${isFinalizing ? "final" : "your"} contribution ${!isFinalizing ? theme.text.bold(`#${nextZkeyIndex}`) : ""} to storage.\n${theme.symbols.warning} This step may take a while based on circuit size and your contribution speed. Everything's fine, just be patient.`;
884
+ spinner.text = `Uploading ${isFinalizing ? "final" : "your"} contribution ${!isFinalizing ? theme.text.bold(`#${nextZkeyIndex}`) : ""} to storage.\n${theme.symbols.warning} This step may take a while based on circuit size and your internet speed. Everything's fine, just be patient.`;
813
885
  spinner.start();
814
- if (!isFinalizing)
815
- await multiPartUpload(cloudFunctions, bucketName, nextZkeyStorageFilePath, nextZkeyLocalFilePath, Number(process.env.CONFIG_STREAM_CHUNK_SIZE_IN_MB), ceremony.id, participantData.tempContributionData);
886
+ const progressBar = customProgressBar(ProgressBarType.UPLOAD, `your contribution`);
887
+ if (!isFinalizing) {
888
+ await multiPartUpload(cloudFunctions, bucketName, nextZkeyStorageFilePath, nextZkeyLocalFilePath, Number(process.env.CONFIG_STREAM_CHUNK_SIZE_IN_MB), ceremony.id, participantData.tempContributionData, progressBar);
889
+ progressBar.stop();
890
+ }
816
891
  else
817
892
  await multiPartUpload(cloudFunctions, bucketName, nextZkeyStorageFilePath, nextZkeyLocalFilePath, Number(process.env.CONFIG_STREAM_CHUNK_SIZE_IN_MB));
893
+ // small sleep to ensure the previous step is completed
894
+ await sleep(5000);
818
895
  spinner.succeed(`${isFinalizing ? `Contribution` : `Contribution ${theme.text.bold(`#${nextZkeyIndex}`)}`} correctly saved to storage`);
819
896
  // Advance to next contribution step (VERIFYING) if not finalizing.
820
897
  if (!isFinalizing) {
@@ -992,7 +1069,7 @@ const promptCircomCompiler = async () => {
992
1069
  * Shows a list of circuits for a single option selection.
993
1070
  * @dev the circuit names are derived from local R1CS files.
994
1071
  * @param options <Array<string>> - an array of circuits names.
995
- * @returns Promise<string> - the name of the choosen circuit.
1072
+ * @returns Promise<string> - the name of the chosen circuit.
996
1073
  */
997
1074
  const promptCircuitSelector = async (options) => {
998
1075
  const { circuitFilename } = await prompts({
@@ -1010,7 +1087,7 @@ const promptCircuitSelector = async (options) => {
1010
1087
  * Shows a list of standard EC2 VM instance types for a single option selection.
1011
1088
  * @notice the suggested VM configuration type is calculated based on circuit constraint size.
1012
1089
  * @param constraintSize <number> - the amount of circuit constraints
1013
- * @returns Promise<string> - the name of the choosen VM type.
1090
+ * @returns Promise<string> - the name of the chosen VM type.
1014
1091
  */
1015
1092
  const promptVMTypeSelector = async (constraintSize) => {
1016
1093
  let suggestedConfiguration = 0;
@@ -1107,7 +1184,7 @@ const promptVMDiskTypeSelector = async () => {
1107
1184
  /**
1108
1185
  * Show a series of questions about the circuits.
1109
1186
  * @param constraintSize <number> - the amount of circuit constraints.
1110
- * @param timeoutMechanismType <CeremonyTimeoutType> - the choosen timeout mechanism type for the ceremony.
1187
+ * @param timeoutMechanismType <CeremonyTimeoutType> - the chosen timeout mechanism type for the ceremony.
1111
1188
  * @param needPromptCircomCompiler <boolean> - a boolean value indicating if the questions related to the Circom compiler version and commit hash must be asked.
1112
1189
  * @param enforceVM <boolean> - a boolean value indicating if the contribution verification could be supported by VM-only approach or not.
1113
1190
  * @returns Promise<Array<Circuit>> - circuit info prompted by the coordinator.
@@ -1120,7 +1197,7 @@ const promptCircuitInputData = async (constraintSize, timeoutMechanismType, same
1120
1197
  let circomVersion = "";
1121
1198
  let circomCommitHash = "";
1122
1199
  let circuitInputData;
1123
- let useCfOrVm;
1200
+ let cfOrVm;
1124
1201
  let vmDiskType;
1125
1202
  let vmConfigurationType = "";
1126
1203
  const questions = [
@@ -1175,18 +1252,21 @@ const promptCircuitInputData = async (constraintSize, timeoutMechanismType, same
1175
1252
  circomVersion = version;
1176
1253
  circomCommitHash = commitHash;
1177
1254
  }
1178
- // Ask for prefered contribution verification method (CF vs VM).
1255
+ // Ask for preferred contribution verification method (CF vs VM).
1179
1256
  if (!enforceVM) {
1180
1257
  const { confirmation } = await askForConfirmation(`The contribution verification can be performed using Cloud Functions (CF, cheaper for small contributions but limited to 1M constraints) or custom virtual machines (expensive but could scale up to 30M constraints). Be aware about VM costs and if you wanna learn more, please visit the documentation to have a complete overview about cost estimation of the two mechanisms.\nChoose the contribution verification mechanism`, `CF`, // eq. true.
1181
1258
  `VM` // eq. false.
1182
1259
  );
1183
- useCfOrVm = confirmation;
1260
+ cfOrVm = confirmation
1261
+ ? "CF" /* CircuitContributionVerificationMechanism.CF */
1262
+ : "VM" /* CircuitContributionVerificationMechanism.VM */;
1184
1263
  }
1185
- else
1186
- useCfOrVm = "VM" /* CircuitContributionVerificationMechanism.VM */;
1187
- if (useCfOrVm === undefined)
1264
+ else {
1265
+ cfOrVm = "VM" /* CircuitContributionVerificationMechanism.VM */;
1266
+ }
1267
+ if (cfOrVm === undefined)
1188
1268
  showError(COMMAND_ERRORS.COMMAND_ABORT_PROMPT, true);
1189
- if (!useCfOrVm) {
1269
+ if (cfOrVm === "VM" /* CircuitContributionVerificationMechanism.VM */) {
1190
1270
  // Ask for selecting the specific VM configuration type.
1191
1271
  vmConfigurationType = await promptVMTypeSelector(constraintSize);
1192
1272
  // Ask for selecting the specific VM disk (volume) type.
@@ -1220,9 +1300,7 @@ const promptCircuitInputData = async (constraintSize, timeoutMechanismType, same
1220
1300
  paramsConfiguration: circuitConfigurationValues
1221
1301
  },
1222
1302
  verification: {
1223
- cfOrVm: useCfOrVm
1224
- ? "CF" /* CircuitContributionVerificationMechanism.CF */
1225
- : "VM" /* CircuitContributionVerificationMechanism.VM */,
1303
+ cfOrVm,
1226
1304
  vm: {
1227
1305
  vmConfigurationType,
1228
1306
  vmDiskType
@@ -1258,9 +1336,7 @@ const promptCircuitInputData = async (constraintSize, timeoutMechanismType, same
1258
1336
  paramsConfiguration: circuitConfigurationValues
1259
1337
  },
1260
1338
  verification: {
1261
- cfOrVm: useCfOrVm
1262
- ? "CF" /* CircuitContributionVerificationMechanism.CF */
1263
- : "VM" /* CircuitContributionVerificationMechanism.VM */,
1339
+ cfOrVm,
1264
1340
  vm: {
1265
1341
  vmConfigurationType,
1266
1342
  vmDiskType
@@ -1304,7 +1380,7 @@ const promptCircuitAddition = async () => {
1304
1380
  * Shows a list of pre-computed zKeys for a single option selection.
1305
1381
  * @dev the names are derived from local zKeys files.
1306
1382
  * @param options <Array<string>> - an array of pre-computed zKeys names.
1307
- * @returns Promise<string> - the name of the choosen pre-computed zKey.
1383
+ * @returns Promise<string> - the name of the chosen pre-computed zKey.
1308
1384
  */
1309
1385
  const promptPreComputedZkeySelector = async (options) => {
1310
1386
  const { preComputedZkeyFilename } = await prompts({
@@ -1342,13 +1418,13 @@ const promptNeededPowersForCircuit = async (suggestedSmallestNeededPowers) => {
1342
1418
  * Shows a list of PoT files for a single option selection.
1343
1419
  * @dev the names are derived from local PoT files.
1344
1420
  * @param options <Array<string>> - an array of PoT file names.
1345
- * @returns Promise<string> - the name of the choosen PoT.
1421
+ * @returns Promise<string> - the name of the chosen PoT.
1346
1422
  */
1347
1423
  const promptPotSelector = async (options) => {
1348
1424
  const { potFilename } = await prompts({
1349
1425
  type: "select",
1350
1426
  name: "potFilename",
1351
- message: theme.text.bold("Select the Powers of Tau file choosen for the circuit"),
1427
+ message: theme.text.bold("Select the Powers of Tau file chosen for the circuit"),
1352
1428
  choices: options.map((option) => {
1353
1429
  console.log(option);
1354
1430
  return { title: option, value: option };
@@ -1418,7 +1494,7 @@ const promptToTypeEntropyOrBeacon = async (isEntropy = true) => {
1418
1494
  * @return <Promise<string>> - the entropy.
1419
1495
  */
1420
1496
  const promptForEntropy = async () => {
1421
- // Prompt for entropy generation prefered method.
1497
+ // Prompt for entropy generation preferred method.
1422
1498
  const { confirmation } = await askForConfirmation(`Do you prefer to type your entropy or generate it randomly?`, "Manually", "Randomly");
1423
1499
  if (confirmation === undefined)
1424
1500
  showError(COMMAND_ERRORS.COMMAND_ABORT_PROMPT, true);
@@ -1537,16 +1613,37 @@ const checkAuth = async (firebaseApp) => {
1537
1613
  showError(THIRD_PARTY_SERVICES_ERRORS.GITHUB_NOT_AUTHENTICATED, true);
1538
1614
  // Retrieve local access token.
1539
1615
  const token = String(getLocalAccessToken());
1540
- // Get credentials.
1541
- const credentials = exchangeGithubTokenForCredentials(token);
1542
- // Sign in to Firebase using credentials.
1543
- await signInToFirebase(firebaseApp, credentials);
1616
+ let providerUserId;
1617
+ let username;
1618
+ const authMethod = getLocalAuthMethod();
1619
+ switch (authMethod) {
1620
+ case "github": {
1621
+ // Get credentials.
1622
+ const credentials = exchangeGithubTokenForCredentials(token);
1623
+ // Sign in to Firebase using credentials.
1624
+ await signInToFirebase(firebaseApp, credentials);
1625
+ // Get Github unique identifier (handle-id).
1626
+ providerUserId = await getGithubProviderUserId(String(token));
1627
+ username = getUserHandleFromProviderUserId(providerUserId);
1628
+ break;
1629
+ }
1630
+ case "bandada": {
1631
+ const userCredentials = await signInWithCustomToken(getAuth(), token);
1632
+ providerUserId = userCredentials.user.uid;
1633
+ username = providerUserId;
1634
+ break;
1635
+ }
1636
+ case "siwe": {
1637
+ const userCredentials = await signInWithCustomToken(getAuth(), token);
1638
+ providerUserId = userCredentials.user.uid;
1639
+ username = providerUserId;
1640
+ break;
1641
+ }
1642
+ }
1544
1643
  // Get current authenticated user.
1545
1644
  const user = getCurrentFirebaseAuthUser(firebaseApp);
1546
- // Get Github unique identifier (handle-id).
1547
- const providerUserId = await getGithubProviderUserId(String(token));
1548
1645
  // Greet the user.
1549
- console.log(`Greetings, @${theme.text.bold(getUserHandleFromProviderUserId(providerUserId))} ${theme.emojis.wave}\n`);
1646
+ console.log(`Greetings, @${theme.text.bold(username)} ${theme.emojis.wave}\n`);
1550
1647
  return {
1551
1648
  user,
1552
1649
  token,
@@ -1635,7 +1732,7 @@ const handleAdditionOfCircuitsToCeremony = async (r1csOptions, wasmOptions, cere
1635
1732
  wasmFilename.split(`.${commonTerms.foldersAndPathsTerms.wasm}`)[0]);
1636
1733
  if (matchingWasms.length !== 1)
1637
1734
  showError(COMMAND_ERRORS.COMMAND_SETUP_MISMATCH_R1CS_WASM, true);
1638
- // Get input data for choosen circuit.
1735
+ // Get input data for chosen circuit.
1639
1736
  const circuitInputData = await getInputDataToAddCircuitToCeremony(choosenCircuitFilename, matchingWasms[0], ceremonyTimeoutMechanismType, sameCircomCompiler, circuitSequencePosition, sharedCircomCompilerData);
1640
1737
  // Store circuit data.
1641
1738
  inputDataForCircuits.push(circuitInputData);
@@ -1725,7 +1822,7 @@ const checkAndDownloadSmallestPowersOfTau = async (powers, ptauCompleteFilename)
1725
1822
  * number of powers greater than or equal to the powers needed by the zKey), the coordinator will be asked
1726
1823
  * to provide a number of powers manually, ranging from the smallest possible to the largest.
1727
1824
  * @param neededPowers <number> - the smallest amount of powers needed by the zKey.
1728
- * @returns Promise<string, string> - the information about the choosen Powers of Tau file for the pre-computed zKey
1825
+ * @returns Promise<string, string> - the information about the chosen Powers of Tau file for the pre-computed zKey
1729
1826
  * along with related powers.
1730
1827
  */
1731
1828
  const handlePreComputedZkeyPowersOfTauSelection = async (neededPowers) => {
@@ -1826,7 +1923,9 @@ const setup = async (cmd) => {
1826
1923
  let ceremonyId = ""; // The unique identifier of the ceremony.
1827
1924
  const { firebaseApp, firebaseFunctions, firestoreDatabase } = await bootstrapCommandExecutionAndServices();
1828
1925
  // Check for authentication.
1829
- const { user, providerUserId } = cmd.auth ? await authWithToken(firebaseApp, cmd.auth) : await checkAuth(firebaseApp);
1926
+ const { user, providerUserId } = cmd.auth
1927
+ ? await authWithToken(firebaseApp, cmd.auth)
1928
+ : await checkAuth(firebaseApp);
1830
1929
  // Preserve command execution only for coordinators.
1831
1930
  if (!(await isCoordinator(user)))
1832
1931
  showError(COMMAND_ERRORS.COMMAND_NOT_COORDINATOR, true);
@@ -1843,7 +1942,7 @@ const setup = async (cmd) => {
1843
1942
  // if there is the file option, then set up the non interactively
1844
1943
  if (cmd.template) {
1845
1944
  // 1. parse the file
1846
- // tmp data - do not cleanup files as we need them
1945
+ // tmp data - do not cleanup files as we need them
1847
1946
  const spinner = customSpinner(`Parsing ${theme.text.bold(cmd.template)} setup configuration file...`, `clock`);
1848
1947
  spinner.start();
1849
1948
  const setupCeremonyData = await parseCeremonyFile(cmd.template);
@@ -1853,8 +1952,6 @@ const setup = async (cmd) => {
1853
1952
  // create a new bucket
1854
1953
  const bucketName = await handleCeremonyBucketCreation(firebaseFunctions, ceremonySetupData.ceremonyPrefix);
1855
1954
  console.log(`\n${theme.symbols.success} Ceremony bucket name: ${theme.text.bold(bucketName)}`);
1856
- // create S3 clienbt
1857
- const s3 = new S3Client({ region: 'us-east-1' });
1858
1955
  // loop through each circuit
1859
1956
  for await (const circuit of setupCeremonyData.circuits) {
1860
1957
  // Local paths.
@@ -1864,25 +1961,24 @@ const setup = async (cmd) => {
1864
1961
  const potLocalPathAndFileName = getPotLocalFilePath(circuit.files.potFilename);
1865
1962
  const zkeyLocalPathAndFileName = getZkeyLocalFilePath(circuit.files.initialZkeyFilename);
1866
1963
  // 2. download the pot and wasm files
1867
- const streamPipeline = promisify(pipeline);
1868
1964
  await checkAndDownloadSmallestPowersOfTau(convertToDoubleDigits(circuit.metadata?.pot), circuit.files.potFilename);
1869
- // download the wasm to calculate the hash
1870
- const spinner = customSpinner(`Downloading the ${theme.text.bold(`#${circuit.name}`)} WASM file from the project's bucket...`, `clock`);
1965
+ // 3. generate the zKey
1966
+ const spinner = customSpinner(`Generating genesis zKey for circuit ${theme.text.bold(circuit.name)}...`, `clock`);
1871
1967
  spinner.start();
1872
- const command = new GetObjectCommand({ Bucket: ceremonySetupData.circuitArtifacts[index].artifacts.bucket, Key: ceremonySetupData.circuitArtifacts[index].artifacts.wasmStoragePath });
1873
- const response = await s3.send(command);
1874
- if (response.$metadata.httpStatusCode !== 200) {
1875
- throw new Error("There was an error while trying to download the wasm file. Please check that the file has the correct permissions (public) set.");
1968
+ if (existsSync(zkeyLocalPathAndFileName)) {
1969
+ spinner.succeed(`The genesis zKey for circuit ${theme.text.bold(circuit.name)} is already present on disk`);
1876
1970
  }
1877
- if (response.Body instanceof Readable)
1878
- await streamPipeline(response.Body, createWriteStream(wasmLocalPathAndFileName));
1879
- spinner.stop();
1880
- // 3. generate the zKey
1881
- await zKey.newZKey(r1csLocalPathAndFileName, getPotLocalFilePath(circuit.files.potFilename), zkeyLocalPathAndFileName, undefined);
1971
+ else {
1972
+ await zKey.newZKey(r1csLocalPathAndFileName, getPotLocalFilePath(circuit.files.potFilename), zkeyLocalPathAndFileName, undefined);
1973
+ spinner.succeed(`Generation of the genesis zKey for circuit ${theme.text.bold(circuit.name)} completed successfully`);
1974
+ }
1975
+ const hashSpinner = customSpinner(`Calculating hashes for circuit ${theme.text.bold(circuit.name)}...`, `clock`);
1976
+ hashSpinner.start();
1882
1977
  // 4. calculate the hashes
1883
1978
  const wasmBlake2bHash = await blake512FromPath(wasmLocalPathAndFileName);
1884
1979
  const potBlake2bHash = await blake512FromPath(getPotLocalFilePath(circuit.files.potFilename));
1885
1980
  const initialZkeyBlake2bHash = await blake512FromPath(zkeyLocalPathAndFileName);
1981
+ hashSpinner.succeed(`Hashes for circuit ${theme.text.bold(circuit.name)} calculated successfully`);
1886
1982
  // 5. upload the artifacts
1887
1983
  // Upload zKey to Storage.
1888
1984
  await handleCircuitArtifactUploadToStorage(firebaseFunctions, bucketName, circuit.files.initialZkeyStoragePath, zkeyLocalPathAndFileName, circuit.files.initialZkeyFilename);
@@ -1900,9 +1996,9 @@ const setup = async (cmd) => {
1900
1996
  // 6 update the setup data object
1901
1997
  ceremonySetupData.circuits[index].files = {
1902
1998
  ...circuit.files,
1903
- potBlake2bHash: potBlake2bHash,
1904
- wasmBlake2bHash: wasmBlake2bHash,
1905
- initialZkeyBlake2bHash: initialZkeyBlake2bHash
1999
+ potBlake2bHash,
2000
+ wasmBlake2bHash,
2001
+ initialZkeyBlake2bHash
1906
2002
  };
1907
2003
  ceremonySetupData.circuits[index].zKeySizeInBytes = getFileStats(zkeyLocalPathAndFileName).size;
1908
2004
  }
@@ -2110,16 +2206,29 @@ const expirationCountdownForGithubOAuth = (expirationInSeconds) => {
2110
2206
  */
2111
2207
  const onVerification = async (verification) => {
2112
2208
  // Copy code to clipboard.
2113
- clipboard.writeSync(verification.user_code);
2114
- clipboard.readSync();
2209
+ let noClipboard = false;
2210
+ try {
2211
+ clipboard.writeSync(verification.user_code);
2212
+ clipboard.readSync();
2213
+ }
2214
+ catch (error) {
2215
+ noClipboard = true;
2216
+ }
2115
2217
  // Display data.
2116
- console.log(`${theme.symbols.warning} Visit ${theme.text.bold(theme.text.underlined(verification.verification_uri))} on this device to generate a new token and authenticate`);
2117
- console.log(`${theme.symbols.info} Your auth code: ${theme.text.bold(verification.user_code)} (${theme.emojis.clipboard} ${theme.symbols.success})\n`);
2218
+ console.log(`${theme.symbols.warning} Visit ${theme.text.bold(theme.text.underlined(verification.verification_uri))} on this device to generate a new token and authenticate\n`);
2219
+ console.log(theme.colors.magenta(figlet.textSync("Code is Below", { font: "ANSI Shadow" })), "\n");
2220
+ const message = !noClipboard ? `has been copied to your clipboard (${theme.emojis.clipboard})` : ``;
2221
+ console.log(`${theme.symbols.info} Your auth code: ${theme.text.bold(verification.user_code)} ${message} ${theme.symbols.success}\n`);
2118
2222
  const spinner = customSpinner(`Redirecting to Github...`, `clock`);
2119
2223
  spinner.start();
2120
2224
  await sleep(10000); // ~10s to make users able to read the CLI.
2121
- // Automatically open the page (# Step 2).
2122
- await open(verification.verification_uri);
2225
+ try {
2226
+ // Automatically open the page (# Step 2).
2227
+ await open(verification.verification_uri);
2228
+ }
2229
+ catch (error) {
2230
+ console.log(`${theme.symbols.info} Please authenticate via GitHub at ${verification.verification_uri}`);
2231
+ }
2123
2232
  spinner.stop();
2124
2233
  // Countdown for time expiration.
2125
2234
  expirationCountdownForGithubOAuth(verification.expires_in);
@@ -2170,6 +2279,7 @@ const auth = async () => {
2170
2279
  // Generate a new access token using Github Device Flow (OAuth 2.0).
2171
2280
  const newToken = await executeGithubDeviceFlow(String(process.env.AUTH_GITHUB_CLIENT_ID));
2172
2281
  // Store the new access token.
2282
+ setLocalAuthMethod("github");
2173
2283
  setLocalAccessToken(newToken);
2174
2284
  }
2175
2285
  else
@@ -2190,6 +2300,244 @@ const auth = async () => {
2190
2300
  terminate(providerUserId);
2191
2301
  };
2192
2302
 
2303
+ const { BANDADA_API_URL } = process.env;
2304
+ const bandadaApi = new ApiSdk(BANDADA_API_URL);
2305
+ const addMemberToGroup = async (groupId, dashboardUrl, identity) => {
2306
+ const commitment = identity.commitment.toString();
2307
+ const group = await bandadaApi.getGroup(groupId);
2308
+ const providerName = group.credentials.id.split("_")[0].toLowerCase();
2309
+ // 6. open a new window with the url:
2310
+ const url = `${dashboardUrl}credentials?group=${groupId}&member=${commitment}&provider=${providerName}`;
2311
+ console.log(`${theme.text.bold(`Verification URL:`)} ${theme.text.underlined(url)}`);
2312
+ open(url);
2313
+ const { confirmation } = await askForConfirmation("Did you join the Bandada group in the browser?");
2314
+ if (!confirmation)
2315
+ showError("You must join the Bandada group to continue the login process", true);
2316
+ };
2317
+ const isGroupMember = async (groupId, identity) => {
2318
+ const commitment = identity.commitment.toString();
2319
+ const isMember = await bandadaApi.isGroupMember(groupId, commitment);
2320
+ return isMember;
2321
+ };
2322
+
2323
+ const { BANDADA_DASHBOARD_URL, BANDADA_GROUP_ID } = process.env;
2324
+ const authBandada = async () => {
2325
+ try {
2326
+ const { firebaseFunctions } = await bootstrapCommandExecutionAndServices();
2327
+ const spinner = customSpinner(`Checking identity string for Semaphore...`, `clock`);
2328
+ spinner.start();
2329
+ // 1. check if _identity string exists in local storage
2330
+ let identityString;
2331
+ const isIdentityStringStored = checkLocalBandadaIdentity();
2332
+ if (isIdentityStringStored) {
2333
+ identityString = getLocalBandadaIdentity();
2334
+ spinner.succeed(`Identity seed found\n`);
2335
+ }
2336
+ else {
2337
+ spinner.warn(`Identity seed not found\n`);
2338
+ // 2. generate a random _identity string and save it in local storage
2339
+ const { seed } = await prompts({
2340
+ type: "text",
2341
+ name: "seed",
2342
+ message: theme.text.bold(`Enter a secret string to use as your identity seed in Semaphore:`),
2343
+ initial: false
2344
+ });
2345
+ identityString = seed;
2346
+ setLocalBandadaIdentity(identityString);
2347
+ }
2348
+ // 3. create a semaphore identity with _identity string as a seed
2349
+ const identity = new Identity(identityString);
2350
+ // 4. check if the user is a member of the group
2351
+ console.log(`Checking Bandada membership...`);
2352
+ const isMember = await isGroupMember(BANDADA_GROUP_ID, identity);
2353
+ if (!isMember) {
2354
+ await addMemberToGroup(BANDADA_GROUP_ID, BANDADA_DASHBOARD_URL, identity);
2355
+ }
2356
+ // 5. generate a proof that the user owns the commitment.
2357
+ spinner.text = `Generating proof of identity...`;
2358
+ spinner.start();
2359
+ // publicSignals = [hash(externalNullifier, identityNullifier), commitment]
2360
+ const initDirectoryName = getLocalDirname();
2361
+ const directoryName = initDirectoryName.includes("/src") ? "." : initDirectoryName;
2362
+ const { proof, publicSignals } = await groth16.fullProve({
2363
+ identityTrapdoor: identity.trapdoor,
2364
+ identityNullifier: identity.nullifier,
2365
+ externalNullifier: BANDADA_GROUP_ID
2366
+ }, `${directoryName}/public/mini-semaphore.wasm`, `${directoryName}/public/mini-semaphore.zkey`);
2367
+ spinner.succeed(`Proof generated.\n`);
2368
+ spinner.text = `Sending proof to verification...`;
2369
+ spinner.start();
2370
+ // 6. send proof to a cloud function that verifies it and checks membership
2371
+ const cf = httpsCallable(firebaseFunctions, commonTerms.cloudFunctionsNames.bandadaValidateProof);
2372
+ const result = await cf({
2373
+ proof,
2374
+ publicSignals
2375
+ });
2376
+ const { valid, token, message } = result.data;
2377
+ if (!valid) {
2378
+ showError(message, true);
2379
+ deleteLocalAuthMethod();
2380
+ deleteLocalAccessToken();
2381
+ deleteLocalBandadaIdentity();
2382
+ }
2383
+ spinner.succeed(`Proof verified.\n`);
2384
+ spinner.text = `Authenticating...`;
2385
+ spinner.start();
2386
+ // 7. Auth to p0tion firebase
2387
+ const credentials = await signInWithCustomToken(getAuth(), token);
2388
+ setLocalAuthMethod("bandada");
2389
+ setLocalAccessToken(token);
2390
+ spinner.succeed(`Authenticated as ${theme.text.bold(credentials.user.uid)}.`);
2391
+ console.log(`\n${theme.symbols.warning} You can always log out by running the ${theme.text.bold(`phase2cli logout`)} command`);
2392
+ }
2393
+ catch (error) {
2394
+ // Delete local token.
2395
+ console.log("An error crashed the process. Deleting local token and identity.");
2396
+ console.error(error);
2397
+ deleteLocalAuthMethod();
2398
+ deleteLocalAccessToken();
2399
+ deleteLocalBandadaIdentity();
2400
+ }
2401
+ process.exit(0);
2402
+ };
2403
+
2404
+ const showVerificationCodeAndUri = async (OAuthDeviceCode) => {
2405
+ // Copy code to clipboard.
2406
+ let noClipboard = false;
2407
+ try {
2408
+ clipboard.writeSync(OAuthDeviceCode.user_code);
2409
+ clipboard.readSync();
2410
+ }
2411
+ catch (error) {
2412
+ noClipboard = true;
2413
+ }
2414
+ // Display data.
2415
+ console.log(`${theme.symbols.warning} Visit ${theme.text.bold(theme.text.underlined(OAuthDeviceCode.verification_uri))} on this device to generate a new token and authenticate\n`);
2416
+ console.log(theme.colors.magenta(figlet.textSync("Code is Below", { font: "ANSI Shadow" })), "\n");
2417
+ const message = !noClipboard ? `has been copied to your clipboard (${theme.emojis.clipboard})` : ``;
2418
+ console.log(`${theme.symbols.info} Your auth code: ${theme.text.bold(OAuthDeviceCode.user_code)} ${message} ${theme.symbols.success}\n`);
2419
+ const spinner = customSpinner(`Redirecting to Github...`, `clock`);
2420
+ spinner.start();
2421
+ await sleep(10000); // ~10s to make users able to read the CLI.
2422
+ try {
2423
+ // Automatically open the page (# Step 2).
2424
+ await open(OAuthDeviceCode.verification_uri);
2425
+ }
2426
+ catch (error) {
2427
+ console.log(`${theme.symbols.info} Please authenticate via GitHub at ${OAuthDeviceCode.verification_uri}`);
2428
+ }
2429
+ spinner.stop();
2430
+ };
2431
+ /**
2432
+ * Return the token to sign in to Firebase after passing the SIWE Device Flow
2433
+ * @param clientId <string> - The client id of the Auth0 application.
2434
+ * @param firebaseFunctions <any> - The Firebase functions instance to call the cloud function
2435
+ * @returns <string> - The token to sign in to Firebase
2436
+ */
2437
+ const executeSIWEDeviceFlow = async (clientId, firebaseFunctions) => {
2438
+ // Call Auth0 endpoint to request device code uri
2439
+ const OAuthDeviceCode = (await fetch$1(`${process.env.AUTH0_APPLICATION_URL}/oauth/device/code`, {
2440
+ method: "POST",
2441
+ headers: { "content-type": "application/json" },
2442
+ body: JSON.stringify({
2443
+ client_id: clientId,
2444
+ scope: "openid",
2445
+ audience: `${process.env.AUTH0_APPLICATION_URL}/api/v2/`
2446
+ })
2447
+ }).then((_res) => _res.json()));
2448
+ await showVerificationCodeAndUri(OAuthDeviceCode);
2449
+ // Poll Auth0 endpoint until you get token or request expires
2450
+ let isSignedIn = false;
2451
+ let isExpired = false;
2452
+ let auth0Token = "";
2453
+ while (!isSignedIn && !isExpired) {
2454
+ // Call Auth0 endpoint to request token
2455
+ const OAuthToken = (await fetch$1(`${process.env.AUTH0_APPLICATION_URL}/oauth/token`, {
2456
+ method: "POST",
2457
+ headers: { "content-type": "application/json" },
2458
+ body: JSON.stringify({
2459
+ client_id: clientId,
2460
+ device_code: OAuthDeviceCode.device_code,
2461
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
2462
+ })
2463
+ }).then((_res) => _res.json()));
2464
+ if (OAuthToken.error) {
2465
+ if (OAuthToken.error === "authorization_pending") {
2466
+ // Wait for the user to sign in
2467
+ await sleep(OAuthDeviceCode.interval * 1000);
2468
+ }
2469
+ else if (OAuthToken.error === "slow_down") {
2470
+ // Wait for the user to sign in
2471
+ await sleep(OAuthDeviceCode.interval * 1000 * 2);
2472
+ }
2473
+ else if (OAuthToken.error === "expired_token") {
2474
+ // The user didn't sign in on time
2475
+ isExpired = true;
2476
+ }
2477
+ }
2478
+ else {
2479
+ // The user signed in
2480
+ isSignedIn = true;
2481
+ auth0Token = OAuthToken.access_token;
2482
+ }
2483
+ }
2484
+ // Send token to cloud function to check nonce, create user and retrieve token
2485
+ const cf = httpsCallable(firebaseFunctions, commonTerms.cloudFunctionsNames.checkNonceOfSIWEAddress);
2486
+ const result = await cf({
2487
+ auth0Token
2488
+ });
2489
+ const { token, valid, message } = result.data;
2490
+ if (!valid) {
2491
+ showError(message, true);
2492
+ deleteLocalAuthMethod();
2493
+ deleteLocalAccessToken();
2494
+ }
2495
+ return token;
2496
+ };
2497
+ /**
2498
+ * Auth command using Sign In With Ethereum
2499
+ * @notice The auth command allows a user to make the association of their Ethereum account with the CLI by leveraging SIWE as an authentication mechanism.
2500
+ * @dev Under the hood, the command handles a manual Device Flow following the guidelines in the SIWE documentation.
2501
+ */
2502
+ const authSIWE = async () => {
2503
+ try {
2504
+ const { firebaseFunctions } = await bootstrapCommandExecutionAndServices();
2505
+ // Console more context for the user.
2506
+ console.log(`${theme.symbols.info} ${theme.text.bold(`You are about to authenticate on this CLI using your Ethereum address (device flow - OAuth 2.0 mechanism).\n${theme.symbols.warning} Please, note that only a Sign-in With Ethereum signature will be required`)}\n`);
2507
+ const spinner = customSpinner(`Checking authentication token...`, `clock`);
2508
+ spinner.start();
2509
+ await sleep(5000);
2510
+ // Manage OAuth Github or SIWE token.
2511
+ const isLocalTokenStored = checkLocalAccessToken();
2512
+ if (!isLocalTokenStored) {
2513
+ spinner.fail(`No local authentication token found\n`);
2514
+ // Generate a new access token using Github Device Flow (OAuth 2.0).
2515
+ const newToken = await executeSIWEDeviceFlow(String(process.env.AUTH_SIWE_CLIENT_ID), firebaseFunctions);
2516
+ // Store the new access token.
2517
+ setLocalAuthMethod("siwe");
2518
+ setLocalAccessToken(newToken);
2519
+ }
2520
+ else
2521
+ spinner.succeed(`Local authentication token found\n`);
2522
+ // Get access token from local store.
2523
+ const token = String(getLocalAccessToken());
2524
+ spinner.text = `Authenticating...`;
2525
+ spinner.start();
2526
+ // Exchange token for credential.
2527
+ const credentials = await signInWithCustomToken(getAuth(), token);
2528
+ spinner.succeed(`Authenticated as ${theme.text.bold(credentials.user.uid)}.`);
2529
+ console.log(`\n${theme.symbols.warning} You can always log out by running the ${theme.text.bold(`phase2cli logout`)} command`);
2530
+ process.exit(0);
2531
+ }
2532
+ catch (error) {
2533
+ // Delete local token.
2534
+ console.log("An error crashed the process. Deleting local token and identity.");
2535
+ console.error(error);
2536
+ deleteLocalAuthMethod();
2537
+ deleteLocalAccessToken();
2538
+ }
2539
+ };
2540
+
2193
2541
  /**
2194
2542
  * Return the verification result for latest contribution.
2195
2543
  * @param firestoreDatabase <Firestore> - the Firestore service instance associated to the current Firebase application.
@@ -2312,8 +2660,8 @@ const handleDiskSpaceRequirementForNextContribution = async (cloudFunctions, cer
2312
2660
  spinner.fail(`You may not have enough memory to calculate the contribution for the Circuit ${theme.colors.magenta(`${circuitSequencePosition}`)}.\n\n${theme.symbols.info} The required amount of disk space is ${contributionDiskSpaceRequirement < 0.01
2313
2661
  ? theme.text.bold(`< 0.01`)
2314
2662
  : theme.text.bold(contributionDiskSpaceRequirement)} GB but you only have ${participantFreeDiskSpace > 0 ? theme.text.bold(participantFreeDiskSpace.toFixed(2)) : theme.text.bold(0)} GB available memory \nThe estimate ${theme.text.bold("may not be 100% correct")} since is based on the aggregate free memory on your disks but some may not be detected!\n`);
2315
- const { confirmation } = await askForConfirmation(`Please, we kindly ask you to continue with the contribution if you have noticed the estimate is wrong and you have enough memory in your machine`, "Continue", "Exit");
2316
- wannaContributeOrHaveEnoughMemory = !!confirmation;
2663
+ const { confirmationEnoughMemory } = await askForConfirmation(`Please, we kindly ask you to continue with the contribution if you have noticed the estimate is wrong and you have enough memory in your machine`, "Continue", "Exit");
2664
+ wannaContributeOrHaveEnoughMemory = !!confirmationEnoughMemory;
2317
2665
  if (circuitSequencePosition > 1) {
2318
2666
  console.log(`${theme.symbols.info} Please note, you have time until ceremony ends to free up your memory and complete remaining contributions`);
2319
2667
  // Asks the contributor if their wants to terminate contributions for the ceremony.
@@ -2381,8 +2729,12 @@ const handlePublicAttestation = async (firestoreDatabase, circuits, ceremonyId,
2381
2729
  // Write public attestation locally.
2382
2730
  writeFile(getAttestationLocalFilePath(`${ceremonyPrefix}_${commonTerms.foldersAndPathsTerms.attestation}.log`), Buffer.from(publicAttestation));
2383
2731
  await sleep(1000); // workaround for file descriptor unexpected close.
2384
- const gistUrl = await publishGist(participantAccessToken, publicAttestation, ceremonyName, ceremonyPrefix);
2385
- console.log(`\n${theme.symbols.info} Your public attestation has been successfully posted as Github Gist (${theme.text.bold(theme.text.underlined(gistUrl))})`);
2732
+ let gistUrl = "";
2733
+ const isGithub = getLocalAuthMethod() === "github";
2734
+ if (isGithub) {
2735
+ gistUrl = await publishGist(participantAccessToken, publicAttestation, ceremonyName, ceremonyPrefix);
2736
+ console.log(`\n${theme.symbols.info} Your public attestation has been successfully posted as Github Gist (${theme.text.bold(theme.text.underlined(gistUrl))})`);
2737
+ }
2386
2738
  // Prepare a ready-to-share tweet.
2387
2739
  await handleTweetGeneration(ceremonyName, gistUrl);
2388
2740
  };
@@ -2407,7 +2759,6 @@ const listenToCeremonyCircuitDocumentChanges = (firestoreDatabase, ceremonyId, p
2407
2759
  const { avgTimings, waitingQueue } = changedCircuit.data();
2408
2760
  const { fullContribution, verifyCloudFunction } = avgTimings;
2409
2761
  const { currentContributor } = waitingQueue;
2410
- // Get circuit current contributor participant document.
2411
2762
  const circuitCurrentContributor = await getDocumentById(firestoreDatabase, getParticipantsCollectionPath(ceremonyId), currentContributor);
2412
2763
  // Check data.
2413
2764
  if (!circuitCurrentContributor.data())
@@ -2436,6 +2787,7 @@ const listenToCeremonyCircuitDocumentChanges = (firestoreDatabase, ceremonyId, p
2436
2787
  }
2437
2788
  });
2438
2789
  };
2790
+ let contributionInProgress = false;
2439
2791
  /**
2440
2792
  * Listen to current authenticated participant document changes.
2441
2793
  * @dev this is the core business logic related to the execution of the contribute command.
@@ -2563,11 +2915,21 @@ const listenToParticipantDocumentChanges = async (firestoreDatabase, cloudFuncti
2563
2915
  (!noTemporaryContributionData && resumingWithSameTemporaryData);
2564
2916
  // Scenario (3.B).
2565
2917
  if (isCurrentContributor && hasResumableStep && startingOrResumingContribution) {
2918
+ if (contributionInProgress) {
2919
+ console.warn(`\n${theme.symbols.warning} Received instruction to start/resume contribution but contribution is already in progress...[skipping]`);
2920
+ return;
2921
+ }
2566
2922
  // Communicate resume / start of the contribution to participant.
2567
2923
  await simpleLoader(`${changedContributionStep === "DOWNLOADING" /* ParticipantContributionStep.DOWNLOADING */ ? `Starting` : `Resuming`} your contribution...`, `clock`, 3000);
2568
- // Start / Resume the contribution for the participant.
2569
- await handleStartOrResumeContribution(cloudFunctions, firestoreDatabase, ceremony, circuit, participant, entropy, providerUserId, false // not finalizing.
2570
- );
2924
+ try {
2925
+ contributionInProgress = true;
2926
+ // Start / Resume the contribution for the participant.
2927
+ await handleStartOrResumeContribution(cloudFunctions, firestoreDatabase, ceremony, circuit, participant, entropy, providerUserId, false, // not finalizing.
2928
+ circuits.length);
2929
+ }
2930
+ finally {
2931
+ contributionInProgress = false;
2932
+ }
2571
2933
  }
2572
2934
  // Scenario (3.A).
2573
2935
  else if (isWaitingForContribution)
@@ -2616,7 +2978,9 @@ const listenToParticipantDocumentChanges = async (firestoreDatabase, cloudFuncti
2616
2978
  // Get latest contribution verification result.
2617
2979
  await getLatestVerificationResult(firestoreDatabase, ceremony.id, circuit.id, participant.id);
2618
2980
  // Get next circuit for contribution.
2619
- const nextCircuit = getCircuitBySequencePosition(circuits, changedContributionProgress + 1);
2981
+ const nextCircuit = timeoutExpired
2982
+ ? getCircuitBySequencePosition(circuits, changedContributionProgress)
2983
+ : getCircuitBySequencePosition(circuits, changedContributionProgress + 1);
2620
2984
  // Check disk space requirements for participant.
2621
2985
  const wannaGenerateAttestation = await handleDiskSpaceRequirementForNextContribution(cloudFunctions, ceremony.id, nextCircuit.data.sequencePosition, nextCircuit.data.zKeySizeInBytes, timeoutExpired, providerUserId);
2622
2986
  // Check if the participant would like to generate a new attestation.
@@ -2654,11 +3018,12 @@ const listenToParticipantDocumentChanges = async (firestoreDatabase, cloudFuncti
2654
3018
  */
2655
3019
  const contribute = async (opt) => {
2656
3020
  const { firebaseApp, firebaseFunctions, firestoreDatabase } = await bootstrapCommandExecutionAndServices();
2657
- // Check for authentication.
2658
- const { user, providerUserId, token } = await checkAuth(firebaseApp);
2659
3021
  // Get options.
2660
3022
  const ceremonyOpt = opt.ceremony;
2661
3023
  const entropyOpt = opt.entropy;
3024
+ const { auth } = opt;
3025
+ // Check for authentication.
3026
+ const { user, providerUserId, token } = auth ? await authWithToken(firebaseApp, auth) : await checkAuth(firebaseApp);
2662
3027
  // Prepare data.
2663
3028
  let selectedCeremony;
2664
3029
  // Retrieve the opened ceremonies.
@@ -2694,7 +3059,7 @@ const contribute = async (opt) => {
2694
3059
  const userDoc = await getDocumentById(firestoreDatabase, commonTerms.collections.users.name, user.uid);
2695
3060
  const userData = userDoc.data();
2696
3061
  if (!userData) {
2697
- spinner.fail(`Unfortunately we could not find a user document with your information. This likely means that you did not pass the GitHub reputation checks and therefore are not elegible to contribute to any ceremony. Please contact the coordinator if you believe this to be an error.`);
3062
+ spinner.fail(`Unfortunately we could not find a user document with your information. This likely means that you did not pass the GitHub reputation checks and therefore are not eligible to contribute to any ceremony. If you believe you pass the requirements, it might be possible that your profile is private and we were not able to fetch your real statistics, in this case please consider making your profile public for the duration of the contribution. Please contact the coordinator if you believe this to be an error.`);
2698
3063
  process.exit(0);
2699
3064
  }
2700
3065
  // Check the user's current participant readiness for contribution status (eligible, already contributed, timed out).
@@ -2845,7 +3210,7 @@ const observe = async () => {
2845
3210
  // Preserve command execution only for coordinators].
2846
3211
  if (!(await isCoordinator(user)))
2847
3212
  showError(COMMAND_ERRORS.COMMAND_NOT_COORDINATOR, true);
2848
- // Get running cerimonies info (if any).
3213
+ // Get running ceremonies info (if any).
2849
3214
  const runningCeremoniesDocs = await getOpenedCeremonies(firestoreDatabase);
2850
3215
  // Ask to select a ceremony.
2851
3216
  const ceremony = await promptForCeremonySelection(runningCeremoniesDocs, false);
@@ -2894,7 +3259,7 @@ const handleVerificationKey = async (cloudFunctions, bucketName, finalZkeyLocalF
2894
3259
  spinner.text = "Writing verification key...";
2895
3260
  // Write the verification key locally.
2896
3261
  writeLocalJsonFile(verificationKeyLocalFilePath, vKey);
2897
- await sleep(3000); // workaound for file descriptor.
3262
+ await sleep(3000); // workaround for file descriptor.
2898
3263
  // Upload verification key to storage.
2899
3264
  await multiPartUpload(cloudFunctions, bucketName, verificationKeyStorageFilePath, verificationKeyLocalFilePath, Number(process.env.CONFIG_STREAM_CHUNK_SIZE_IN_MB));
2900
3265
  spinner.succeed(`Verification key correctly saved on storage`);
@@ -2914,13 +3279,13 @@ const handleVerifierSmartContract = async (cloudFunctions, bucketName, finalZkey
2914
3279
  const packagePath = `${dirname(fileURLToPath(import.meta.url))}`;
2915
3280
  const verifierPath = packagePath.includes(`src/commands`)
2916
3281
  ? `${dirname(fileURLToPath(import.meta.url))}/../../../../node_modules/snarkjs/templates/verifier_groth16.sol.ejs`
2917
- : `${dirname(fileURLToPath(import.meta.url))}/../../../node_modules/snarkjs/templates/verifier_groth16.sol.ejs`;
3282
+ : `${dirname(fileURLToPath(import.meta.url))}/../node_modules/snarkjs/templates/verifier_groth16.sol.ejs`;
2918
3283
  // Export the Solidity verifier smart contract.
2919
3284
  const verifierCode = await exportVerifierContract(finalZkeyLocalFilePath, verifierPath);
2920
3285
  spinner.text = `Writing verifier smart contract...`;
2921
3286
  // Write the verification key locally.
2922
3287
  writeFile(verifierContractLocalFilePath, verifierCode);
2923
- await sleep(3000); // workaound for file descriptor.
3288
+ await sleep(3000); // workaround for file descriptor.
2924
3289
  // Upload verifier smart contract to storage.
2925
3290
  await multiPartUpload(cloudFunctions, bucketName, verifierContractStorageFilePath, verifierContractLocalFilePath, Number(process.env.CONFIG_STREAM_CHUNK_SIZE_IN_MB));
2926
3291
  spinner.succeed(`Verifier smart contract correctly saved on storage`);
@@ -2941,11 +3306,12 @@ const handleVerifierSmartContract = async (cloudFunctions, bucketName, finalZkey
2941
3306
  * @param participant <FirebaseDocumentInfo> - the Firestore document of the participant (coordinator).
2942
3307
  * @param beacon <string> - the value used to compute the final contribution while finalizing the ceremony.
2943
3308
  * @param coordinatorIdentifier <string> - the identifier of the coordinator.
3309
+ * @param circuitsLength <number> - the number of circuits in the ceremony.
2944
3310
  */
2945
- const handleCircuitFinalization = async (cloudFunctions, firestoreDatabase, ceremony, circuit, participant, beacon, coordinatorIdentifier) => {
3311
+ const handleCircuitFinalization = async (cloudFunctions, firestoreDatabase, ceremony, circuit, participant, beacon, coordinatorIdentifier, circuitsLength) => {
2946
3312
  // Step (1).
2947
- await handleStartOrResumeContribution(cloudFunctions, firestoreDatabase, ceremony, circuit, participant, computeSHA256ToHex(beacon), coordinatorIdentifier, true);
2948
- await sleep(2000); // workaound for descriptors.
3313
+ await handleStartOrResumeContribution(cloudFunctions, firestoreDatabase, ceremony, circuit, participant, computeSHA256ToHex(beacon), coordinatorIdentifier, true, circuitsLength);
3314
+ await sleep(2000); // workaround for descriptors.
2949
3315
  // Extract data.
2950
3316
  const { prefix: circuitPrefix } = circuit.data;
2951
3317
  const { prefix: ceremonyPrefix } = ceremony.data;
@@ -2979,10 +3345,11 @@ const handleCircuitFinalization = async (cloudFunctions, firestoreDatabase, cere
2979
3345
  * @dev For proper execution, the command requires the coordinator to be authenticated with a GitHub account (run auth command first) in order to
2980
3346
  * handle sybil-resistance and connect to GitHub APIs to publish the gist containing the final public attestation.
2981
3347
  */
2982
- const finalize = async () => {
3348
+ const finalize = async (opt) => {
2983
3349
  const { firebaseApp, firebaseFunctions, firestoreDatabase } = await bootstrapCommandExecutionAndServices();
2984
3350
  // Check for authentication.
2985
- const { user, providerUserId, token: coordinatorAccessToken } = await checkAuth(firebaseApp);
3351
+ const { auth } = opt;
3352
+ const { user, providerUserId, token: coordinatorAccessToken } = auth ? await authWithToken(firebaseApp, auth) : await checkAuth(firebaseApp);
2986
3353
  // Preserve command execution only for coordinators.
2987
3354
  if (!(await isCoordinator(user)))
2988
3355
  showError(COMMAND_ERRORS.COMMAND_NOT_COORDINATOR, true);
@@ -3017,7 +3384,7 @@ const finalize = async () => {
3017
3384
  const circuits = await getCeremonyCircuits(firestoreDatabase, selectedCeremony.id);
3018
3385
  // Handle finalization for each ceremony circuit.
3019
3386
  for await (const circuit of circuits)
3020
- await handleCircuitFinalization(firebaseFunctions, firestoreDatabase, selectedCeremony, circuit, participant, beacon, providerUserId);
3387
+ await handleCircuitFinalization(firebaseFunctions, firestoreDatabase, selectedCeremony, circuit, participant, beacon, providerUserId, circuits.length);
3021
3388
  process.stdout.write(`\n`);
3022
3389
  const spinner = customSpinner(`Wrapping up the finalization of the ceremony...`, "clock");
3023
3390
  spinner.start();
@@ -3032,7 +3399,7 @@ const finalize = async () => {
3032
3399
  // Generate attestation with final contributions.
3033
3400
  const publicAttestation = await generateValidContributionsAttestation(firestoreDatabase, circuits, selectedCeremony.id, participant.id, contributions, providerUserId, ceremonyName, true);
3034
3401
  // Write public attestation locally.
3035
- writeFile(getAttestationLocalFilePath(`${prefix}_${finalContributionIndex}_${commonTerms.foldersAndPathsTerms.attestation}.log`), Buffer.from(publicAttestation));
3402
+ writeFile(getFinalAttestationLocalFilePath(`${prefix}_${finalContributionIndex}_${commonTerms.foldersAndPathsTerms.attestation}.log`), Buffer.from(publicAttestation));
3036
3403
  await sleep(3000); // workaround for file descriptor unexpected close.
3037
3404
  const gistUrl = await publishGist(coordinatorAccessToken, publicAttestation, ceremonyName, prefix);
3038
3405
  console.log(`\n${theme.symbols.info} Your public final attestation has been successfully posted as Github Gist (${theme.text.bold(theme.text.underlined(gistUrl))})`);
@@ -3093,7 +3460,9 @@ const logout = async () => {
3093
3460
  const auth = getAuth();
3094
3461
  await signOut(auth);
3095
3462
  // Delete local token.
3463
+ deleteLocalAuthMethod();
3096
3464
  deleteLocalAccessToken();
3465
+ deleteLocalBandadaIdentity();
3097
3466
  await sleep(3000); // ~3s.
3098
3467
  spinner.stop();
3099
3468
  console.log(`${theme.symbols.success} Logout successfully completed`);
@@ -3155,6 +3524,37 @@ const listCeremonies = async () => {
3155
3524
  }
3156
3525
  };
3157
3526
 
3527
+ const listParticipants = async () => {
3528
+ try {
3529
+ const { firestoreDatabase } = await bootstrapCommandExecutionAndServices();
3530
+ const allCeremonies = await getAllCeremonies(firestoreDatabase);
3531
+ const selectedCeremony = await promptForCeremonySelection(allCeremonies, true);
3532
+ const docRef = doc(firestoreDatabase, commonTerms.collections.ceremonies.name, selectedCeremony.id);
3533
+ const participantsRef = collection(docRef, "participants");
3534
+ const participantsSnapshot = await getDocs(participantsRef);
3535
+ const participants = participantsSnapshot.docs.map((participantDoc) => participantDoc.data().userId);
3536
+ console.log(participants);
3537
+ /* const usersRef = collection(firestoreDatabase, "users")
3538
+ const usersSnapshot = await getDocs(usersRef)
3539
+ const users = usersSnapshot.docs.map((userDoc) => userDoc.data())
3540
+ console.log(users) */
3541
+ }
3542
+ catch (err) {
3543
+ showError(`Something went wrong: ${err.toString()}`, true);
3544
+ }
3545
+ process.exit(0);
3546
+ };
3547
+
3548
+ const setCeremonyCommands = (program) => {
3549
+ const ceremony = program.command("ceremony").description("manage ceremonies");
3550
+ ceremony
3551
+ .command("participants")
3552
+ .description("retrieve participants list of a ceremony")
3553
+ .requiredOption("-c, --ceremony <string>", "the prefix of the ceremony you want to retrieve information about", "")
3554
+ .action(listParticipants);
3555
+ return ceremony;
3556
+ };
3557
+
3158
3558
  // Get pkg info (e.g., name, version).
3159
3559
  const packagePath = `${dirname(fileURLToPath(import.meta.url))}/..`;
3160
3560
  const { description, version, name } = JSON.parse(readFileSync(`${packagePath}/package.json`, "utf8"));
@@ -3163,44 +3563,52 @@ const program = createCommand();
3163
3563
  program.name(name).description(description).version(version);
3164
3564
  // User commands.
3165
3565
  program.command("auth").description("authenticate yourself using your Github account (OAuth 2.0)").action(auth);
3566
+ program
3567
+ .command("auth-bandada")
3568
+ .description("authenticate yourself in a privacy-perserving manner using Bandada")
3569
+ .action(authBandada);
3570
+ program
3571
+ .command("auth-siwe")
3572
+ .description("authenticate yourself using your Ethereum account (Sign In With Ethereum - SIWE)")
3573
+ .action(authSIWE);
3166
3574
  program
3167
3575
  .command("contribute")
3168
3576
  .description("compute contributions for a Phase2 Trusted Setup ceremony circuits")
3169
3577
  .option("-c, --ceremony <string>", "the prefix of the ceremony you want to contribute for", "")
3170
3578
  .option("-e, --entropy <string>", "the entropy (aka toxic waste) of your contribution", "")
3579
+ .option("-a, --auth <string>", "the Github OAuth 2.0 token", "")
3171
3580
  .action(contribute);
3172
3581
  program
3173
3582
  .command("clean")
3174
3583
  .description("clean up output generated by commands from the current working directory")
3175
3584
  .action(clean);
3176
- program
3177
- .command("list")
3178
- .description("List all ceremonies prefixes")
3179
- .action(listCeremonies);
3585
+ program.command("list").description("List all ceremonies prefixes").action(listCeremonies);
3180
3586
  program
3181
3587
  .command("logout")
3182
3588
  .description("sign out from Firebae Auth service and delete Github OAuth 2.0 token from local storage")
3183
3589
  .action(logout);
3184
3590
  program
3185
3591
  .command("validate")
3186
- .description("Validate that a Ceremony Setup file is correct")
3592
+ .description("validate that a Ceremony Setup file is correct")
3187
3593
  .requiredOption("-t, --template <path>", "The path to the ceremony setup template", "")
3188
3594
  .option("-c, --constraints <number>", "The number of constraints to check against")
3189
3595
  .action(validate);
3190
3596
  // Only coordinator commands.
3191
- const ceremony = program.command("coordinate").description("commands for coordinating a ceremony");
3192
- ceremony
3597
+ const coordinate = program.command("coordinate").description("commands for coordinating a ceremony");
3598
+ coordinate
3193
3599
  .command("setup")
3194
3600
  .description("setup a Groth16 Phase 2 Trusted Setup ceremony for zk-SNARK circuits")
3195
- .option('-t, --template <path>', 'The path to the ceremony setup template', '')
3196
- .option('-a, --auth <string>', 'The Github OAuth 2.0 token', '')
3601
+ .option("-t, --template <path>", "The path to the ceremony setup template", "")
3602
+ .option("-a, --auth <string>", "The Github OAuth 2.0 token", "")
3197
3603
  .action(setup);
3198
- ceremony
3604
+ coordinate
3199
3605
  .command("observe")
3200
3606
  .description("observe in real-time the waiting queue of each ceremony circuit")
3201
3607
  .action(observe);
3202
- ceremony
3608
+ coordinate
3203
3609
  .command("finalize")
3204
3610
  .description("finalize a Phase2 Trusted Setup ceremony by applying a beacon, exporting verification key and verifier contract")
3611
+ .option("-a, --auth <string>", "the Github OAuth 2.0 token", "")
3205
3612
  .action(finalize);
3613
+ setCeremonyCommands(program);
3206
3614
  program.parseAsync(process.argv);