@maci-protocol/circuits 0.0.0-ci.2653bc0 → 0.0.0-ci.2d2f5fb

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 (41) hide show
  1. package/LICENSE +1 -2
  2. package/build/ts/{genZkeys.d.ts → generateZkeys.d.ts} +1 -1
  3. package/build/ts/generateZkeys.d.ts.map +1 -0
  4. package/build/ts/{genZkeys.js → generateZkeys.js} +1 -1
  5. package/build/ts/generateZkeys.js.map +1 -0
  6. package/build/ts/types.d.ts +11 -12
  7. package/build/ts/types.d.ts.map +1 -1
  8. package/build/tsconfig.build.tsbuildinfo +1 -1
  9. package/circom/circuits.json +7 -7
  10. package/circom/coordinator/non-qv/processMessages.circom +106 -107
  11. package/circom/coordinator/non-qv/tallyVotes.circom +38 -32
  12. package/circom/coordinator/qv/processMessages.circom +107 -105
  13. package/circom/coordinator/qv/tallyVotes.circom +56 -54
  14. package/circom/utils/{calculateTotal.circom → CalculateTotal.circom} +2 -0
  15. package/circom/utils/{verifySignature.circom → EdDSAPoseidonVerifier.circom} +40 -66
  16. package/circom/utils/MessageHasher.circom +57 -0
  17. package/circom/utils/MessageToCommand.circom +107 -0
  18. package/circom/utils/PoseidonHasher.circom +29 -0
  19. package/circom/utils/{privToPubKey.circom → PrivateToPublicKey.circom} +12 -10
  20. package/circom/utils/VerifySignature.circom +39 -0
  21. package/circom/utils/full/MessageValidator.circom +93 -0
  22. package/circom/utils/full/StateLeafAndBallotTransformer.circom +122 -0
  23. package/circom/utils/non-qv/{messageValidator.circom → MessageValidator.circom} +15 -13
  24. package/circom/utils/non-qv/{stateLeafAndBallotTransformer.circom → StateLeafAndBallotTransformer.circom} +36 -36
  25. package/circom/utils/qv/{messageValidator.circom → MessageValidator.circom} +15 -13
  26. package/circom/utils/qv/{stateLeafAndBallotTransformer.circom → StateLeafAndBallotTransformer.circom} +36 -36
  27. package/circom/utils/trees/BinaryMerkleRoot.circom +62 -0
  28. package/circom/utils/trees/CheckRoot.circom +49 -0
  29. package/circom/utils/trees/LeafExists.circom +27 -0
  30. package/circom/utils/trees/MerklePathIndicesGenerator.circom +44 -0
  31. package/circom/utils/trees/MerkleTreeInclusionProof.circom +50 -0
  32. package/circom/utils/trees/incrementalQuinaryTree.circom +2 -2
  33. package/circom/voter/PollJoined.circom +43 -0
  34. package/circom/voter/PollJoining.circom +54 -0
  35. package/package.json +15 -12
  36. package/build/ts/genZkeys.d.ts.map +0 -1
  37. package/build/ts/genZkeys.js.map +0 -1
  38. package/circom/utils/hashers.circom +0 -78
  39. package/circom/utils/messageToCommand.circom +0 -78
  40. package/circom/utils/trees/incrementalMerkleTree.circom +0 -198
  41. package/circom/voter/poll.circom +0 -93
@@ -0,0 +1,43 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local imports
4
+ include "../utils/PoseidonHasher.circom";
5
+ include "../utils/PrivateToPublicKey.circom";
6
+ include "../utils/trees/BinaryMerkleRoot.circom";
7
+
8
+ // Poll Joined Circuit
9
+ // Allows a user to prove that they have joined a MACI poll.
10
+ // This is to be used with the MACI offchain implementation to allow
11
+ // users to authenticate to the relayer service (to reduce spamming).
12
+ template PollJoined(stateTreeDepth) {
13
+ // Constants defining the tree structure
14
+ var STATE_TREE_ARITY = 2;
15
+
16
+ // User's private key
17
+ signal input privateKey;
18
+ // User's voice credits balance
19
+ signal input voiceCreditsBalance;
20
+ // Path elements
21
+ signal input pathElements[stateTreeDepth][STATE_TREE_ARITY - 1];
22
+ // Path indices
23
+ signal input pathIndices[stateTreeDepth];
24
+ // Poll State tree root which proves the user is joined
25
+ signal input stateRoot;
26
+ // The actual tree depth (might be <= stateTreeDepth) Used in BinaryMerkleRoot
27
+ signal input actualStateTreeDepth;
28
+
29
+ // User private to public key
30
+ var derivedPublicKey[2] = PrivateToPublicKey()(privateKey);
31
+
32
+ var stateLeaf = PoseidonHasher(3)([derivedPublicKey[0], derivedPublicKey[1], voiceCreditsBalance]);
33
+
34
+ // Inclusion proof
35
+ var calculatedRoot = BinaryMerkleRoot(stateTreeDepth)(
36
+ stateLeaf,
37
+ actualStateTreeDepth,
38
+ pathIndices,
39
+ pathElements
40
+ );
41
+
42
+ calculatedRoot === stateRoot;
43
+ }
@@ -0,0 +1,54 @@
1
+ pragma circom 2.0.0;
2
+
3
+ // local imports
4
+ include "../utils/PoseidonHasher.circom";
5
+ include "../utils/PrivateToPublicKey.circom";
6
+ include "../utils/trees/BinaryMerkleRoot.circom";
7
+
8
+ // Poll Joining Circuit
9
+ // Allows a user to prove knowledge of a private key that is signed up to
10
+ // a MACI contract.
11
+ template PollJoining(stateTreeDepth) {
12
+ // Constants defining the tree structure
13
+ var STATE_TREE_ARITY = 2;
14
+
15
+ // User's private key
16
+ signal input privateKey;
17
+ // Poll's public key
18
+ signal input pollPublicKey[2];
19
+ // Siblings
20
+ signal input siblings[stateTreeDepth][STATE_TREE_ARITY - 1];
21
+ // Indices
22
+ signal input indices[stateTreeDepth];
23
+ // User's hashed private key
24
+ signal input nullifier;
25
+ // MACI State tree root which proves the user is signed up
26
+ signal input stateRoot;
27
+ // The actual tree depth (might be <= stateTreeDepth) used in BinaryMerkleRoot
28
+ signal input actualStateTreeDepth;
29
+ // The poll id
30
+ signal input pollId;
31
+
32
+ // Compute the nullifier (hash of private key and poll id)
33
+ var computedNullifier = PoseidonHasher(2)([privateKey, pollId]);
34
+ nullifier === computedNullifier;
35
+
36
+ // User private to public key
37
+ var derivedPublicKey[2] = PrivateToPublicKey()(privateKey);
38
+ // Hash the public key
39
+ var publicKeyHash = PoseidonHasher(2)([derivedPublicKey[0], derivedPublicKey[1]]);
40
+
41
+ // Ensure the poll public key is the same as the maci one (public input)
42
+ derivedPublicKey[0] === pollPublicKey[0];
43
+ derivedPublicKey[1] === pollPublicKey[1];
44
+
45
+ // Inclusion proof
46
+ var calculatedRoot = BinaryMerkleRoot(stateTreeDepth)(
47
+ publicKeyHash,
48
+ actualStateTreeDepth,
49
+ indices,
50
+ siblings
51
+ );
52
+
53
+ calculatedRoot === stateRoot;
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maci-protocol/circuits",
3
- "version": "0.0.0-ci.2653bc0",
3
+ "version": "0.0.0-ci.2d2f5fb",
4
4
  "private": false,
5
5
  "description": "zk-SNARK circuits for MACI",
6
6
  "main": "build/ts/index.js",
@@ -18,7 +18,7 @@
18
18
  "scripts": {
19
19
  "build-test-circuits-c": "ts-node ./ts/compile.ts --cWitness",
20
20
  "build-test-circuits-wasm": "ts-node ./ts/compile.ts",
21
- "gen-zkeys": "ts-node ./ts/genZkeys.ts",
21
+ "generate-zkeys": "ts-node ./ts/generateZkeys.ts",
22
22
  "info": "NODE_OPTIONS=--max-old-space-size=4096 ts-node ./ts/info.ts",
23
23
  "watch": "tsc --watch",
24
24
  "build": "tsc -p tsconfig.build.json",
@@ -28,12 +28,15 @@
28
28
  "mocha-test": "NODE_OPTIONS=--max-old-space-size=4096 ts-mocha --exit -g '^(?!.*\\[fuzz\\]).*$'",
29
29
  "test": "pnpm run mocha-test ts/__tests__/*.test.ts",
30
30
  "test:fuzz": "NODE_OPTIONS=--max-old-space-size=4096 ts-mocha --exit -g '\\[fuzz\\]' ./ts/__tests__/*.test.ts",
31
- "test:hasher": "pnpm run mocha-test ts/__tests__/Hasher.test.ts",
31
+ "test:poseidonHasher": "pnpm run mocha-test ts/__tests__/PoseidonHasher.test.ts",
32
+ "test:messageHasher": "pnpm run mocha-test ts/__tests__/MessageHasher.test.ts",
32
33
  "test:slAndBallotTransformer": "pnpm run mocha-test ts/__tests__/StateLeafAndBallotTransformer.test.ts",
34
+ "test:slAndBallotTransformerFull": "pnpm run mocha-test ts/__tests__/StateLeafAndBallotTransformerFull.test.ts",
33
35
  "test:messageToCommand": "pnpm run mocha-test ts/__tests__/MessageToCommand.test.ts",
34
36
  "test:messageValidator": "pnpm run mocha-test ts/__tests__/MessageValidator.test.ts",
37
+ "test:messageValidatorFull": "pnpm run mocha-test ts/__tests__/MessageValidatorFull.test.ts",
35
38
  "test:verifySignature": "pnpm run mocha-test ts/__tests__/VerifySignature.test.ts",
36
- "test:privToPubKey": "pnpm run mocha-test ts/__tests__/PrivToPubKey.test.ts",
39
+ "test:privateToPublicKey": "pnpm run mocha-test ts/__tests__/PrivateToPublicKey.test.ts",
37
40
  "test:calculateTotal": "pnpm run mocha-test ts/__tests__/CalculateTotal.test.ts",
38
41
  "test:processMessages": "pnpm run mocha-test ts/__tests__/ProcessMessages.test.ts",
39
42
  "test:tallyVotes": "pnpm run mocha-test ts/__tests__/TallyVotes.test.ts",
@@ -43,10 +46,10 @@
43
46
  "test:pollJoined": "pnpm run mocha-test ts/__tests__/PollJoined.test.ts"
44
47
  },
45
48
  "dependencies": {
46
- "@maci-protocol/core": "0.0.0-ci.2653bc0",
47
- "@maci-protocol/crypto": "0.0.0-ci.2653bc0",
48
- "@maci-protocol/domainobjs": "0.0.0-ci.2653bc0",
49
- "@maci-protocol/sdk": "0.0.0-ci.2653bc0",
49
+ "@maci-protocol/core": "0.0.0-ci.2d2f5fb",
50
+ "@maci-protocol/crypto": "0.0.0-ci.2d2f5fb",
51
+ "@maci-protocol/domainobjs": "0.0.0-ci.2d2f5fb",
52
+ "@maci-protocol/sdk": "0.0.0-ci.2d2f5fb",
50
53
  "@zk-kit/circuits": "^0.4.0",
51
54
  "circomkit": "^0.3.2",
52
55
  "circomlib": "^2.0.5"
@@ -55,17 +58,17 @@
55
58
  "@types/chai": "^4.3.11",
56
59
  "@types/chai-as-promised": "^7.1.8",
57
60
  "@types/mocha": "^10.0.10",
58
- "@types/node": "^22.13.10",
61
+ "@types/node": "^22.15.8",
59
62
  "@types/snarkjs": "^0.7.9",
60
63
  "@zk-kit/baby-jubjub": "^1.0.3",
61
64
  "chai": "^4.3.10",
62
65
  "chai-as-promised": "^7.1.2",
63
- "fast-check": "^4.0.0",
66
+ "fast-check": "^4.1.1",
64
67
  "glob": "^11.0.1",
65
68
  "mocha": "^11.1.0",
66
69
  "ts-mocha": "^11.1.0",
67
70
  "ts-node": "^10.9.1",
68
- "typescript": "^5.8.2"
71
+ "typescript": "^5.8.3"
69
72
  },
70
- "gitHead": "244acf2206f9cf6660e2c091f04de18d3c87fd02"
73
+ "gitHead": "76cfd10ccc6304958b8afc794a66108d44758fa2"
71
74
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"genZkeys.d.ts","sourceRoot":"","sources":["../../ts/genZkeys.ts"],"names":[],"mappings":"AAQA;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,GAAU,aAAa,MAAM,KAAG,OAAO,CAAC,IAAI,CA2CrE,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"genZkeys.js","sourceRoot":"","sources":["../../ts/genZkeys.ts"],"names":[],"mappings":"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"}
@@ -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
- }
@@ -1,93 +0,0 @@
1
- pragma circom 2.0.0;
2
-
3
- // local imports
4
- include "../utils/hashers.circom";
5
- include "../utils/privToPubKey.circom";
6
- include "../utils/trees/incrementalMerkleTree.circom";
7
-
8
- // Poll Joining Circuit
9
- // Allows a user to prove knowledge of a private key that is signed up to
10
- // a MACI contract.
11
- template PollJoining(stateTreeDepth) {
12
- // Constants defining the tree structure
13
- var STATE_TREE_ARITY = 2;
14
-
15
- // User's private key
16
- signal input privKey;
17
- // Poll's public key
18
- signal input pollPubKey[2];
19
- // Siblings
20
- signal input siblings[stateTreeDepth][STATE_TREE_ARITY - 1];
21
- // Indices
22
- signal input indices[stateTreeDepth];
23
- // User's hashed private key
24
- signal input nullifier;
25
- // MACI State tree root which proves the user is signed up
26
- signal input stateRoot;
27
- // The actual tree depth (might be <= stateTreeDepth) used in BinaryMerkleRoot
28
- signal input actualStateTreeDepth;
29
- // The poll id
30
- signal input pollId;
31
-
32
- // Compute the nullifier (hash of private key and poll id)
33
- var computedNullifier = PoseidonHasher(2)([privKey, pollId]);
34
- nullifier === computedNullifier;
35
-
36
- // User private to public key
37
- var derivedPubKey[2] = PrivToPubKey()(privKey);
38
- // Hash the public key
39
- var pubKeyHash = PoseidonHasher(2)([derivedPubKey[0], derivedPubKey[1]]);
40
-
41
- // Ensure the poll public key is the same as the maci one (public input)
42
- derivedPubKey[0] === pollPubKey[0];
43
- derivedPubKey[1] === pollPubKey[1];
44
-
45
- // Inclusion proof
46
- var calculatedRoot = BinaryMerkleRoot(stateTreeDepth)(
47
- pubKeyHash,
48
- actualStateTreeDepth,
49
- indices,
50
- siblings
51
- );
52
-
53
- calculatedRoot === stateRoot;
54
- }
55
-
56
- // Poll Joined Circuit
57
- // Allows a user to prove that they have joined a MACI poll.
58
- // This is to be used with the MACI offchain implementation to allow
59
- // users to authenticate to the relayer service (to reduce spamming).
60
- template PollJoined(stateTreeDepth) {
61
- // Constants defining the tree structure
62
- var STATE_TREE_ARITY = 2;
63
-
64
- // User's private key
65
- signal input privKey;
66
- // User's voice credits balance
67
- signal input voiceCreditsBalance;
68
- // Poll's joined timestamp
69
- signal input joinTimestamp;
70
- // Path elements
71
- signal input pathElements[stateTreeDepth][STATE_TREE_ARITY - 1];
72
- // Path indices
73
- signal input pathIndices[stateTreeDepth];
74
- // Poll State tree root which proves the user is joined
75
- signal input stateRoot;
76
- // The actual tree depth (might be <= stateTreeDepth) Used in BinaryMerkleRoot
77
- signal input actualStateTreeDepth;
78
-
79
- // User private to public key
80
- var derivedPubKey[2] = PrivToPubKey()(privKey);
81
-
82
- var stateLeaf = PoseidonHasher(4)([derivedPubKey[0], derivedPubKey[1], voiceCreditsBalance, joinTimestamp]);
83
-
84
- // Inclusion proof
85
- var stateLeafQip = BinaryMerkleRoot(stateTreeDepth)(
86
- stateLeaf,
87
- actualStateTreeDepth,
88
- pathIndices,
89
- pathElements
90
- );
91
-
92
- stateLeafQip === stateRoot;
93
- }