@maci-protocol/circuits 0.0.0-ci.044d30d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +673 -0
  2. package/LICENSE +22 -0
  3. package/README.md +20 -0
  4. package/build/ts/compile.d.ts +10 -0
  5. package/build/ts/compile.d.ts.map +1 -0
  6. package/build/ts/compile.js +123 -0
  7. package/build/ts/compile.js.map +1 -0
  8. package/build/ts/genZkeys.d.ts +9 -0
  9. package/build/ts/genZkeys.d.ts.map +1 -0
  10. package/build/ts/genZkeys.js +67 -0
  11. package/build/ts/genZkeys.js.map +1 -0
  12. package/build/ts/info.d.ts +2 -0
  13. package/build/ts/info.d.ts.map +1 -0
  14. package/build/ts/info.js +72 -0
  15. package/build/ts/info.js.map +1 -0
  16. package/build/ts/types.d.ts +104 -0
  17. package/build/ts/types.d.ts.map +1 -0
  18. package/build/ts/types.js +3 -0
  19. package/build/ts/types.js.map +1 -0
  20. package/build/tsconfig.build.tsbuildinfo +1 -0
  21. package/circom/circuits.json +58 -0
  22. package/circom/coordinator/non-qv/processMessages.circom +449 -0
  23. package/circom/coordinator/non-qv/tallyVotes.circom +235 -0
  24. package/circom/coordinator/qv/processMessages.circom +451 -0
  25. package/circom/coordinator/qv/tallyVotes.circom +279 -0
  26. package/circom/utils/calculateTotal.circom +22 -0
  27. package/circom/utils/hashers.circom +78 -0
  28. package/circom/utils/messageToCommand.circom +78 -0
  29. package/circom/utils/non-qv/messageValidator.circom +89 -0
  30. package/circom/utils/non-qv/stateLeafAndBallotTransformer.circom +105 -0
  31. package/circom/utils/privToPubKey.circom +36 -0
  32. package/circom/utils/qv/messageValidator.circom +95 -0
  33. package/circom/utils/qv/stateLeafAndBallotTransformer.circom +105 -0
  34. package/circom/utils/trees/BinaryMerkleRoot.circom +54 -0
  35. package/circom/utils/trees/CheckRoot.circom +45 -0
  36. package/circom/utils/trees/LeafExists.circom +27 -0
  37. package/circom/utils/trees/MerkleGeneratePathIndices.circom +40 -0
  38. package/circom/utils/trees/MerkleTreeInclusionProof.circom +49 -0
  39. package/circom/utils/trees/incrementalQuinaryTree.circom +287 -0
  40. package/circom/utils/verifySignature.circom +117 -0
  41. package/circom/voter/poll.circom +92 -0
  42. package/circomkit.json +18 -0
  43. package/package.json +71 -0
@@ -0,0 +1,95 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // zk-kit imports
4
+ include "./safe-comparators.circom";
5
+ // local imports
6
+ include "../verifySignature.circom";
7
+
8
+ /**
9
+ * Checks if a MACI message is valid or not.
10
+ * This template supports the Quadratic Voting (QV).
11
+ */
12
+ template MessageValidator() {
13
+ // Length of the packed command.
14
+ var PACKED_CMD_LENGTH = 4;
15
+
16
+ // State index of the user.
17
+ signal input stateTreeIndex;
18
+ // Number of user sign-ups in the state tree.
19
+ signal input numSignUps;
20
+ // Vote option index.
21
+ signal input voteOptionIndex;
22
+ // Number of valid vote options for the poll.
23
+ signal input voteOptions;
24
+ // Ballot nonce.
25
+ signal input originalNonce;
26
+ // Command nonce.
27
+ signal input nonce;
28
+ // Packed command.
29
+ signal input cmd[PACKED_CMD_LENGTH];
30
+ // Public key of the state leaf (user).
31
+ signal input pubKey[2];
32
+ // ECDSA signature of the command (R part).
33
+ signal input sigR8[2];
34
+ // ECDSA signature of the command (S part).
35
+ signal input sigS;
36
+ // State leaf current voice credit balance.
37
+ signal input currentVoiceCreditBalance;
38
+ // Current number of votes for specific option.
39
+ signal input currentVotesForOption;
40
+ // Vote weight.
41
+ signal input voteWeight;
42
+
43
+ // True when the command is valid; otherwise false.
44
+ signal output isValid;
45
+ // True if the state leaf index is valid
46
+ signal output isStateLeafIndexValid;
47
+ // True if the vote option index is valid
48
+ signal output isVoteOptionIndexValid;
49
+
50
+ // Check (1) - The state leaf index must be valid.
51
+ // The check ensure that the stateTreeIndex < numSignUps as first validation.
52
+ // Must be < because the stateTreeIndex is 0-based. Zero is for blank state leaf
53
+ // while 1 is for the first actual user.
54
+ var computedIsStateLeafIndexValid = SafeLessThan(252)([stateTreeIndex, numSignUps]);
55
+
56
+ // Check (2) - The vote option index must be less than the number of valid vote options (0 indexed).
57
+ var computedIsVoteOptionIndexValid = SafeLessThan(252)([voteOptionIndex, voteOptions]);
58
+
59
+ // Check (3) - The nonce must be correct.
60
+ var computedIsNonceValid = IsEqual()([originalNonce + 1, nonce]);
61
+
62
+ // Check (4) - The signature must be correct.
63
+ var computedIsSignatureValid = VerifySignature()(pubKey, sigR8, sigS, cmd);
64
+
65
+ // Check (5) - There must be sufficient voice credits.
66
+ // The check ensure that the voteWeight is < sqrt(field size)
67
+ // so that voteWeight ^ 2 will not overflow.
68
+ var computedIsVoteWeightValid = SafeLessEqThan(252)([voteWeight, 147946756881789319005730692170996259609]);
69
+
70
+ // Check (6) - Check the current voice credit balance.
71
+ // The check ensure that currentVoiceCreditBalance + (currentVotesForOption ** 2) >= (voteWeight ** 2)
72
+ var computedAreVoiceCreditsSufficient = SafeGreaterEqThan(252)(
73
+ [
74
+ (currentVotesForOption * currentVotesForOption) + currentVoiceCreditBalance,
75
+ voteWeight * voteWeight
76
+ ]
77
+ );
78
+
79
+ // When all six checks are correct, then isValid = 1.
80
+ var computedIsUpdateValid = IsEqual()(
81
+ [
82
+ 6,
83
+ computedIsSignatureValid +
84
+ computedAreVoiceCreditsSufficient +
85
+ computedIsVoteWeightValid +
86
+ computedIsNonceValid +
87
+ computedIsStateLeafIndexValid +
88
+ computedIsVoteOptionIndexValid
89
+ ]
90
+ );
91
+
92
+ isValid <== computedIsUpdateValid;
93
+ isStateLeafIndexValid <== computedIsStateLeafIndexValid;
94
+ isVoteOptionIndexValid <== computedIsVoteOptionIndexValid;
95
+ }
@@ -0,0 +1,105 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./mux1.circom";
5
+ // local import
6
+ include "./messageValidator.circom";
7
+
8
+ /**
9
+ * Processes a command by verifying its validity and updates the state leaf and ballot accordingly.
10
+ * If the message is correct, updates the public key in the state leaf and the nonce
11
+ * in the ballot using multiplexer components.
12
+ * This template supports the Quadratic Voting (QV).
13
+ */
14
+ template StateLeafAndBallotTransformer() {
15
+ // Length of the packed command.
16
+ var PACKED_CMD_LENGTH = 4;
17
+
18
+ // Number of user sign-ups in the state tree.
19
+ signal input numSignUps;
20
+ // Number of valid vote options for the poll.
21
+ signal input voteOptions;
22
+
23
+ // The following signals represents a state leaf (signed up user).
24
+ // Public key.
25
+ signal input slPubKey[2];
26
+ // Current voice credit balance.
27
+ signal input slVoiceCreditBalance;
28
+
29
+ // The following signals represents a ballot.
30
+ // Nonce.
31
+ signal input ballotNonce;
32
+ // Current number of votes for specific option.
33
+ signal input ballotCurrentVotesForOption;
34
+
35
+ // The following signals represents a command.
36
+ // State index of the user.
37
+ signal input cmdStateIndex;
38
+ // Public key of the user.
39
+ signal input cmdNewPubKey[2];
40
+ // Vote option index.
41
+ signal input cmdVoteOptionIndex;
42
+ // Vote weight.
43
+ signal input cmdNewVoteWeight;
44
+ // Nonce.
45
+ signal input cmdNonce;
46
+ // Poll identifier.
47
+ signal input cmdPollId;
48
+ // Salt.
49
+ signal input cmdSalt;
50
+ // ECDSA signature of the command (R part).
51
+ signal input cmdSigR8[2];
52
+ // ECDSA signature of the command (S part).
53
+ signal input cmdSigS;
54
+ // Packed command.
55
+ // nb. we are assuming that the packedCommand is always valid.
56
+ signal input packedCommand[PACKED_CMD_LENGTH];
57
+
58
+ // New state leaf (if the command is valid).
59
+ signal output newSlPubKey[2];
60
+ // New ballot (if the command is valid).
61
+ signal output newBallotNonce;
62
+
63
+ // True when the command is valid; otherwise false.
64
+ signal output isValid;
65
+ // True if the state leaf index is valid
66
+ signal output isStateLeafIndexValid;
67
+ // True if the vote option index is valid
68
+ signal output isVoteOptionIndexValid;
69
+
70
+ // Check if the command / message is valid.
71
+ var (computedMessageValidator, computedIsStateLeafIndexValid, computedIsVoteOptionIndexValid) = MessageValidator()(
72
+ cmdStateIndex,
73
+ numSignUps,
74
+ cmdVoteOptionIndex,
75
+ voteOptions,
76
+ ballotNonce,
77
+ cmdNonce,
78
+ packedCommand,
79
+ slPubKey,
80
+ cmdSigR8,
81
+ cmdSigS,
82
+ slVoiceCreditBalance,
83
+ ballotCurrentVotesForOption,
84
+ cmdNewVoteWeight
85
+ );
86
+
87
+ // If the message is valid then we swap out the public key.
88
+ // This means using a Mux1() for pubKey[0] and another one
89
+ // for pubKey[1].
90
+ var computedNewSlPubKey0Mux = Mux1()([slPubKey[0], cmdNewPubKey[0]], computedMessageValidator);
91
+ var computedNewSlPubKey1Mux = Mux1()([slPubKey[1], cmdNewPubKey[1]], computedMessageValidator);
92
+
93
+ newSlPubKey[0] <== computedNewSlPubKey0Mux;
94
+ newSlPubKey[1] <== computedNewSlPubKey1Mux;
95
+
96
+ // If the message is valid, then we swap out the ballot nonce
97
+ // using a Mux1().
98
+ var computedNewBallotNonceMux = Mux1()([ballotNonce, cmdNonce], computedMessageValidator);
99
+
100
+ newBallotNonce <== computedNewBallotNonceMux;
101
+
102
+ isValid <== computedMessageValidator;
103
+ isStateLeafIndexValid <== computedIsStateLeafIndexValid;
104
+ isVoteOptionIndexValid <== computedIsVoteOptionIndexValid;
105
+ }
@@ -0,0 +1,54 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./mux1.circom";
5
+ include "./comparators.circom";
6
+ // local import
7
+ include "../hashers.circom";
8
+
9
+ // @note taken from @zk-kit/circuits
10
+ // if used directly in processMessages circom complains about duplicated
11
+ // templates (Ark, Poseidon, etc.)
12
+ // This circuit is designed to calculate the root of a binary Merkle
13
+ // tree given a leaf, its depth, and the necessary sibling
14
+ // information (aka proof of membership).
15
+ // A circuit is designed without the capability to iterate through
16
+ // a dynamic array. To address this, a parameter with the static maximum
17
+ // tree depth is defined (i.e. 'MAX_DEPTH'). And additionally, the circuit
18
+ // receives a dynamic depth as an input, which is utilized in calculating the
19
+ // true root of the Merkle tree. The actual depth of the Merkle tree
20
+ // may be equal to or less than the static maximum depth.
21
+ // NOTE: This circuit will successfully verify `out = 0` for `depth > MAX_DEPTH`.
22
+ // Make sure to enforce `depth <= MAX_DEPTH` outside the circuit.
23
+ template BinaryMerkleRoot(MAX_DEPTH) {
24
+ signal input leaf, depth, indices[MAX_DEPTH], siblings[MAX_DEPTH][1];
25
+
26
+ signal output out;
27
+
28
+ signal nodes[MAX_DEPTH + 1];
29
+ nodes[0] <== leaf;
30
+
31
+ signal roots[MAX_DEPTH];
32
+ var root = 0;
33
+
34
+ for (var i = 0; i < MAX_DEPTH; i++) {
35
+ var isDepth = IsEqual()([depth, i]);
36
+
37
+ roots[i] <== isDepth * nodes[i];
38
+
39
+ root += roots[i];
40
+
41
+ var c[2][2] = [
42
+ [nodes[i], siblings[i][0]],
43
+ [siblings[i][0], nodes[i]]
44
+ ];
45
+
46
+ var childNodes[2] = MultiMux1(2)(c, indices[i]);
47
+
48
+ nodes[i + 1] <== PoseidonHasher(2)(childNodes);
49
+ }
50
+
51
+ var isDepth = IsEqual()([depth, MAX_DEPTH]);
52
+
53
+ out <== root + isDepth * nodes[MAX_DEPTH];
54
+ }
@@ -0,0 +1,45 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local import
4
+ include "../hashers.circom";
5
+
6
+ /**
7
+ * Verifies the correct construction of a Merkle tree from a set of leaves.
8
+ * Given a Merkle root and a list of leaves, check if the root is the
9
+ * correct result of inserting all the leaves into the tree (in the given order).
10
+ */
11
+ template CheckRoot(levels) {
12
+ // The total number of leaves in the Merkle tree, calculated as 2 to the power of `levels`.
13
+ var totalLeaves = 2 ** levels;
14
+ // The number of first-level hashers needed, equal to half the total leaves, as each hasher combines two leaves.
15
+ var numLeafHashers = totalLeaves / 2;
16
+ // The number of intermediate hashers, one less than the number of leaf hashers,
17
+ // as each level of hashing reduces the number of hash elements by about half.
18
+ var numIntermediateHashers = numLeafHashers - 1;
19
+
20
+ // Array of leaf values input to the circuit.
21
+ signal input leaves[totalLeaves];
22
+
23
+ // Output signal for the Merkle root that results from hashing all the input leaves.
24
+ signal output root;
25
+
26
+ // Total number of hashers used in constructing the tree, one less than the total number of leaves,
27
+ // since each level of the tree combines two elements into one.
28
+ var numHashers = totalLeaves - 1;
29
+ var computedLevelHashers[numHashers];
30
+
31
+ // Initialize hashers for the leaves, each taking two adjacent leaves as inputs.
32
+ for (var i = 0; i < numLeafHashers; i++){
33
+ computedLevelHashers[i] = PoseidonHasher(2)([leaves[i*2], leaves[i*2+1]]);
34
+ }
35
+
36
+ // Initialize hashers for intermediate levels, each taking the outputs of two hashers from the previous level.
37
+ var k = 0;
38
+ for (var i = numLeafHashers; i < numLeafHashers + numIntermediateHashers; i++) {
39
+ computedLevelHashers[i] = PoseidonHasher(2)([computedLevelHashers[k*2], computedLevelHashers[k*2+1]]);
40
+ k++;
41
+ }
42
+
43
+ // Connect the output of the final hasher in the array to the root output signal.
44
+ root <== computedLevelHashers[numHashers-1];
45
+ }
@@ -0,0 +1,27 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local import
4
+ include "./MerkleTreeInclusionProof.circom";
5
+
6
+ /**
7
+ * Ensures that a leaf exists within a Merkle tree with a given root.
8
+ */
9
+ template LeafExists(levels){
10
+ // The leaf whose existence within the tree is being verified.
11
+ signal input leaf;
12
+
13
+ // The elements along the path needed for the inclusion proof.
14
+ signal input path_elements[levels][1];
15
+ // The indices indicating the path taken through the tree for the leaf.
16
+ signal input path_index[levels];
17
+ // The root of the Merkle tree, against which the inclusion is verified.
18
+ signal input root;
19
+
20
+ var computedMerkleRoot = MerkleTreeInclusionProof(levels)(
21
+ leaf,
22
+ path_index,
23
+ path_elements
24
+ );
25
+
26
+ root === computedMerkleRoot;
27
+ }
@@ -0,0 +1,40 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // zk-kit imports
4
+ include "./safe-comparators.circom";
5
+ // local import
6
+ include "../calculateTotal.circom";
7
+
8
+ /**
9
+ * Calculates the path indices required for Merkle proof verifications.
10
+ * Given a node index within an IMT and the total tree levels, it outputs the path indices leading to that node.
11
+ * The template handles the modulo and division operations to break down the tree index into its constituent path indices.
12
+ */
13
+ template MerkleGeneratePathIndices(levels) {
14
+ var BASE = 2;
15
+
16
+ signal input in;
17
+ signal output out[levels];
18
+
19
+ var m = in;
20
+ var computedResults[levels];
21
+
22
+ for (var i = 0; i < levels; i++) {
23
+ // circom's best practices suggests to avoid using <-- unless you
24
+ // are aware of what's going on. This is the only way to do modulo operation.
25
+ out[i] <-- m % BASE;
26
+ m = m \ BASE;
27
+
28
+ // Check that each output element is less than the base.
29
+ var computedIsOutputElementLessThanBase = SafeLessThan(3)([out[i], BASE]);
30
+ computedIsOutputElementLessThanBase === 1;
31
+
32
+ // Re-compute the total sum.
33
+ computedResults[i] = out[i] * (BASE ** i);
34
+ }
35
+
36
+ // Check that the total sum matches the index.
37
+ var computedCalculateTotal = CalculateTotal(levels)(computedResults);
38
+
39
+ computedCalculateTotal === in;
40
+ }
@@ -0,0 +1,49 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./mux1.circom";
5
+ // local import
6
+ include "../hashers.circom";
7
+
8
+ /**
9
+ * Recomputes a Merkle root from a given leaf and its path in a Merkle tree.
10
+ */
11
+ template MerkleTreeInclusionProof(n_levels) {
12
+ // The leaf node from which the Merkle root is calculated.
13
+ signal input leaf;
14
+ // Indices indicating left or right child for each level of the tree.
15
+ signal input path_index[n_levels];
16
+ // Sibling node values required to compute the hash at each level.
17
+ signal input path_elements[n_levels][1];
18
+
19
+ signal output root;
20
+
21
+ // Stores the hash at each level starting from the leaf to the root.
22
+ signal levelHashes[n_levels + 1];
23
+ // Initialize the first level with the given leaf.
24
+ levelHashes[0] <== leaf;
25
+
26
+ for (var i = 0; i < n_levels; i++) {
27
+ // Validate path_index to be either 0 or 1, ensuring no other values.
28
+ path_index[i] * (1 - path_index[i]) === 0;
29
+
30
+ // Configure the multiplexer based on the path index for the current level.
31
+ var c[2][2] = [
32
+ [levelHashes[i], path_elements[i][0]],
33
+ [path_elements[i][0], levelHashes[i]]
34
+ ];
35
+
36
+ var mux[2] = MultiMux1(2)(
37
+ c,
38
+ path_index[i]
39
+ );
40
+
41
+ var computedLevelHash = PoseidonHasher(2)([mux[0], mux[1]]);
42
+
43
+ // Store the resulting hash as the next level's hash.
44
+ levelHashes[i + 1] <== computedLevelHash;
45
+ }
46
+
47
+ // Set the final level hash as the root.
48
+ root <== levelHashes[n_levels];
49
+ }