diff --git a/.gitignore b/.gitignore index 8c8e03f724..cc1530b6b7 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,6 @@ solc cli/tally.json **/test_tally.json **/tally.json -**/subsidy.json integrationTests/test_tally.json integrationTests/artifacts/** deployedAddresses.json diff --git a/circuits/README.md b/circuits/README.md index 54068f3d56..ce8ca65c48 100644 --- a/circuits/README.md +++ b/circuits/README.md @@ -9,7 +9,6 @@ The main circuits are: - `processMessages.circom` - `tallyVotes.circom` -- (optional) `subsidy.circom` The rest of the circuits are utilities templates that are required for the main circuits to work correctly. These include utilities such as float math, conversion of private keys, and Poseidon hashing/encryption. diff --git a/cli/package.json b/cli/package.json index 5181c62f4b..ce45803fd3 100644 --- a/cli/package.json +++ b/cli/package.json @@ -30,7 +30,6 @@ "test:ceremony": "ts-mocha --exit tests/ceremony-params/ceremonyParams.test.ts", "test:e2e": "ts-mocha --exit tests/e2e/e2e.test.ts", "test:e2e-non-qv": "ts-mocha --exit tests/e2e/e2e.nonQv.test.ts", - "test:e2e-subsidy": "ts-mocha --exit tests/e2e/e2e.subsidy.test.ts", "test:keyChange": "ts-mocha --exit tests/e2e/keyChange.test.ts", "test:unit": "nyc ts-mocha --exit tests/unit/*.test.ts", "test:airdrop": "nyc ts-mocha --exit tests/unit/airdrop.test.ts", diff --git a/contracts/deploy-config-example.json b/contracts/deploy-config-example.json index 9cd24b92d7..169b7c5fc4 100644 --- a/contracts/deploy-config-example.json +++ b/contracts/deploy-config-example.json @@ -29,7 +29,6 @@ "Poll": { "pollDuration": 30, "coordinatorPubkey": "macipk.9a59264310d95cfd8eb7083aebeba221b5c26e77427f12b7c0f50bc1cc35e621", - "subsidyEnabled": false, "useQuadraticVoting": true } } diff --git a/website/.gitignore b/website/.gitignore index afab755933..6ea485ae8d 100644 --- a/website/.gitignore +++ b/website/.gitignore @@ -19,6 +19,9 @@ npm-debug.log* yarn-debug.log* yarn-error.log* -versioned_docs/version-v1.x/solidity-docs -versioned_docs/version-v1.x/typedoc -typedoc \ No newline at end of file +versioned_docs/version-v1.2/solidity-docs +versioned_docs/version-v1.2/typedoc +versioned_docs/version-v1.3_alpha/typedoc/ +versioned_docs/version-v1.3_alpha/solidity-docs/ + +typedoc diff --git a/website/src/scripts/setupSolidityDocs.ts b/website/src/scripts/setupSolidityDocs.ts index be7e3bca94..fde2a61397 100644 --- a/website/src/scripts/setupSolidityDocs.ts +++ b/website/src/scripts/setupSolidityDocs.ts @@ -4,7 +4,7 @@ import path from "path"; import { copyDirectory, insertIndexPage } from "./utils"; // where to move the solidity doc files over -const solidityDocDir = path.resolve(__dirname, "../../versioned_docs/version-v1.x/solidity-docs"); +const solidityDocDir = path.resolve(__dirname, "../../versioned_docs/version-v1.3_alpha/solidity-docs"); // the origin folder (from the contracts package) const sourceDir = path.resolve(__dirname, "../../../contracts/docs"); diff --git a/website/versioned_docs/version-v1.x/audit.md b/website/versioned_docs/version-v1.2/audit.md similarity index 100% rename from website/versioned_docs/version-v1.x/audit.md rename to website/versioned_docs/version-v1.2/audit.md diff --git a/website/versioned_docs/version-v1.x/ci-pipeline.md b/website/versioned_docs/version-v1.2/ci-pipeline.md similarity index 100% rename from website/versioned_docs/version-v1.x/ci-pipeline.md rename to website/versioned_docs/version-v1.2/ci-pipeline.md diff --git a/website/versioned_docs/version-v1.x/circuits.md b/website/versioned_docs/version-v1.2/circuits.md similarity index 100% rename from website/versioned_docs/version-v1.x/circuits.md rename to website/versioned_docs/version-v1.2/circuits.md diff --git a/website/versioned_docs/version-v1.x/cli.md b/website/versioned_docs/version-v1.2/cli.md similarity index 99% rename from website/versioned_docs/version-v1.x/cli.md rename to website/versioned_docs/version-v1.2/cli.md index cafd60acdf..0b5e9ea7d5 100644 --- a/website/versioned_docs/version-v1.x/cli.md +++ b/website/versioned_docs/version-v1.2/cli.md @@ -66,7 +66,7 @@ Public key: macipk.946c756cb8588f7169d37e23a98b92051359d64321cf7372a75757b5e9d55 Private key: macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c ``` -### Generate MACI keys +### Generate MACI keys You can generate MACI keys using the following cli utility. diff --git a/website/versioned_docs/version-v1.x/contracts.md b/website/versioned_docs/version-v1.2/contracts.md similarity index 100% rename from website/versioned_docs/version-v1.x/contracts.md rename to website/versioned_docs/version-v1.2/contracts.md diff --git a/website/versioned_docs/version-v1.x/contributing/code-of-conduct.md b/website/versioned_docs/version-v1.2/contributing/code-of-conduct.md similarity index 100% rename from website/versioned_docs/version-v1.x/contributing/code-of-conduct.md rename to website/versioned_docs/version-v1.2/contributing/code-of-conduct.md diff --git a/website/versioned_docs/version-v1.x/contributing/contributing.md b/website/versioned_docs/version-v1.2/contributing/contributing.md similarity index 100% rename from website/versioned_docs/version-v1.x/contributing/contributing.md rename to website/versioned_docs/version-v1.2/contributing/contributing.md diff --git a/website/versioned_docs/version-v1.x/coordinator-processing.md b/website/versioned_docs/version-v1.2/coordinator-processing.md similarity index 100% rename from website/versioned_docs/version-v1.x/coordinator-processing.md rename to website/versioned_docs/version-v1.2/coordinator-processing.md diff --git a/website/versioned_docs/version-v1.x/deployment.md b/website/versioned_docs/version-v1.2/deployment.md similarity index 100% rename from website/versioned_docs/version-v1.x/deployment.md rename to website/versioned_docs/version-v1.2/deployment.md diff --git a/website/versioned_docs/version-v1.x/installation.md b/website/versioned_docs/version-v1.2/installation.md similarity index 97% rename from website/versioned_docs/version-v1.x/installation.md rename to website/versioned_docs/version-v1.2/installation.md index a1e5bb1566..d183fc0d30 100644 --- a/website/versioned_docs/version-v1.x/installation.md +++ b/website/versioned_docs/version-v1.2/installation.md @@ -113,12 +113,6 @@ Edit `circuits/circom/circuits` to include the circuits you would like to compil "template": "TallyVotesNonQv", "params": [10, 1, 2], "pubs": ["inputHash"] - }, - "SubsidyPerBatch_10-1-2_test": { - "file": "subsidy", - "template": "SubsidyPerBatch", - "params": [10, 1, 2], - "pubs": ["inputHash"] } } ``` diff --git a/website/versioned_docs/version-v1.x/integrating.md b/website/versioned_docs/version-v1.2/integrating.md similarity index 100% rename from website/versioned_docs/version-v1.x/integrating.md rename to website/versioned_docs/version-v1.2/integrating.md diff --git a/website/versioned_docs/version-v1.x/introduction.md b/website/versioned_docs/version-v1.2/introduction.md similarity index 100% rename from website/versioned_docs/version-v1.x/introduction.md rename to website/versioned_docs/version-v1.2/introduction.md diff --git a/website/versioned_docs/version-v1.x/key-change.md b/website/versioned_docs/version-v1.2/key-change.md similarity index 100% rename from website/versioned_docs/version-v1.x/key-change.md rename to website/versioned_docs/version-v1.2/key-change.md diff --git a/website/versioned_docs/version-v1.x/overview.md b/website/versioned_docs/version-v1.2/overview.md similarity index 100% rename from website/versioned_docs/version-v1.x/overview.md rename to website/versioned_docs/version-v1.2/overview.md diff --git a/website/versioned_docs/version-v1.x/poll-types.md b/website/versioned_docs/version-v1.2/poll-types.md similarity index 100% rename from website/versioned_docs/version-v1.x/poll-types.md rename to website/versioned_docs/version-v1.2/poll-types.md diff --git a/website/versioned_docs/version-v1.x/primitives.md b/website/versioned_docs/version-v1.2/primitives.md similarity index 100% rename from website/versioned_docs/version-v1.x/primitives.md rename to website/versioned_docs/version-v1.2/primitives.md diff --git a/website/versioned_docs/version-v1.x/project-ideas.md b/website/versioned_docs/version-v1.2/project-ideas.md similarity index 100% rename from website/versioned_docs/version-v1.x/project-ideas.md rename to website/versioned_docs/version-v1.2/project-ideas.md diff --git a/website/versioned_docs/version-v1.x/purpose.md b/website/versioned_docs/version-v1.2/purpose.md similarity index 100% rename from website/versioned_docs/version-v1.x/purpose.md rename to website/versioned_docs/version-v1.2/purpose.md diff --git a/website/versioned_docs/version-v1.x/spec.md b/website/versioned_docs/version-v1.2/spec.md similarity index 100% rename from website/versioned_docs/version-v1.x/spec.md rename to website/versioned_docs/version-v1.2/spec.md diff --git a/website/versioned_docs/version-v1.x/testing-in-detail.md b/website/versioned_docs/version-v1.2/testing-in-detail.md similarity index 100% rename from website/versioned_docs/version-v1.x/testing-in-detail.md rename to website/versioned_docs/version-v1.2/testing-in-detail.md diff --git a/website/versioned_docs/version-v1.x/testing.md b/website/versioned_docs/version-v1.2/testing.md similarity index 100% rename from website/versioned_docs/version-v1.x/testing.md rename to website/versioned_docs/version-v1.2/testing.md diff --git a/website/versioned_docs/version-v1.x/topup.md b/website/versioned_docs/version-v1.2/topup.md similarity index 100% rename from website/versioned_docs/version-v1.x/topup.md rename to website/versioned_docs/version-v1.2/topup.md diff --git a/website/versioned_docs/version-v1.x/troubleshooting.md b/website/versioned_docs/version-v1.2/troubleshooting.md similarity index 100% rename from website/versioned_docs/version-v1.x/troubleshooting.md rename to website/versioned_docs/version-v1.2/troubleshooting.md diff --git a/website/versioned_docs/version-v1.x/trusted-setup.md b/website/versioned_docs/version-v1.2/trusted-setup.md similarity index 100% rename from website/versioned_docs/version-v1.x/trusted-setup.md rename to website/versioned_docs/version-v1.2/trusted-setup.md diff --git a/website/versioned_docs/version-v1.x/versioning.md b/website/versioned_docs/version-v1.2/versioning.md similarity index 100% rename from website/versioned_docs/version-v1.x/versioning.md rename to website/versioned_docs/version-v1.2/versioning.md diff --git a/website/versioned_docs/version-v1.x/workflow.md b/website/versioned_docs/version-v1.2/workflow.md similarity index 100% rename from website/versioned_docs/version-v1.x/workflow.md rename to website/versioned_docs/version-v1.2/workflow.md diff --git a/website/versioned_docs/version-v1.3_alpha/audit.md b/website/versioned_docs/version-v1.3_alpha/audit.md new file mode 100644 index 0000000000..9150dd285b --- /dev/null +++ b/website/versioned_docs/version-v1.3_alpha/audit.md @@ -0,0 +1,160 @@ +--- +title: MACI Security Audits +description: Overview of MACI audit history with references to audit reports. +sidebar_label: Security audits +sidebar_position: 14 +--- + +# MACI Security Audits + +## Full reports + +- Audit by PSE Audit 2024/02 [report](/audit_reports/20240223_PSE_Audit_audit_report.pdf) +- Audit by HashCloak 2022/09 [report](/audit_reports/202220930_Hashcloak_audit_report.pdf) +- Audit by HashCloak 2021/09 [report](/audit_reports/20210922_Hashcloak_audit_report.pdf) + +## PSE audit 2024 + +In February 2024 the PSE Audit team audited the MACI codebase with a focus on the smart contracts, TypeScript core, and Circom circuits Three critical bugs were found: two within the Circom circuits and one in the smart contracts. All three of these have been fixed. + +Please see the [PSE Audit report](/audit_reports/20240223_PSE_Audit_audit_report.pdf) for details. + +## Veridise disclosure 2023 + +In March 2023, Veridise responsibly disclosed a number of issues to the MACI team, which were identified using their new [tool](https://twitter.com/VeridiseInc/status/1630806464695791616?s=20) for catching ZK circuit bugs. + +Out of five issues disclosed, only three were relevant and have been since fixed by the MACI team. The other two issues were disregarded as they were present in older version of code which is not in use anymore. + +We would like to thank the Veridise team for their effort in keeping open source projects safe. + +### Issue 1 + +**Description** + +In the template `QuinSelector`, if you want to confirm the input signal index is a valid integer less than 2\*\*3, you should add Num2bits(3) to check it. + +**Code Location** + +[`incrementalQuinTree.circom`](https://github.com/privacy-scaling-explorations/maci/blob/78609349aecd94186216ac8743d61b1cb81a097f/circuits/circom/trees/incrementalQuinTree.circom#L30) + +**Fix** + +[Code location](https://github.com/chaosma/maci/blob/60727d4d10406edda32ad28e53d399d41d45ed88/circuits/circom/trees/incrementalQuinTree.circom#L37) + +```javascript +// Ensure that index < choices +component lessThan = SafeLessThan(3); +``` + +This was fixed by adding a new Template, `SafeLesThan` which uses `Num2Bits` as further check on the signals: + +```javascript +// the implicit assumption of LessThan is both inputs are at most n bits +// so we need to add range check for both inputs +template SafeLessThan(n) { + assert(n <= 252); + signal input in[2]; + signal output out; + + component n2b1 = Num2Bits(n); + n2b1.in <== in[0]; + component n2b2 = Num2Bits(n); + n2b2.in <== in[1]; + + component n2b = Num2Bits(n+1); + + n2b.in <== in[0]+ (1< out; +} +``` + +And then used it to constrain the [`index` input signal](https://github.com/chaosma/maci/blob/2d7a3a0efd33dfc3a5f4d3f95bec3adda7abb963/circuits/circom/trees/incrementalQuinTree.circom#L115-L117): + +```javascript +greaterThan[i] = SafeGreaterThan(3); +greaterThan[i].in[0] <== i; +greaterThan[i].in[1] <== index; +``` + +### Issue 3 + +**Description** + +In the template `QuinGeneratePathIndices`, the constraints of the `signal n[levels + 1]` don't perform well for division and modulo counting. + +**Code Location** + +[`incrementalQuinTree.circom`](https://github.com/privacy-scaling-explorations/maci/blob/7c1b3743ea753786011289a356eaa45ba72f9ca1/circuits/circom/trees/incrementalQuinTree.circom#L228-L242) + +**Fix** + +The [updated code](https://github.com/chaosma/maci/blob/2d7a3a0efd33dfc3a5f4d3f95bec3adda7abb963/circuits/circom/trees/incrementalQuinTree.circom#L285-L290) uses the `SafeLessThen` template, as shown below: + +```javascript +for (var i = 0; i < levels; i++) { + // Check that each output element is less than the base + leq[i] = SafeLessThan(3); + leq[i].in[0] <== out[i]; + leq[i].in[1] <== BASE; + leq[i].out === 1; + + // Re-compute the total sum + sum.nums[i] <== out[i] * (BASE ** i); +} +``` + +## HashCloak audit 2022 + +In the summer of 2022, MACI v1 was audited by HashCloak. The audit covered both the zk-SNARK circuits and the Solidity smart contracts. + +This audit revealed a number of high severity issues which have been remediated by the MACI development team. All issues were successfully fixed and reflected in MACI v1.1.1. + +Please see the [HashCloak report](/audit_reports/202220930_Hashcloak_audit_report.pdf) for details. + +## HashCloak audit 2021 + +From July 5th, 2021 to August 2nd, 2021, the Ethereum Foundation’s Applied ZKPs team engaged HashCloak for an audit of the MACI protocol. The audit was conducted with 3 auditors over 15 person weeks. + +The following packages were in scope: + +- Circuits +- Contracts +- Core +- Crypto +- Domainobjs + +From August 18, 2021 to September 22, 2021, Hashcloak assisted the MACI team in resolving the issues. + +Please see the [HashCloak report](/audit_reports/20210922_Hashcloak_audit_report.pdf) for details. diff --git a/website/versioned_docs/version-v1.3_alpha/ci-pipeline.md b/website/versioned_docs/version-v1.3_alpha/ci-pipeline.md new file mode 100644 index 0000000000..b2203e4a49 --- /dev/null +++ b/website/versioned_docs/version-v1.3_alpha/ci-pipeline.md @@ -0,0 +1,38 @@ +--- +title: CI Pipeline +description: Introduction to how MACI's CI works +sidebar_label: CI +sidebar_position: 15 +--- + +# Continuous Integration (CI) Pipeline + +CI (Continuous Integration) pipeline is an automated workflow to ensure that software is always in a working state. An event like opening a pull request causes a pipeline to run. The pipeline consists of an automated build process and a suite of automated tests (See [Testing](https://pse.dev/docs/testing) for more details). + +![cicd-maci drawio-7](https://user-images.githubusercontent.com/1610146/185962260-091cd952-5444-44f3-89e3-be64e81d4c21.png) + +## Pipeline Triggers + +### Commit to Main Branch + +Each commit (i.e. a merged PR) to the main branch triggers the pipeline. The pipeline creates packages that can be deployed to any environment. Packages are uploaded to an artifact repository (e.g. npm). + +![cicd-maci drawio-12](https://user-images.githubusercontent.com/1610146/183404579-8bcb76fe-34b6-4748-a5ae-e2e4b010bd86.png) + +### Pull Request (PR) + +When a pull request has been created (or updated), it triggers the PR pipeline. It gives the reviewer confidence that the software works as expected with the introduced code changes. + +![cicd-maci drawio-9](https://user-images.githubusercontent.com/1610146/183391880-d3a20f29-2708-4d72-988d-4781c0396e48.png) + +### Nightly + +Nightly build runs every midnight. It is to ensure that all required dependencies are present and to show no bugs have been introduced. + +![cicd-maci drawio-11](https://user-images.githubusercontent.com/1610146/183404455-cc2aaace-fe52-40f4-b5e4-3c852c5ff516.png) + +### Tag Push + +When a tag has been pushed, it triggers a release pipeline. It will draft a release note with an auto-generated changelog and publish npm package(s). + +![cicd-maci drawio-5](https://user-images.githubusercontent.com/1610146/185958513-51dadaf1-7f72-404b-b482-149b91edcaab.png) diff --git a/website/versioned_docs/version-v1.3_alpha/circuits.md b/website/versioned_docs/version-v1.3_alpha/circuits.md new file mode 100644 index 0000000000..b808da124c --- /dev/null +++ b/website/versioned_docs/version-v1.3_alpha/circuits.md @@ -0,0 +1,494 @@ +--- +title: MACI Circuits +description: Introduction to the core zk-SNARK circuits of MACI +sidebar_label: Circuits +sidebar_position: 9 +--- + +# zk-SNARKS in MACI + +MACI uses zk-SNARKs to essentially hide how each person voted while still revealing the final vote result. This gives voters privacy and helps reduce bribery while still ensuring that the final results were tallied correctly off-chain. + +## MACI Circuits + +MACI has two main zk-SNARK [circuits](https://github.com/privacy-scaling-explorations/maci/tree/dev/circuits): + +1. [`ProcessMessages.circom`](https://github.com/privacy-scaling-explorations/maci/blob/dev/circuits/circom/processMessages.circom), which takes a batch of encrypted messages, decrypts them, and generates a proof that the coordinator's local processing was performed correctly. +2. [`TallyVotes.circom`](https://github.com/privacy-scaling-explorations/maci/blob/dev/circuits/circom/tallyVotes.circom), which counts votes from users' ballots, batch by batch. + +The rest of the circuits are utilities templates that are required for the main circuits to work correctly. These include utilities such as float math, conversion of private keys, and Poseidon hashing/encryption. + +Each circuit is parameterised and it is important to set the right parameters that match your use case. For example, if you want to support up to 3125 messages, the message tree depth parameter should be set to `5` (as $5^5 = 3125$). + +## Background + +### zk-SNARKs + +zk-SNARKs are a type of zero-knowledge proof which allows a "prover" to prove to a "verifier" that they know a secret without revealing the secret itself. In MACI, the prover is the coordinator. MACI uses zk-SNARKs to prove that the coordinator has correctly processed the batches of messages and that all votes have been tallied correctly. A smart contract acts as the verifier to check the proof from the coordinator. Users can also verify that the process was done correctly at any point after the proof generation. + +### Circom + +MACI's circuits are written using [Circom](https://docs.circom.io/), a domain-specific language (DSL) used to write zk-SNARK circuits. Circom syntax resembles JavaScript, and it currently is one of the most popular DSL in use by zk developers. Please refer to their documentation to learn more about the language. + +### Proving system + +MACI uses [Groth16](https://eprint.iacr.org/2016/260.pdf) as its proving system. Groth16 is a zk-SNARK proving system that allows for the generation of proofs that are small and fast to verify. + +## How are the circuits used? + +The circuits are used by the coordinator (the prover) to prove that they have correctly processed a batch of messages and tallied the votes correctly. This happens after a Poll has completed, and the coordinator has merged the state and message trees. The coordinator then generates a proof for each batch of messages, and submits them to the contract. The contract then verifies the proofs and updates the commitments on chain. + +## How do the Circuits fit in a voting round? + +![flow](/img/circuits/processingAfterPollEnds.svg) + +## How do the circuits work? + +### Message processing ([`processMessages`](https://github.com/privacy-scaling-explorations/maci/blob/dev/circuits/circom/processMessages.circom)) + +This circuit allows the coordinator to prove that they have correctly processed each message in reverse order, in a consecutive batch of 5 ^ msgBatchDepth messages to the respective state leaf within the state tree. Coordinators would use this circuit to prove correct execution at the end of each Poll. + +The `processMessages` circuit will try to decrypt the messages, and based on the content of the message, update within itself the trees, to generate a proof that the coordinator's off-chain processing was done correctly. In other words, the circuit takes a final state, an initial state, and the leaves (messages and user signups) - it processes these messages via the different state transitions to finally check that the expected state is correct. +The pre-requisites for this circuit are: + +- the related Poll has ended +- the state tree has been merged +- the message tree has been merged + +This circuit requires the coordinator's private key, hence a proof for this circuit can only be generated by the coordinator. The private key is needed in order to generate the ECDH shared key used to decrypt the messages. + +![ProcessMessages](/img/circuits/processMessages.svg) + +:::info +A version working with non quadratic voting (non-qv) is also available. This version is called `processMessagesNonQV` and is to be used when the Poll is not using the quadratic voting feature. Note that by default MACI works with quadratic voting. +::: + +#### Parameters + +| # | Parameter | Description | +| --- | ------------------------ | ---------------------------------------------------- | +| 0 | State tree depth | Allows $(5^{n})$ signups. | +| 1 | Message tree depth | Allows $(5^{n})$ votes or key-change messages. | +| 2 | Message batch tree depth | Allows $(5^{n})$ messages to be processed per batch. | +| 3 | Vote option tree depth | Allows $(5^{n})$ vote options. | + +#### Inputs + +| Input signal | Description | +| -------------------------------- | --------------------------------------------------------------------------------------- | +| `inputHash` | The SHA256 hash of inputs supplied by the contract | +| `packedVals` | Described below | +| `pollEndTimestamp` | The Unix timestamp at which the poll ends | +| `msgRoot` | The root of the message tree | +| `msgs` | The batch of messages as an array of arrays | +| `msgSubrootPathElements` | Described below | +| `coordinatorPubKeyHash` | $poseidon_2([cPk_x, cPk_y])$ | +| `newSbCommitment` | Described below | +| `coordPrivKey` | The coordinator's private key | +| `coordPubKey` | The coordinator's public key | +| `encPubKeys` | The public keys used to generate shared ECDH encryption keys to encrypt the messages | +| `currentStateRoot` | The state root before the commands are applied | +| `currentStateLeaves` | The state leaves upon which messages are applied | +| `currentStateLeavesPathElements` | The Merkle path to each incremental state root | +| `currentSbCommitment` | Described below | +| `currentSbSalt` | Described below | +| `newSbCommitment` | Described below | +| `newSbSalt` | Described below | +| `currentBallotRoot` | The root of the ballot tree before messages are applied | +| `currentBallots` | The ballots upon which ballots are applied | +| `currentBallotsPathElements` | The Merkle path to each incremental ballot root | +| `currentVoteWeights` | The existing vote weight for the vote option in the ballot which each command refers to | +| `currentVoteWeightsPathElements` | The Merkle path from each vote weight to the vote option root in its ballot | + +##### `inputHash` + +All inputs to this circuit are private except for `inputHash`. To save gas during verification, the `MessageProcessor` contract hashes the following values using SHA256 and uses the hash as the sole element of $ic$: + +1. `packedVals` +2. `coordinatorPubKeyHash` +3. `msgRoot` +4. `currentSbCommitment` +5. `newSbCommitment` +6. `pollEndTimestamp` + +The hash is computed using the `sha256` Solidity function and is then subject to modulo $p$. + +##### `packedVals` + +`packedVals` is the following values represented as one field element. Consider that a field element is roughly 253 bits. The big-endian bit-representation is as such: + +| Bits | Value | +| ----------- | -------------------------- | +| 1st 53 bits | `0` | +| 2nd 50 bits | `batchEndIndex` | +| 3rd 50 bits | `currentMessageBatchIndex` | +| 4th 50 bits | `numSignUps` | +| 5th 50 bits | `maxVoteOptions` | + +For instance, if `maxVoteOptions` is 25 and `batchEndIndex` is `5`, and all other values are 0, the following is the `packedVals` representation in hexadecimal: + +`140000000000000000000000000000000000019` + +##### `currentSbCommitment` and `newSbCommitment` + +The `currentSbCommitment` is the $poseidon_3$ hash of the state tree root, the ballot tree root, and a random salt. The purpose of the random salt, which should be unique to each batch, is to ensure that the value of `currentSbCommitment` always changes even if all the commands in a batch are invalid and therefore do not change the state tree or ballot tree root. + +The result of applying a batch of messages to `currentSbCommitment` is `newSbCommitment`. + +##### `currentSbSalt` + +The salt used to produce `currentSbCommitment` (see above). + +##### `newSbSalt` + +The salt used to produce `newSbCommitment` (see above). + +##### `msgSubrootPathElements` + +The index of each message in `msgs` is consecutive. As such, in order to prove that each message in `msgs` is indeed a leaf of the message tree, we compute the subtree root of `msgs`, and then verify that the subtree root is indeed a subroot of `msgRoot`. + +A simplified example using a tree of arity 2: + +``` + r + / \ + s ... + / \ + o o + / \ / \ + a b c d +``` + +To prove that `a...d` are leaves of the tree with root `r`, we prove that the leaves have the subroot `s` with depth 2, and _then_ prove that `s` is a member of `r` at depth 1. + +The implementation for this is in the `QuinBatchLeavesExists` circuit in `https://github.com/privacy-scaling-explorations/maci/blob/dev/circuits/circom/trees/incrementalQuinTree.circom`. + +This method requires fewer circuit constraints than if we verified a Merkle proof for each leaf. + +#### Statements that the circuit proves + +1. That the prover knows the preimage to `inputHash` (see above) +2. That the prover knows the preimage to `currentSbCommitment` (that is, the state root, ballot root, and `currentSbSalt`) +3. That `maxVoteOptions <= (5 ^ voteOptionTreeDepth)` +4. That `numSignUps <= (5 ^ stateTreeDepth)` +5. That `coordPubKey` is correctly derived from `coordPrivKey` +6. That `coordPubKey` is the preimage to the Poseidon hash of `coordPubKey` (provided by the contract) +7. That each message in `msgs` exists in the message tree +8. That after decrypting and applying each message, in reverse order, to the corresponding state and ballot leaves, the new state root, new ballot root, and `newSbSalt` are the preimage to `newSbCommitment` + +### Tally Votes ([`tallyVotes`](https://github.com/privacy-scaling-explorations/maci/blob/dev/circuits/circom/tallyVotes.circom)) + +#### Parameters + +| # | Parameter | Description | +| --- | ---------------------- | -------------------------------------------------------- | +| 0 | State tree depth | Allows $(5^{n})$ signups. | +| 1 | State leaf batch depth | Allows $(5^{n})$ users' votes to be processed per batch. | +| 2 | Vote option tree depth | Allows $(5^{n})$ vote options. | + +![TallyVotes](/img/circuits/tallyVotes.svg) + +:::info +A version working with non quadratic voting (non-qv) is also available. This version is called `tallyVotesNonQv` and is to be used when the Poll is not using the quadratic voting feature. Note that by default MACI works with quadratic voting. +::: + +#### Input signals + +| Input signal | Description | +| --------------------------------------- | ---------------------------------------------------------------- | +| `inputHash` | The SHA256 hash of inputs supplied by the contract | +| `packedVals` | Described below | +| `sbCommitment` | Described below | +| `currentTallyCommitment` | Described below | +| `newTallyCommitment` | Described below | +| `stateRoot` | The root of the state tree after all messages have been applied | +| `ballotRoot` | The root of the ballot tree after all messages have been applied | +| `sbSalt` | The salt used to produce `sbCommitment` | +| `ballots` | The ballots in the batch being tallied | +| `ballotPathElements` | The Merkle path to each ballot leaf | +| `votes` | The votes in each ballot cast per result | +| `currentResults` | The current tally of votes per vote option | +| `currentResultsRootSalt` | A random value | +| `currentSpentVoiceCreditSubtotal` | The subtotal of voice credits spent across all vote options | +| `currentSpentVoiceCreditSubtotalSalt` | A random value | +| `currentPerVOSpentVoiceCredits` | The voice credits spent on each vote option so far | +| `currentPerVOSpentVoiceCreditsRootSalt` | A random value | +| `newResultsRootSalt` | A random value | +| `newPerVOSpentVoiceCreditsRootSalt` | A random value | +| `newSpentVoiceCreditSubtotalSalt` | A random value | + +##### `inputHash` + +All inputs to this circuit are private except for `inputHash`. To save gas during verification, the `Tally` contract hashes the following values using SHA256 and uses the hash as the sole element of $ic$: + +1. `packedVals` +2. `sbCommitment` +3. `currentTallyCommitment` +4. `newTallyCommitment` + +The hash is computed using the `sha256` Solidity function and is then subject to modulo $p$. + +##### `packedVals` + +`packedVals` is the following values represented as one field element. Consider that a field element is roughly 253 bits. The big-endian bit-representation is as such: + +| Bits | Value | +| ----------- | ----------------- | +| 1st 53 bits | `0` | +| 2nd 50 bits | `0` | +| 3rd 50 bits | `0` | +| 4th 50 bits | `numSignUps` | +| 5th 50 bits | `batchStartIndex` | + +`numSignUps`, a value provided by the contract, is the number of users who have signed up. This is one less than the number of leaves inserted in the state tree (since the 0th state leaf is a [blank state leaf](./primitives#state-leaf)). `batchStartIndex` is the ballot tree index at which the batch begins. + +For instance, if `numSignUps` is 25 and the batch index is `5`, and all other values are 0, the following is the `packedVals` representation in hexadecimal: + +`64000000000005` + +##### `sbCommitment` + +The commitment to `stateRoot`, `ballotRoot`, and `sbSalt`: + +$poseidon_3([stateRoot, ballotRoot, sbSalt])$ + +Proving preimage of `sbCommitment` is one out of the several steps required to prove that the votes were tallied correctly. By establishing that the coordinator knows `ballotRoot`, the coordinator can (using other parts of the circuit) prove that they know the preimage of the ballot leaves in the batch being tallied. + +##### `currentTallyCommitment` and `newTallyCommitment` + +A tally is represented by a _tally commitment_, which is the $poseidon_3$ hash of: + +1. $tc_r$: a commitment to the votes per option + - This is the hash of the Merkle root $r_r$ of the votes and a salt $r_s$, computed as $poseidon_2([r_r, r_s])$ +2. $tc_t$: a commitment to the total spent voice credits + - This is the hash of the total spent voice credits $t_c$ and a salt $t_s$, computed as $poseidon_2([t_c, t_s])$ +3. $tc_p$: a commitment to the spent voice credits per vote option + - This is the hash of the Merkle root of the spent voice credits per vote option $p_v$ and a salt $p_s$, computed as $poseidon_2([p_v, p_s])$ + +The tally commitment is computed as such: + +$poseidon_3([tc_r, tc_t, tc_p])$ + +#### Statements that the circuit proves + +1. That the coordinator knows the preimage of `sbCommitment` +2. That the coordinator knows the preimage of `inputHash` +3. That `batchStartIndex` is less than or equal to `numSignUps` +4. That each ballot in `ballots` is in a member of the ballot tree with the Merkle root `ballotRoot` at indices `batchStartIndex` to `batchStartIndex + (5 ** intStateTreeDepth)` +5. That each set of votes (`votes[i]`) has the Merkle root $blt_r$ whose value equals `ballots[i][1]` +6. That the tally is valid, which is: + - That the sum of votes per vote option is correct + +### Utility circuits + +#### Process Messages Input Hasher + +A utility circuit used by the main `processMessages` circuit to hash its inputs. + +![ProcessMessagesInputHasher](/img/circuits/processMessagesInputHasher.svg) + +It outputs one field element, which is the SHA256 hash of the following inputs: + +1. `packedVals` +2. `pollEndTimestamp` +3. `msgRoot` +4. `coordinatorPubKeyHash` +5. `newSbCommitment` +6. `currentSbCommitment` + +#### Tally Votes Input Hasher + +A utility template that generates a sha256 hash of the provided tally inputs. + +![TallyVotesInputHasher](/img/circuits/tallyInputHasher.svg) + +It outputs one field element, which is the SHA256 hash of the following inputs: + +1. `packedVals` +2. `sbCommitment` +3. `currentTallyCommitment` +4. `newTallyCommitment` + +#### ResultsCommitmentVerifier + +A utility circuit used by the main `tallyVotes` circuit to verify that the results commitment is correct. + +![ResultsCommitmentVerifier](/img/circuits/resultsCommitmentVerifier.svg) + +#### QuinCheckRoot + +Utility circuit that given a quin Merkle root and a list of leaves, check if the root is the correct result of inserting all the leaves into the tree in the given order. + +![QuinCheckRoot](/img/circuits/quinCheckRoot.svg) + +#### CalculateTotal + +Utility circuit used to calculate the sum of an array of elements. + +![CalculateTotal](/img/circuits/calculateTotal.svg) + +#### ECDH + +Utility circuit used to generate a shared key from a private key and a public key. + +![ECDH](/img/circuits/ecdh.svg) + +#### Poseidon + +Utility circuit used to generate a Poseidon hash. In this case, it supports up to 13 inputs. + +![Poseidon13](/img/circuits/poseidonHasher13.svg) + +#### MessageToCommand + +Utility circuit used to convert a message into a command, this involves decrypting the message. + +![MessageToCommand](/img/circuits/messageToCommand.svg) + +#### MessageValidator + +Utility circuit used to validate a message. This performs several checks: + +- `stateTreeIndex` is valid +- `voteOptionIndex` is valid +- `nonce` is valid +- the signature is valid +- the user signed up before poll end timestamp +- the user had enough voice credits + +![MessageValidator](/img/circuits/messageValidator.svg) + +#### PrivToPubKey + +Utility circuit used to generate a public key from a private key. + +![PrivToPubKey](/img/circuits/privToPubkey.svg) + +#### VerifySignature + +Utility circuit used to verify a EdDSA signature + +![VerifySignature](/img/circuits/verifySignature.svg) + +#### UnpackElement + +Utility circuit used to unpack an input element. + +![UnpackElement](/img/circuits/unpackElement.svg) + +#### QuinSelector + +Utility circuit used to select one element from an array of n elements at a given index. + +![QuinSelector](/img/circuits/quinSelector.svg) + +#### Splicer + +Utility circuit used to insert one element in an array at position `index`. + +![Splicer](/img/circuits/splicer.svg) + +#### QuinBatchLeavesExists + +Utility circuit used to check if a batch of leaves exists in a quinary tree. + +![QuinBatchLeavesExists](/img/circuits/quinBatchLeavesExists.svg) + +#### QuinGeneratePathIndices + +Utility circuit used to generate the indices needed to traverse the tree until we find the leaf we are looking for. + +![QuinGeneratePathIndices](/img/circuits/quinGeneratePathIndices.svg) + +#### ProcessTopup + +Utility circuit used to process a topup message. + +![ProcessTopup](/img/circuits/processTopup.svg) + +#### ProcessOne + +Utility circuit used to process one message. + +![ProcessOne](/img/circuits/processOne.svg) + +## Compile circuits + +### Prerequisites + +Before building the project, make sure you have the following dependencies installed: + +- [circom](https://docs.circom.io/downloads/downloads/) + +### Building MACI circuits + +To build the main circuits of MACI, run the following command (`-c` postfix for c++ witness gen, and `-wasm` postfix for WASM witness gen only): + +``` +pnpm build-test-circuits-c +pnpm build-test-circuits-wasm +``` + +Please note that the circuits are configured with testing purpose parameters, which means it can only handle a limited amount of messages (up to 25 messages). For more information on the parameters and how to configure them, please refer to the individual circuit documentation within this page. Also, within the [configure-circomkit](https://maci.pse.dev/docs/installation#configure-circomkit) section of the `installation` page, you'll see how you can update the config file with new params. + +To compile a single circuit, you can run: + +``` +pnpm circom:build $CIRCUIT_NAME +``` + +> Please note that the name should match one of the circuit names inside the `circom.json` file. + +### Generating zKeys + +Run from the root directory to save to the `cli/zkeys` folder: + +```bash +pnpm setup:zkeys +``` + +Run from the circuits folder with `--outPath` to save to a custom folder: + +```bash +cd circuits && pnpm gen-zkeys --outPath ./CUSTOM_FOLDER_NAME +``` + +The larger the trees, the more time this process may take. You may also need a +machine with a very large amount of memory. + +> Note that you will have to modify the parameters inside the `./circuits/circom/circuits.json` file to match your use case. For example, if you want to support up to 3125 messages, the message tree depth parameter should be set to `5` (as $5^5 = 3125$). + +#### Measure the circuit sizes + +The size of a circuit is denoted by its number of constraints. The larger this +number, the more time it takes to compile it, generate its `.zkey` file, and +perform phase 2 contributions. + +Run this command to measure a circuit: + +```bash +pnpm exec snarkjs r1cs info CIRCUIT_NAME.circom +``` + +#### Download the `.ptau` file + +This file should be the result of the Perpetual Powers of Tau trusted setup +contribution which [Hermez Network +selected](https://blog.hermez.io/hermez-cryptographic-setup/). + +When running the `setup:zkeys` command, the `.ptau` file will be downloaded automatically. + +### Generating and Validating ZK Proofs + +To generate and validate ZK proofs from the artifacts produced by `circom`, you will need [`snarkjs`](https://github.com/iden3/snarkjs#groth16-1). + +## Testing + +To test the circuits package, please use `pnpm run test`. This will run all of the tests inside the tests folder. + +To run individual tests, you can use the following commands (for all other circuits please refer to the `package.json` scripts section): + +- `pnpm run test:processMessages` to run the tests for the `processMessages` circuit. +- `pnpm run test:tallyVotes` to run the tests for the `tallyVotes` circuit. + +More details on testing are provided in the [testing section](/docs/testing) of the documentation. diff --git a/website/versioned_docs/version-v1.3_alpha/cli.md b/website/versioned_docs/version-v1.3_alpha/cli.md new file mode 100644 index 0000000000..e27c2ec1a0 --- /dev/null +++ b/website/versioned_docs/version-v1.3_alpha/cli.md @@ -0,0 +1,689 @@ +--- +title: MACI Command-line interface (CLI) +description: Introduction to the MACI CLI interface that allows for effective deployment and testing +sidebar_label: Command-line interface +sidebar_position: 7 +--- + +# Command-line interface + +MACI provides a command-line interface that allows for effective deployment and +testing. Applications that build on top of MACI, such as +[clr.fund](https://clr.fund/), implement their own web UIs. + +Note that all the example commands default to a local Ethereum testnet at +`http://localhost:8545`, and use the Ethereum private key +`0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3`. Do not +send any real funds to the address generated by this key. + +For testing purposes, you can run: + +```bash +# in maci/contracts +pnpm run hardhat +``` + +> Note that you will need a hardhat.config file in your current directory to be able to run the cli. + +## Subcommands + +| Command | Description | Options | +| -------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `create` | Deploy the contracts | `-i, --initialVoiceCredits `: The initial voice credits
`-p, --initialVoiceCreditsProxyAddress `: The initial voice credits proxy contract address
`-g, --signupGatekeeperAddress `: The signup gatekeeper contract address
`-ph3, --poseidonT3Address `: The PoseidonT3 contract address
`-ph4, --poseidonT4Address `: The PoseidonT4 contract address
`-ph5, --poseidonT5Address `: The PoseidonT5 contract address
`-ph6, --poseidonT6Address `: The PoseidonT6 contract address
`-q, --quiet`: Whether to print values to the console
`-s, --stateTreeDepth `: The state tree depth
`-uq, --use-quadratic-voting"`: Whether to use quadratic voting
`-r, --rpc-provider `: The rpc provider URL | +| `checkVerifyingKeys` | Check that the verifying keys in the contract match the local ones | `-q, --quiet`: Whether to print values to the console
`-vk, --vk-contract `: The VkRegistry contract address
`-s, --state-tree-depth `: The state tree depth
`-i, --int-state-tree-depth `: The intermediate state tree depth
`-m, --msg-tree-depth `: The message tree depth
`-v, --vote-option-tree-depth `: The vote option tree depth
`-b, --msg-batch-depth `: The message batch depth
`-p, --process-messages-zkey `: The process messages zkey path (see different options to use specific circuits [Trusted setup](https://maci.pse.dev/docs/trusted-setup) or [Testing](https://maci.pse.dev/docs/testing/#pre-compiled-artifacts-for-testing))
`-t, --tally-votes-zkey `: The tally votes zkey path (see different options to use specific circuits [Trusted setup](https://maci.pse.dev/docs/trusted-setup) or [Testing](https://maci.pse.dev/docs/testing/#pre-compiled-artifacts-for-testing)) | +| `genMaciPubKey` | Generate a new MACI public key | `-sk, --privkey `: The private key | +| `genMaciKeyPair` | Generate a new MACI key pair | `-sp, --seed seed value for keypair` | +| `airdrop` | Airdrop topup credits to the coordinator | `-a, --amount `: The amount of topup
`-x, --maci-address `: The MACI contract address
`-o, --poll-id `: Poll id
`-t, --token-address `: The token address
`-q, --quiet`: Whether to print values to the console | +| `deployVkRegistry` | Deploy a new verification key registry contract | `-q, --quiet`: Whether to print values to the console | +| `show` | Show the deployed contract addresses | No options | +| `deployPoll` | Deploy a new poll | `-t, --duration `: The poll duration
`-i, --int-state-tree-depth `: The int state tree depth
`-b, --msg-batch-depth `: The message tree sub depth
`-m, --msg-tree-depth `: The message tree depth
`-v, --vote-option-tree-depth `: The vote option tree depth
`-pk, --pubkey `: The coordinator public key
`-x, --maci-address `: The MACI contract address
`-q, --quiet`: Whether to print values to the console
"-vk, `--vkRegistryAddress `: The vk registry contract address | +| `setVerifyingKeys` | Set the verifying keys | `-s, --state-tree-depth `: The state tree depth
`-i, --int-state-tree-depth `: The intermediate state tree depth
`-m, --msg-tree-depth `: The message tree depth
`-v, --vote-option-tree-depth `: The vote option tree depth
`-b, --msg-batch-depth `: The message batch depth
`-p, --process-messages-zkey `: The process messages zkey path (see different options to use specific circuits [Trusted setup](https://maci.pse.dev/docs/trusted-setup) or [Testing](https://maci.pse.dev/docs/testing/#pre-compiled-artifacts-for-testing))
`-t, --tally-votes-zkey `: The tally votes zkey path (see different options to use specific circuits [Trusted setup](https://maci.pse.dev/docs/trusted-setup) or [Testing](https://maci.pse.dev/docs/testing/#pre-compiled-artifacts-for-testing))
`-k, --vk-registry `: The vk registry contract address
`-q, --quiet`: Whether to print values to the console | +| `publish` | Publish a new message to a MACI Poll contract | `-p, --pubkey `: The MACI public key which should replace the user's public key in the state tree
`-x, --maci-address `: The MACI contract address
`-sk, --privkey `: Your serialized MACI private key
`-i, --state-index `: The user's state index
`-v, --vote-option-index `: The vote option index
`-n, --nonce `: The message nonce
`-s, --salt `: The message salt
`-o, --poll-id `: The poll id
`-w, --new-vote-weight `: The new vote weight
`-q, --quiet`: Whether to print values to the console | +| `mergeMessages` | Merge the message accumulator queue | `-q, --quiet`: Whether to print values to the console
`-x, --maci-address `: The MACI contract address
`-o, --poll-id `: The poll id
`-n, --num-queue-ops `: The number of queue operations | +| `mergeSignups` | Merge the signups accumulator queue | `-q, --quiet`: Whether to print values to the console
`-x, --maci-address `: The MACI contract address
`-o, --poll-id `: The poll id
`-n, --num-queue-ops `: The number of queue operations | +| `timeTravel` | Fast-forward the time (only works for local hardhat testing) | `-s, --seconds `: The number of seconds to fast-forward
`-q, --quiet`: Whether to print values to the console | +| `signup` | Sign up to a MACI contract | `-p, --pubkey `: The MACI public key
`-x, --maci-address `: The MACI contract address
`-s, --sg-data `: The signup gateway data
`-i, --ivcp-data `: The initial voice credit proxy data
`-q, --quiet`: Whether to print values to the console | +| `isRegisteredUser` | Checks if user is registered with public key | `-p, --pubkey `: The MACI public key
`-x, --maci-address `: The MACI contract address
`-q, --quiet`: Whether to print values to the console | +| `topup` | Top up an account with voice credits | `-a, --amount `: The amount of topup
`-x, --maci-address `: The MACI contract address
`-i, --state-index `: State leaf index
`-o, --poll-id `: Poll id
`-q, --quiet`: Whether to print values to the console | +| `fundWallet` | Fund a wallet with Ether | `-a, --amount `: The amount of Ether
`-w, --address
`: The address to fund
`-q, --quiet`: Whether to print values to the console | +| `verify` | Verify the results of a poll on-chain | `-o, --poll-id `: The poll id
`-t, --tally-file `: The tally file with results, per vote option spent credits, spent voice credits total
`-x, --maci-address `: The MACI contract address
`-tc, --tally-contract `: The tally contract address
`-q, --quiet`: Whether to print values to the console | +| `genProofs` | Generate the proofs for a poll | `-sk, --privkey `: Your serialized MACI private key
`-x, --maci-address `: The MACI contract address
`-o, --poll-id `: The poll id
`-t, --tally-file `: The tally file
`-r, --rapidsnark `: The path to the rapidsnark binary
`-wp, --process-witnessgen `: The path to the process witness generation binary
`-wt, --tally-witnessgen `: The path to the tally witness generation binary
`-zp, --process-zkey `-zt, --tally-zkey `: The path to the tally zkey
`-q, --quiet`: Whether to print values to the console
`-f, --output `: The output directory for proofs
`-tx, --transaction-hash :` Transaction hash of MACI contract creation
`-w, --wasm`: Whether to use the wasm binaries
`-pw, --process-wasm `: The path to the process witness generation wasm binary
`-tw, --tally-wasm `: The path to the tally witness generation wasm binary
`-uq, --use-quadratic-voting`: Whether to process messages and tally votes using quadratic voting or not | +| `proveOnChain` | Prove the results of a poll on chain | `-o, --poll-id `: The poll id
`-q, --quiet`: Whether to print values to the console
`-x, --maci-address `: The MACI contract address
`-p, --message-processor-address `: The message processor contract address
`-t, --tally-contract `: The tally contract address
`-f, --proof-dir `: The proof output directory from the genProofs subcommand | + +## Public and private key format + +MACI uses private keys in the BabyJub field for operations which occur within +zk-SNARKs, such as decrypting messages or signing commands. As MACI is deployed +on Ethereum, we seek to avoid confusing BabyJub private keys with Ethereum +private keys. To that end, users should pass serialized formats of public and +private keys to this CLI. We use `maci-domainobj`'s `PrivKey.serialize` and +`PubKey.serialize` functions to do so. + +Examples of serialized public and private keys: + +``` +Public key: macipk.946c756cb8588f7169d37e23a98b92051359d64321cf7372a75757b5e9d5590d +Private key: macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c +``` + +### Generate MACI keys + +You can generate MACI keys using the following cli utility. + +```bash +node build/ts/index.js genMaciKeyPair +``` + +Example output: + +```bash +[✓] Public key: macipk.946c756cb8588f7169d37e23a98b92051359d64321cf7372a75757b5e9d5590d +[✓] Private key: macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c +``` + +If you already have a MACI private key in serialized form, you can generate its corresponding public key using the following command: + +```bash +node build/ts/index.js genMaciPubKey -sk macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c +``` + +Example output: + +``` +[✓] Public key: macipk.946c756cb8588f7169d37e23a98b92051359d64321cf7372a75757b5e9d5590d +``` + +### Coordinator: Deploy VkRegistry + +This command deploys an instance of a VkRegistry contract. Multiple MACI +contracts can refer to the same VkRegistry as long as they are all owned (via +`Ownable.sol`) by the same account. + +Example usage: + +```bash +node build/ts/index.js deployVkRegistry +``` + +Example output: + +``` +[✓] VkRegistry deployed at: 0x6b5A4751307F6751E265c194244552A9995B6B3D +``` + +### Coordinator: Set verifying keys + +Note that the filename of the `.zkey` files must follow this format: + +``` +ProcessMessages_---_test..zkey +TallyVotes_-->_test.>.zkey +``` + +Example usage: + +```bash +node build/ts/index.js setVerifyingKeys \ + -s 10 -i 1 -m 2 -v 2 -b 1 \ + -p ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \ + -t ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey \ +``` + +Example output: + +``` +[i] Setting verifying keys... +[i] Transaction hash: 0x6b5b2959ba5161497d5499a0f9d9c69f773cd5f9b82f80a79253797b066863e3 +[✓] Verifying keys set successfully +``` + +### Coordinator: Create MACI instance + +Example usage: + +```bash +node build/ts/index.js create -s 10 +``` + +Example output: + +``` +[✓] MACI deployed at: 0xB08CEd0f34940a3E576Cf023b287f9Db2f306a1f +``` + +### Coordinator: Deploy poll + +Example usage: + +```bash +node ./build/ts/index.js deployPoll \ + -pk macipk.946c756cb8588f7169d37e23a98b92051359d64321cf7372a75757b5e9d5590d \ + -t 300 -i 1 -m 2 -b 1 -v 2 +``` + +Example output: + +``` +[i] Poll ID: 0 +[i] Poll contract: 0xB6389Da0285c7B1FC0ba352F5A1D5fb1A492a786 +[i] Message processor contract: 0xE0bF6021e023a197DBb3fABE64efA880E13D3f4b +[i] Tally contract: 0x3f21BC64076e7c9ed8695d053DCCBE6D8d5E6f43 +[i] Subsidy contract: 0xb848ef765E289762e9BE66a38006DDc4D23AeF24 +``` + +### User: sign up + +Example usage: + +```bash +node ./build/ts/index.js signup \ + -p macipk.182a49caec452e9966f5fef65363c3c795bf8cda482cae8289a4684c0f5bcb7b +``` + +Example output: + +``` +[i] Transaction hash: 0x4c7c9f65187fcf6e243804b75555bda48cbae4c317bb312f1b9f95ac4b7697b1 +[✓] State index: 1 +``` + +### User: publish message + +Example usage: + +```bash +node build/ts/index.js publish \ + -p macipk.182a49caec452e9966f5fef65363c3c795bf8cda482cae8289a4684c0f5bcb7b \ + -sk macisk.569cf25e35654046ecd9f176d9e6e47115d767fabfe0e97a206dd62e7a3a8546 \ + -i 1 -v 0 -w 9 -n 1 -o 0 +``` + +Example output: + +``` +[i] Transaction hash: 0xa2ab91c821bf7fa73fedcf19a5371a0f0866ae0747d22f82f1685afca0e5db49 +[i] Ephemeral private key: macisk.2631d585e46f059e4909ab35172451542ed7723a1ace120fcf49d68e27f935b0 +``` + +### Coordinator: Time travel (Testing only) + +Example usage: + +```bash +node build/ts/index.js timeTravel -s 300 +``` + +Example output: + +``` +[✓] Fast-forwarded 300 seconds +``` + +### Coordinator: merge state tree + +Example usage: + +```bash +node build/ts/index.js mergeSignups -o 0 +``` + +Example output: + +``` +[i] Merging state subroots 1 / 1 +[i] Transaction hash: 0xd7e7312f70831ec05bb23f23f506ef37d6ce0c2056c1b72f7bb989653d1c8a42 +[✓] Executed mergeMaciStateAqSubRoots(); gas used: 720061 +[✓] All state subtrees have been merged. +[i] Merging subroots to a main state root... +[i] Transaction hash: 0xb5e98d328b066d91e1b7aa35775fe624be446b540a00bcb4b27a02477636b569 +[✓] Executed mergeStateAq(); gas used: 1004720 +``` + +### Coordinator: merge message tree + +Example usage: + +```bash +node build/ts/index.js mergeMessages -o 0 +``` + +Example output: + +``` +[i] Merging message subroots 1 / 1 +[✓] Executed mergeMessageAqSubRoots(); gas used: 602448 +[i] Transaction hash: 0xdf9d11c6b35fcccff82dafa3aa15f760e3f7694a72b07007fbdb359d44df0bea +[✓] All message subtrees have been merged. +[i] Merging subroots to a main message root... +[✓] Executed mergeMessageAq(); gas used: 173346 +[i] Transaction hash: 0x1f18ec08fd14db90a0d1d02d1ed27c0bfd3bc138701e812c4c3382572fc4d151 +[✓] The message tree has been merged. +``` + +### Coordinator: generate Maci state offchain + +Example usage to generate the state locally from the smart contracts events: + +```bash +node build/ts/index.js genLocalState \ + --poll-id 0 \ + --output localState.json \ + --privkey macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c \ + --blocks-per-batch 50 +``` + +Example output: + +``` +[i] Fetching logs from 0 till 228 and generating the offline maci state +[✓] The state has been written to localState.json +``` + +### Coordinator: generate proofs + +Example usage: + +**C++ witness parameters** + +```bash +node build/ts/index.js genProofs -x 0x89962fa216d39fCcaaC11e1e462340d80ab6Cf4D \ + -sk macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c \ + -o 0 \ + -t tally.json \ + -f proofs \ + -r ~/rapidsnark/build/prover \ + -wp ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test_cpp/ProcessMessages_10-2-1-2_test \ + -wt ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test_cpp/TallyVotes_10-1-2_test \ + -zp ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \ + -zt ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey \ +``` + +**WASM Parameters** + +```bash +node build/ts/index.js genProofs \ + -sk macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c \ + -o 0 \ + -t tally.json \ + -f proofs \ + -zp ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \ + -zt ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey \ + -tw ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test_js/TallyVotes_10-1-2_test.wasm \ + -pw ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test_js/ProcessMessages_10-2-1-2_test.wasm \ + -w true \ +``` + +**Non Quadratic Voting** + +```bash +node build/ts/index.js genProofs \ + -sk macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c \ + -o 0 \ + -t tally.json \ + -f proofs \ + -zp ./zkeys/ProcessMessagesNonQv_10-2-1-2_test/ProcessMessagesNonQv_10-2-1-2_test.0.zkey \ + -zt ./zkeys/TallyVotesNonQv_10-1-2_test/TallyVotesNonQv_10-1-2_test.0.zkey \ + -tw ./zkeys/TallyVotesNonQv_10-1-2_test/TallyVotesNonQv_10-1-2_test_js/TallyVotesNonQv_10-1-2_test.wasm \ + -pw ./zkeys/ProcessMessagesNonQv_10-2-1-2_test/ProcessMessagesNonQv_10-2-1-2_test_js/ProcessMessagesNonQv_10-2-1-2_test.wasm \ + -w true \ + -uq false +``` + +Example output: + +``` +[i] starting to fetch logs from block 0 +[i] Generating proofs of message processing... +[i] Progress: 1 / 1 +[i] gen processMessage proof took 17.322 seconds + +[i] Generating proofs of vote tallying... +[i] Progress: 1 / 1 +[✓] The tally commitment is correct +[i] gen tally proof took 4.951 seconds +``` + +### Coordinator: generate proofs using a local state file + +Example usage to generate the proofs locally from the local state file created with genLocalState: + +**C++ witness parameters** + +```bash +node build/ts/index.js genProofs \ + --privkey macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c \ + --poll-id 0 \ + --rapidsnark ~/rapidsnark/build/prover \ + --process-witnessgen ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test_cpp/ProcessMessages_10-2-1-2_test \ + --tally-witnessgen ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test_cpp/TallyVotes_10-1-2_test \ + --process-zkey /zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \ + --tally-zkey ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey \ + --tally-file tally.json \ + --output proofs/ \ + --state-file localState.json +``` + +**WASM Params** + +```bash +node build/ts/index.js genProofs \ + --privkey macisk.08a06aef74c7f6a6f73704e30677418731bc738500f4e6c63dbfe41af8d6719c \ + --poll-id 0 \ + --process-zkey ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \ + --tally-zkey ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey \ + --tally-file tally.json \ + --output proofs/ \ + --state-file localState.json \ + -tw ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test_js/TallyVotes_10-1-2_test.wasm \ + -pw ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test_js/ProcessMessages_10-2-1-2_test.wasm \ + -w true +``` + +Example output: + +``` +[i] Generating proofs of message processing... +[i] Progress: 1 / 1 +[i] gen processMessage proof took 17.053 seconds + +[i] Generating proofs of vote tallying... +[i] Progress: 1 / 1 +[✓] The tally commitment is correct +[i] gen tally proof took 4.746 seconds +``` + +### Coordinator: prove on chain + +Example usage: + +```bash +node build/ts/index.js proveOnChain \ + -o 0 \ + -f proofs/ +``` + +Example output: + +``` +[i] Submitting proofs of message processing... +[i] Transaction hash: 0xa8acf67d6520ceaf5eef8acbf4cda7f5c2657122e2a72a092b9f4503282d70b9 +[i] Progress: 1 / 1 +[✓] All message processing proofs have been submitted. +[i] Submitting proofs of vote tallying... +[i] Progress: 1 / 1 +[i] Transaction hash: 0x691687ab6fb504919859901f297cdb7d8c4d736756d2d4edf345d721bb82365b +[✓] All vote tallying proofs have been submitted. +``` + +### Anyone: verify tally + +Example usage: + +```bash +node build/ts/index.js verify \ + -o 0 \ + -t tally.json +``` + +Example output: + +``` +[i] on-chain tally commitment: 83601b7979c13506317b58e859950e9e92e1e6d326810d89332cc13909833ec +[✓] The on-chain tally commitment matches. +[i] The on-chain tally matches the off-chain tally. +``` + +## Demonstration + +### Scenario: + +1. Alice votes for Party A +2. Alice changes her key +3. Eve tries to bribe Alice to change her vote to Party B +4. Alice submits an invalid vote for Party B +5. The coordinator processes the votes, computes, and verifies the final tally +6. The expected result is: Party A has some votes and Party B has 0 votes. + +Implication: Alice's invalid vote was not counted, and Eve had no way to tell. + +### Examples of serialized public and private keys: + +``` +Coordinator: +Public key: macipk.281830024fb6d21a4c73a89a7139aff61fbbddad731ef2dc2db9516171fd390e +Private key: macisk.bf92af7614b07e2ba19dce65bb7fef2b93d83b84da2cf2e3af690104fbc52511 + +Alice: +Public key: macipk.1cac8e4e5b54d7dcce4aa06e71d8b9f324458756e7a9368383d005592719512a +Private key: macisk.63e796e4e5d18a5fcf4ccef1e74e83b807a165d6727bb89201782240458f7420 +``` + +### Coordinator: Deploy VkRegistry + +```bash +node build/ts/index.js deployVkRegistry +``` + +Output: + +```bash +[✓] VkRegistry deployed at: 0x7607Cfe2fA0d62F725537e55d83C693Cc3C76EF2 +``` + +### Coordinator: Set verifying keys + +```bash +node build/ts/index.js setVerifyingKeys \ + --state-tree-depth 10 \ + --int-state-tree-depth 1 \ + --msg-tree-depth 2 \ + --vote-option-tree-depth 2 \ + --msg-batch-depth 1 \ + --process-messages-zkey ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \ + --tally-votes-zkey ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey +``` + +Output: + +```bash +[i] Setting verifying keys... +[i] Transaction hash: 0xbd5d06935537fb59903c27b9bdb19a41d422f75e1dfd6eb61f028bf3a7b82c76 +[✓] Verifying keys set successfully +``` + +### Coordinator: Create MACI instance + +```bash +node build/ts/index.js create -s 10 +``` + +Output: + +```bash +[✓] MACI deployed at: 0xC131D3eeD9D6D410A7bfc200d81b9795f1bb5ed6 +``` + +### Coordinator: Deploy poll + +```bash +node ./build/ts/index.js deployPoll \ + -pk macipk.281830024fb6d21a4c73a89a7139aff61fbbddad731ef2dc2db9516171fd390e \ + -t 1000 -i 1 -m 2 -b 1 -v 2 +``` + +Output: + +```bash +[i] Poll ID: 0 +[i] Poll contract: 0x2c3Adf2852788662148038511aD80962aaf631D7 +[i] Message processor contract: 0xd3C3C6530fE4073292D6EAfdEAdEeAbf1A3DC19B +[i] Tally contract: 0x06c1939F6cBb68D42333F140CAE815cc36D341b0 +[i] Subsidy contract: 0xCB74254716c96B07c812c73A5945e68aa1de4569 +``` + +### Alice: sign up + +```bash +node ./build/ts/index.js signup \ + --pubkey macipk.1cac8e4e5b54d7dcce4aa06e71d8b9f324458756e7a9368383d005592719512a +``` + +Output: + +```bash +[i] Transaction hash: 0x7ab4c2d23686049432d19bb64c8ee4e8776fff134d971dcf27e1f513b4fdb97f +[✓] State index: 1 +``` + +### Alice: votes for Party A (option index 0) + +```bash +node build/ts/index.js publish \ + --pubkey macipk.1cac8e4e5b54d7dcce4aa06e71d8b9f324458756e7a9368383d005592719512a \ + --privkey macisk.63e796e4e5d18a5fcf4ccef1e74e83b807a165d6727bb89201782240458f7420 \ + --state-index 1 \ + --vote-option-index 0 \ + --new-vote-weight 9 \ + --nonce 1 \ + --poll-id 0 +``` + +Output: + +```bash +[i] Transaction hash: 0x60936cfb0b25c8618d3cb8d0f5497106d5f6e3776f3212932975442d874eddbd +[i] Ephemeral private key: macisk.103b8c4c98700d06f47522892032fce54bd03cd197cee495ede3802730409910 +``` + +### Alice: submits an invalid vote for Party B (option index 1) with different public key + +```bash +node build/ts/index.js publish \ + --pubkey macipk.1cac8e4e5b54d7dcce4aa06e71d8b9f324458756e7a9368383d005592719512a \ + --privkey macisk.63e796e4e5d18a5fcf4ccef1e74e83b807a165d6727bb89201782240458f7420 \ + --state-index 1 \ + --vote-option-index 1 \ + --new-vote-weight 9 \ + --nonce 2 \ + --poll-id 0 +``` + +Output: + +```bash +[i] Transaction hash: 0x73f74b13d276cd311ce5421a145debc71e97e48abc8be2f9a0a548b26f7920f9 +[i] Ephemeral private key: macisk.1e490d67477b4c5f08806973fca2bea81e723c60deba6bdeacab56f7a4bd867b +``` + +### Coordinator: Time Travel + +```bash +node build/ts/index.js timeTravel -s 1000 +``` + +Output: + +``` +[✓] Fast-forwarded 1000 seconds +``` + +### Coordinator: merge state tree + +```bash +node build/ts/index.js mergeSignups --poll-id 0 +``` + +Output: + +```bash +[i] Merging state subroots 1 / 1 +[i] Transaction hash: 0xd01932e8dfad251f9b0d288290ac17f12bc449ea859a6921f63edf6b4b06f4c9 +[✓] Executed mergeMaciStateAqSubRoots(); gas used: 720061 +[✓] All state subtrees have been merged. +[i] Merging subroots to a main state root... +[i] Transaction hash: 0x25f60a9b5a24d11b87c41d8a4f681e3fd895b3bdf78ea86755b9800005662ce6 +[✓] Executed mergeStateAq(); gas used: 1004720 +``` + +### Coordinator: merge message tree + +```bash +node build/ts/index.js mergeMessages --poll-id 0 +``` + +Output: + +```bash +[i] Merging message subroots 1 / 1 +[✓] Executed mergeMessageAqSubRoots(); gas used: 600520 +[i] Transaction hash: 0xac0e8a01277db1b6282f8fb3763a8a4aeeebb3e12a41dd0dee9fc2804a4c9e81 +[✓] All message subtrees have been merged. +[i] Merging subroots to a main message root... +[✓] Executed mergeMessageAq(); gas used: 173346 +[i] Transaction hash: 0x472f0fd515c7cd2a02c430189e4ee92a6843bd6b19807484ce454cb7dab0e931 +[✓] The message tree has been merged. +``` + +### Coordinator: generate proofs + +```bash +node build/ts/index.js genProofs \ + --privkey macisk.bf92af7614b07e2ba19dce65bb7fef2b93d83b84da2cf2e3af690104fbc52511 \ + --poll-id 0 \ + --process-zkey ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test.0.zkey \ + --tally-zkey ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test.0.zkey \ + --tally-file tally.json \ + --output proofs/ \ + -tw ./zkeys/TallyVotes_10-1-2_test/TallyVotes_10-1-2_test_js/TallyVotes_10-1-2_test.wasm \ + -pw ./zkeys/ProcessMessages_10-2-1-2_test/ProcessMessages_10-2-1-2_test_js/ProcessMessages_10-2-1-2_test.wasm \ + -w true +``` + +Output: + +```bash +[i] Generating proofs of message processing... +[i] Progress: 1 / 1 +[i] gen processMessage proof took 16.644 seconds + +[i] Generating proofs of vote tallying... +[i] Progress: 1 / 1 +[✓] The tally commitment is correct +[i] gen tally proof took 4.809 seconds +``` + +### Coordinator: prove on chain + +```bash +node build/ts/index.js proveOnChain \ + --poll-id 0 \ + --proof-dir proofs/ +``` + +Output: + +```bash +[i] Submitting proofs of message processing... +[i] Transaction hash: 0x9c3280af80de2436f9a886e4cd94218e01fe35ea3d3e671aad97b5aa5d6108ed +[i] Progress: 1 / 1 +[✓] All message processing proofs have been submitted. +[i] Submitting proofs of vote tallying... +[i] Progress: 1 / 1 +[i] Transaction hash: 0x3e82ae3ad04215d4f357455ab5a610eba082796d2abc698aad91b046d16b9350 +[✓] All vote tallying proofs have been submitted. +``` + +### Anyone: verify + +```bash +node build/ts/index.js verify \ + --poll-id 0 \ + --tally-file tally.json +``` + +Output: + +```bash +[i] on-chain tally commitment: 1ed004ac21a5397a512cbe749e7110934a434837f4818265043fd2e2e9cbec91 +[✓] The on-chain tally commitment matches. +``` diff --git a/website/versioned_docs/version-v1.3_alpha/contracts.md b/website/versioned_docs/version-v1.3_alpha/contracts.md new file mode 100644 index 0000000000..4758e5027e --- /dev/null +++ b/website/versioned_docs/version-v1.3_alpha/contracts.md @@ -0,0 +1,426 @@ +--- +title: MACI Smart Contracts +description: MACI is composed of multiple smart contracts, which together with the zk-SNARK circuits, can be used to carry out on-chain voting +sidebar_label: Smart Contracts +sidebar_position: 8 +--- + +# Smart Contracts + +MACI is composed of multiple smart contracts, which together with the zk-SNARK circuits, can be used to carry out on-chain voting. + +The main contracts are presented and explained below. + +## MACI.sol + +`MACI.sol` is the core contract of the project, as it provides the base layer for user signups and Polls to be created. + +The constructor shown below accepts several arguments: + +- `PollFactory` address +- `MessageProcessorFactory` address +- `TallyFactory` address +- `SignUpGatekeeper` address +- `InitialVoiceCreditProxy` address +- `TopupCredit` address +- The depth of the state tree + +```javascript +constructor( + IPollFactory _pollFactory, + IMessageProcessorFactory _messageProcessorFactory, + ITallyFactory _tallyFactory, + SignUpGatekeeper _signUpGatekeeper, + InitialVoiceCreditProxy _initialVoiceCreditProxy, + TopupCredit _topupCredit, + uint8 _stateTreeDepth +) payable { + // Deploy the state AccQueue + stateAq = new AccQueueQuinaryBlankSl(STATE_TREE_SUBDEPTH); + stateAq.enqueue(BLANK_STATE_LEAF_HASH); + + // because we add a blank leaf we need to count one signup + // so we don't allow max + 1 + unchecked { + numSignUps++; + } + + pollFactory = _pollFactory; + messageProcessorFactory = _messageProcessorFactory; + tallyFactory = _tallyFactory; + topupCredit = _topupCredit; + signUpGatekeeper = _signUpGatekeeper; + initialVoiceCreditProxy = _initialVoiceCreditProxy; + stateTreeDepth = _stateTreeDepth; + + // Verify linked poseidon libraries + if (hash2([uint256(1), uint256(1)]) == 0) revert PoseidonHashLibrariesNotLinked(); +} + +``` + +Upon deployment, the contract will deploy a new `AccQueueQuinaryBlankSl` contract using the `STATE_TREE_SUBDEPTH`. By default, this is defined as `uint8 internal constant STATE_TREE_SUBDEPTH = 2;`. + +Should this be changed, it will be necessary to amend the `contracts/ts/genEmptyBallotRootsContract.ts` file to reflect the change. The first action on this deployed contract, is to enqueue (add) an empty hash (defined as `6769006970205099520508948723718471724660867171122235270773600567925038008762`). + +After this, the contracts will be stored to state, and then the contract will perform a simple sanity check to ensure that the Poseidon hash libraries were linked successfully. + +Next, we have the `signUp` function, which allows users to `signUp`, as long as they pass the conditions set in the `SignUpGatekeeper` contract. This contract can use any mean necessary to gatekeep access to MACI's polls. For instance, only wallets with a specific ERC721 token can be allowed to sign up. + +This function does the following: + +- checks that the maximum number of signups has not been reached. As of now, this will be $5 ** 10 - 1$ due to circuit limitations. +- ensure the subtrees have not been merged already, to prevent a DoS on the coordinator full tree merge +- checks that the provided public key is a valid baby-jubjub point +- increases signups counter +- registers the user using the sign up gatekeeper contract. It is important that whichever gatekeeper is used, this reverts if a user tries to sign up twice or the conditions are not met (i.e returning false is not enough) +- calls the voice credit proxy to retrieve the number of allocated voice credits allocated to this voter +- hashes the voice credits alongside the user's MACI public key and the current time +- enqueues this hashed data into the `stateAq` contract + +```javascript +function signUp( + PubKey memory _pubKey, + bytes memory _signUpGatekeeperData, + bytes memory _initialVoiceCreditProxyData +) public virtual { + // prevent new signups until we merge the roots (possible DoS) + if (subtreesMerged) revert SignupTemporaryBlocked(); + + // ensure we do not have more signups than what the circuits support + if (numSignUps >= uint256(TREE_ARITY) ** uint256(stateTreeDepth)) revert TooManySignups(); + + if (_pubKey.x >= SNARK_SCALAR_FIELD || _pubKey.y >= SNARK_SCALAR_FIELD) { + revert MaciPubKeyLargerThanSnarkFieldSize(); + } + + // Increment the number of signups + // cannot overflow with realistic STATE_TREE_DEPTH + // values as numSignUps < 5 ** STATE_TREE_DEPTH -1 + unchecked { + numSignUps++; + } + + // Register the user via the sign-up gatekeeper. This function should + // throw if the user has already registered or if ineligible to do so. + signUpGatekeeper.register(msg.sender, _signUpGatekeeperData); + + // Get the user's voice credit balance. + uint256 voiceCreditBalance = initialVoiceCreditProxy.getVoiceCredits(msg.sender, _initialVoiceCreditProxyData); + + uint256 timestamp = block.timestamp; + // Create a state leaf and enqueue it. + uint256 stateLeaf = hashStateLeaf(StateLeaf(_pubKey, voiceCreditBalance, timestamp)); + uint256 stateIndex = stateAq.enqueue(stateLeaf); + + emit SignUp(stateIndex, _pubKey.x, _pubKey.y, voiceCreditBalance, timestamp); +} +``` + +Once everything has been setup, polls can be deployed using the `deployPoll` function. It should be noted that currently, after the first poll is deployed, in order to deploy a new one, the state tree must have been merged (and this can be triggered by Poll contracts using `Poll.mergeMaciStateAqSubRoots` and `Poll.mergeMaciStateAq`) + +```javascript +function deployPoll( + uint256 _duration, + TreeDepths memory _treeDepths, + PubKey memory _coordinatorPubKey, + address _verifier, + address _vkRegistry, + bool useSubsidy +) public virtual onlyOwner returns (PollContracts memory pollAddr) { + // cache the poll to a local variable so we can increment it + uint256 pollId = nextPollId; + + // Increment the poll ID for the next poll + // 2 ** 256 polls available + unchecked { + nextPollId++; + } + + if (pollId > 0) { + if (!stateAq.treeMerged()) revert PreviousPollNotCompleted(pollId); + } + + MaxValues memory maxValues = MaxValues({ + maxMessages: uint256(TREE_ARITY) ** _treeDepths.messageTreeDepth, + maxVoteOptions: uint256(TREE_ARITY) ** _treeDepths.voteOptionTreeDepth + }); + + address _owner = owner(); + + address p = pollFactory.deploy( + _duration, + maxValues, + _treeDepths, + _coordinatorPubKey, + address(this), + topupCredit, + _owner + ); + + address mp = messageProcessorFactory.deploy(_verifier, _vkRegistry, p, _owner); + address tally = tallyFactory.deploy(_verifier, _vkRegistry, p, mp, _owner); + + polls[pollId] = p; + + // store the addresses in a struct so they can be returned + pollAddr = PollContracts({ poll: p, messageProcessor: mp, tally: tally }); + + emit DeployPoll(pollId, _coordinatorPubKey.x, _coordinatorPubKey.y, pollAddr); +} +``` + +## Poll.sol + +This contract allows users to submit their votes. + +The main functions of the contract are as follows: + +- `topup` - This function accepts two parameters, a `stateIndex`, and an `amount`. It can only be called before the voting deadline. + After checking whether the deadline has passed or not, it will validate that the contract has not reached the maximum number of messages, if the checks passes, it will increase the number of messages by 1. + It will then try to transfer the amount of `topUpCredit` tokens. + Finally, it will create a new Message object that will be hashed and enqueued in the `messageAq` contract. This messageAq contract is reserved for this one poll only and will only contain its messages. +- `publishMessage` - This function allows anyone to publish a message, and it accepts the message object as well as an ephemeral public key. This key together with the coordinator public key will be used to generate a shared ECDH key that will encrypt the message. + Before saving the message, the function will check that the voting deadline has not passed, as well as the max number of messages was not reached. +- `publisMessageBatch` - This function allows to submit a batch of messages, and it accepts an array of messages with their corresponding public keys used in the encryption step. It will call the `publishMessage` function for each message in the array. + +The `mergeMaciStateAqSubRoots` function can be called by the contract admin after the voting deadline and looks like the following: + +```javascript +function mergeMaciStateAqSubRoots(uint256 _numSrQueueOps, uint256 _pollId) public onlyOwner isAfterVotingDeadline { + // This function cannot be called after the stateAq was merged + if (stateAqMerged) revert StateAqAlreadyMerged(); + + // merge subroots + extContracts.maci.mergeStateAqSubRoots(_numSrQueueOps, _pollId); + + emit MergeMaciStateAqSubRoots(_numSrQueueOps); +} +``` + +If the subtrees have not been merged on the MACI contract's `stateAq`, then it will merge it by calling `mergeStateAqSubroots`. It accepts two parameters: + +- `_numSrQueueOps` - the number of operations required +- `_pollId` - the id of the poll + +After merging the subroots, a coordinator's job is to merge the main state root, using `mergeMaciStateAq`: + +```javascript +function mergeMaciStateAq(uint256 _pollId) public onlyOwner isAfterVotingDeadline { + // This function can only be called once per Poll after the voting + // deadline + if (stateAqMerged) revert StateAqAlreadyMerged(); + + // set merged to true so it cannot be called again + stateAqMerged = true; + + // the subtrees must have been merged first + if (!extContracts.maci.stateAq().subTreesMerged()) revert StateAqSubtreesNeedMerge(); + + mergedStateRoot = extContracts.maci.mergeStateAq(_pollId); + + // Set currentSbCommitment + uint256[3] memory sb; + sb[0] = mergedStateRoot; + sb[1] = emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1]; + sb[2] = uint256(0); + + currentSbCommitment = hash3(sb); + + numSignups = extContracts.maci.numSignUps(); + emit MergeMaciStateAq(mergedStateRoot, numSignups); +} +``` + +This function only accepts one parameter, and can be called by the owner only, after the voting deadline. The parameter is the pollId for which we want to perform the operation. This function can only be called once per poll, and it will check that the sub trees have been merged on MACI's AccQueue contract. Finally it will merge the whole AccQueue to generate the state root, and store the current commitment comprised of: + +the Poseidon hash of the merkle root, an empty ballot root stored in the emptyBallotRoots mapping (shown below), and a zero. + +```javascript +emptyBallotRoots[0] = uint256(6579820437991406069687396372962263845395426835385368878767605633903648955255); +emptyBallotRoots[1] = uint256(9105453741665960449792281626882014222103501499246287334255160659262747058842); +emptyBallotRoots[2] = uint256(14830222164980158319423900821611648302565544940504586015002280367515043751869); +emptyBallotRoots[3] = uint256(12031563002271722465187541954825013132282571927669361737331626664787916495335); +emptyBallotRoots[4] = uint256(5204612805325639173251450278876337947880680931527922506745154187077640790699); +``` + +It will also store the number of signups at this current block, as well as the merkle root of the state tree. + +Now, the coordinator can also perform similar operations to merge the message tree. + +- `mergeMessageAqSubRoots` - merges the Poll's messages tree subroot +- `mergeMessageAq` - merges the Poll's messages tree + +## PollFactory.sol + +`PollFactory` is a smart contract that is used to deploy new Polls. This is used by MACI inside the `deployPoll` function. + +```ts +function deploy( + uint256 _duration, + MaxValues calldata _maxValues, + TreeDepths calldata _treeDepths, + PubKey calldata _coordinatorPubKey, + address _maci, + TopupCredit _topupCredit, + address _pollOwner +) public virtual returns (address pollAddr) { + /// @notice Validate _maxValues + /// maxVoteOptions must be less than 2 ** 50 due to circuit limitations; + /// it will be packed as a 50-bit value along with other values as one + /// of the inputs (aka packedVal) + if (_maxValues.maxVoteOptions >= (2 ** 50)) { + revert InvalidMaxValues(); + } + + /// @notice deploy a new AccQueue contract to store messages + AccQueue messageAq = new AccQueueQuinaryMaci(_treeDepths.messageTreeSubDepth); + + /// @notice the smart contracts that a Poll would interact with + ExtContracts memory extContracts = ExtContracts({ + maci: IMACI(_maci), + messageAq: messageAq, + topupCredit: _topupCredit + }); + + // deploy the poll + Poll poll = new Poll(_duration, _maxValues, _treeDepths, _coordinatorPubKey, extContracts); + + // Make the Poll contract own the messageAq contract, so only it can + // run enqueue/merge + messageAq.transferOwnership(address(poll)); + + // init Poll + poll.init(); + + poll.transferOwnership(_pollOwner); + + pollAddr = address(poll); +} +``` + +Upon deployment, the following will happen: + +- ownership of the `messageAq` contract is transferred to the deployed poll contract +- ownership of the new `Poll` contract is transferred to the poll owner, which in `MACI` is set as the owner of `MACI`. + +## MessageProcessor + +This contract is used to prepare parameters for the zk-SNARK circuits as well as for verifying proofs. It should be deployed alongside `MACI` and ownership assigned to the coordinator. +It will process messages in batches, and after all batches have been processed, the `sbCommitment` can then be used for the `Tally` and `Subsidy` contracts. + +## Tally + +:::info +The `Tally` contract is present also in a non quadratic voting fashion, and is slightly smaller due to not having the `verifyPerVOSpentVoiceCredits` function. This is not required because with normal (non quadratic) voting, each vote by a user is not the square root of the voice credits spent. +::: + +The `Tally` contract is used by the coordinator to submit commitments to the tally results via the `tallyVotes` function. This is done in batches and the final commitment can be used by the users to verify the validity of the results. + +Below are the functions which users can use to verify the results: + +- `verifySpentVoiceCredits` +- `verifyPerVOSpentVoiceCredits` +- `verifyTallyResult` + +## SignUpToken (optional) + +This contract can be used by the `SignUpGateKeeper` to determine whether a user is allowed to register. The default contract provided with MACI is a simple ERC721 token. Coordinators can use this contract to mint a token for each of the participants in the voting process, and gatekeep access to a round by using a `SignUpTokenGatekeeper` contract. + +## SignUpGatekeeper + +MACI requires a signup gatekeeper to ensure that only designed users register. It is up to MACI's deployer how they wish to allow sign-ups, therefore they can implement their own GateKeeper. The repository comes with different options: + +- `FreeForAllSignUpGatekeeper` - This allows anyone to signup on MACI. +- `SignUpTokenGatekeeper` - This makes use of a ERC721 token to gatekeep the signup function. +- `EASGatekeeper` - This allows gatekeeping signups to only users who have a specific EAS attestation. + +An abstract contract to inherit from is also provided, with two function signatures as shown below: + +```ts +abstract contract SignUpGatekeeper { + function setMaciInstance(MACI _maci) public virtual {} + function register(address _user, bytes memory _data) public virtual {} +} +``` + +The MACI contract will need to call the `SignUpGatekeeper.register` function inside the `MACI.signUp` function. + +## VoiceCreditProxy + +The VoiceCreditProxy contract is used to assign voice credits to users. Whichever implementation should the MACI deployers use, this must implement a view function that returns the balance for a user, such as the one below: + +```javascript +function getVoiceCredits(address _user, bytes memory _data) public virtual view returns (uint256) {} +``` + +The repository comes with a simple implementation called `InitialVoiceCreditProxy` which assigns a fixed amount of voice credits to each user. + +## Hasher + +This contract exposes methods to hash different number of parameters with the Poseidon hash function. + +## VkRegistry + +The VkRegistry is a contract that holds the verifying keys for the zk-SNARK circuits. It holds two different sets of keys: + +- `processVks` - The keys for the processMessages circuit +- `tallyVks` - The keys for the tallyVotes circuit + +Each circuit will have a signature which is its compile-time constants represented as a uint256. + +## Params + +A contract holding three structs: + +```c +/// @notice A struct holding the depths of the merkle trees +struct TreeDepths { + uint8 intStateTreeDepth; + uint8 messageTreeSubDepth; + uint8 messageTreeDepth; + uint8 voteOptionTreeDepth; +} + +/// @notice A struct holding the max values for the poll +struct MaxValues { + uint256 maxMessages; + uint256 maxVoteOptions; +} + +/// @notice A struct holding the external contracts +/// that are to be passed to a Poll contract on +/// deployment +struct ExtContracts { + IMACI maci; + AccQueue messageAq; + TopupCredit topupCredit; +} +``` + +Struct parameters are used to avoid stack too deep errors in the other contracts. + +## AccQueue + +The AccQueue contract represents a Merkle Tree where each leaf insertion only updates a subtree. To obtain the main tree root, the subtrees must be merged together by the contract owner. This requires at least two operations, a `mergeSubRoots` and a `merge`. + +The contract can be initialized to work as a traditional Merkle Tree (2 leaves per node) or a Quinary Tree (5 leaves per node). This can be achieved by passing either two or five as parameter to the constructor (`_hashLength`). Any other values should not be accepted. + +Below are presented the most important functions of the smart contract: + +- `enqueue` - Allows to add a leaf to the queue for the current subtree. Only one parameter is accepted and that is the leaf to insert. +- `insertSubTree` - Admin only function which allows to insert a full subtree (batch enqueue) +- `mergeSubRoots` - Allows the contract owner to merge all of the subtrees to form the shortest possible tree. The argument `_numSrQueueOps` can be used to perform the operation in multiple transactions (as this might trigger the block gas limit). +- `merge` - Allows the contract admin to form a main tree with the desired depth. The depth must fit all of the leaves. + +## EmptyBallotRoots + +This contract contains the roots of Ballot trees of five leaf configurations. + +```javascript +emptyBallotRoots[0] = uint256(6579820437991406069687396372962263845395426835385368878767605633903648955255); +emptyBallotRoots[1] = uint256(9105453741665960449792281626882014222103501499246287334255160659262747058842); +emptyBallotRoots[2] = uint256(14830222164980158319423900821611648302565544940504586015002280367515043751869); +emptyBallotRoots[3] = uint256(12031563002271722465187541954825013132282571927669361737331626664787916495335); +emptyBallotRoots[4] = uint256(5204612805325639173251450278876337947880680931527922506745154187077640790699); +``` diff --git a/website/versioned_docs/version-v1.3_alpha/contributing/code-of-conduct.md b/website/versioned_docs/version-v1.3_alpha/contributing/code-of-conduct.md new file mode 100644 index 0000000000..a499186bb7 --- /dev/null +++ b/website/versioned_docs/version-v1.3_alpha/contributing/code-of-conduct.md @@ -0,0 +1,91 @@ +--- +title: MACI Contributor Code of Conduct +description: The Contributor Covenant Code of Conduct for MACI +sidebar_label: Code of Conduct +--- + +# Contributor Covenant Code of Conduct + +Please see our guide on [contributing to MACI](/docs/contributing). + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or + advances of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email + address, without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.0, [available here](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html). + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +For answers to common questions about this code of conduct, see [the FAQ](https://www.contributor-covenant.org/faq). [Translations are available here](https://www.contributor-covenant.org/translations). diff --git a/website/versioned_docs/version-v1.3_alpha/contributing/contributing.md b/website/versioned_docs/version-v1.3_alpha/contributing/contributing.md new file mode 100644 index 0000000000..138f906839 --- /dev/null +++ b/website/versioned_docs/version-v1.3_alpha/contributing/contributing.md @@ -0,0 +1,125 @@ +--- +title: Contributing to MACI +description: Instructions on how to contribute to MACI +sidebar_label: Contributing +sidebar_position: 21 +--- + +# Contributing + +🎉 Thank you for being interested in contributing to MACI! 🎉 + +Feel welcome and read the following sections in order to know how to ask questions and how to work on something. + +All members of our community are expected to follow our [Code of Conduct](/docs/contributing/code-of-conduct). Please make sure you are welcoming and friendly in all of our spaces. + +We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. There is a lot we want to achieve, and this can only be made possible thanks to your support. 👏 + +## Issues + +The best way to contribute to our projects is by opening a [new issue](https://github.com/privacy-scaling-explorations/maci/issues) or tackling one of the issues listed [here](https://github.com/privacy-scaling-explorations/maci/contribute). + +## Pull Requests + +Pull requests are great if you want to add a feature or fix a bug. Here's a quick guide: + +1. Ensure there is an issue tracking your work. + +2. Fork the repo. + +3. Run the tests. We only take pull requests with passing tests. + +4. Add a test for your change. Only refactoring and documentation changes require no new tests. + +5. Make sure to check out the [Style Guide](#style-guide) and ensure that your code complies with the rules. + +6. Make sure you read our [GitHub processes](https://github.com/privacy-scaling-explorations/maci/discussions/847) documentation. + +7. Make the test pass. + +8. Commit your changes. + +9. Push to your fork and submit a pull request on our `dev` branch. Please provide us with some explanation of why you made the changes you made. For new features make sure to explain a standard use case to us. + +10. Link any issues that the PR is addressing as described in our processes documentation. + +## CI (Github Actions) Tests + +We use GitHub Actions to test each PR before it is merged. + +When you submit your PR (or later change that code), a CI build will automatically be kicked off. A note will be added to the PR, and will indicate the current status of the build. + +Please refer to our [testing guide](/docs/testing) for more details on how we run tests across the monorepo. + +## Style Guide + +### Code rules + +We always use ESLint and Prettier. To check that your code follows the rules, simply run the pnpm script `pnpm run lint` and `pnpm run prettier`. When committing, `eslint` is run automatically, so you will be required to fix any error before being able to push a commit. We highly recommend to tackle warnings as well. + +### Commits rules + +For commits it is recommended to use [Conventional Commits](https://www.conventionalcommits.org). You may install the [commitizen](https://commitizen-tools.github.io/commitizen/) tool to help you with this. + +Each commit message consists of a **header**, a **body** and a **footer**. The **header** has a special format that includes a **type**, a **scope** and a **subject**: + +``` + (): + + + +