# p0tion Coordinator Guide This document shall be used as a guide for everyone who wants to coordinate their Trusted Setup Phase 2 ceremony using p0tion. [toc] # Context There are multiple *proving systems* to generate and verify proofs such as Groth16, Halo2, Plonk, and so on. We are going to focus only on Groth16 which is one of the most widespread proving systems due to its ability to generate small, fast, and cheap-to-verify proofs and thanks to the widespread domain-specific language (*Circom*) used to write circuits. *Proving* something means basically to prove that a secret is an element of a given *elliptic curve*, a subset of algebraic curves used in this context to perform cryptographic operations securely and efficiently. So far so good … ## What is a Trusted Setup Ceremony? To generate and verify proofs securely, a cryptographic event must be run where a group of people collaborate to create a set of cryptographic parameters needed to kick-off zkSNARKs-based systems. The goal is to ensure that no one can influence or manipulate the parameter creation process. The idea is to share the burden of the setup among many participants, thus each produces only a fragment of the information needed to generate the ceremony parameter, the so-called ***********toxic waste***********. As the name could suggest, this information must be thrown away by the participants and it only takes at least one of them to successfully dispose of the ***********toxic waste*********** to ensure the security of the ceremony. This is due to a malicious party needing all fragments to break the system; that’s why these events are called ********MPC******** **Trusted Setup** **Ceremonies**. ## How does a Trusted Setup works? Any Trusted Setup ceremony is organized in two subsequent steps: the **Phase 1**, which is universally reusable in any point of contribution as input for any zkSNARKs Phase 2. Briefly, the goal of the Phase 1 is to securely generate zk-SNARK parameters for circuits of up to a huge amount of constraints while the **Phase 2**, is a circuit-specific ceremony that must be done for each individual application circuit. Luckily, both phases have a similar workflow. Both assume that there is at least one *coordinator* and *multiple participants* taking turns in (generally) sequential rounds. The coordinator generates and publishes a challenge file, which the first participant downloads, and generates some entropy (the so-called *toxic waste*). Then, the participant runs a computation to produce a new challenge file, which is made available for the coordinator to verify. If the contribution was deemed correct, the next participant will repeat the process starting from this latest contribution, otherwise they are going to recompute the work taking the position of the previous participant. The process is repeated indefinitely until the coordinator decides to end the ceremony or a predetermined end date is reached. Ultimately, the ceremony results in the extraction of a key for the specific circuit being used. ## Why would anyone run a ceremony? The Groth16 proving system boasts small, fast, and cheap-to-verify proofs. The hunt for universal *SNARKs* as fast as single-circuit Groth16 has (unsuccessfully) spawned many new projects in the space. A largely cited criticism drifts away from performances but rather that it is not universal - every change to a circuit requires a new Phase 2 Trusted Setup ceremony. Therefore, for production use, Groth16 zk-SNARK circuits require a MPC (*Multi-Party Computation*) Trusted Setup ceremony to generate the parameters that can kick-off zkSNARKs-based systems. ## Why p0tion? Making one of these MPC protocols requires time and development resources for design, auditing, testing, security, operations, ceremony conduction plan, guides and so on. That’s why we are working on the p0tion toolkit to automate the setup, execution, coordination and finalization of Phase 2 Trusted Setup ceremonies for one or more zkSNARKs circuit(s). [**p0tion**](https://github.com/privacy-scaling-explorations/p0tion) is a project (formerly known as MPC Phase 2 Suite) from the MACI/QFI team of PSE. You could think p0tion as a toolkit to effortlessy manage Trusted Setup Phase 2 ceremonies for multiple circuit at the same time. Developing one of these MPC protocols requires time and development resources for design, auditing, testing, security, operations, ceremony conduction plan, guides and so on. That’s why we are working towards [p0tion](https://github.com/privacy-scaling-explorations/p0tion) to be an agnostic-from-ceremony public good toolkit, usable by everyone, to make their Groth16 zk-applications scale and safely production-ready. __Values__ - **Secure Groth16 circuits in Prod.** Circom developers, including the MACI and QFI team can implement continuous delivery of ***secure*** groth16 zkApps within an agile setting by automating phase2 ceremonies. - **Easy to read and use**. Documentation and code is clear, concise, and articulate; someone new to the tool could pick it up and deploy a ceremony in under an hour. - **Ready for change** Developers can have confidence in the security of the ceremony tool and can fork/adapt the code for their own ceremony. - **Infrastructure as Code**. Black-boxing the entire process for infrastructure setup, coordination, scaling and ceremony conduction. ## Code & Docs The current codebase (*v1.x*) is broken down into three different packages - `actions` key features, types and helpers on which the `backend` and `cli` packages are built. Think this package as an agnostic set of ready-to-use functions (*SDK*). - `backend` configuration and deployment of the infrastructure (Firebase Cloud Functions which in turn interact with AWS S3 and AWS EC2). - `phase2cli` a command-line interface built for coordinators and contributors to Trusted Setup Phase2 ceremonies running on top of p0tion infrastructure. The official GitHub repository can be found [here](https://github.com/privacy-scaling-explorations/p0tion). # Getting Started This section provides a detailed description of the subsequent steps necessary for deploying and coordinating a ceremony using p0tion. ## Prerequisites We recommend you have the following four accounts properly configured and active before you begin operating with p0tion. * Node Package Manager account (required to publish the package). * Amazon Web Service (AWS) account (required to use AWS S3 Storage, Lambda, SNS and EC2). * Google Cloud Platform (GCP) account (required to use Firebase services). * GitHub Account (required for creating a new OAuth Application). Although p0tion is easy to set up, there are some technical requirements that coordinators must carefully put into practice * Basics of AWS/GCP. * Comfortable using a Command-Line Interface (CLI) * Understand the importance of security and secrets (e.g., AWS access keys) * Running on a stable connection, possibly wired for large circuits configurations. ## Installation Clone the repository ```bash! git clone https://github.com/privacy-scaling-explorations/p0tion.git ``` Install the dependencies and build the packages ```bash! yarn && yarn build ``` ## Configuration p0tion makes use of a mix of services between AWS - GCP Firebase to overcome the limitations of one and the other. The following instructions should be followed to correctly configure the environment. __nb.__ p0tion uses OAuth 2.0 as the default method for authentication on Firebase. ### AWS Infrastructure 0. Login or create a [new AWS Account](https://portal.aws.amazon.com/billing/signup?nc2=h_ct&src=header_signup&redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start/email). - The AWS free tier account will cover a good number of requests for ceremonies but there could be some costs based on your ceremony circuits size. 1. Create an access key for a user with Admin privileges (__NOT ROOT USER__) 2. Setup the `awscli` ([docs](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)) and add the keys for this user. 3. Install `terraform` ([docs](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)) 4. Decide on an AWS region (by default this is **us-east-1**) - if you want to change you will need to do the following: 1. update **aws/lambda/index.mjs** ([exact line](https://github.com/privacy-scaling-explorations/p0tion/blob/dev/packages/backend/aws/lambda/index.mjs#L3)) to the new region 2. update **main.tf** ([exact line](https://github.com/privacy-scaling-explorations/p0tion/blob/dev/packages/backend/aws/main.tf#L2)) to the new region 5. zip the Lambda folder: 1. `cd lambda` 2. `zip -r ../lambda.zip .` 6. Run terraform: 1. `terraform init` 2. `terraform plan` 3. `terraform apply` 4. `terraform output secret_key` - To print the secret access key for the IAM user 6. Store the other values (sns_topic_arn etc.) - These will be needed for the backend .env file configuration The IAM user created with the steps above can be used for all p0tion's features. ### Firebase Project 0. Login or create a [new Google Account](https://accounts.google.com/signup/v2/webcreateaccount?biz=false&cc=IT&continue=https%3A%2F%2Ffirebase.google.com%2F_d%2Freturn%3Fcontinue%3Dhttps%253A%252F%252Ffirebase.google.com%252Fdocs%252Ffunctions%252Fbeta&dsh=S-569564009%3A1681834109581250&flowEntry=SignUp&flowName=GlifWebSignIn&ifkv=AQMjQ7T6fQwgXpvobNeY3XHnj5Oj3MNqx6YIoJZX1MSyDyOEcKqOf6f3s1uChfk6eZz2UXRdL6Mj&hl=en). 1. Setup your GCP account with "pay-as-you-go billing" ([Firebase Blaze plan](https://firebase.google.com/pricing)). 2. In the Firebase console click: **Add a new project** ![](https://i.imgur.com/co4SDUC.png) 3. Type an appropriate name and press **Continue**. - At this point you can choose between enabling Google analytics or not. This will not affect our process in any way, you could choose either. 4. Press **Create project** to complete your project creation. ### Authentication Service As already mentioned, the `phase2cli` p0tion uses OAuth 2.0 to authenticate any user to Firebase. This could be further extended by adapting other third parties for OAuth 2.0 or by relying on custom services. However, here we assume that the use of `phase2cli` is configured to support only the GitHub OAuth 2.0 Device Flow authentication mechanism. :warning: You must have your e-mail set as __PUBLIC__ on Github settings to be recognized as coordinator in p0tion. The e-mail must match the one used to configure the `backend` package environment later. On GitHub, navigate to **Settings** -> **Developer settings**. ![](https://i.imgur.com/ApzhtRL.png) Click on **OAuth Apps**, press **new**, and enter the requested information. ![](https://i.imgur.com/uRXic9L.png) All parameters are arbitrary, aside from the callback URL (e.g., `https://app_name.firebaseapp.com/__/auth/handler`). This information can be gathered from Firebase when configuring GitHub as OAuth provider for your Firebase application. To obtain your Callback URL, get back to the Firebase tab in your browser. If you have created a fresh new application, the browser tab would look like the following one ![](https://i.imgur.com/jzkLnnw.png) Click on **GitHub** and toggle the enable button at the top right of the screenshot: ![](https://i.imgur.com/wMVXLKu.png) Now let's take the callback URL and copy back to GitHub. Fill the remaining items, including ticking **Enable Device Flow** and then click on **Register Application**. Now, we have the client ID and can generate the client secret. Click on **Generate a new client secret**: ![](https://i.imgur.com/l2lCfj7.png) Then, move back to Firebase and fill the remaining details: ![](https://i.imgur.com/7rgygoI.png) Click on **Save**, and that is everything for Authentication Service configuration. #### Testing For running unit and e2e tests, coordinators need to enable the "Email and Password" authentication mechanism on Firebase. :warning: Do not enable email/password authentication unless you are looking to run unit/e2e test. Also, please disable it afterwards before running any production ceremony. Click on **Add new provider** and on **Email/Password**: ![](https://i.imgur.com/bPngbwe.png) Enable **Email/Password** only and click on **Save**: ![](https://i.imgur.com/GLKwTUQ.png) ### Firebase Application You will need to create a new web application to be associated with the `phase2cli`. Move to the **Project Overview** page and click on the **</>** web icon ![](https://i.imgur.com/pkYrKI0.png) Add a name and click on **Register App** ![](https://i.imgur.com/OYboYl2.png) Then, store the details provided on the screen and click on continue. ![](https://i.imgur.com/M4NNKt8.png) These details could be recovered at any time and should not be considered as secrets. ### Service Account A Service Account key is required to interact with the Firebase Admin SDK and deploy the Cloud Functions. This is a JSON file that can be downloaded from the web console or from GCP IAM's console. The latter makes it possible to customize the permissions of the account. Therefore, it will be the method of choice when needed for running CI tests as the former doesn't have sufficient privileges by default. #### Download from Web console Please click on **Project Settings** -> **Service accounts** ![](https://i.imgur.com/82fPaTs.png) Then, click on **Generate new private key**: ![](https://i.imgur.com/i5nFJlk.png) Finally, download it by clicking on **Generate key**: ![](https://i.imgur.com/VwpXXA7.png) Make sure to save this file inside p0tion's repo at the following path: ```bash! packages/backend/serviceAccountKey.json ``` #### Download from GCP IAM's console w/ granular permissions Navigate to: [https://console.cloud.google.com/iam-admin/iam?project=](https://console.cloud.google.com/iam-admin/iam?project=) with your project name appended as the project parameter. Now, click **Service Accounts** on the menu on the left ![](https://i.imgur.com/OrZqG1A.png) And click on **Create Service Account** on the top of the newly opened page ![](https://i.imgur.com/cVM7lwp.png) Then, we can assign name and description to create the account. ![](https://i.imgur.com/UvFoERo.png) At the next step, we are able to assign roles ![](https://i.imgur.com/TSRu2c9.png) If you'd like to run tests in production and deploy Cloud functions via GitHub actions, please set the following: ![](https://i.imgur.com/DNoMNGy.png) Finally, we have successfully created and configured this service account. Now, let's allow it to access the **Default compute service account** which will have its name in the form of `numbers-compute@developer.gserviceaccount.com` ![](https://i.imgur.com/wV7IDUn.png) On the Service account tab, select this account and at the right of the screen (under **Actions**) click on the tree dots sign and press **Manage Permissions** ![](https://i.imgur.com/fXwLZM1.png) Now, click on **Grant Access** ![](https://i.imgur.com/3NR8vBq.png) Please, paste the full name of your Service Account (e.g., `name\@project_name.iam.gserviceaccount.com`) ![](https://i.imgur.com/wOD58CS.png) Select **Service Account User** as role, and click on Save. Finally, let's generate the service account key. Navigate back to the created service account, click on **Keys** and then **Create new key** ![](https://i.imgur.com/wvA9x9o.png) ![](https://i.imgur.com/IPhAHcU.png) Select **JSON** and there we have it, the key will be automatically downloaded. ![](https://i.imgur.com/XCUzavS.png) ### Environment Variables You're ready to setup the `.env` files necessary to deploy the Cloud Functions and setup the `actions` integration core package. #### Backend package Navigate to the `backend` package and prepare the `.env` file ```bash! cd packages/backend && cp .default.env .env ``` ```bash! ### AWS S3 STORAGE ### ### These configs are related to the configuration of the interaction with the ### AWS S3 bucket used as storage for ceremony artifacts. # The AWS access key identifier related to S3 APIs. AWS_ACCESS_KEY_ID="YOUR-AWS-ACCESS-KEY-ID" # The AWS secret access key related to S3 APIs. AWS_SECRET_ACCESS_KEY="YOUR-AWS-SECRET-ACCESS-KEY" # The AWS region where your buckets are located. AWS_REGION="YOUR-AWS-REGION" # The pre-signed URL expiration expressed in seconds. AWS_PRESIGNED_URL_EXPIRATION="900" # The postfix used to create S3 buckets for storing the ceremonies artifacts. AWS_CEREMONY_BUCKET_POSTFIX="-ph2-ceremony" # The AWS AMI ID (default to Amazon Linux 2 in eu-central-1). AWS_AMI_ID="ami-022e1a32d3f742bd8" # The EC2 instance role to access S3 AWS_ROLE_ARN="YOUR-AWS-ROLE-ARN" # The SNS topic ARN to publish notifications AWS_SNS_TOPIC_ARN="YOUR-AWS-SNS-TOPIC-ARN" ### GENERIC ### ### These configs are generic and not tied to Firebase or AWS services. # GitHub OAuth2 ## Minimum amount of followers for the GitHub account GITHUB_MINIMUM_FOLLOWERS="1" ## Minimum amount of users being followed by the GitHub account GITHUB_MINIMUM_FOLLOWING="5" ## Minimum amount of public repos for the GitHub account GITHUB_MINIMUM_PUBLIC_REPOS="2" ## Personal access token for API rate limiting (no privileges required) GITHUB_ACCESS_TOKEN="YOUR-GITHUB-ACCESS-TOKEN" # The email address of the user who is going to be the coordinator of all ceremonies. # nb. right now, only one user could be a coordinator for all ceremonies deployed within the same instance. # Note that the email should be visible from third-party (e.g., Github public email). # @todo allow to use a custom domain to allow multiple coordinators. CUSTOM_CLAIMS_COORDINATOR_EMAIL_ADDRESS_OR_DOMAIN="YOUR-EMAIL-ADDRESS-OR-DOMAIN" # The name of the verification software used to verify a contribution. # NB. this must match the name of the npm package used to verify contributions as specified on the package.json file. CUSTOM_CONTRIBUTION_VERIFICATION_SOFTWARE_NAME="snarkjs" # The version of the verification software (snarkjs) used to verify a contribution. # NB. this must match the version specified on the package.json file. CUSTOM_CONTRIBUTION_VERIFICATION_SOFTWARE_VERSION="0.5.0" # The commit hash of the version of the verification software (snarkjs) used to verify a contribution. # NB. this must match the commit hash of the release of the version specified on the package.json file. CUSTOM_CONTRIBUTION_VERIFICATION_SOFTWARE_COMMIT_HASH="6660254b81a3ed86b961df2a9c1b53ccdddc1216" ``` Start adding your IAM credentials generated from the previous steps, as well as the SNS topic ARN, ARN of the EC2 instance role and the AWS_AMI_ID. Please note that only Amazon Linux 2 instances will work right out of the box (as they come packaged with the **awscli**). Please refer to [AWS docs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) for a list of AMI_IDs. ```bash! AWS_ACCESS_KEY_ID="YOUR-AWS-ACCESS-KEY-ID" AWS_SECRET_ACCESS_KEY="YOUR-AWS-SECRET-ACCESS-KEY" AWS_REGION="YOUR-AWS-REGION" # (can be any [AWS region](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/) such as us-east-1) AWS_PRESIGNED_URL_EXPIRATION="900" # (can leave to default) AWS_CEREMONY_BUCKET_POSTFIX="-ph2-ceremony" # (a postfix to be appended to each bucket to make it unique) # The AWS AMI ID (default to Amazon Linux 2 in eu-central-1). AWS_AMI_ID="ami-022e1a32d3f742bd8" # The EC2 instance role to access S3 AWS_ROLE_ARN="YOUR-AWS-ROLE-ARN" # The SNS topic ARN to publish notifications AWS_SNS_TOPIC_ARN="YOUR-AWS-SNS-TOPIC-ARN" ``` Then, add the email of the coordinator here ```bash! CUSTOM_CLAIMS_COORDINATOR_EMAIL_ADDRESS_OR_DOMAIN="YOUR-EMAIL-ADDRESS-OR-DOMAIN" ``` The `GITHUB_MINIMUM_X` variables are used to determine the minimum acceptance requirements for GitHub accounts. These are only required when GitHub is the chosen authentication provider. The variables dictate the minimum public repositories, minimum number of follower, minimum number of accounts followed. Please note that these restrictions do not apply to coordinators but to contributors only. The last part of the config file relate to the verification software (snarkJS) and its version. Assuming that `snarkJS` version 0.5.0 is installed, no changes are needed. If a different version is installed in the `backend` package, please modify it accordingly. #### Actions package Navigate to the `actions` package and prepare the `.env` file ```bash! cd packages/actions && cp .default.env .env ``` ```bash # This environemnt must be configured both for core functionalities and testing. # The tests can be executed against a pre-deployed Firebase instance or # locally on your machine using the Firebase emulator. ### FIREBASE ### ### These configs are related to the configuration of the Firebase services. # The Firebase Application API key for making request against the services. # nb. this is going to be auto-generated when creating a new application. FIREBASE_API_KEY="YOUR-FIREBASE-API-KEY" # The URL to Firebase Authentication service (should point to default). # nb. this is going to be auto-generated when creating a new application. FIREBASE_AUTH_DOMAIN="YOUR-APPLICATION-NAME.firebaseapp.com" # The Firebase Application project id (should match with application name). FIREBASE_PROJECT_ID="YOUR-PROJECT-ID" # The Firebase unique message sender identifier (to recognize the application user). # nb. this is going to be auto-generated when creating a new application. FIREBASE_MESSAGING_SENDER_ID="YOUR-MESSAGING-SENDER-ID" # The Firebase unique identifier for your application. # nb. this is going to be auto-generated when creating a new application. FIREBASE_APP_ID="YOUR-APP-ID" # The Firebase Cloud Function direct URL to call verifycontribution() V2 CF. # nb. this is necessary due to Version 2 of Cloud Functions which requires direct link to enble HTTPs callable functionalities. FIREBASE_CF_URL_VERIFY_CONTRIBUTION="YOUR-VERIFY-CONTRIBUTION-CF-URL" ### AWS S3 STORAGE ### ### These configs are related to the configuration of the interaction with the ### AWS S3 bucket used as storage for ceremony artifacts. # The chunk size to be used when executing multi-part upload or downloads. # default 50 MBs. # (e.g. a 200 MB file setting a stream chunk size of 50 MB is going to be splitted and uploaded/downloaded in 4 chunks). CONFIG_STREAM_CHUNK_SIZE_IN_MB=50 # The postfix string for each ceremony bucket. # default "-ph2-ceremony" CONFIG_CEREMONY_BUCKET_POSTFIX="-ph2-ceremony" # The amount of time in seconds which indicates the duration about the validity of a pre-signed URL. # default: 7200 seconds = 2 hours. CONFIG_PRESIGNED_URL_EXPIRATION_IN_SECONDS=7200 # AWS S3 access keys only required for unit/e2e testing (can be ommited) # The AWS access key identifier related to S3 APIs. AWS_ACCESS_KEY_ID="YOUR-AWS-ACCESS-KEY-ID" # The AWS secret access key related to S3 APIs. AWS_SECRET_ACCESS_KEY="YOUR-AWS-SECRET-ACCESS-KEY" # The AWS region where your buckets are located. AWS_REGION="YOUR-AWS-REGION" # The AWS AMI ID (default to Amazon Linux 2). AWS_AMI_ID="ami-022e1a32d3f742bd8" # The EC2 instance role to access S3 AWS_ROLE_ARN="YOUR-AWS-ROLE-ARN" ### AUTHENTICATION ### ### These configs are related to the authentication of users. # The unique identifier for the Github client associated to the OAuth Application. AUTH_GITHUB_CLIENT_ID="YOUR-GITHUB-CLIENT-ID" # A GitHub personal access token GITHUB_ACCESS_TOKEN="YOUR_GITHUB_ACCESS_TOKEN" ### For production testing purposes only. # The email of the user associated to a Google account. # default: use a GMail account to enable correct simulation using puppeteer package. AUTH_USER_EMAIL="USER-EMAIL" # The password of the user associated to a Google account. AUTH_GITHUB_USER_PW="USER-EMAIL-PW" # The GMail APIs client identifier associated with the Google account. # nb. you should enable GMail APIs manually. AUTH_GMAIL_CLIENT_ID="GMAIL-CLIENT-ID" # The GMail APIs client secret associated with the Google account. # nb. you should enable GMail APIs manually. AUTH_GMAIL_CLIENT_SECRET="GMAIL-CLIENT-SECRET" # The GMail APIs redirect URL associated with the Google account. # nb. you should enable GMail APIs manually. AUTH_GMAIL_REDIRECT_URL="GMAIL-REDIRECT-URL" # The GMail APIs refresh token associated with the Google account. # nb. you should enable GMail APIs manually. AUTH_GMAIL_REFRESH_TOKEN="GMAIL-REFRESH-TOKEN" ``` Please note the following: * `CONFIG_CEREMONY_BUCKET_POSTFIX` should be exactly the same as `AWS_CEREMONY_BUCKET_POSTFIX` in the backend config file. * **Firebase** related variables are the same that will go into the phase2cli config and that are shared with all contributors. * **GITHUB** AND **GMAIL** configs are only required for security tests (which can be found in `packages/actions/test/unit/security.test.ts`). These test can be skipped as they do not perform any functional testing, but are there to show some of the security work that was conducted on p0tion. Thus, the following variables can be **omitted**: * `AUTH_USER_EMAIL="USER-EMAIL"` * `AUTH_GITHUB_USER_PW="USER-EMAIL-PW"` * `AUTH_GMAIL_CLIENT_ID="GMAIL-CLIENT-ID"` * `AUTH_GMAIL_CLIENT_SECRET="GMAIL-CLIENT-SECRET"` * `AUTH_GMAIL_REDIRECT_URL="GMAIL-REDIRECT-URL"` * `AUTH_GMAIL_REFRESH_TOKEN="GMAIL-REFRESH-TOKEN"` #### Add your Firebase application name Inside `packages/backend/.firebaserc`, modify the entry for **prod** with the name of the created Firebase project. ```json! { "projects": { "dev": "demo-p0tion", "prod": "YOUR-NAME-HERE" } } ``` ### Firestore Service Use the Firebase web dashboard to navigate to the Firestore service and setup a new default database for your application ![](https://i.imgur.com/PPziIdh.png) Select production mode: ![](https://i.imgur.com/10A1wGs.png) Select your preferred region (note that this cannot be changed later) and click on **Enable**: ![](https://i.imgur.com/1cH8XDp.png) :warning: Make sure that Firebase is configured in _native mode_ and __NOT__ in _datastore only mode_. Otherwise you will not be able to use it with the proper SDK and thus p0tion will not work. If you set it to datastore mode, follow this [guide](https://cloud.google.com/datastore/docs/firestore-or-datastore ) to rollback to native mode. ## Deploy Cloud Functions In the end, we are ready to safely deploy the Cloud Functions and setup the Firestore Database. Navigate to the `backend` package and authenticate to Firebase: ```bash! yarn firebase:login ``` In your browser, you will see a page similar to this, click allow and continue ![](https://i.imgur.com/jSVkdhw.png) Then, deploy the `backend` package remotely to your Firebase application by running: ```bash! yarn firebase:deploy ``` A successful deployment will look like the screenshot below: ![](https://i.imgur.com/b3X5EFX.jpg) ### Test p0tion In order to check that everything works fine, you could run the tests. Navigate back to the root the project and run the following commands: * `yarn test:prod` will run the tests in the production environment while, * `yarn test:dev` will run the tests in the Firebase emulator without any additional configuration required. Please, note that this suite is limited compared to the production one. The first run will involve a download of the suite and you will need Java JDK version 11 or higher to be able to run it. If everything okay, all tests will be green and p0tion is ready to be used to create and manage Groth16 Phase 2 Trusted Setup ceremonies. ### Cloud Functions Callback URL The `verifyContribution` Cloud function uses the Cloud Functions V2 engine and must be called using the HTTPS callback URL. This is not an optional step because the URL is required when configuring the environment variables. Please, navigate to the **Functions** tab on the left of the console ![](https://i.imgur.com/pKaRMvF.png) The URL can be found under the **Trigger** columns: ![](https://i.imgur.com/sURk69o.png) ## Setup a ceremony The step you all have been waiting for (yay!), creating a new ceremony. Navigate to `packages/phase2cli` and configure the environment following guidelines from the previous configurations (actions and backend). Remember to fill the environment file with the same information which will be shared with participants. ### Authentication As p0tion user, you need to login with GitHub OAuth 2.0 by running ```bash! yarn auth ``` The command will automatically open a new browser tab on the GitHub's device activation page ![](https://i.imgur.com/r3ah2SU.png) The device code displayed in the terminal is already clipboarded! After that, you will be prompted to accept the ceremony application to access your GitHub account and assign the permission to read/create gists on your behalf (this would be needed for public attestation publication. You could revoke the permission at any time). ![](https://i.imgur.com/kbIxpIo.png) ### Ceremony Setup To setup a new ceremony run ```bash! yarn coordinate:setup ``` Fill in the requested information * Ceremony name * Description of the ceremony * Opening time * Closing time ![](https://i.imgur.com/ptqsqGc.png) Choose your prefered timeout mechanism for the ceremony * **Fixed** - based on a fixed time window for each contributor. * **Dynamic** - self-update approach with latest average contribution time. This requires an acceptance threshold to mitigate uninclusive ceremonies. ![](https://i.imgur.com/RXmkRuj.png) Then, you will be asked for the penalty (amount of time contributors have to wait after being timedout) ![](https://i.imgur.com/rR2tlyc.png) Enter information about the ceremony circuits. Remember, you could have more than one circuit per ceremony. Please note, the order in which you enter the information will be the order in which participants contribute to the circuits. ![](https://i.imgur.com/lalZpcQ.png) If the circuit require any parameter, you can input them at this stage: ![](https://i.imgur.com/bKmY4MS.png) If you chose `fixed` previously, you will be prompted to input the time participants have for contributing (_contribution fixed window_). Consider that a larger circuit will require a significantly greater time for the contribution! ![](https://i.imgur.com/MA1ABol.png) This process is repeated for each circuit. At the end, the summary of the ceremony data and related circuits will be shown. ![](https://i.imgur.com/RDxflNW.png) If this information looks good, please select **Yes** at the next prompt to continue with the setup. At this point, p0tion will look for the genesis zKey in the current directory. If no zKey is present, it will attempt to generate it using the smallest Powers of Tau that fits the circuit. The Powers of Tau files are downloaded from the output of the [Hermez PoT Trusted Setup ceremony](https://blog.hermez.io/hermez-cryptographic-setup/). This may require tons of memory if large circuits are used. Therefore, in this case, be sure to use a powerful machine. ![](https://i.imgur.com/SVOcWZR.png) After the generation, the artifacts are uploaded to a fresh ceremony AWS S3 bucket. ![](https://i.imgur.com/1cm3djo.png) The ceremony will automatically open for contribution when the time set for the start is reached. ## Contribution Now, it's time to distribute your configured environment by publishing the `phase2cli` NPM package. ### Distribute CLI Package 0. Login or create a [new NPM account](https://www.npmjs.com/login). 1. [Create a new NPM organization](https://docs.npmjs.com/creating-an-organization) 2. Create a new [Access Token (publish)](https://docs.npmjs.com/creating-and-viewing-access-tokens) and store it safely. 3. Navigate to `phase2cli` package. 4. Open the `package.json`. 5. Change the `name` property with your NPM organization name `name: "@YOUR-ORG/phase2cli"` and save. 6. Install and build `yarn && yarn build` 7. Copy over the `.env` file to the `dist` folder. 8. Then, to publish the package run `npm login && npm publish` 9. You should see the package published under your NPM organization and, that's it. Contributors will need to install the `"@YOUR-ORG/phase2cli` package in order to contribute to your ceremony. ## Finalize a ceremony When the contribution period of your ceremony ends, the coordinator is able to finalize it by running ```bash! yarn coordinate:finalize ``` ![](https://i.imgur.com/ilscgTf.png) After selecting the ceremony, the finalization beacon must be provided. The random beacon should be a random value based on some publicly available data (e.g., a 2^n iteration of SHA256 over the hash evaluated on some high entropy and publicly available data). For example, the value of a block at a particular height in one or more blockchains, or League of Entropy (drand). ![](https://i.imgur.com/7VGCyHP.png) Then, the entire process is automated and the ceremony output artifacts are available for download in the ceremony AWS S3 bucket. ## Common Errors This list will be mantained to help any future coordinators. If any error which are not present here arise, please open an issue on the GitHub repository. ### Missing Blaze Plan for Firebase **Problem** ![](https://i.imgur.com/moFldnO.png) **Solution** ![](https://i.imgur.com/G0OaL46.png) Click on **Upgrade**, then on **Select plan** ![](https://i.imgur.com/YuCJugR.png) Click on **Continue**: ![](https://i.imgur.com/iGsiZDT.png) Select your country (and currency) and click on **Confirm**: ![](https://i.imgur.com/q5iVvp1.png) Fill all information and then press **Confirm Purchase** down below: ![](https://i.imgur.com/ZDQG97v.png) ### Warning: Closing file descriptor 77 on garbage collection **Problem** ``` (node:36493) Warning: Closing file descriptor 77 on garbage collection (Use `node --trace-warnings ...` to show where the warning was created) (node:36493) [DEP0137] DeprecationWarning: Closing a FileHandle object on garbage collection is deprecated. Please close FileHandle objects explicitly using FileHandle.prototype.close(). In the future, an error will be thrown if a file descriptor is closed during garbage collection. ``` **Solution** This is related to how `snarkjs` deals with file descriptors and could be safely ignored. ### Unexpected error when downloading **Problem** ```bash ✔ Specify the amount of Powers of Tau used to generate the pre-computed zKey … 23 🕛 Downloading the #23 smallest PoT file needed from the Hermez Cryptography Phase 1 Trusted Setup...node:internal/process/promises:279 triggerUncaughtException(err, true /* fromPromise */); ^ Error: aborted at connResetException (node:internal/errors:692:14) at TLSSocket.socketCloseListener (node:_http_client:414:19) at TLSSocket.emit (node:events:539:35) at node:net:709:12 at TCP.done (node:_tls_wrap:582:7) { code: 'ECONNRESET' } error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. ``` **Solution** Please check your internet connection. PoT/zKeys files can weight tons of GB of disk space, and require strong and stable internet connections. ### Unexpected error when uploading **Problem** ```bash ✔ Select the Powers of Tau file choosen for the circuit › powersOfTau28_hez_final_23.ptau ✔ Ceremony bucket has been successfully created 🕓 Uploading processmessages_6-8-3-3_test_00000.zkey file to ceremony storage...file:///Users/daehyun/workspace/p0tion/mpc-phase2-suite/packages/phase2cli/dist/src/index.node.mjs:521 throw new Error(`Unable to upload chunk number ${i}. Please, terminate the current session and retry to resume from the latest uploaded chunk.`); ^ Error: Unable to upload chunk number 23. Please, terminate the current session and retry to resume from the latest uploaded chunk. at uploadParts (file:///Users/daehyun/workspace/p0tion/mpc-phase2-suite/packages/phase2cli/dist/src/index.node.mjs:521:19) at runMicrotasks (<anonymous>) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async multiPartUpload (file:///Users/daehyun/workspace/p0tion/mpc-phase2-suite/packages/phase2cli/dist/src/index.node.mjs:576:37) at async handleCircuitArtifactUploadToStorage (file:///Users/daehyun/workspace/p0tion/mpc-phase2-suite/packages/phase2cli/dist/src/index.node.mjs:2847:5) at async Command.setup (file:///Users/daehyun/workspace/p0tion/mpc-phase2-suite/packages/phase2cli/dist/src/index.node.mjs:2971:13) at async Command.parseAsync (/Users/daehyun/workspace/p0tion/mpc-phase2-suite/node_modules/commander/lib/command.js:916:5) error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. ``` **Solution** Please check your internet connection and try again. Uploading very large zKey files require a stable connection. ### Failing deploy due to error in firestore.indexes.json It might happen that if the Firebase infrastructure deploy (`yarn firebase:deploy`) fails, the `firestore.indexes.json` file is overwritten with the error log. In this case, please paste the following inside: ```json { "indexes": [ { "collectionGroup": "ceremonies", "queryScope": "COLLECTION", "fields": [ { "fieldPath": "state", "order": "ASCENDING" }, { "fieldPath": "endDate", "order": "ASCENDING" } ] }, { "collectionGroup": "ceremonies", "queryScope": "COLLECTION", "fields": [ { "fieldPath": "state", "order": "ASCENDING" }, { "fieldPath": "startDate", "order": "ASCENDING" } ] } ], "fieldOverrides": [] } ```