@maci-protocol/circuits 0.0.0-ci.00107eb

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 (59) hide show
  1. package/CHANGELOG.md +673 -0
  2. package/LICENSE +21 -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/generateZkeys.d.ts +9 -0
  9. package/build/ts/generateZkeys.d.ts.map +1 -0
  10. package/build/ts/generateZkeys.js +67 -0
  11. package/build/ts/generateZkeys.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 +74 -0
  22. package/circom/coordinator/full/MessageProcessor.circom +253 -0
  23. package/circom/coordinator/full/SingleMessageProcessor.circom +203 -0
  24. package/circom/coordinator/non-qv/MessageProcessor.circom +252 -0
  25. package/circom/coordinator/non-qv/SingleMessageProcessor.circom +199 -0
  26. package/circom/coordinator/non-qv/VoteTally.circom +161 -0
  27. package/circom/coordinator/qv/MessageProcessor.circom +250 -0
  28. package/circom/coordinator/qv/SingleMessageProcessor.circom +207 -0
  29. package/circom/coordinator/qv/VoteTally.circom +179 -0
  30. package/circom/coordinator/qv/VoteTallyWithIndividualCounts.circom +226 -0
  31. package/circom/utils/CalculateTotal.circom +24 -0
  32. package/circom/utils/EdDSAPoseidonVerifier.circom +91 -0
  33. package/circom/utils/MessageHasher.circom +57 -0
  34. package/circom/utils/MessageToCommand.circom +107 -0
  35. package/circom/utils/PoseidonHasher.circom +29 -0
  36. package/circom/utils/PrivateToPublicKey.circom +38 -0
  37. package/circom/utils/VerifySignature.circom +39 -0
  38. package/circom/utils/full/MessageValidator.circom +91 -0
  39. package/circom/utils/full/StateLeafAndBallotTransformer.circom +122 -0
  40. package/circom/utils/non-qv/MessageValidator.circom +91 -0
  41. package/circom/utils/non-qv/ResultCommitmentVerifier.circom +84 -0
  42. package/circom/utils/non-qv/StateLeafAndBallotTransformer.circom +105 -0
  43. package/circom/utils/qv/MessageValidator.circom +97 -0
  44. package/circom/utils/qv/ResultCommitmentVerifier.circom +107 -0
  45. package/circom/utils/qv/StateLeafAndBallotTransformer.circom +105 -0
  46. package/circom/utils/trees/BinaryMerkleRoot.circom +65 -0
  47. package/circom/utils/trees/CheckRoot.circom +49 -0
  48. package/circom/utils/trees/LeafExists.circom +27 -0
  49. package/circom/utils/trees/MerkleTreeInclusionProof.circom +50 -0
  50. package/circom/utils/trees/QuinaryCheckRoot.circom +54 -0
  51. package/circom/utils/trees/QuinaryGeneratePathIndices.circom +44 -0
  52. package/circom/utils/trees/QuinaryLeafExists.circom +30 -0
  53. package/circom/utils/trees/QuinarySelector.circom +42 -0
  54. package/circom/utils/trees/QuinaryTreeInclusionProof.circom +55 -0
  55. package/circom/utils/trees/Splicer.circom +76 -0
  56. package/circom/voter/PollJoined.circom +43 -0
  57. package/circom/voter/PollJoining.circom +54 -0
  58. package/circomkit.json +18 -0
  59. package/package.json +74 -0
@@ -0,0 +1,226 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./comparators.circom";
5
+ // zk-kit import
6
+ include "./unpack-element.circom";
7
+ // local imports
8
+ include "../../utils/trees/CheckRoot.circom";
9
+ include "../../utils/trees/LeafExists.circom";
10
+ include "../../utils/trees/QuinaryCheckRoot.circom";
11
+ include "../../utils/qv/ResultCommitmentVerifier.circom";
12
+ include "../../utils/CalculateTotal.circom";
13
+ include "../../utils/PoseidonHasher.circom";
14
+
15
+ /**
16
+ * Processes batches of votes and verifies their validity in a Merkle tree structure.
17
+ * This template supports Quadratic Voting (QV) with individual vote counting.
18
+ * Note: this circuit is not using right now, this is a part of individual vote counts functionality.
19
+ * Not finished yet, don't use it in production. It is kept here for future use.
20
+ */
21
+ template VoteTallyWithIndividualCountsQv(
22
+ stateTreeDepth,
23
+ tallyProcessingStateTreeDepth,
24
+ voteOptionTreeDepth
25
+ ) {
26
+ // Ensure there's at least one level in the vote option tree.
27
+ assert(voteOptionTreeDepth > 0);
28
+ // Ensure the intermediate state tree has at least one level.
29
+ assert(tallyProcessingStateTreeDepth > 0);
30
+ // The intermediate state tree must be smaller than the full state tree.
31
+ assert(tallyProcessingStateTreeDepth < stateTreeDepth);
32
+
33
+ // Number of children per node in the tree, defining the tree's branching factor.
34
+ var TREE_ARITY = 5;
35
+ var BALLOT_TREE_ARITY = 2;
36
+ var VOTE_COUNTS_TREE_ARITY = 2;
37
+
38
+ // The number of ballots processed at once, determined by the depth of the intermediate state tree.
39
+ var ballotBatchSize = BALLOT_TREE_ARITY ** tallyProcessingStateTreeDepth;
40
+ var voteCountsBatchSize = VOTE_COUNTS_TREE_ARITY ** tallyProcessingStateTreeDepth;
41
+ // Number of voting options available, determined by the depth of the vote option tree.
42
+ var totalVoteOptions = TREE_ARITY ** voteOptionTreeDepth;
43
+
44
+ // Number of elements in each ballot.
45
+ var BALLOT_LENGTH = 2;
46
+ // Index for the nonce in the ballot array.
47
+ var BALLOT_NONCE_INDEX = 0;
48
+ // Index for the voting option root in the ballot array.
49
+ var BALLOT_VOTE_OPTION_ROOT_INDEX = 1;
50
+ // Difference in tree depths, used in path calculations.
51
+ var STATE_TREE_DEPTH_DIFFERENCE = stateTreeDepth - tallyProcessingStateTreeDepth;
52
+ // Number of elements in each vote count leaf.
53
+ var VOTE_COUNTS_LENGTH = 2;
54
+ // Index for the voting option index.
55
+ var VOTE_COUNTS_NONCE_INDEX = 0;
56
+ // Index for root of the vote count per option.
57
+ var VOTE_COUNTS_ROOT_INDEX = 1;
58
+
59
+ // Root of the state Merkle tree, representing the overall state before voting.
60
+ signal input stateRoot;
61
+ // Root of the ballot Merkle tree, representing the submitted ballots.
62
+ signal input ballotRoot;
63
+ // Root of the vote counts Merkle tree, representing the counts of votes for each option.
64
+ signal input voteCountsRoot;
65
+ // Salt used in commitment to secure the ballot data.
66
+ signal input sbSalt;
67
+ // Commitment to the state and ballots.
68
+ signal input sbCommitment;
69
+ // Commitment to the current tally before this batch.
70
+ signal input currentTallyCommitment;
71
+ // Commitment to the new tally after processing this batch.
72
+ signal input newTallyCommitment;
73
+ // Start index of given batch
74
+ signal input index;
75
+ // Number of users that signup
76
+ signal input totalSignups;
77
+ // Ballots and their corresponding path elements for verification in the tree.
78
+ signal input ballots[ballotBatchSize][BALLOT_LENGTH];
79
+ signal input ballotPathElements[STATE_TREE_DEPTH_DIFFERENCE][BALLOT_TREE_ARITY - 1];
80
+ signal input votes[ballotBatchSize][totalVoteOptions];
81
+ // Individual vote count tree and their corresponding path elements for verification in the tree.
82
+ signal input voteCounts[voteCountsBatchSize][VOTE_COUNTS_LENGTH];
83
+ signal input voteCountsPathElements[STATE_TREE_DEPTH_DIFFERENCE][VOTE_COUNTS_TREE_ARITY - 1];
84
+ signal input voteCountsData[voteCountsBatchSize][totalVoteOptions];
85
+ // Current results for each vote option.
86
+ signal input currentResults[totalVoteOptions];
87
+ // Salt for the root of the current results.
88
+ signal input currentResultsRootSalt;
89
+ // Total voice credits spent so far.
90
+ signal input currentSpentVoiceCreditSubtotal;
91
+ // Salt for the total spent voice credits.
92
+ signal input currentSpentVoiceCreditSubtotalSalt;
93
+ // Spent voice credits per vote option.
94
+ signal input currentPerVoteOptionSpentVoiceCredits[totalVoteOptions];
95
+ // Salt for the root of spent credits per option.
96
+ signal input currentPerVoteOptionSpentVoiceCreditsRootSalt;
97
+ // Salt for the root of the new results.
98
+ signal input newResultsRootSalt;
99
+ // Salt for the new spent credits per vote option root.
100
+ signal input newPerVoteOptionSpentVoiceCreditsRootSalt;
101
+ // Salt for the new total spent voice credits root.
102
+ signal input newSpentVoiceCreditSubtotalSalt;
103
+
104
+ // Verify sbCommitment.
105
+ var computedSbCommitment = PoseidonHasher(3)([stateRoot, ballotRoot, sbSalt]);
106
+ computedSbCommitment === sbCommitment;
107
+
108
+ // Validates that the index is within the valid range of sign-ups.
109
+ var totalSignupsValid = LessEqThan(50)([index, totalSignups]);
110
+ totalSignupsValid === 1;
111
+
112
+ // Hashes each ballot for subroot generation, and checks the existence of the leaf in the Merkle tree.
113
+ var computedBallotHashers[ballotBatchSize];
114
+ var computedVoteCountsHashers[voteCountsBatchSize];
115
+
116
+ for (var i = 0; i < ballotBatchSize; i++) {
117
+ computedBallotHashers[i] = PoseidonHasher(2)([
118
+ ballots[i][BALLOT_NONCE_INDEX],
119
+ ballots[i][BALLOT_VOTE_OPTION_ROOT_INDEX]
120
+ ]);
121
+ }
122
+
123
+ for (var i = 0; i < voteCountsBatchSize; i++) {
124
+ computedVoteCountsHashers[i] = PoseidonHasher(2)([
125
+ voteCounts[i][VOTE_COUNTS_NONCE_INDEX],
126
+ voteCounts[i][VOTE_COUNTS_ROOT_INDEX]
127
+ ]);
128
+ }
129
+
130
+ var computedBallotSubroot = CheckRoot(tallyProcessingStateTreeDepth)(computedBallotHashers);
131
+ var computedBallotPathIndices[STATE_TREE_DEPTH_DIFFERENCE] = Num2Bits(STATE_TREE_DEPTH_DIFFERENCE)(index / ballotBatchSize);
132
+
133
+ var computedVoteCountsSubroot = CheckRoot(tallyProcessingStateTreeDepth)(computedVoteCountsHashers);
134
+ var computedVoteCountsPathIndices[STATE_TREE_DEPTH_DIFFERENCE] = Num2Bits(STATE_TREE_DEPTH_DIFFERENCE)(index / voteCountsBatchSize);
135
+
136
+ // Verifies each ballot's existence within the ballot tree.
137
+ LeafExists(STATE_TREE_DEPTH_DIFFERENCE)(
138
+ computedBallotSubroot,
139
+ ballotPathElements,
140
+ computedBallotPathIndices,
141
+ ballotRoot
142
+ );
143
+
144
+ // Verifies each vote count's existence within the vote count tree.
145
+ LeafExists(STATE_TREE_DEPTH_DIFFERENCE)(
146
+ computedVoteCountsSubroot,
147
+ voteCountsPathElements,
148
+ computedVoteCountsPathIndices,
149
+ voteCountsRoot
150
+ );
151
+
152
+ // Processes vote options, verifying each against its declared root.
153
+ var computedVoteTree[ballotBatchSize];
154
+
155
+ for (var i = 0; i < ballotBatchSize; i++) {
156
+ computedVoteTree[i] = QuinaryCheckRoot(voteOptionTreeDepth)(votes[i]);
157
+ computedVoteTree[i] === ballots[i][BALLOT_VOTE_OPTION_ROOT_INDEX];
158
+ }
159
+
160
+ // Processes vote counts, verifying each against its declared root.
161
+ var computedVoteCountsTree[voteCountsBatchSize];
162
+
163
+ for (var i = 0; i < voteCountsBatchSize; i++) {
164
+ computedVoteCountsTree[i] = QuinaryCheckRoot(voteOptionTreeDepth)(voteCountsData[i]);
165
+ computedVoteCountsTree[i] === voteCounts[i][VOTE_COUNTS_ROOT_INDEX];
166
+ }
167
+
168
+ // Calculates new results and spent voice credits based on the current and incoming votes.
169
+ var computedIsFirstBatch = IsZero()(index);
170
+ var computedIsZero = IsZero()(computedIsFirstBatch);
171
+
172
+ // Tally the new results.
173
+ var computedCalculateTotalResult[totalVoteOptions];
174
+ for (var i = 0; i < totalVoteOptions; i++) {
175
+ var numsRC[ballotBatchSize + 1];
176
+ numsRC[ballotBatchSize] = currentResults[i] * computedIsZero;
177
+ for (var j = 0; j < ballotBatchSize; j++) {
178
+ numsRC[j] = votes[j][i];
179
+ }
180
+
181
+ computedCalculateTotalResult[i] = CalculateTotal(ballotBatchSize + 1)(numsRC);
182
+ }
183
+
184
+ // Tally the new spent voice credit total.
185
+ var numsSVC[ballotBatchSize * totalVoteOptions + 1];
186
+ numsSVC[ballotBatchSize * totalVoteOptions] = currentSpentVoiceCreditSubtotal * computedIsZero;
187
+ for (var i = 0; i < ballotBatchSize; i++) {
188
+ for (var j = 0; j < totalVoteOptions; j++) {
189
+ numsSVC[i * totalVoteOptions + j] = votes[i][j] * votes[i][j];
190
+ }
191
+ }
192
+
193
+ var computedNewSpentVoiceCreditSubtotal = CalculateTotal(ballotBatchSize * totalVoteOptions + 1)(numsSVC);
194
+
195
+ // Tally the spent voice credits per vote option.
196
+ var computedNewPerVOSpentVoiceCredits[totalVoteOptions];
197
+
198
+ for (var i = 0; i < totalVoteOptions; i++) {
199
+ var computedTotalVoiceCreditSpent[ballotBatchSize + 1];
200
+ computedTotalVoiceCreditSpent[ballotBatchSize] = currentPerVoteOptionSpentVoiceCredits[i] * computedIsZero;
201
+ for (var j = 0; j < ballotBatchSize; j++) {
202
+ computedTotalVoiceCreditSpent[j] = votes[j][i] * votes[j][i];
203
+ }
204
+
205
+ computedNewPerVOSpentVoiceCredits[i] = CalculateTotal(ballotBatchSize + 1)(computedTotalVoiceCreditSpent);
206
+ }
207
+
208
+ // Verifies the updated results and spent credits, ensuring consistency and correctness of tally updates.
209
+ ResultCommitmentVerifierQv(voteOptionTreeDepth)(
210
+ computedIsFirstBatch,
211
+ currentTallyCommitment,
212
+ newTallyCommitment,
213
+ currentResults,
214
+ currentResultsRootSalt,
215
+ computedCalculateTotalResult,
216
+ newResultsRootSalt,
217
+ currentSpentVoiceCreditSubtotal,
218
+ currentSpentVoiceCreditSubtotalSalt,
219
+ computedNewSpentVoiceCreditSubtotal,
220
+ newSpentVoiceCreditSubtotalSalt,
221
+ currentPerVoteOptionSpentVoiceCredits,
222
+ currentPerVoteOptionSpentVoiceCreditsRootSalt,
223
+ computedNewPerVOSpentVoiceCredits,
224
+ newPerVoteOptionSpentVoiceCreditsRootSalt
225
+ );
226
+ }
@@ -0,0 +1,24 @@
1
+ pragma circom 2.0.0;
2
+
3
+ /**
4
+ * Computes the cumulative sum of an array of length input signals.
5
+ * It iterates through each input, aggregating the sum up to that point,
6
+ * and outputs the total sum of all inputs. This template is useful for
7
+ * operations requiring the total sum of multiple signals, ensuring the
8
+ * final output reflects the cumulative total of the inputs provided.
9
+ */
10
+ template CalculateTotal(length) {
11
+ // Array of values.
12
+ signal input nums[length];
13
+ // Total sum.
14
+ signal output sum;
15
+
16
+ signal sums[length];
17
+ sums[0] <== nums[0];
18
+
19
+ for (var i = 1; i < length; i++) {
20
+ sums[i] <== sums[i - 1] + nums[i];
21
+ }
22
+
23
+ sum <== sums[length - 1];
24
+ }
@@ -0,0 +1,91 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib imports
4
+ include "./compconstant.circom";
5
+ include "./comparators.circom";
6
+ include "./pointbits.circom";
7
+ include "./bitify.circom";
8
+ include "./escalarmulany.circom";
9
+ include "./escalarmulfix.circom";
10
+ // local imports
11
+ include "./PoseidonHasher.circom";
12
+
13
+ /**
14
+ * Variant of the EdDSAPoseidonVerifier template from circomlib
15
+ * https://github.com/iden3/circomlib/blob/master/circuits/eddsa.circom
16
+ */
17
+ template EdDSAPoseidonVerifier() {
18
+ // The prime subgroup order.
19
+ var SUBGROUP_ORDER = 2736030358979909402780800718157159386076813972158567259200215660948447373041;
20
+
21
+ // The base point of the BabyJubJub curve.
22
+ var BASE8[2] = [
23
+ 5299619240641551281634865583518297030282874472190772894086521144482721001553,
24
+ 16950150798460657717958625567821834550301663161624707787222815936182638968203
25
+ ];
26
+
27
+ // The x and y coordinates of the public key.
28
+ signal input publicKeyX;
29
+ signal input publicKeyY;
30
+ // Signature scalar.
31
+ signal input signatureScalar;
32
+ // The x and y coordinates of the signature point.
33
+ signal input signaturePointX;
34
+ signal input signaturePointY;
35
+ // Message hash.
36
+ signal input messageHash;
37
+ // Output signal for the validity of the signature.
38
+ signal output isValid;
39
+
40
+ // Ensure signatureScalar<Subgroup Order.
41
+ // convert the signature scalar signatureScalar into its binary representation.
42
+ var computedNum2Bits[254] = Num2Bits(254)(signatureScalar);
43
+
44
+ var computedCompConstantIn[254] = computedNum2Bits;
45
+ computedCompConstantIn[253] = 0;
46
+
47
+ // A component that ensures signatureScalar is within a valid range,
48
+ // comparing it against a constant representing the subgroup order.
49
+ var computedCompConstant = CompConstant(SUBGROUP_ORDER - 1)(computedCompConstantIn);
50
+
51
+ // Calculate the h = H(R, A, msg).
52
+ var computedH2Bits[254] = Num2Bits_strict()(PoseidonHasher(5)([
53
+ signaturePointX,
54
+ signaturePointY,
55
+ publicKeyX,
56
+ publicKeyY,
57
+ messageHash
58
+ ]));
59
+
60
+ // These components perform point doubling operations on the public key
61
+ // to align it within the correct subgroup as part of the verification process.
62
+ var (computedDouble1XOut, computedDouble1YOut) = BabyDbl()(publicKeyX, publicKeyY);
63
+ var (computedDouble2XOut, computedDouble2YOut) = BabyDbl()(computedDouble1XOut, computedDouble1YOut);
64
+ var (computedDouble3XOut, computedDouble3YOut) = BabyDbl()(computedDouble2XOut, computedDouble2YOut);
65
+
66
+ // A component that performs scalar multiplication of the
67
+ // adjusted public key by the hash output, essential for the verification calculation.
68
+ var computedEscalarMulAny[2] = EscalarMulAny(254)(computedH2Bits, [computedDouble3XOut, computedDouble3YOut]);
69
+
70
+ // Compute the right side: right = R8 + right2.
71
+ var (computedAddRightXOut, computedAddRightYOut) = BabyAdd()(signaturePointX, signaturePointY, computedEscalarMulAny[0], computedEscalarMulAny[1]);
72
+
73
+ // Fixed-base scalar multiplication of a base point by signatureScalar.
74
+ var computedEscalarMulFix[2] = EscalarMulFix(254, BASE8)(computedNum2Bits);
75
+
76
+ // Components to check the equality of x and y coordinates
77
+ // between the computed and expected points of the signature.
78
+ var computedIsRightValid = IsEqual()([computedEscalarMulFix[0], computedAddRightXOut]);
79
+ var computedIsLeftValid = IsEqual()([computedEscalarMulFix[1], computedAddRightYOut]);
80
+ var computedIsLeftRightValid = IsEqual()([computedIsRightValid + computedIsLeftValid, 2]);
81
+
82
+ // Components to handle edge cases and ensure that all conditions
83
+ // for a valid signature are met, including the
84
+ // public key not being zero and other integrity checks.
85
+ var computedIsAxZero = IsZero()(publicKeyX);
86
+ var computedIsAxEqual = IsEqual()([computedIsAxZero, 0]);
87
+ var computedIsCcZero = IsZero()(computedCompConstant);
88
+ var computedIsValid = IsEqual()([computedIsLeftRightValid + computedIsAxEqual + computedIsCcZero, 3]);
89
+
90
+ isValid <== computedIsValid;
91
+ }
@@ -0,0 +1,57 @@
1
+ pragma circom 2.0.0;
2
+
3
+ include "./PoseidonHasher.circom";
4
+
5
+ /**
6
+ * Hashes a MACI message and the public key used for message encryption.
7
+ * This template processes 10 message inputs and a 2-element public key
8
+ * combining them using the Poseidon hash function. The hashing process involves two stages:
9
+ * 1. hashing message parts data groups of five and,
10
+ * 2. hashing the grouped results alongside the first message input and
11
+ * the encryption public key to produce a final hash output.
12
+ */
13
+ template MessageHasher() {
14
+ // Message parts
15
+ var MESSAGE_PARTS = 10;
16
+ var STATE_INDEX = 0;
17
+ var VOTE_OPTION_INDEX = 1;
18
+ var NEW_VOTE_WEIGHT = 2;
19
+ var NONCE = 3;
20
+ var POLL_ID = 4;
21
+ var SIGNATURE_POINT_X = 5;
22
+ var SIGNATURE_POINT_Y = 6;
23
+ var SIGNATURE_SCALAR = 7;
24
+ var ENCRYPTED_PUBLIC_KEY_X = 8;
25
+ var ENCRYPTED_PUBLIC_KEY_Y = 9;
26
+
27
+ // The MACI message is composed of 10 parts.
28
+ signal input data[MESSAGE_PARTS];
29
+ // the public key used to encrypt the message.
30
+ signal input encryptionPublicKey[2];
31
+
32
+ // we output an hash.
33
+ signal output hash;
34
+
35
+ var computedHasherPart1 = PoseidonHasher(5)([
36
+ data[STATE_INDEX],
37
+ data[VOTE_OPTION_INDEX],
38
+ data[NEW_VOTE_WEIGHT],
39
+ data[NONCE],
40
+ data[POLL_ID]
41
+ ]);
42
+
43
+ var computedHasherPart2 = PoseidonHasher(5)([
44
+ data[SIGNATURE_POINT_X],
45
+ data[SIGNATURE_POINT_Y],
46
+ data[SIGNATURE_SCALAR],
47
+ data[ENCRYPTED_PUBLIC_KEY_X],
48
+ data[ENCRYPTED_PUBLIC_KEY_Y]
49
+ ]);
50
+
51
+ hash <== PoseidonHasher(4)([
52
+ computedHasherPart1,
53
+ computedHasherPart2,
54
+ encryptionPublicKey[0],
55
+ encryptionPublicKey[1]
56
+ ]);
57
+ }
@@ -0,0 +1,107 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./bitify.circom";
5
+ // zk-kit imports
6
+ include "./ecdh.circom";
7
+ include "./unpack-element.circom";
8
+ include "./poseidon-cipher.circom";
9
+
10
+ /**
11
+ * Converts a MACI message to a command by decrypting it.
12
+ * Processes encrypted MACI messages into structured MACI commands
13
+ * by decrypting using a shared key derived from ECDH. After decryption,
14
+ * unpacks and assigns decrypted values to specific command components.
15
+ */
16
+ template MessageToCommand() {
17
+ var MESSAGE_LENGTH = 7;
18
+ var PACKED_COMMAND_LENGTH = 4;
19
+ var UNPACK_ELEMENT_LENGTH = 5;
20
+ var DECRYPTED_LENGTH = 9;
21
+ var MESSAGE_PARTS = 10;
22
+
23
+ // Element indices.
24
+ var ELEMENT_POLL_ID = 0;
25
+ var ELEMENT_NONCE = 1;
26
+ var ELEMENT_NEW_VOTE_WEIGHT = 2;
27
+ var ELEMENT_VOTE_OPTION_INDEX = 3;
28
+ var ELEMENT_STATE_INDEX = 4;
29
+
30
+ // Command indices.
31
+ var COMMAND_STATE_INDEX = 0;
32
+ var COMMAND_PUBLIC_KEY_X = 1;
33
+ var COMMAND_PUBLIC_KEY_Y = 2;
34
+ var COMMAND_SALT = 3;
35
+
36
+ // Decryptor indices.
37
+ var SIGNATURE_POINT_X = 4;
38
+ var SIGNATURE_POINT_Y = 5;
39
+ var SIGNATURE_SCALAR = 6;
40
+
41
+ // The message is an array of 10 parts.
42
+ signal input message[MESSAGE_PARTS];
43
+ // The encryption private key
44
+ signal input encryptionPrivateKey;
45
+ // The encryption public key
46
+ signal input encryptionPublicKey[2];
47
+
48
+ // Command parts.
49
+ signal output stateIndex;
50
+ // The new public key.
51
+ signal output newPublicKey[2];
52
+ // The vote option index.
53
+ signal output voteOptionIndex;
54
+ // The new vote weight.
55
+ signal output newVoteWeight;
56
+ // The nonce.
57
+ signal output nonce;
58
+ // The poll id.
59
+ signal output pollId;
60
+ // The salt.
61
+ signal output salt;
62
+ // The signature point.
63
+ signal output signaturePoint[2];
64
+ // The signature scalar.
65
+ signal output signatureScalar;
66
+
67
+ // Packed command.
68
+ signal output packedCommandOut[PACKED_COMMAND_LENGTH];
69
+
70
+ // Generate the shared key for decrypting the message.
71
+ var computedEcdh[2] = Ecdh()(encryptionPrivateKey, encryptionPublicKey);
72
+
73
+ // Decrypt the message using Poseidon decryption.
74
+ var computedDecryptor[DECRYPTED_LENGTH] = PoseidonDecryptWithoutCheck(MESSAGE_LENGTH)(
75
+ message,
76
+ 0,
77
+ computedEcdh
78
+ );
79
+
80
+ // Save the decrypted message into a packed command signal.
81
+ signal packedCommand[PACKED_COMMAND_LENGTH];
82
+
83
+ for (var i = 0; i < PACKED_COMMAND_LENGTH; i++) {
84
+ packedCommand[i] <== computedDecryptor[i];
85
+ }
86
+
87
+ var computedUnpackElement[UNPACK_ELEMENT_LENGTH] = UnpackElement(UNPACK_ELEMENT_LENGTH)(
88
+ packedCommand[COMMAND_STATE_INDEX]
89
+ );
90
+
91
+ // Everything below were packed into the first element.
92
+ pollId <== computedUnpackElement[ELEMENT_POLL_ID];
93
+ nonce <== computedUnpackElement[ELEMENT_NONCE];
94
+ newVoteWeight <== computedUnpackElement[ELEMENT_NEW_VOTE_WEIGHT];
95
+ voteOptionIndex <== computedUnpackElement[ELEMENT_VOTE_OPTION_INDEX];
96
+ stateIndex <== computedUnpackElement[ELEMENT_STATE_INDEX];
97
+
98
+ newPublicKey[0] <== packedCommand[COMMAND_PUBLIC_KEY_X];
99
+ newPublicKey[1] <== packedCommand[COMMAND_PUBLIC_KEY_Y];
100
+ salt <== packedCommand[COMMAND_SALT];
101
+
102
+ signaturePoint[0] <== computedDecryptor[SIGNATURE_POINT_X];
103
+ signaturePoint[1] <== computedDecryptor[SIGNATURE_POINT_Y];
104
+ signatureScalar <== computedDecryptor[SIGNATURE_SCALAR];
105
+
106
+ packedCommandOut <== packedCommand;
107
+ }
@@ -0,0 +1,29 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // zk-kit imports
4
+ include "./poseidon-cipher.circom";
5
+
6
+ /**
7
+ * Computes the Poseidon hash for an array of n inputs, including a default initial state
8
+ * of zero not counted in n. First, extends the inputs by prepending a zero, creating an array [0, inputs].
9
+ * Then, the Poseidon hash of the extended inputs is calculated, with the first element of the
10
+ * result assigned as the output.
11
+ */
12
+ template PoseidonHasher(n) {
13
+ signal input inputs[n];
14
+ signal output out;
15
+
16
+ // [0, inputs].
17
+ var computedExtendedInputs[n + 1];
18
+ computedExtendedInputs[0] = 0;
19
+
20
+ for (var i = 0; i < n; i++) {
21
+ computedExtendedInputs[i + 1] = inputs[i];
22
+ }
23
+
24
+ // Compute the Poseidon hash of the extended inputs.
25
+ var computedPoseidonPerm[n + 1];
26
+ computedPoseidonPerm = PoseidonPerm(n + 1)(computedExtendedInputs);
27
+
28
+ out <== computedPoseidonPerm[0];
29
+ }
@@ -0,0 +1,38 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib imports
4
+ include "./bitify.circom";
5
+ include "./comparators.circom";
6
+ include "./escalarmulfix.circom";
7
+
8
+ /**
9
+ * Converts a private key to a public key on the BabyJubJub curve.
10
+ * The input private key needs to be hashed and then pruned before.
11
+ */
12
+ template PrivateToPublicKey() {
13
+ // The base point of the BabyJubJub curve.
14
+ var BASE8[2] = [
15
+ 5299619240641551281634865583518297030282874472190772894086521144482721001553,
16
+ 16950150798460657717958625567821834550301663161624707787222815936182638968203
17
+ ];
18
+
19
+ // The prime subgroup order.
20
+ var SUBGROUP_ORDER = 2736030358979909402780800718157159386076813972158567259200215660948447373041;
21
+
22
+ // The private key
23
+ signal input privateKey;
24
+ // The public key
25
+ signal output publicKey[2];
26
+
27
+ // Check if private key is in the prime subgroup order
28
+ var isLessThan = LessThan(251)([privateKey, SUBGROUP_ORDER]);
29
+ isLessThan === 1;
30
+
31
+ // Convert the private key to bits.
32
+ var computedPrivateBits[253] = Num2Bits(253)(privateKey);
33
+
34
+ // Perform scalar multiplication with the basepoint.
35
+ var computedPublicKey[2] = EscalarMulFix(253, BASE8)(computedPrivateBits);
36
+
37
+ publicKey <== computedPublicKey;
38
+ }
@@ -0,0 +1,39 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local imports
4
+ include "./EdDSAPoseidonVerifier.circom";
5
+ include "./PoseidonHasher.circom";
6
+
7
+ /**
8
+ * Verifies the EdDSA signature for a given command, which has exactly four elements in the hash preimage.
9
+ */
10
+ template VerifySignature() {
11
+ // Number of elements in the hash preimage.
12
+ var PRE_IMAGE_LENGTH = 4;
13
+
14
+ // Public key of the signer, consisting of two coordinates [x, y].
15
+ signal input publicKey[2];
16
+ // signaturePoint point from the signature, consisting of two coordinates [x, y].
17
+ signal input signaturePoint[2];
18
+ // Scalar component of the signature.
19
+ signal input signatureScalar;
20
+ // The preimage data that was hashed, an array of four elements.
21
+ signal input preimage[PRE_IMAGE_LENGTH];
22
+ // The validity of the signature.
23
+ signal output isValid;
24
+
25
+ // Hash the preimage using the Poseidon hashing function configured for four inputs.
26
+ var computedPreimage = PoseidonHasher(4)(preimage);
27
+
28
+ // Instantiate the patched EdDSA Poseidon verifier with the necessary inputs.
29
+ var computedIsValid = EdDSAPoseidonVerifier()(
30
+ publicKey[0],
31
+ publicKey[1],
32
+ signatureScalar,
33
+ signaturePoint[0],
34
+ signaturePoint[1],
35
+ computedPreimage
36
+ );
37
+
38
+ isValid <== computedIsValid;
39
+ }