@maci-protocol/core 0.0.0-ci.01622be

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.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # `maci-core`
2
+
3
+ [![NPM Package][core-npm-badge]][core-npm-link]
4
+ [![Actions Status][core-actions-badge]][core-actions-link]
5
+
6
+ This submodule assists with handling key business logic functions and
7
+ processes.
8
+
9
+ ## Overview
10
+
11
+ One may conceive of MACI as a state machine with 1) data and 2) functions which
12
+ transform said data. This makes it easier to reason about the system, write
13
+ tests, and implement functionality. It also allows us to implement the smart
14
+ contracts in discrete components which are easy to test.
15
+
16
+ To this end, this submodule exposes a `MaciState` class and a `Poll` class.
17
+ Developers should instantiate objects from these classes to test MACI. For
18
+ instance, [`MACI.test.ts`](https://github.com/privacy-scaling-explorations/maci/blob/dev/packages/contracts/tests/MACI.test.ts) creates a
19
+ `MaciState` object and every time it interacts with the MACI smart contract, it
20
+ mirrors said interaction on the `MaciState` and `Poll`. As such, the developer
21
+ can then use their helper functions like `maciState.signUp()`,
22
+ `poll.publishMessage`, `poll.processMessages()`, and `poll.tallyVotes()` to
23
+ step through the various stages of the MACI flow.
24
+
25
+ ## `MaciState`
26
+
27
+ ### Key functions
28
+
29
+ #### **`signUp`**
30
+
31
+ Accepts a user's public key and creates a new state leaf and ballot leaf.
32
+
33
+ In testing, whenever a test suite submits a `signUp()` transaction, it should
34
+ call `maciState.signUp()` as well, so that the off-chain representation of MACI
35
+ is kept up to date.
36
+
37
+ In production, `genMaciStateFromContract()` in
38
+ [`genMaciState.ts`](https://github.com/privacy-scaling-explorations/maci/blob/dev/contracts/ts/genMaciState.ts) uses this function when it
39
+ scans a MACI contract's event log for signups, so as to bring its `MaciState`
40
+ instance up to date.
41
+
42
+ #### **`deployPoll`**
43
+
44
+ Creates a new `Poll`. This should be done whenever the MACI contract's
45
+ `deployPoll()` function is called.
46
+
47
+ ### Helper functions
48
+
49
+ #### **`copy`**
50
+
51
+ A function that deep-copies an object.
52
+
53
+ ### Key data structures
54
+
55
+ #### **`stateTree`**
56
+
57
+ `stateTree` is a quinary Merkle tree, chosen over a binary tree due to the gas and circuit constraints associated with the Poseidon hash function ([details here][ethresearch-link]). Each leaf in this tree represents a participant's public key, their voice credit balance and the block timestamp at which they signed up. The tree features a configurable depth and an arity of five, with insertions starting at index 1. The zeroth leaf is reserved as a security measure against denial-of-service attacks.
58
+
59
+ ## **`Poll`**
60
+
61
+ A `Poll` is an off-chain representation of a Poll. In testing, `Poll` instances
62
+ should mirror their on-chain counterparts.
63
+
64
+ ### Key functions
65
+
66
+ #### **`publishMessage`**
67
+
68
+ Publishes a message by updating the message tree and message accumulation
69
+ queue.
70
+
71
+ #### **`processMessages`**
72
+
73
+ Processes a batch of messages and returns the inputs to the `processMessages`
74
+ circuit which can be used to prove correct execution.
75
+
76
+ #### **`tallyVotes`**
77
+
78
+ Tallies a batch of votes and returns the inputs to the `tallyVotes`
79
+ circuit which can be used to prove correct execution.
80
+
81
+ ### Helper functions
82
+
83
+ #### **`copy`**
84
+
85
+ Deep-copies and returns this object.
86
+
87
+ ### Key data structures
88
+
89
+ #### **`messageTree`**
90
+
91
+ `messageTree` is also a quinary Merkle tree. Each message in this tree represents an encrypted command, such as a user casting a vote in a poll or changing their public key.
92
+
93
+ ## Testing
94
+
95
+ For more details about testing please refer to the [tests documentation](https://maci.pse.dev/docs/testing).
96
+
97
+ [core-npm-badge]: https://img.shields.io/npm/v/maci-core.svg
98
+ [core-npm-link]: https://www.npmjs.com/package/maci-core
99
+ [core-actions-badge]: https://github.com/privacy-scaling-explorations/maci/actions/workflows/core-build.yml/badge.svg
100
+ [core-actions-link]: https://github.com/privacy-scaling-explorations/maci/actions?query=workflow%3Acore
101
+ [ethresearch-link]: https://ethresear.ch/t/gas-and-circuit-constraint-benchmarks-of-binary-and-quinary-incremental-merkle-trees-using-the-poseidon-hash-function/7446
102
+
103
+ ## Directory Structure
104
+
105
+ - `ts/`: The home for our core classes, `MaciState` and `Poll`
106
+ - `ts/utls/`: Contains supporting utilities
107
+ - `ts/__tests__/`: A dedicated test suite directory
@@ -0,0 +1,66 @@
1
+ import { IncrementalQuinTree } from "@maci-protocol/crypto";
2
+ import { PublicKey, type Keypair } from "@maci-protocol/domainobjs";
3
+ import type { IJsonMaciState, IMaciState, ITreeDepths } from "./utils/types";
4
+ import { Poll } from "./Poll";
5
+ import { EMode } from "./utils/constants";
6
+ /**
7
+ * A representation of the MACI contract.
8
+ */
9
+ export declare class MaciState implements IMaciState {
10
+ polls: Map<bigint, Poll>;
11
+ publicKeys: PublicKey[];
12
+ stateTreeDepth: number;
13
+ stateTree?: IncrementalQuinTree;
14
+ totalSignups: number;
15
+ pollBeingProcessed?: boolean;
16
+ currentPollBeingProcessed?: bigint;
17
+ /**
18
+ * Constructs a new MaciState object.
19
+ * @param stateTreeDepth - The depth of the state tree.
20
+ */
21
+ constructor(stateTreeDepth: number);
22
+ /**
23
+ * Sign up a user with the given public key.
24
+ * @param publicKey - The public key of the user.
25
+ * @returns The index of the newly signed-up user in the state tree.
26
+ */
27
+ signUp(publicKey: PublicKey): number;
28
+ /**
29
+ * Deploy a new poll with the given parameters.
30
+ * @param pollEndTimestamp - The Unix timestamp at which the poll ends.
31
+ * @param treeDepths - The depths of the tree.
32
+ * @param messageBatchSize - The batch size for processing messages.
33
+ * @param coordinatorKeypair - The keypair of the MACI round coordinator.
34
+ * @param voteOptions - The number of vote options for this poll.
35
+ * @param mode - The voting mode
36
+ * @returns The index of the newly deployed poll.
37
+ */
38
+ deployPoll(pollEndTimestamp: bigint, treeDepths: ITreeDepths, messageBatchSize: number, coordinatorKeypair: Keypair, voteOptions: bigint, mode: EMode): bigint;
39
+ /**
40
+ * Deploy a null poll.
41
+ */
42
+ deployNullPoll(): void;
43
+ /**
44
+ * Create a deep copy of the MaciState object.
45
+ * @returns A new instance of the MaciState object with the same properties.
46
+ */
47
+ copy: () => MaciState;
48
+ /**
49
+ * Check if the MaciState object is equal to another MaciState object.
50
+ * @param m - The MaciState object to compare.
51
+ * @returns True if the two MaciState objects are equal, false otherwise.
52
+ */
53
+ equals: (m: MaciState) => boolean;
54
+ /**
55
+ * Serialize the MaciState object to a JSON object.
56
+ * @returns A JSON object representing the MaciState object.
57
+ */
58
+ toJSON(): IJsonMaciState;
59
+ /**
60
+ * Create a new MaciState object from a JSON object.
61
+ * @param json - The JSON object representing the MaciState object.
62
+ * @returns A new instance of the MaciState object with the properties from the JSON object.
63
+ */
64
+ static fromJSON(json: IJsonMaciState): MaciState;
65
+ }
66
+ //# sourceMappingURL=MaciState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MaciState.d.ts","sourceRoot":"","sources":["../../ts/MaciState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,KAAK,OAAO,EAAU,MAAM,2BAA2B,CAAC;AAE5E,OAAO,KAAK,EAAE,cAAc,EAAa,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAExF,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,KAAK,EAAoB,MAAM,mBAAmB,CAAC;AAE5D;;GAEG;AACH,qBAAa,SAAU,YAAW,UAAU;IAE1C,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAA2B;IAGnD,UAAU,EAAE,SAAS,EAAE,CAAM;IAG7B,cAAc,EAAE,MAAM,CAAC;IAGvB,SAAS,CAAC,EAAE,mBAAmB,CAAC;IAEhC,YAAY,SAAK;IAGjB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC;;;OAGG;gBACS,cAAc,EAAE,MAAM;IAUlC;;;;OAIG;IACH,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM;IAOpC;;;;;;;;;OASG;IACH,UAAU,CACR,gBAAgB,EAAE,MAAM,EACxB,UAAU,EAAE,WAAW,EACvB,gBAAgB,EAAE,MAAM,EACxB,kBAAkB,EAAE,OAAO,EAC3B,WAAW,EAAE,MAAM,EACnB,IAAI,EAAE,KAAK,GACV,MAAM;IAkBT;;OAEG;IACH,cAAc,IAAI,IAAI;IAItB;;;OAGG;IACH,IAAI,QAAO,SAAS,CAQlB;IAEF;;;;OAIG;IACH,MAAM,GAAI,GAAG,SAAS,KAAG,OAAO,CAsB9B;IAEF;;;OAGG;IACH,MAAM,IAAI,cAAc;IAWxB;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,SAAS;CAgBjD"}
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MaciState = void 0;
4
+ const domainobjs_1 = require("@maci-protocol/domainobjs");
5
+ const Poll_1 = require("./Poll");
6
+ const constants_1 = require("./utils/constants");
7
+ /**
8
+ * A representation of the MACI contract.
9
+ */
10
+ class MaciState {
11
+ /**
12
+ * Constructs a new MaciState object.
13
+ * @param stateTreeDepth - The depth of the state tree.
14
+ */
15
+ constructor(stateTreeDepth) {
16
+ // a MaciState can hold multiple polls
17
+ this.polls = new Map();
18
+ // the public keys of the users
19
+ this.publicKeys = [];
20
+ this.totalSignups = 0;
21
+ /**
22
+ * Create a deep copy of the MaciState object.
23
+ * @returns A new instance of the MaciState object with the same properties.
24
+ */
25
+ this.copy = () => {
26
+ const copied = new MaciState(this.stateTreeDepth);
27
+ copied.publicKeys = this.publicKeys.map((x) => x.copy());
28
+ copied.polls = new Map(Array.from(this.polls, ([key, value]) => [key, value.copy()]));
29
+ return copied;
30
+ };
31
+ /**
32
+ * Check if the MaciState object is equal to another MaciState object.
33
+ * @param m - The MaciState object to compare.
34
+ * @returns True if the two MaciState objects are equal, false otherwise.
35
+ */
36
+ this.equals = (m) => {
37
+ const result = this.stateTreeDepth === m.stateTreeDepth &&
38
+ this.polls.size === m.polls.size &&
39
+ this.publicKeys.length === m.publicKeys.length;
40
+ if (!result) {
41
+ return false;
42
+ }
43
+ for (let i = 0; i < this.polls.size; i += 1) {
44
+ if (!this.polls.get(BigInt(i))?.equals(m.polls.get(BigInt(i)))) {
45
+ return false;
46
+ }
47
+ }
48
+ for (let i = 0; i < this.publicKeys.length; i += 1) {
49
+ if (!this.publicKeys[i].equals(m.publicKeys[i])) {
50
+ return false;
51
+ }
52
+ }
53
+ return true;
54
+ };
55
+ this.stateTreeDepth = stateTreeDepth;
56
+ // we put a blank state leaf to prevent a DoS attack
57
+ this.publicKeys.push(domainobjs_1.padKey);
58
+ // we need to increase the number of signups by one given
59
+ // that we already added the blank leaf
60
+ this.totalSignups += 1;
61
+ }
62
+ /**
63
+ * Sign up a user with the given public key.
64
+ * @param publicKey - The public key of the user.
65
+ * @returns The index of the newly signed-up user in the state tree.
66
+ */
67
+ signUp(publicKey) {
68
+ this.totalSignups += 1;
69
+ this.stateTree?.insert(publicKey.hash());
70
+ return this.publicKeys.push(publicKey.copy()) - 1;
71
+ }
72
+ /**
73
+ * Deploy a new poll with the given parameters.
74
+ * @param pollEndTimestamp - The Unix timestamp at which the poll ends.
75
+ * @param treeDepths - The depths of the tree.
76
+ * @param messageBatchSize - The batch size for processing messages.
77
+ * @param coordinatorKeypair - The keypair of the MACI round coordinator.
78
+ * @param voteOptions - The number of vote options for this poll.
79
+ * @param mode - The voting mode
80
+ * @returns The index of the newly deployed poll.
81
+ */
82
+ deployPoll(pollEndTimestamp, treeDepths, messageBatchSize, coordinatorKeypair, voteOptions, mode) {
83
+ const poll = new Poll_1.Poll(pollEndTimestamp, coordinatorKeypair, treeDepths, {
84
+ messageBatchSize,
85
+ tallyBatchSize: constants_1.STATE_TREE_ARITY ** treeDepths.tallyProcessingStateTreeDepth,
86
+ }, this, voteOptions, mode);
87
+ this.polls.set(BigInt(this.polls.size), poll);
88
+ return BigInt(this.polls.size - 1);
89
+ }
90
+ /**
91
+ * Deploy a null poll.
92
+ */
93
+ deployNullPoll() {
94
+ this.polls.set(BigInt(this.polls.size), null);
95
+ }
96
+ /**
97
+ * Serialize the MaciState object to a JSON object.
98
+ * @returns A JSON object representing the MaciState object.
99
+ */
100
+ toJSON() {
101
+ return {
102
+ stateTreeDepth: this.stateTreeDepth,
103
+ polls: Array.from(this.polls.values()).map((poll) => poll.toJSON()),
104
+ publicKeys: this.publicKeys.map((publicKey) => publicKey.toJSON()),
105
+ pollBeingProcessed: Boolean(this.pollBeingProcessed),
106
+ currentPollBeingProcessed: this.currentPollBeingProcessed ? this.currentPollBeingProcessed.toString() : "",
107
+ totalSignups: this.totalSignups,
108
+ };
109
+ }
110
+ /**
111
+ * Create a new MaciState object from a JSON object.
112
+ * @param json - The JSON object representing the MaciState object.
113
+ * @returns A new instance of the MaciState object with the properties from the JSON object.
114
+ */
115
+ static fromJSON(json) {
116
+ const maciState = new MaciState(json.stateTreeDepth);
117
+ // assign the json values to the new instance
118
+ maciState.publicKeys = json.publicKeys.map((publicKey) => domainobjs_1.PublicKey.fromJSON(publicKey));
119
+ maciState.pollBeingProcessed = json.pollBeingProcessed;
120
+ maciState.currentPollBeingProcessed = BigInt(json.currentPollBeingProcessed);
121
+ maciState.totalSignups = json.totalSignups;
122
+ // re-generate the polls and set the maci state reference
123
+ maciState.polls = new Map(json.polls.map((jsonPoll, index) => [BigInt(index), Poll_1.Poll.fromJSON(jsonPoll, maciState)]));
124
+ return maciState;
125
+ }
126
+ }
127
+ exports.MaciState = MaciState;
128
+ //# sourceMappingURL=MaciState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MaciState.js","sourceRoot":"","sources":["../../ts/MaciState.ts"],"names":[],"mappings":";;;AACA,0DAA4E;AAI5E,iCAA8B;AAC9B,iDAA4D;AAE5D;;GAEG;AACH,MAAa,SAAS;IAoBpB;;;OAGG;IACH,YAAY,cAAsB;QAvBlC,sCAAsC;QACtC,UAAK,GAAsB,IAAI,GAAG,EAAgB,CAAC;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BAAkB,CAAC;QACvD,SAAS,CAAC,yBAAyB,GAAG,MAAM,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAC;QAC7E,SAAS,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;QAE3C,yDAAyD;QACzD,SAAS,CAAC,KAAK,GAAG,IAAI,GAAG,CACvB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,QAAmB,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,WAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,CACpG,CAAC;QAEF,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAvKD,8BAuKC"}
@@ -0,0 +1,228 @@
1
+ import { IncrementalQuinTree } from "@maci-protocol/crypto";
2
+ import { VoteCommand, Keypair, Ballot, PublicKey, Message, StateLeaf } from "@maci-protocol/domainobjs";
3
+ import { LeanIMT } from "@zk-kit/lean-imt";
4
+ import type { ITreeDepths, IBatchSizes, IPoll, IJsonPoll, IProcessMessagesOutput, ITallyCircuitInputs, IProcessMessagesCircuitInputs, IPollJoiningCircuitInputs, IJoiningCircuitArgs } from "./index";
5
+ import type { MaciState } from "./MaciState";
6
+ import type { IGetVoiceCreditsLeft, IJoinedCircuitArgs, IPollJoinedCircuitInputs } from "./utils/types";
7
+ import { EMode } from "./utils/constants";
8
+ /**
9
+ * A representation of the Poll contract.
10
+ */
11
+ export declare class Poll implements IPoll {
12
+ coordinatorKeypair: Keypair;
13
+ treeDepths: ITreeDepths;
14
+ batchSizes: IBatchSizes;
15
+ voteOptions: bigint;
16
+ maxVoteOptions: number;
17
+ actualStateTreeDepth: number;
18
+ pollEndTimestamp: bigint;
19
+ ballots: Ballot[];
20
+ ballotTree?: IncrementalQuinTree;
21
+ messages: Message[];
22
+ commands: VoteCommand[];
23
+ encryptionPublicKeys: PublicKey[];
24
+ stateCopied: boolean;
25
+ publicKeys: PublicKey[];
26
+ stateTree?: LeanIMT;
27
+ numBatchesProcessed: number;
28
+ currentMessageBatchIndex: number;
29
+ maciStateRef: MaciState;
30
+ pollId: bigint;
31
+ sbSalts: Record<number | string, bigint>;
32
+ resultRootSalts: Record<number | string, bigint>;
33
+ perVoteOptionSpentVoiceCreditsRootSalts: Record<number | string, bigint>;
34
+ spentVoiceCreditSubtotalSalts: Record<number | string, bigint>;
35
+ tallyResult: bigint[];
36
+ perVoteOptionSpentVoiceCredits: bigint[];
37
+ numBatchesTallied: number;
38
+ totalSpentVoiceCredits: bigint;
39
+ emptyBallot: Ballot;
40
+ emptyBallotHash?: bigint;
41
+ chainHash: bigint;
42
+ batchHashes: bigint[];
43
+ pollStateLeaves: StateLeaf[];
44
+ pollStateTree?: IncrementalQuinTree;
45
+ pollNullifiers: Map<bigint, boolean>;
46
+ private mode;
47
+ private totalSignups;
48
+ /**
49
+ * Constructs a new Poll object.
50
+ * @param pollEndTimestamp - The Unix timestamp at which the poll ends.
51
+ * @param coordinatorKeypair - The keypair of the coordinator.
52
+ * @param treeDepths - The depths of the trees used in the poll.
53
+ * @param batchSizes - The sizes of the batches used in the poll.
54
+ * @param maciStateRef - The reference to the MACI state.
55
+ * @param pollId - The poll id
56
+ */
57
+ constructor(pollEndTimestamp: bigint, coordinatorKeypair: Keypair, treeDepths: ITreeDepths, batchSizes: IBatchSizes, maciStateRef: MaciState, voteOptions: bigint, mode: EMode);
58
+ /**
59
+ * Check if user has already joined the poll by checking if the nullifier is registered
60
+ */
61
+ hasJoined: (nullifier: bigint) => boolean;
62
+ /**
63
+ * Join the anonymous user to the Poll (to the tree)
64
+ * @param nullifier - Hashed private key used as nullifier
65
+ * @param publicKey - The poll public key.
66
+ * @param newVoiceCreditBalance - New voice credit balance of the user.
67
+ * @returns The index of added state leaf
68
+ */
69
+ joinPoll: (nullifier: bigint, publicKey: PublicKey, newVoiceCreditBalance: bigint) => number;
70
+ /**
71
+ * Update a Poll with data from MaciState.
72
+ * This is the step where we copy the state from the MaciState instance,
73
+ * and set the number of signups we have so far.
74
+ * @note It should be called to generate the state for poll joining with totalSignups set as
75
+ * the number of signups in the MaciState. For message processing, you should set totalSignups as
76
+ * the number of users who joined the poll.
77
+ */
78
+ updatePoll: (totalSignups: bigint) => void;
79
+ /**
80
+ * Process one message.
81
+ * @param message - The message to process.
82
+ * @param encryptionPublicKey - The public key associated with the encryption private key.
83
+ * @returns A number of variables which will be used in the zk-SNARK circuit.
84
+ */
85
+ processMessage: (message: Message, encryptionPublicKey: PublicKey) => IProcessMessagesOutput;
86
+ /**
87
+ * Get voice credits left for the voting command.
88
+ *
89
+ * @param args - arguments for getting voice credits
90
+ * @returns voice credits left
91
+ */
92
+ getVoiceCreditsLeft({ stateLeaf, originalVoteWeight, newVoteWeight, mode }: IGetVoiceCreditsLeft): bigint;
93
+ /**
94
+ * Inserts a Message and the corresponding public key used to generate the
95
+ * ECDH shared key which was used to encrypt said message.
96
+ * @param message - The message to insert
97
+ * @param encryptionPublicKey - The public key used to encrypt the message
98
+ */
99
+ publishMessage: (message: Message, encryptionPublicKey: PublicKey) => void;
100
+ /**
101
+ * Updates message chain hash
102
+ * @param messageHash hash of message with encryptionPublicKey
103
+ */
104
+ updateChainHash: (messageHash: bigint) => void;
105
+ /**
106
+ * Create circuit input for pollJoining
107
+ * @param args Poll joining circuit inputs
108
+ * @returns stringified circuit inputs
109
+ */
110
+ joiningCircuitInputs: ({ maciPrivateKey, stateLeafIndex, pollPublicKey, }: IJoiningCircuitArgs) => IPollJoiningCircuitInputs;
111
+ /**
112
+ * Create circuit input for pollJoined
113
+ * @param args Poll joined circuit inputs
114
+ * @returns stringified circuit inputs
115
+ */
116
+ joinedCircuitInputs: ({ maciPrivateKey, stateLeafIndex, voiceCreditsBalance, }: IJoinedCircuitArgs) => IPollJoinedCircuitInputs;
117
+ /**
118
+ * Pad last unclosed batch
119
+ */
120
+ padLastBatch: () => void;
121
+ /**
122
+ * This method checks if there are any unprocessed messages in the Poll instance.
123
+ * @returns Returns true if the number of processed batches is
124
+ * less than the total number of batches, false otherwise.
125
+ */
126
+ hasUnprocessedMessages: () => boolean;
127
+ /**
128
+ * Process _batchSize messages starting from the saved index. This
129
+ * function will process messages even if the number of messages is not an
130
+ * exact multiple of _batchSize. e.g. if there are 10 messages, index is
131
+ * 8, and _batchSize is 4, this function will only process the last two
132
+ * messages in this.messages, and finally update the zeroth state leaf.
133
+ * Note that this function will only process as many state leaves as there
134
+ * are ballots to prevent accidental inclusion of a new user after this
135
+ * poll has concluded.
136
+ * @param pollId The ID of the poll associated with the messages to
137
+ * process
138
+ * @param quiet - Whether to log errors or not
139
+ * @returns stringified circuit inputs
140
+ */
141
+ processMessages: (pollId: bigint, quiet?: boolean) => IProcessMessagesCircuitInputs;
142
+ /**
143
+ * Generates partial circuit inputs for processing a batch of messages
144
+ * @param index - The index of the partial batch.
145
+ * @returns stringified partial circuit inputs
146
+ */
147
+ private generateProcessMessagesCircuitInputsPartial;
148
+ /**
149
+ * Process all messages. This function does not update the ballots or state
150
+ * leaves; rather, it copies and then updates them. This makes it possible
151
+ * to test the result of multiple processMessage() invocations.
152
+ * @returns The state leaves and ballots of the poll
153
+ */
154
+ processAllMessages: () => {
155
+ stateLeaves: StateLeaf[];
156
+ ballots: Ballot[];
157
+ };
158
+ /**
159
+ * Checks whether there are any untallied ballots.
160
+ * @returns Whether there are any untallied ballots
161
+ */
162
+ hasUntalliedBallots: () => boolean;
163
+ /**
164
+ * This method tallies a ballots and updates the tally results.
165
+ *
166
+ * @returns the circuit inputs for the TallyVotes circuit.
167
+ */
168
+ tallyVotes: () => ITallyCircuitInputs;
169
+ /**
170
+ * This method generates a commitment to the total spent voice credits.
171
+ *
172
+ * This is the hash of the total spent voice credits and a salt, computed as Poseidon([totalCredits, _salt]).
173
+ * @param salt - The salt used in the hash function.
174
+ * @param ballotsToCount - The number of ballots to count for the calculation.
175
+ * @param mode - Voting mode, default QV.
176
+ * @returns Returns the hash of the total spent voice credits and a salt, computed as Poseidon([totalCredits, _salt]).
177
+ */
178
+ private generateSpentVoiceCreditSubtotalCommitment;
179
+ /**
180
+ * This method generates a commitment to the spent voice credits per vote option.
181
+ *
182
+ * This is the hash of the Merkle root of the spent voice credits per vote option and a salt, computed as Poseidon([root, _salt]).
183
+ * @param salt - The salt used in the hash function.
184
+ * @param ballotsToCount - The number of ballots to count for the calculation.
185
+ * @param mode - Voting mode, default is QV.
186
+ * @returns Returns the hash of the Merkle root of the spent voice credits per vote option and a salt, computed as Poseidon([root, _salt]).
187
+ */
188
+ private generatePerVoteOptionSpentVoiceCreditsCommitment;
189
+ /**
190
+ * Create a deep copy of the Poll object.
191
+ * @returns A new instance of the Poll object with the same properties.
192
+ */
193
+ copy: () => Poll;
194
+ /**
195
+ * Check if the Poll object is equal to another Poll object.
196
+ * @param poll - The Poll object to compare.
197
+ * @returns True if the two Poll objects are equal, false otherwise.
198
+ */
199
+ equals: (poll: Poll) => boolean;
200
+ /**
201
+ * Serialize the Poll object to a JSON object
202
+ * @returns a JSON object
203
+ */
204
+ toJSON(): IJsonPoll;
205
+ /**
206
+ * Deserialize a json object into a Poll instance
207
+ * @param json the json object to deserialize
208
+ * @param maciState the reference to the MaciState Class
209
+ * @returns a new Poll instance
210
+ */
211
+ static fromJSON(json: IJsonPoll, maciState: MaciState): Poll;
212
+ /**
213
+ * Set the coordinator's keypair
214
+ * @param serializedPrivateKey - the serialized private key
215
+ */
216
+ setCoordinatorKeypair: (serializedPrivateKey: string) => void;
217
+ /**
218
+ * Set the number of signups to match the ones from the contract
219
+ * @param totalSignups - the number of signups
220
+ */
221
+ setTotalSignups: (totalSignups: bigint) => void;
222
+ /**
223
+ * Get the number of signups
224
+ * @returns The number of signups
225
+ */
226
+ gettotalSignups: () => bigint;
227
+ }
228
+ //# sourceMappingURL=Poll.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Poll.d.ts","sourceRoot":"","sources":["../../ts/Poll.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EAYp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