@maci-protocol/circuits 0.0.0-ci.f433bba → 0.0.0-ci.f4e2c46

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 (58) hide show
  1. package/LICENSE +1 -2
  2. package/README.md +2 -2
  3. package/build/ts/{genZkeys.d.ts → generateZkeys.d.ts} +1 -1
  4. package/build/ts/generateZkeys.d.ts.map +1 -0
  5. package/build/ts/{genZkeys.js → generateZkeys.js} +1 -1
  6. package/build/ts/generateZkeys.js.map +1 -0
  7. package/build/ts/types.d.ts +13 -14
  8. package/build/ts/types.d.ts.map +1 -1
  9. package/build/tsconfig.build.tsbuildinfo +1 -1
  10. package/circom/circuits.json +35 -19
  11. package/circom/coordinator/full/MessageProcessor.circom +253 -0
  12. package/circom/coordinator/full/SingleMessageProcessor.circom +204 -0
  13. package/circom/coordinator/non-qv/MessageProcessor.circom +252 -0
  14. package/circom/coordinator/non-qv/SingleMessageProcessor.circom +200 -0
  15. package/circom/coordinator/non-qv/VoteTally.circom +162 -0
  16. package/circom/coordinator/qv/MessageProcessor.circom +250 -0
  17. package/circom/coordinator/qv/SingleMessageProcessor.circom +208 -0
  18. package/circom/coordinator/qv/VoteTally.circom +180 -0
  19. package/circom/utils/{calculateTotal.circom → CalculateTotal.circom} +8 -6
  20. package/circom/utils/{verifySignature.circom → EdDSAPoseidonVerifier.circom} +40 -66
  21. package/circom/utils/MessageHasher.circom +57 -0
  22. package/circom/utils/MessageToCommand.circom +107 -0
  23. package/circom/utils/PoseidonHasher.circom +29 -0
  24. package/circom/utils/{privToPubKey.circom → PrivateToPublicKey.circom} +12 -10
  25. package/circom/utils/VerifySignature.circom +39 -0
  26. package/circom/utils/full/MessageValidator.circom +91 -0
  27. package/circom/utils/full/StateLeafAndBallotTransformer.circom +122 -0
  28. package/circom/utils/non-qv/{messageValidator.circom → MessageValidator.circom} +17 -15
  29. package/circom/utils/non-qv/ResultCommitmentVerifier.circom +84 -0
  30. package/circom/utils/non-qv/{stateLeafAndBallotTransformer.circom → StateLeafAndBallotTransformer.circom} +36 -36
  31. package/circom/utils/qv/{messageValidator.circom → MessageValidator.circom} +17 -15
  32. package/circom/utils/qv/ResultCommitmentVerifier.circom +107 -0
  33. package/circom/utils/qv/{stateLeafAndBallotTransformer.circom → StateLeafAndBallotTransformer.circom} +36 -36
  34. package/circom/utils/trees/BinaryMerkleRoot.circom +62 -0
  35. package/circom/utils/trees/CheckRoot.circom +49 -0
  36. package/circom/utils/trees/LeafExists.circom +27 -0
  37. package/circom/utils/trees/MerklePathIndicesGenerator.circom +44 -0
  38. package/circom/utils/trees/MerkleTreeInclusionProof.circom +50 -0
  39. package/circom/utils/trees/QuinaryCheckRoot.circom +54 -0
  40. package/circom/utils/trees/QuinaryGeneratePathIndices.circom +44 -0
  41. package/circom/utils/trees/QuinaryLeafExists.circom +30 -0
  42. package/circom/utils/trees/QuinarySelector.circom +42 -0
  43. package/circom/utils/trees/QuinaryTreeInclusionProof.circom +55 -0
  44. package/circom/utils/trees/Splicer.circom +76 -0
  45. package/circom/voter/PollJoined.circom +43 -0
  46. package/circom/voter/PollJoining.circom +54 -0
  47. package/package.json +19 -16
  48. package/build/ts/genZkeys.d.ts.map +0 -1
  49. package/build/ts/genZkeys.js.map +0 -1
  50. package/circom/coordinator/non-qv/processMessages.circom +0 -447
  51. package/circom/coordinator/non-qv/tallyVotes.circom +0 -232
  52. package/circom/coordinator/qv/processMessages.circom +0 -449
  53. package/circom/coordinator/qv/tallyVotes.circom +0 -277
  54. package/circom/utils/hashers.circom +0 -78
  55. package/circom/utils/messageToCommand.circom +0 -78
  56. package/circom/utils/trees/incrementalMerkleTree.circom +0 -198
  57. package/circom/utils/trees/incrementalQuinaryTree.circom +0 -287
  58. package/circom/voter/poll.circom +0 -93
@@ -1,277 +0,0 @@
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/incrementalMerkleTree.circom";
9
- include "../../utils/trees/incrementalQuinaryTree.circom";
10
- include "../../utils/calculateTotal.circom";
11
- include "../../utils/hashers.circom";
12
-
13
- /**
14
- * Processes batches of votes and verifies their validity in a Merkle tree structure.
15
- * This template supports Quadratic Voting (QV).
16
- */
17
- template TallyVotes(
18
- stateTreeDepth,
19
- intStateTreeDepth,
20
- voteOptionTreeDepth
21
- ) {
22
- // Ensure there's at least one level in the vote option tree.
23
- assert(voteOptionTreeDepth > 0);
24
- // Ensure the intermediate state tree has at least one level.
25
- assert(intStateTreeDepth > 0);
26
- // The intermediate state tree must be smaller than the full state tree.
27
- assert(intStateTreeDepth < stateTreeDepth);
28
-
29
- // Number of children per node in the tree, defining the tree's branching factor.
30
- var TREE_ARITY = 5;
31
- var BALLOT_TREE_ARITY = 2;
32
-
33
- // The number of ballots processed at once, determined by the depth of the intermediate state tree.
34
- var batchSize = BALLOT_TREE_ARITY ** intStateTreeDepth;
35
- // Number of voting options available, determined by the depth of the vote option tree.
36
- var numVoteOptions = TREE_ARITY ** voteOptionTreeDepth;
37
-
38
- // Number of elements in each ballot.
39
- var BALLOT_LENGTH = 2;
40
- // Index for the nonce in the ballot array.
41
- var BALLOT_NONCE_IDX = 0;
42
- // Index for the voting option root in the ballot array.
43
- var BALLOT_VO_ROOT_IDX = 1;
44
- // Difference in tree depths, used in path calculations.
45
- var k = stateTreeDepth - intStateTreeDepth;
46
-
47
- // Root of the state Merkle tree, representing the overall state before voting.
48
- signal input stateRoot;
49
- // Root of the ballot Merkle tree, representing the submitted ballots.
50
- signal input ballotRoot;
51
- // Salt used in commitment to secure the ballot data.
52
- signal input sbSalt;
53
- // Commitment to the state and ballots.
54
- signal input sbCommitment;
55
- // Commitment to the current tally before this batch.
56
- signal input currentTallyCommitment;
57
- // Commitment to the new tally after processing this batch.
58
- signal input newTallyCommitment;
59
- // Start index of given batch
60
- signal input index;
61
- // Number of users that signup
62
- signal input numSignUps;
63
- // Ballots and their corresponding path elements for verification in the tree.
64
- signal input ballots[batchSize][BALLOT_LENGTH];
65
- signal input ballotPathElements[k][BALLOT_TREE_ARITY - 1];
66
- signal input votes[batchSize][numVoteOptions];
67
- // Current results for each vote option.
68
- signal input currentResults[numVoteOptions];
69
- // Salt for the root of the current results.
70
- signal input currentResultsRootSalt;
71
- // Total voice credits spent so far.
72
- signal input currentSpentVoiceCreditSubtotal;
73
- // Salt for the total spent voice credits.
74
- signal input currentSpentVoiceCreditSubtotalSalt;
75
- // Spent voice credits per vote option.
76
- signal input currentPerVOSpentVoiceCredits[numVoteOptions];
77
- // Salt for the root of spent credits per option.
78
- signal input currentPerVOSpentVoiceCreditsRootSalt;
79
- // Salt for the root of the new results.
80
- signal input newResultsRootSalt;
81
- // Salt for the new spent credits per vote option root.
82
- signal input newPerVOSpentVoiceCreditsRootSalt;
83
- // Salt for the new total spent voice credits root.
84
- signal input newSpentVoiceCreditSubtotalSalt;
85
-
86
- // Verify sbCommitment.
87
- var computedSbCommitment = PoseidonHasher(3)([stateRoot, ballotRoot, sbSalt]);
88
- computedSbCommitment === sbCommitment;
89
-
90
- // Validates that the index is within the valid range of sign-ups.
91
- var numSignUpsValid = LessEqThan(50)([index, numSignUps]);
92
- numSignUpsValid === 1;
93
-
94
- // Hashes each ballot for subroot generation, and checks the existence of the leaf in the Merkle tree.
95
- var computedBallotHashers[batchSize];
96
-
97
- for (var i = 0; i < batchSize; i++) {
98
- computedBallotHashers[i] = PoseidonHasher(2)([ballots[i][BALLOT_NONCE_IDX], ballots[i][BALLOT_VO_ROOT_IDX]]);
99
- }
100
-
101
- var computedBallotSubroot = CheckRoot(intStateTreeDepth)(computedBallotHashers);
102
- var computedBallotPathIndices[k] = MerkleGeneratePathIndices(k)(index / batchSize);
103
-
104
- // Verifies each ballot's existence within the ballot tree.
105
- LeafExists(k)(
106
- computedBallotSubroot,
107
- ballotPathElements,
108
- computedBallotPathIndices,
109
- ballotRoot
110
- );
111
-
112
- // Processes vote options, verifying each against its declared root.
113
- var computedVoteTree[batchSize];
114
- for (var i = 0; i < batchSize; i++) {
115
- computedVoteTree[i] = QuinCheckRoot(voteOptionTreeDepth)(votes[i]);
116
- computedVoteTree[i] === ballots[i][BALLOT_VO_ROOT_IDX];
117
- }
118
-
119
- // Calculates new results and spent voice credits based on the current and incoming votes.
120
- var computedIsFirstBatch = IsZero()(index);
121
- var computedIsZero = IsZero()(computedIsFirstBatch);
122
-
123
- // Tally the new results.
124
- var computedCalculateTotalResult[numVoteOptions];
125
- for (var i = 0; i < numVoteOptions; i++) {
126
- var numsRC[batchSize + 1];
127
- numsRC[batchSize] = currentResults[i] * computedIsZero;
128
- for (var j = 0; j < batchSize; j++) {
129
- numsRC[j] = votes[j][i];
130
- }
131
-
132
- computedCalculateTotalResult[i] = CalculateTotal(batchSize + 1)(numsRC);
133
- }
134
-
135
- // Tally the new spent voice credit total.
136
- var numsSVC[batchSize * numVoteOptions + 1];
137
- numsSVC[batchSize * numVoteOptions] = currentSpentVoiceCreditSubtotal * computedIsZero;
138
- for (var i = 0; i < batchSize; i++) {
139
- for (var j = 0; j < numVoteOptions; j++) {
140
- numsSVC[i * numVoteOptions + j] = votes[i][j] * votes[i][j];
141
- }
142
- }
143
-
144
- var computedNewSpentVoiceCreditSubtotal = CalculateTotal(batchSize * numVoteOptions + 1)(numsSVC);
145
-
146
- // Tally the spent voice credits per vote option.
147
- var computedNewPerVOSpentVoiceCredits[numVoteOptions];
148
-
149
- for (var i = 0; i < numVoteOptions; i++) {
150
- var computedNumsSVC[batchSize + 1];
151
- computedNumsSVC[batchSize] = currentPerVOSpentVoiceCredits[i] * computedIsZero;
152
- for (var j = 0; j < batchSize; j++) {
153
- computedNumsSVC[j] = votes[j][i] * votes[j][i];
154
- }
155
-
156
- computedNewPerVOSpentVoiceCredits[i] = CalculateTotal(batchSize + 1)(computedNumsSVC);
157
- }
158
-
159
- // Verifies the updated results and spent credits, ensuring consistency and correctness of tally updates.
160
- ResultCommitmentVerifier(voteOptionTreeDepth)(
161
- computedIsFirstBatch,
162
- currentTallyCommitment,
163
- newTallyCommitment,
164
- currentResults,
165
- currentResultsRootSalt,
166
- computedCalculateTotalResult,
167
- newResultsRootSalt,
168
- currentSpentVoiceCreditSubtotal,
169
- currentSpentVoiceCreditSubtotalSalt,
170
- computedNewSpentVoiceCreditSubtotal,
171
- newSpentVoiceCreditSubtotalSalt,
172
- currentPerVOSpentVoiceCredits,
173
- currentPerVOSpentVoiceCreditsRootSalt,
174
- computedNewPerVOSpentVoiceCredits,
175
- newPerVOSpentVoiceCreditsRootSalt
176
- );
177
- }
178
-
179
- /**
180
- * Performs verifications and computations related to current voting results.
181
- * Also, computes and outputs a commitment to the new results.
182
- * This template supports the Quadratic Voting (QV).
183
- */
184
- template ResultCommitmentVerifier(voteOptionTreeDepth) {
185
- // Number of children per node in the tree, defining the tree's branching factor.
186
- var TREE_ARITY = 5;
187
- // Number of voting options available, determined by the depth of the vote option tree.
188
- var numVoteOptions = TREE_ARITY ** voteOptionTreeDepth;
189
-
190
- // Equal to 1 if this is the first batch, otherwise 0.
191
- signal input isFirstBatch;
192
- // Commitment to the current tally before this batch.
193
- signal input currentTallyCommitment;
194
- // Commitment to the new tally after processing this batch.
195
- signal input newTallyCommitment;
196
-
197
- // Current results for each vote option.
198
- signal input currentResults[numVoteOptions];
199
- // Salt for the root of the current results.
200
- signal input currentResultsRootSalt;
201
-
202
- // New results for each vote option.
203
- signal input newResults[numVoteOptions];
204
- // Salt for the root of the new results.
205
- signal input newResultsRootSalt;
206
-
207
- // Total voice credits spent so far.
208
- signal input currentSpentVoiceCreditSubtotal;
209
- // Salt for the total spent voice credits.
210
- signal input currentSpentVoiceCreditSubtotalSalt;
211
-
212
- // Total new voice credits spent.
213
- signal input newSpentVoiceCreditSubtotal;
214
- // Salt for the new total spent voice credits.
215
- signal input newSpentVoiceCreditSubtotalSalt;
216
-
217
- // Spent voice credits per vote option.
218
- signal input currentPerVOSpentVoiceCredits[numVoteOptions];
219
- // Salt for the root of spent credits per option.
220
- signal input currentPerVOSpentVoiceCreditsRootSalt;
221
-
222
- // New spent voice credits per vote option.
223
- signal input newPerVOSpentVoiceCredits[numVoteOptions];
224
- // Salt for the root of new spent credits per option.
225
- signal input newPerVOSpentVoiceCreditsRootSalt;
226
-
227
- // Compute the commitment to the current results.
228
- var computedCurrentResultsRoot = QuinCheckRoot(voteOptionTreeDepth)(currentResults);
229
-
230
- // Verify currentResultsCommitmentHash.
231
- var computedCurrentResultsCommitment = PoseidonHasher(2)([computedCurrentResultsRoot, currentResultsRootSalt]);
232
-
233
- // Compute the commitment to the current spent voice credits.
234
- var computedCurrentSpentVoiceCreditsCommitment = PoseidonHasher(2)([currentSpentVoiceCreditSubtotal, currentSpentVoiceCreditSubtotalSalt]);
235
-
236
- // Compute the root of the spent voice credits per vote option.
237
- var computedCurrentPerVOSpentVoiceCreditsRoot = QuinCheckRoot(voteOptionTreeDepth)(currentPerVOSpentVoiceCredits);
238
- var computedCurrentPerVOSpentVoiceCreditsCommitment = PoseidonHasher(2)([computedCurrentPerVOSpentVoiceCreditsRoot, currentPerVOSpentVoiceCreditsRootSalt]);
239
-
240
- // Commit to the current tally.
241
- var computedCurrentTallyCommitment = PoseidonHasher(3)([
242
- computedCurrentResultsCommitment,
243
- computedCurrentSpentVoiceCreditsCommitment,
244
- computedCurrentPerVOSpentVoiceCreditsCommitment
245
- ]);
246
-
247
- // Check if the current tally commitment is correct only if this is not the first batch.
248
- // computedIsZero.out is 1 if this is not the first batch.
249
- // computedIsZero.out is 0 if this is the first batch.
250
- var computedIsZero = IsZero()(isFirstBatch);
251
-
252
- // hz is 0 if this is the first batch, currentTallyCommitment should be 0 if this is the first batch.
253
- // hz is 1 if this is not the first batch, currentTallyCommitment should not be 0 if this is the first batch.
254
- signal hz;
255
- hz <== computedIsZero * computedCurrentTallyCommitment;
256
- hz === currentTallyCommitment;
257
-
258
- // Compute the root of the new results.
259
- var computedNewResultsRoot = QuinCheckRoot(voteOptionTreeDepth)(newResults);
260
- var computedNewResultsCommitment = PoseidonHasher(2)([computedNewResultsRoot, newResultsRootSalt]);
261
-
262
- // Compute the commitment to the new spent voice credits value.
263
- var computedNewSpentVoiceCreditsCommitment = PoseidonHasher(2)([newSpentVoiceCreditSubtotal, newSpentVoiceCreditSubtotalSalt]);
264
-
265
- // Compute the root of the spent voice credits per vote option.
266
- var computedNewPerVOSpentVoiceCreditsRoot = QuinCheckRoot(voteOptionTreeDepth)(newPerVOSpentVoiceCredits);
267
- var computedNewPerVOSpentVoiceCreditsCommitment = PoseidonHasher(2)([computedNewPerVOSpentVoiceCreditsRoot, newPerVOSpentVoiceCreditsRootSalt]);
268
-
269
- // Commit to the new tally.
270
- var computedNewTallyCommitment = PoseidonHasher(3)([
271
- computedNewResultsCommitment,
272
- computedNewSpentVoiceCreditsCommitment,
273
- computedNewPerVOSpentVoiceCreditsCommitment
274
- ]);
275
-
276
- computedNewTallyCommitment === newTallyCommitment;
277
- }
@@ -1,78 +0,0 @@
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
- }
30
-
31
- /**
32
- * Hashes a MACI message and the public key used for message encryption.
33
- * This template processes 10 message inputs and a 2-element public key
34
- * combining them using the Poseidon hash function. The hashing process involves two stages:
35
- * 1. hashing message parts in groups of five and,
36
- * 2. hashing the grouped results alongside the first message input and
37
- * the encryption public key to produce a final hash output.
38
- */
39
- template MessageHasher() {
40
- // The MACI message is composed of 10 parts.
41
- signal input in[10];
42
- // the public key used to encrypt the message.
43
- signal input encPubKey[2];
44
- // we output an hash.
45
- signal output hash;
46
-
47
- // Hasher4(
48
- // Hasher5_1(in[1], in[2], in[3], in[4], in[5]),
49
- // Hasher5_2(in[6], in[7], in[8], in[9], in[10])
50
- // in[11],
51
- // in[12]
52
- // )
53
-
54
- var computedHasher5_1;
55
- computedHasher5_1 = PoseidonHasher(5)([
56
- in[0],
57
- in[1],
58
- in[2],
59
- in[3],
60
- in[4]
61
- ]);
62
-
63
- var computedHasher5_2;
64
- computedHasher5_2 = PoseidonHasher(5)([
65
- in[5],
66
- in[6],
67
- in[7],
68
- in[8],
69
- in[9]
70
- ]);
71
-
72
- hash <== PoseidonHasher(4)([
73
- computedHasher5_1,
74
- computedHasher5_2,
75
- encPubKey[0],
76
- encPubKey[1]
77
- ]);
78
- }
@@ -1,78 +0,0 @@
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
- // local imports
10
- include "./hashers.circom";
11
-
12
- /**
13
- * Converts a MACI message to a command by decrypting it.
14
- * Processes encrypted MACI messages into structured MACI commands
15
- * by decrypting using a shared key derived from ECDH. After decryption,
16
- * unpacks and assigns decrypted values to specific command components.
17
- */
18
- template MessageToCommand() {
19
- var MSG_LENGTH = 7;
20
- var PACKED_CMD_LENGTH = 4;
21
- var UNPACKED_CMD_LENGTH = 8;
22
- var UNPACK_ELEM_LENGTH = 5;
23
- var DECRYPTED_LENGTH = 9;
24
- var MESSAGE_PARTS = 10;
25
-
26
- // The message is an array of 10 parts.
27
- signal input message[MESSAGE_PARTS];
28
- signal input encPrivKey;
29
- signal input encPubKey[2];
30
-
31
- // Command parts.
32
- signal output stateIndex;
33
- signal output newPubKey[2];
34
- signal output voteOptionIndex;
35
- signal output newVoteWeight;
36
- signal output nonce;
37
- signal output pollId;
38
- signal output salt;
39
- signal output sigR8[2];
40
- signal output sigS;
41
- // Packed command.
42
- signal output packedCommandOut[PACKED_CMD_LENGTH];
43
-
44
- // Generate the shared key for decrypting the message.
45
- var computedEcdh[2] = Ecdh()(encPrivKey, encPubKey);
46
-
47
- // Decrypt the message using Poseidon decryption.
48
- var computedDecryptor[DECRYPTED_LENGTH] = PoseidonDecryptWithoutCheck(MSG_LENGTH)(
49
- message,
50
- 0,
51
- computedEcdh
52
- );
53
-
54
- // Save the decrypted message into a packed command signal.
55
- signal packedCommand[PACKED_CMD_LENGTH];
56
- for (var i = 0; i < PACKED_CMD_LENGTH; i++) {
57
- packedCommand[i] <== computedDecryptor[i];
58
- }
59
-
60
- var computedUnpackElement[UNPACK_ELEM_LENGTH] = UnpackElement(UNPACK_ELEM_LENGTH)(packedCommand[0]);
61
-
62
- // Everything below were packed into the first element.
63
- stateIndex <== computedUnpackElement[4];
64
- voteOptionIndex <== computedUnpackElement[3];
65
- newVoteWeight <== computedUnpackElement[2];
66
- nonce <== computedUnpackElement[1];
67
- pollId <== computedUnpackElement[0];
68
-
69
- newPubKey[0] <== packedCommand[1];
70
- newPubKey[1] <== packedCommand[2];
71
- salt <== packedCommand[3];
72
-
73
- sigR8[0] <== computedDecryptor[4];
74
- sigR8[1] <== computedDecryptor[5];
75
- sigS <== computedDecryptor[6];
76
-
77
- packedCommandOut <== packedCommand;
78
- }
@@ -1,198 +0,0 @@
1
- pragma circom 2.0.0;
2
-
3
- // zk-kit imports
4
- include "./safe-comparators.circom";
5
- // circomlib import
6
- include "./mux1.circom";
7
- include "./comparators.circom";
8
- // local import
9
- include "../hashers.circom";
10
- include "../calculateTotal.circom";
11
-
12
- /**
13
- * Recomputes a Merkle root from a given leaf and its path in a Merkle tree.
14
- */
15
- template MerkleTreeInclusionProof(n_levels) {
16
- // The leaf node from which the Merkle root is calculated.
17
- signal input leaf;
18
- // Indices indicating left or right child for each level of the tree.
19
- signal input path_index[n_levels];
20
- // Sibling node values required to compute the hash at each level.
21
- signal input path_elements[n_levels][1];
22
-
23
- signal output root;
24
-
25
- // Stores the hash at each level starting from the leaf to the root.
26
- signal levelHashes[n_levels + 1];
27
- // Initialize the first level with the given leaf.
28
- levelHashes[0] <== leaf;
29
-
30
- for (var i = 0; i < n_levels; i++) {
31
- // Validate path_index to be either 0 or 1, ensuring no other values.
32
- path_index[i] * (1 - path_index[i]) === 0;
33
-
34
- // Configure the multiplexer based on the path index for the current level.
35
- var c[2][2] = [
36
- [levelHashes[i], path_elements[i][0]],
37
- [path_elements[i][0], levelHashes[i]]
38
- ];
39
-
40
- var mux[2] = MultiMux1(2)(
41
- c,
42
- path_index[i]
43
- );
44
-
45
- var computedLevelHash = PoseidonHasher(2)([mux[0], mux[1]]);
46
-
47
- // Store the resulting hash as the next level's hash.
48
- levelHashes[i + 1] <== computedLevelHash;
49
- }
50
-
51
- // Set the final level hash as the root.
52
- root <== levelHashes[n_levels];
53
- }
54
-
55
- /**
56
- * Ensures that a leaf exists within a Merkle tree with a given root.
57
- */
58
- template LeafExists(levels){
59
- // The leaf whose existence within the tree is being verified.
60
- signal input leaf;
61
-
62
- // The elements along the path needed for the inclusion proof.
63
- signal input path_elements[levels][1];
64
- // The indices indicating the path taken through the tree for the leaf.
65
- signal input path_index[levels];
66
- // The root of the Merkle tree, against which the inclusion is verified.
67
- signal input root;
68
-
69
- var computedMerkleRoot = MerkleTreeInclusionProof(levels)(
70
- leaf,
71
- path_index,
72
- path_elements
73
- );
74
-
75
- root === computedMerkleRoot;
76
- }
77
-
78
- /**
79
- * Verifies the correct construction of a Merkle tree from a set of leaves.
80
- * Given a Merkle root and a list of leaves, check if the root is the
81
- * correct result of inserting all the leaves into the tree (in the given order).
82
- */
83
- template CheckRoot(levels) {
84
- // The total number of leaves in the Merkle tree, calculated as 2 to the power of `levels`.
85
- var totalLeaves = 2 ** levels;
86
- // The number of first-level hashers needed, equal to half the total leaves, as each hasher combines two leaves.
87
- var numLeafHashers = totalLeaves / 2;
88
- // The number of intermediate hashers, one less than the number of leaf hashers,
89
- // as each level of hashing reduces the number of hash elements by about half.
90
- var numIntermediateHashers = numLeafHashers - 1;
91
-
92
- // Array of leaf values input to the circuit.
93
- signal input leaves[totalLeaves];
94
-
95
- // Output signal for the Merkle root that results from hashing all the input leaves.
96
- signal output root;
97
-
98
- // Total number of hashers used in constructing the tree, one less than the total number of leaves,
99
- // since each level of the tree combines two elements into one.
100
- var numHashers = totalLeaves - 1;
101
- var computedLevelHashers[numHashers];
102
-
103
- // Initialize hashers for the leaves, each taking two adjacent leaves as inputs.
104
- for (var i = 0; i < numLeafHashers; i++){
105
- computedLevelHashers[i] = PoseidonHasher(2)([leaves[i*2], leaves[i*2+1]]);
106
- }
107
-
108
- // Initialize hashers for intermediate levels, each taking the outputs of two hashers from the previous level.
109
- var k = 0;
110
- for (var i = numLeafHashers; i < numLeafHashers + numIntermediateHashers; i++) {
111
- computedLevelHashers[i] = PoseidonHasher(2)([computedLevelHashers[k*2], computedLevelHashers[k*2+1]]);
112
- k++;
113
- }
114
-
115
- // Connect the output of the final hasher in the array to the root output signal.
116
- root <== computedLevelHashers[numHashers-1];
117
- }
118
-
119
- /**
120
- * Calculates the path indices required for Merkle proof verifications.
121
- * Given a node index within an IMT and the total tree levels, it outputs the path indices leading to that node.
122
- * The template handles the modulo and division operations to break down the tree index into its constituent path indices.
123
- */
124
- template MerkleGeneratePathIndices(levels) {
125
- var BASE = 2;
126
-
127
- signal input in;
128
- signal output out[levels];
129
-
130
- var m = in;
131
- var computedResults[levels];
132
-
133
- for (var i = 0; i < levels; i++) {
134
- // circom's best practices suggests to avoid using <-- unless you
135
- // are aware of what's going on. This is the only way to do modulo operation.
136
- out[i] <-- m % BASE;
137
- m = m \ BASE;
138
-
139
- // Check that each output element is less than the base.
140
- var computedIsOutputElementLessThanBase = SafeLessThan(3)([out[i], BASE]);
141
- computedIsOutputElementLessThanBase === 1;
142
-
143
- // Re-compute the total sum.
144
- computedResults[i] = out[i] * (BASE ** i);
145
- }
146
-
147
- // Check that the total sum matches the index.
148
- var computedCalculateTotal = CalculateTotal(levels)(computedResults);
149
-
150
- computedCalculateTotal === in;
151
- }
152
-
153
- // @note taken from @zk-kit/circuits
154
- // if used directly in processMessages circom complains about duplicated
155
- // templates (Ark, Poseidon, etc.)
156
- // This circuit is designed to calculate the root of a binary Merkle
157
- // tree given a leaf, its depth, and the necessary sibling
158
- // information (aka proof of membership).
159
- // A circuit is designed without the capability to iterate through
160
- // a dynamic array. To address this, a parameter with the static maximum
161
- // tree depth is defined (i.e. 'MAX_DEPTH'). And additionally, the circuit
162
- // receives a dynamic depth as an input, which is utilized in calculating the
163
- // true root of the Merkle tree. The actual depth of the Merkle tree
164
- // may be equal to or less than the static maximum depth.
165
- // NOTE: This circuit will successfully verify `out = 0` for `depth > MAX_DEPTH`.
166
- // Make sure to enforce `depth <= MAX_DEPTH` outside the circuit.
167
- template BinaryMerkleRoot(MAX_DEPTH) {
168
- signal input leaf, depth, indices[MAX_DEPTH], siblings[MAX_DEPTH][1];
169
-
170
- signal output out;
171
-
172
- signal nodes[MAX_DEPTH + 1];
173
- nodes[0] <== leaf;
174
-
175
- signal roots[MAX_DEPTH];
176
- var root = 0;
177
-
178
- for (var i = 0; i < MAX_DEPTH; i++) {
179
- var isDepth = IsEqual()([depth, i]);
180
-
181
- roots[i] <== isDepth * nodes[i];
182
-
183
- root += roots[i];
184
-
185
- var c[2][2] = [
186
- [nodes[i], siblings[i][0]],
187
- [siblings[i][0], nodes[i]]
188
- ];
189
-
190
- var childNodes[2] = MultiMux1(2)(c, indices[i]);
191
-
192
- nodes[i + 1] <== PoseidonHasher(2)(childNodes);
193
- }
194
-
195
- var isDepth = IsEqual()([depth, MAX_DEPTH]);
196
-
197
- out <== root + isDepth * nodes[MAX_DEPTH];
198
- }