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:
ProcessMessages.circom
, which takes a batch of encrypted messages, decrypts them, and generates a proof that the coordinator's local processing was performed correctly.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 ).
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, 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 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?
How do the circuits work?
Message processing (processMessages
)
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.
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 signups. |
1 | Message tree depth | Allows votes or key-change messages. |
2 | Message batch tree depth | Allows messages to be processed per batch. |
3 | Vote option tree depth | Allows 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 | |
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 :
packedVals
coordinatorPubKeyHash
msgRoot
currentSbCommitment
newSbCommitment
pollEndTimestamp
The hash is computed using the sha256
Solidity function and is then subject to modulo .
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 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
- That the prover knows the preimage to
inputHash
(see above) - That the prover knows the preimage to
currentSbCommitment
(that is, the state root, ballot root, andcurrentSbSalt
) - That
maxVoteOptions <= (5 ^ voteOptionTreeDepth)
- That
numSignUps <= (5 ^ stateTreeDepth)
- That
coordPubKey
is correctly derived fromcoordPrivKey
- That
coordPubKey
is the preimage to the Poseidon hash ofcoordPubKey
(provided by the contract) - That each message in
msgs
exists in the message tree - 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 tonewSbCommitment
Tally Votes (tallyVotes
)
Parameters
# | Parameter | Description |
---|---|---|
0 | State tree depth | Allows signups. |
1 | State leaf batch depth | Allows users' votes to be processed per batch. |
2 | Vote option tree depth | Allows vote options. |
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 :
packedVals
sbCommitment
currentTallyCommitment
newTallyCommitment
The hash is computed using the sha256
Solidity function and is then subject to modulo .
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). 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
:
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 hash of:
- : a commitment to the votes per option
- This is the hash of the Merkle root of the votes and a salt , computed as
- : a commitment to the total spent voice credits
- This is the hash of the total spent voice credits and a salt , computed as
- : 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 and a salt , computed as
The tally commitment is computed as such:
Statements that the circuit proves
- That the coordinator knows the preimage of
sbCommitment
- That the coordinator knows the preimage of
inputHash
- That
batchStartIndex
is less than or equal tonumSignUps
- That each ballot in
ballots
is in a member of the ballot tree with the Merkle rootballotRoot
at indicesbatchStartIndex
tobatchStartIndex + (5 ** intStateTreeDepth)
- That each set of votes (
votes[i]
) has the Merkle root whose value equalsballots[i][1]
- 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.
It outputs one field element, which is the SHA256 hash of the following inputs:
packedVals
pollEndTimestamp
msgRoot
coordinatorPubKeyHash
newSbCommitment
currentSbCommitment
Tally Votes Input Hasher
A utility template that generates a sha256 hash of the provided tally inputs.
It outputs one field element, which is the SHA256 hash of the following inputs:
packedVals
sbCommitment
currentTallyCommitment
newTallyCommitment
ResultsCommitmentVerifier
A utility circuit used by the main tallyVotes
circuit to verify that the results commitment is correct.
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.
CalculateTotal
Utility circuit used to calculate the sum of an array of elements.
ECDH
Utility circuit used to generate a shared key from a private key and a public key.
Poseidon
Utility circuit used to generate a Poseidon hash. In this case, it supports up to 13 inputs.
MessageToCommand
Utility circuit used to convert a message into a command, this involves decrypting the message.
MessageValidator
Utility circuit used to validate a message. This performs several checks:
stateTreeIndex
is validvoteOptionIndex
is validnonce
is valid- the signature is valid
- the user signed up before poll end timestamp
- the user had enough voice credits
PrivToPubKey
Utility circuit used to generate a public key from a private key.
VerifySignature
Utility circuit used to verify a EdDSA signature
UnpackElement
Utility circuit used to unpack an input element.
QuinSelector
Utility circuit used to select one element from an array of n elements at a given index.
Splicer
Utility circuit used to insert one element in an array at position index
.
QuinBatchLeavesExists
Utility circuit used to check if a batch of leaves exists in a quinary tree.
QuinGeneratePathIndices
Utility circuit used to generate the indices needed to traverse the tree until we find the leaf we are looking for.
ProcessTopup
Utility circuit used to process a topup message.
ProcessOne
Utility circuit used to process one message.
Compile circuits
Prerequisites
Before building the project, make sure you have the following dependencies installed:
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 -- --out-path $OUT_PATH
pnpm build-test-circuits-wasm -- --out-path $OUT_PATH
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 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:
pnpm setup:zkeys -- --outPath ../cli/zkeys
Run from the circuits folder with --outPath
to save to a custom folder:
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 to5
(as ).
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:
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.
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
.
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 theprocessMessages
circuit.pnpm run test:tallyVotes
to run the tests for thetallyVotes
circuit.
More details on testing are provided in the testing section of the documentation.