@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,107 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./comparators.circom";
5
+ // local imports
6
+ include "../trees/QuinaryCheckRoot.circom";
7
+ include "../PoseidonHasher.circom";
8
+
9
+ /**
10
+ * Performs verifications and computations related to current voting results.
11
+ * Also, computes and outputs a commitment to the new results.
12
+ * This template supports the Quadratic Voting (QV).
13
+ */
14
+ template ResultCommitmentVerifierQv(voteOptionTreeDepth) {
15
+ // Number of children per node in the tree, defining the tree's branching factor.
16
+ var TREE_ARITY = 5;
17
+ // Number of voting options available, determined by the depth of the vote option tree.
18
+ var totalVoteOptions = TREE_ARITY ** voteOptionTreeDepth;
19
+
20
+ // Equal to 1 if this is the first batch, otherwise 0.
21
+ signal input isFirstBatch;
22
+ // Commitment to the current tally before this batch.
23
+ signal input currentTallyCommitment;
24
+ // Commitment to the new tally after processing this batch.
25
+ signal input newTallyCommitment;
26
+
27
+ // Current results for each vote option.
28
+ signal input currentResults[totalVoteOptions];
29
+ // Salt for the root of the current results.
30
+ signal input currentResultsRootSalt;
31
+
32
+ // New results for each vote option.
33
+ signal input newResults[totalVoteOptions];
34
+ // Salt for the root of the new results.
35
+ signal input newResultsRootSalt;
36
+
37
+ // Total voice credits spent so far.
38
+ signal input currentSpentVoiceCreditSubtotal;
39
+ // Salt for the total spent voice credits.
40
+ signal input currentSpentVoiceCreditSubtotalSalt;
41
+
42
+ // Total new voice credits spent.
43
+ signal input newSpentVoiceCreditSubtotal;
44
+ // Salt for the new total spent voice credits.
45
+ signal input newSpentVoiceCreditSubtotalSalt;
46
+
47
+ // Spent voice credits per vote option.
48
+ signal input currentPerVoteOptionSpentVoiceCredits[totalVoteOptions];
49
+ // Salt for the root of spent credits per option.
50
+ signal input currentPerVoteOptionSpentVoiceCreditsRootSalt;
51
+
52
+ // New spent voice credits per vote option.
53
+ signal input newPerVoteOptionSpentVoiceCredits[totalVoteOptions];
54
+ // Salt for the root of new spent credits per option.
55
+ signal input newPerVoteOptionSpentVoiceCreditsRootSalt;
56
+
57
+ // Compute the commitment to the current results.
58
+ var computedCurrentResultsRoot = QuinaryCheckRoot(voteOptionTreeDepth)(currentResults);
59
+
60
+ // Verify currentResultsCommitmentHash.
61
+ var computedCurrentResultsCommitment = PoseidonHasher(2)([computedCurrentResultsRoot, currentResultsRootSalt]);
62
+
63
+ // Compute the commitment to the current spent voice credits.
64
+ var computedCurrentSpentVoiceCreditsCommitment = PoseidonHasher(2)([currentSpentVoiceCreditSubtotal, currentSpentVoiceCreditSubtotalSalt]);
65
+
66
+ // Compute the root of the spent voice credits per vote option.
67
+ var computedCurrentPerVoteOptionSpentVoiceCreditsRoot = QuinaryCheckRoot(voteOptionTreeDepth)(currentPerVoteOptionSpentVoiceCredits);
68
+ var computedCurrentPerVoteOptionSpentVoiceCreditsCommitment = PoseidonHasher(2)([computedCurrentPerVoteOptionSpentVoiceCreditsRoot, currentPerVoteOptionSpentVoiceCreditsRootSalt]);
69
+
70
+ // Commit to the current tally.
71
+ var computedCurrentTallyCommitment = PoseidonHasher(3)([
72
+ computedCurrentResultsCommitment,
73
+ computedCurrentSpentVoiceCreditsCommitment,
74
+ computedCurrentPerVoteOptionSpentVoiceCreditsCommitment
75
+ ]);
76
+
77
+ // Check if the current tally commitment is correct only if this is not the first batch.
78
+ // computedIsZero.out is 1 if this is not the first batch.
79
+ // computedIsZero.out is 0 if this is the first batch.
80
+ var computedIsZero = IsZero()(isFirstBatch);
81
+
82
+ // isFirstCommitment is 0 if this is the first batch, currentTallyCommitment should be 0 if this is the first batch.
83
+ // isFirstCommitment is 1 if this is not the first batch, currentTallyCommitment should not be 0 if this is the first batch.
84
+ signal isFirstCommitment;
85
+ isFirstCommitment <== computedIsZero * computedCurrentTallyCommitment;
86
+ isFirstCommitment === currentTallyCommitment;
87
+
88
+ // Compute the root of the new results.
89
+ var computedNewResultsRoot = QuinaryCheckRoot(voteOptionTreeDepth)(newResults);
90
+ var computedNewResultsCommitment = PoseidonHasher(2)([computedNewResultsRoot, newResultsRootSalt]);
91
+
92
+ // Compute the commitment to the new spent voice credits value.
93
+ var computedNewSpentVoiceCreditsCommitment = PoseidonHasher(2)([newSpentVoiceCreditSubtotal, newSpentVoiceCreditSubtotalSalt]);
94
+
95
+ // Compute the root of the spent voice credits per vote option.
96
+ var computedNewPerVoteOptionSpentVoiceCreditsRoot = QuinaryCheckRoot(voteOptionTreeDepth)(newPerVoteOptionSpentVoiceCredits);
97
+ var computedNewPerVoteOptionSpentVoiceCreditsCommitment = PoseidonHasher(2)([computedNewPerVoteOptionSpentVoiceCreditsRoot, newPerVoteOptionSpentVoiceCreditsRootSalt]);
98
+
99
+ // Commit to the new tally.
100
+ var computedNewTallyCommitment = PoseidonHasher(3)([
101
+ computedNewResultsCommitment,
102
+ computedNewSpentVoiceCreditsCommitment,
103
+ computedNewPerVoteOptionSpentVoiceCreditsCommitment
104
+ ]);
105
+
106
+ computedNewTallyCommitment === newTallyCommitment;
107
+ }
@@ -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_COMMAND_LENGTH = 4;
17
+
18
+ // Number of user sign-ups in the state tree.
19
+ signal input totalSignups;
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 stateLeafPublicKey[2];
26
+ // Current voice credit balance.
27
+ signal input stateLeafVoiceCreditBalance;
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 commandStateIndex;
38
+ // Public key of the user.
39
+ signal input commandPublicKey[2];
40
+ // Vote option index.
41
+ signal input commandVoteOptionIndex;
42
+ // Vote weight.
43
+ signal input commandNewVoteWeight;
44
+ // Nonce.
45
+ signal input commandNonce;
46
+ // Poll identifier.
47
+ signal input commandPollId;
48
+ // Salt.
49
+ signal input commandSalt;
50
+ // EdDSA signature of the command (R part).
51
+ signal input commandSignaturePoint[2];
52
+ // EdDSA signature of the command (S part).
53
+ signal input commandSignatureScalar;
54
+ // Packed command.
55
+ // nb. we are assuming that the packedCommand is always valid.
56
+ signal input packedCommand[PACKED_COMMAND_LENGTH];
57
+
58
+ // New state leaf (if the command is valid).
59
+ signal output newStateLeafPublicKey[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 (computedIsValid, computedIsStateLeafIndexValid, computedIsVoteOptionIndexValid) = MessageValidator()(
72
+ commandStateIndex,
73
+ totalSignups,
74
+ commandVoteOptionIndex,
75
+ voteOptions,
76
+ ballotNonce,
77
+ commandNonce,
78
+ packedCommand,
79
+ stateLeafPublicKey,
80
+ commandSignaturePoint,
81
+ commandSignatureScalar,
82
+ stateLeafVoiceCreditBalance,
83
+ ballotCurrentVotesForOption,
84
+ commandNewVoteWeight
85
+ );
86
+
87
+ // If the message is valid then we swap out the public key.
88
+ // This means using a Mux1() for publicKey[0] and another one
89
+ // for publicKey[1].
90
+ var computedNewstateLeafPublicKey0Mux = Mux1()([stateLeafPublicKey[0], commandPublicKey[0]], computedIsValid);
91
+ var computedNewstateLeafPublicKey1Mux = Mux1()([stateLeafPublicKey[1], commandPublicKey[1]], computedIsValid);
92
+
93
+ newStateLeafPublicKey[0] <== computedNewstateLeafPublicKey0Mux;
94
+ newStateLeafPublicKey[1] <== computedNewstateLeafPublicKey1Mux;
95
+
96
+ // If the message is valid, then we swap out the ballot nonce
97
+ // using a Mux1().
98
+ var computedNewBallotNonceMux = Mux1()([ballotNonce, commandNonce], computedIsValid);
99
+
100
+ newBallotNonce <== computedNewBallotNonceMux;
101
+
102
+ isValid <== computedIsValid;
103
+ isStateLeafIndexValid <== computedIsStateLeafIndexValid;
104
+ isVoteOptionIndexValid <== computedIsVoteOptionIndexValid;
105
+ }
@@ -0,0 +1,65 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./mux1.circom";
5
+ include "./comparators.circom";
6
+ // local import
7
+ include "../PoseidonHasher.circom";
8
+
9
+ // @note taken from @zk-kit/circuits
10
+ // if used directly in MessageProcessor 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
+ // The leaf node of the Merkle tree.
25
+ signal input leaf;
26
+ // The depth of the Merkle tree.
27
+ signal input depth;
28
+ // The index of the leaf node in the Merkle tree.
29
+ signal input index;
30
+ // The sibling nodes of the leaf node in the Merkle tree.
31
+ signal input siblings[MAX_DEPTH][1];
32
+
33
+ // The output of the Merkle tree root.
34
+ signal output out;
35
+
36
+ // The indices of the leaf node in the Merkle tree.
37
+ signal indices[MAX_DEPTH] <== Num2Bits(MAX_DEPTH)(index);
38
+
39
+ signal nodes[MAX_DEPTH + 1];
40
+ nodes[0] <== leaf;
41
+
42
+ signal roots[MAX_DEPTH];
43
+ var root = 0;
44
+
45
+ for (var i = 0; i < MAX_DEPTH; i++) {
46
+ var isDepth = IsEqual()([depth, i]);
47
+
48
+ roots[i] <== isDepth * nodes[i];
49
+
50
+ root += roots[i];
51
+
52
+ var c[2][2] = [
53
+ [nodes[i], siblings[i][0]],
54
+ [siblings[i][0], nodes[i]]
55
+ ];
56
+
57
+ var childNodes[2] = MultiMux1(2)(c, indices[i]);
58
+
59
+ nodes[i + 1] <== PoseidonHasher(2)(childNodes);
60
+ }
61
+
62
+ var isDepth = IsEqual()([depth, MAX_DEPTH]);
63
+
64
+ out <== root + isDepth * nodes[MAX_DEPTH];
65
+ }
@@ -0,0 +1,49 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local import
4
+ include "../PoseidonHasher.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 TOTAL_LEVELS = 2 ** levels;
14
+ // The number of first-level hashers needed, equal to half the total leaves, as each hasher combines two leaves.
15
+ var LEAF_HASHERS = TOTAL_LEVELS / 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 INTERMEDIATE_HASHERS = LEAF_HASHERS - 1;
19
+
20
+ // Array of leaf values input to the circuit.
21
+ signal input leaves[TOTAL_LEVELS];
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 hashersLength = TOTAL_LEVELS - 1;
29
+ var computedLevelHashers[hashersLength];
30
+
31
+ // Initialize hashers for the leaves, each taking two adjacent leaves as inputs.
32
+ for (var i = 0; i < LEAF_HASHERS; 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 index = 0;
38
+
39
+ for (var i = LEAF_HASHERS; i < LEAF_HASHERS + INTERMEDIATE_HASHERS; i++) {
40
+ computedLevelHashers[i] = PoseidonHasher(2)([
41
+ computedLevelHashers[index * 2],
42
+ computedLevelHashers[index * 2 + 1]
43
+ ]);
44
+ index++;
45
+ }
46
+
47
+ // Connect the output of the final hasher in the array to the root output signal.
48
+ root <== computedLevelHashers[hashersLength - 1];
49
+ }
@@ -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_indices[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_indices,
23
+ path_elements
24
+ );
25
+
26
+ root === computedMerkleRoot;
27
+ }
@@ -0,0 +1,50 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // circomlib import
4
+ include "./mux1.circom";
5
+ // local import
6
+ include "../PoseidonHasher.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_indices[n_levels];
16
+ // Sibling node values required to compute the hash at each level.
17
+ signal input path_elements[n_levels][1];
18
+
19
+ // The merkle root.
20
+ signal output root;
21
+
22
+ // Stores the hash at each level starting from the leaf to the root.
23
+ signal levelHashes[n_levels + 1];
24
+ // Initialize the first level with the given leaf.
25
+ levelHashes[0] <== leaf;
26
+
27
+ for (var i = 0; i < n_levels; i++) {
28
+ // Validate path_indices to be either 0 or 1, ensuring no other values.
29
+ path_indices[i] * (1 - path_indices[i]) === 0;
30
+
31
+ // Configure the multiplexer based on the path index for the current level.
32
+ var multiplexer[2][2] = [
33
+ [levelHashes[i], path_elements[i][0]],
34
+ [path_elements[i][0], levelHashes[i]]
35
+ ];
36
+
37
+ var multiplexerResult[2] = MultiMux1(2)(
38
+ multiplexer,
39
+ path_indices[i]
40
+ );
41
+
42
+ var computedLevelHash = PoseidonHasher(2)([multiplexerResult[0], multiplexerResult[1]]);
43
+
44
+ // Store the resulting hash as the next level's hash.
45
+ levelHashes[i + 1] <== computedLevelHash;
46
+ }
47
+
48
+ // Set the final level hash as the root.
49
+ root <== levelHashes[n_levels];
50
+ }
@@ -0,0 +1,54 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local imports
4
+ include "../PoseidonHasher.circom";
5
+
6
+ /**
7
+ * Computes the root of a quintary Merkle tree given a list of leaves.
8
+ * This template constructs a Merkle tree with each node having 5 children (quintary)
9
+ * and computes the root by hashing with Poseidon the leaves and intermediate nodes in the given order.
10
+ * The computation is performed by first hashing groups of 5 leaves to form the bottom layer of nodes,
11
+ * then recursively hashing groups of these nodes to form the next layer, and so on, until the root is computed.
12
+ */
13
+ template QuinaryCheckRoot(levels) {
14
+ var LEAVES_PER_NODE = 5;
15
+ var totalLeaves = LEAVES_PER_NODE ** levels;
16
+ var numLeafHashers = LEAVES_PER_NODE ** (levels - 1);
17
+
18
+ signal input leaves[totalLeaves];
19
+ signal output root;
20
+
21
+ // Determine the total number of hashers.
22
+ var numHashers = 0;
23
+ for (var i = 0; i < levels; i++) {
24
+ numHashers += LEAVES_PER_NODE ** i;
25
+ }
26
+
27
+ var computedHashers[numHashers];
28
+
29
+ // Initialize hashers for the leaves.
30
+ for (var i = 0; i < numLeafHashers; i++) {
31
+ computedHashers[i] = PoseidonHasher(5)([
32
+ leaves[i * LEAVES_PER_NODE + 0],
33
+ leaves[i * LEAVES_PER_NODE + 1],
34
+ leaves[i * LEAVES_PER_NODE + 2],
35
+ leaves[i * LEAVES_PER_NODE + 3],
36
+ leaves[i * LEAVES_PER_NODE + 4]
37
+ ]);
38
+ }
39
+
40
+ // Initialize hashers for intermediate nodes and compute the root.
41
+ var k = 0;
42
+ for (var i = numLeafHashers; i < numHashers; i++) {
43
+ computedHashers[i] = PoseidonHasher(5)([
44
+ computedHashers[k * LEAVES_PER_NODE + 0],
45
+ computedHashers[k * LEAVES_PER_NODE + 1],
46
+ computedHashers[k * LEAVES_PER_NODE + 2],
47
+ computedHashers[k * LEAVES_PER_NODE + 3],
48
+ computedHashers[k * LEAVES_PER_NODE + 4]
49
+ ]);
50
+ k++;
51
+ }
52
+
53
+ root <== computedHashers[numHashers - 1];
54
+ }
@@ -0,0 +1,44 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // zk-kit import
4
+ include "./safe-comparators.circom";
5
+ // local imports
6
+ include "../CalculateTotal.circom";
7
+
8
+ /**
9
+ * Calculates the path indices required for Merkle proof verifications (e.g., QuinaryTreeInclusionProof, QuinaryLeafExists).
10
+ * Given a node index within an IQT 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
+ * e.g., if the index is 30 and the number of levels is 4, the output should be [0, 1, 1, 0].
13
+ */
14
+ template QuinaryGeneratePathIndices(levels) {
15
+ // The number of leaves per node (tree arity)
16
+ var LEAVES_PER_NODE = 5;
17
+
18
+ // The index within the tree
19
+ signal input index;
20
+ // The generated path indices leading to the node of the provided index
21
+ signal output out[levels];
22
+
23
+ var indexModulus = index;
24
+ var computedResults[levels];
25
+
26
+ for (var i = 0; i < levels; i++) {
27
+ // circom's best practices suggests to avoid using <-- unless you
28
+ // are aware of what's going on. This is the only way to do modulo operation.
29
+ out[i] <-- indexModulus % LEAVES_PER_NODE;
30
+ indexModulus = indexModulus \ LEAVES_PER_NODE;
31
+
32
+ // Check that each output element is less than the base.
33
+ var computedIsOutputElementLessThanBase = SafeLessThan(3)([out[i], LEAVES_PER_NODE]);
34
+ computedIsOutputElementLessThanBase === 1;
35
+
36
+ // Re-compute the total sum.
37
+ computedResults[i] = out[i] * (LEAVES_PER_NODE ** i);
38
+ }
39
+
40
+ // Check that the total sum matches the index.
41
+ var computedCalculateTotal = CalculateTotal(levels)(computedResults);
42
+
43
+ computedCalculateTotal === index;
44
+ }
@@ -0,0 +1,30 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local imports
4
+ include "./QuinaryTreeInclusionProof.circom";
5
+
6
+ /**
7
+ * Verifies if a given leaf exists within an IQT.
8
+ * Takes a leaf, its path to the root (specified by indices and path elements),
9
+ * and the root itself, to verify the leaf's inclusion within the tree.
10
+ */
11
+ template QuinaryLeafExists(levels){
12
+ // The number of leaves per node (tree arity)
13
+ var LEAVES_PER_NODE = 5;
14
+ // Number of leaves per path level (excluding the leaf itself)
15
+ var LEAVES_PER_PATH_LEVEL = LEAVES_PER_NODE - 1;
16
+
17
+ // The leaf to check for inclusion
18
+ signal input leaf;
19
+ // The path indices at each level of the tree
20
+ signal input path_indices[levels];
21
+ // The sibling nodes at each level of the tree
22
+ signal input path_elements[levels][LEAVES_PER_PATH_LEVEL];
23
+ // The computed root of the tree
24
+ signal input root;
25
+
26
+ // Verify the Merkle path.
27
+ var computedRoot = QuinaryTreeInclusionProof(levels)(leaf, path_indices, path_elements);
28
+
29
+ root === computedRoot;
30
+ }
@@ -0,0 +1,42 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // zk-kit import
4
+ include "./safe-comparators.circom";
5
+ // local imports
6
+ include "../CalculateTotal.circom";
7
+
8
+ /**
9
+ * Selects an item from a list based on the given index.
10
+ * It verifies the index is within the valid range and then iterates over the inputs to find the match.
11
+ * For each item, it checks if its position equals the given index and if so, multiplies the item
12
+ * by the result of the equality check, effectively selecting it.
13
+ * The sum of these results yields the selected item, ensuring only the item at the specified index be the output.
14
+ *
15
+ * nb. The number of items must be less than 8, and the index must be less than the number of items.
16
+ */
17
+ template QuinarySelector(choices) {
18
+ // The input elements to select from.
19
+ signal input in[choices];
20
+ // The index of the element to select
21
+ signal input index;
22
+ // The selected total sum of the elements.
23
+ signal output out;
24
+
25
+ // Ensure that index < choices.
26
+ var computedIndex = SafeLessThan(3)([index, choices]);
27
+ computedIndex === 1;
28
+
29
+ // Initialize an array to hold the results of equality checks.
30
+ var computedResults[choices];
31
+
32
+ // For each item, check whether its index equals the input index.
33
+ // The result is multiplied by the corresponding input value.
34
+ for (var i = 0; i < choices; i++) {
35
+ var computedIsIndexEqual = IsEqual()([i, index]);
36
+
37
+ computedResults[i] = computedIsIndexEqual * in[i];
38
+ }
39
+
40
+ // Calculate the total sum of the results array.
41
+ out <== CalculateTotal(choices)(computedResults);
42
+ }
@@ -0,0 +1,55 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local imports
4
+ include "../PoseidonHasher.circom";
5
+ include "./Splicer.circom";
6
+
7
+ /**
8
+ * Computes the root of an IQT given a leaf, its path, and sibling nodes at each level of the tree.
9
+ * It iteratively incorporates the leaf or the hash from the previous level with sibling nodes using
10
+ * the Splicer to place the leaf or hash at the correct position based on path_indices.
11
+ * Then, it hashes these values together with PoseidonHasher to move up the tree.
12
+ * This process repeats for each level (levels) of the tree, culminating in the computation of the tree's root.
13
+ */
14
+ template QuinaryTreeInclusionProof(levels) {
15
+ // The number of leaves per node (tree arity)
16
+ var LEAVES_PER_NODE = 5;
17
+ // Number of leaves per path level (excluding the leaf itself)
18
+ var LEAVES_PER_PATH_LEVEL = LEAVES_PER_NODE - 1;
19
+
20
+ // The leaf to check for inclusion
21
+ signal input leaf;
22
+ // The path indices at each level of the tree
23
+ signal input path_indices[levels];
24
+ // The sibling nodes at each level of the tree
25
+ signal input path_elements[levels][LEAVES_PER_PATH_LEVEL];
26
+ // The computed root of the tree
27
+ signal output root;
28
+
29
+ var currentLeaf = leaf;
30
+
31
+ // Iteratively hash each level of path_elements with the leaf or previous hash
32
+ for (var i = 0; i < levels; i++) {
33
+ var elements[LEAVES_PER_PATH_LEVEL];
34
+
35
+ for (var j = 0; j < LEAVES_PER_PATH_LEVEL; j++) {
36
+ elements[j] = path_elements[i][j];
37
+ }
38
+
39
+ var computedSplicedLeaf[LEAVES_PER_NODE] = Splicer(LEAVES_PER_PATH_LEVEL)(
40
+ elements,
41
+ currentLeaf,
42
+ path_indices[i]
43
+ );
44
+
45
+ currentLeaf = PoseidonHasher(5)([
46
+ computedSplicedLeaf[0],
47
+ computedSplicedLeaf[1],
48
+ computedSplicedLeaf[2],
49
+ computedSplicedLeaf[3],
50
+ computedSplicedLeaf[4]
51
+ ]);
52
+ }
53
+
54
+ root <== currentLeaf;
55
+ }