Skip to content

Commit

Permalink
docs(smart contracts): update smart contracts docs and separate in pages
Browse files Browse the repository at this point in the history
  • Loading branch information
ctrlc03 committed May 20, 2024
1 parent ee6a16e commit c8e1530
Show file tree
Hide file tree
Showing 16 changed files with 491 additions and 431 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ The network options are: **_localhost, sepolia, and optimism-sepolia_**, and the

## MACI Contract

The MACI contract is the core of the protocol. Contracts can inherit from MACI and thus expose the signup and topup functions. As with standalone MACI, one would need to deploy a [sign up gatekeeper](/docs/developers-references/smart-contracts/contracts#signupgatekeeper) as well as the [voice credit proxy](/docs/developers-references/smart-contracts/contracts#voicecreditproxy).
The MACI contract is the core of the protocol. Contracts can inherit from MACI and thus expose the signup and topup functions. As with standalone MACI, one would need to deploy a [sign up gatekeeper](/docs/developers-references/smart-contracts/Gatekeepers) as well as the [voice credit proxy](/docs/developers-references/smart-contracts/VoiceCreditProxy).

As an example, within the quadratic funding infrastructure project, the QFI contract inherits from MACI and allows sign up via the contribute function.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
title: AccQueue Smart Contract
description: AccQueue smart contract
sidebar_label: AccQueue
sidebar_position: 1
---

The AccQueue contract represents a Merkle Tree where each leaf insertion only updates a subtree. To obtain the main tree root, the subtrees must be merged together by the contract owner. This requires at least two operations, a `mergeSubRoots` and a `merge`.

The contract can be initialized to work as a traditional Merkle Tree (2 leaves per node) or a Quinary Tree (5 leaves per node). This can be achieved by passing either two or five as parameter to the constructor (`_hashLength`). Any other values should not be accepted.

Below are presented the most important functions of the smart contract:

- `enqueue` - Allows to add a leaf to the queue for the current subtree. Only one parameter is accepted and that is the leaf to insert.
- `insertSubTree` - Admin only function which allows to insert a full subtree (batch enqueue)
- `mergeSubRoots` - Allows the contract owner to merge all of the subtrees to form the shortest possible tree. The argument `_numSrQueueOps` can be used to perform the operation in multiple transactions (as this might trigger the block gas limit).
- `merge` - Allows the contract admin to form a main tree with the desired depth. The depth must fit all of the leaves.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
title: Gatekeepers Smart Contract
description: Gatekeepers smart contract
sidebar_label: Gatekeepers
sidebar_position: 6
---

MACI requires a signup gatekeeper to ensure that only designed users register. It is up to MACI's deployer how they wish to allow sign-ups, therefore they can implement their own GateKeeper. The repository comes with different options:

- `FreeForAllSignUpGatekeeper` - This allows anyone to signup on MACI.
- `SignUpTokenGatekeeper` - This makes use of a ERC721 token to gatekeep the signup function.
- `EASGatekeeper` - This allows gatekeeping signups to only users who have a specific EAS attestation.
- `HatsGatekeeper` - This allows gatekeeping signups to only users who have a specific Hat.
- `GitcoinPassportGatekeeper` - This allows gatekeeping signups to only users who have a specific Gitcoin Passport score.

An abstract contract to inherit from is also provided, with two function signatures as shown below:

```ts
abstract contract SignUpGatekeeper {
function setMaciInstance(MACI _maci) public virtual {}
function register(address _user, bytes memory _data) public virtual {}
}
```

The MACI contract will need to call the `SignUpGatekeeper.register` function inside the `MACI.signUp` function.
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
---
title: MACI Smart Contract
description: MACI main smart contract
sidebar_label: MACI
sidebar_position: 1
---

`MACI.sol` is the core contract of the project, as it provides the base layer for user signups and Polls to be created.

The constructor shown below accepts several arguments:

- `PollFactory` address
- `MessageProcessorFactory` address
- `TallyFactory` address
- `SignUpGatekeeper` address
- `InitialVoiceCreditProxy` address
- The depth of the state tree

```javascript
constructor(
IPollFactory _pollFactory,
IMessageProcessorFactory _messageProcessorFactory,
ITallyFactory _tallyFactory,
SignUpGatekeeper _signUpGatekeeper,
InitialVoiceCreditProxy _initialVoiceCreditProxy,
uint8 _stateTreeDepth
) payable {
// initialize and insert the blank leaf
InternalLazyIMT._init(lazyIMTData, _stateTreeDepth);
InternalLazyIMT._insert(lazyIMTData, BLANK_STATE_LEAF_HASH);

pollFactory = _pollFactory;
messageProcessorFactory = _messageProcessorFactory;
tallyFactory = _tallyFactory;
signUpGatekeeper = _signUpGatekeeper;
initialVoiceCreditProxy = _initialVoiceCreditProxy;
stateTreeDepth = _stateTreeDepth;

// Verify linked poseidon libraries
if (hash2([uint256(1), uint256(1)]) == 0) revert PoseidonHashLibrariesNotLinked();
}

```

Upon deployment, the contract will initialize the state tree, and insert the blank leaf hash.

After this, all of the parameters will be stored to state, and then the contract will perform a simple sanity check to ensure that the Poseidon hash libraries were linked successfully.

## SignUp

Next, we have the `signUp` function, which allows users to `signUp`, as long as they pass the conditions set in the `SignUpGatekeeper` contract. This contract can use any mean necessary to gatekeep access to MACI's polls. For instance, only wallets with a specific ERC721 token can be allowed to sign up.

This function does the following:

- checks that the maximum number of signups has not been reached. Given a tree depth of 10, this will be $2 ** 10 - 1$.
- checks that the provided public key is a valid baby-jubjub point
- registers the user using the sign up gatekeeper contract. It is important that whichever gatekeeper is used, this reverts if a user tries to sign up twice or the conditions are not met (i.e returning false is not enough)
- calls the voice credit proxy to retrieve the number of allocated voice credits allocated to this voter
- hashes the voice credits alongside the user's MACI public key and the current time
- insert this hashed data into the state tree.

```javascript
function signUp(
PubKey memory _pubKey,
bytes memory _signUpGatekeeperData,
bytes memory _initialVoiceCreditProxyData
) public virtual {
// ensure we do not have more signups than what the circuits support
if (lazyIMTData.numberOfLeaves >= uint256(TREE_ARITY) ** uint256(stateTreeDepth)) revert TooManySignups();

// ensure that the public key is on the baby jubjub curve
if (!CurveBabyJubJub.isOnCurve(_pubKey.x, _pubKey.y)) {
revert InvalidPubKey();
}

// Register the user via the sign-up gatekeeper. This function should
// throw if the user has already registered or if ineligible to do so.
signUpGatekeeper.register(msg.sender, _signUpGatekeeperData);

// Get the user's voice credit balance.
uint256 voiceCreditBalance = initialVoiceCreditProxy.getVoiceCredits(msg.sender, _initialVoiceCreditProxyData);

uint256 timestamp = block.timestamp;

// Create a state leaf and insert it into the tree.
uint256 stateLeaf = hashStateLeaf(StateLeaf(_pubKey, voiceCreditBalance, timestamp));
InternalLazyIMT._insert(lazyIMTData, stateLeaf);

emit SignUp(lazyIMTData.numberOfLeaves - 1, _pubKey.x, _pubKey.y, voiceCreditBalance, timestamp);
}
```

## DeployPoll

Once everything has been setup, polls can be deployed using the `deployPoll` function. Polls can be deployed concurrently, as each deployment has its own separate set of contracts and state.

```javascript
function deployPoll(
uint256 _duration,
TreeDepths memory _treeDepths,
PubKey memory _coordinatorPubKey,
address _verifier,
address _vkRegistry,
Mode _mode
) public virtual returns (PollContracts memory pollAddr) {
// cache the poll to a local variable so we can increment it
uint256 pollId = nextPollId;

// Increment the poll ID for the next poll
// 2 ** 256 polls available
unchecked {
nextPollId++;
}

// check coordinator key is a valid point on the curve
if (!CurveBabyJubJub.isOnCurve(_coordinatorPubKey.x, _coordinatorPubKey.y)) {
revert InvalidPubKey();
}

MaxValues memory maxValues = MaxValues({
maxMessages: uint256(MESSAGE_TREE_ARITY) ** _treeDepths.messageTreeDepth,
maxVoteOptions: uint256(MESSAGE_TREE_ARITY) ** _treeDepths.voteOptionTreeDepth
});

// the owner of the message processor and tally contract will be the msg.sender
address _msgSender = msg.sender;

address p = pollFactory.deploy(_duration, maxValues, _treeDepths, _coordinatorPubKey, address(this));

address mp = messageProcessorFactory.deploy(_verifier, _vkRegistry, p, _msgSender, _mode);
address tally = tallyFactory.deploy(_verifier, _vkRegistry, p, mp, _msgSender, _mode);

polls[pollId] = p;

// store the addresses in a struct so they can be returned
pollAddr = PollContracts({ poll: p, messageProcessor: mp, tally: tally });

emit DeployPoll(pollId, _coordinatorPubKey.x, _coordinatorPubKey.y, pollAddr);
}
```

Polls require the following information:

- `duration`: the duration of the poll
- `treeDepths`: the depth of the state tree, message tree, and vote option tree
- `coordinatorPubKey`: the public key of the poll's coordinator
- `verifier`: the address of the zk-SNARK verifier contract
- `vkRegistry`: the address of the vk registry contract
- `mode`: the mode of the poll, to set whether it supports quadratic voting or non quadratic voting
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
title: MessageProcessor Smart Contract
description: MessageProcessor smart contract
sidebar_label: MessageProcessor
sidebar_position: 4
---

This contract is used to prepare parameters for the zk-SNARK circuits as well as for verifying proofs. It should be deployed alongside a `Poll` and ownership assigned to the coordinator.
It will process messages in batches, and after all batches have been processed, the `sbCommitment` can then be used for the `Tally` contract verification steps.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
title: Params Smart Contract
description: Params smart contract
sidebar_label: Params
sidebar_position: 9
---

A contract holding three structs:

```c
/// @notice A struct holding the depths of the merkle trees
struct TreeDepths {
uint8 intStateTreeDepth;
uint8 messageTreeSubDepth;
uint8 messageTreeDepth;
uint8 voteOptionTreeDepth;
}

/// @notice A struct holding the max values for the poll
struct MaxValues {
uint256 maxMessages;
uint256 maxVoteOptions;
}

/// @notice A struct holding the external contracts
/// that are to be passed to a Poll contract on
/// deployment
struct ExtContracts {
IMACI maci;
AccQueue messageAq;
}
```

Struct parameters are used to avoid stack too deep errors in the other contracts.
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
---
title: Poll Smart Contract
description: MACI Poll Contract
sidebar_label: Poll
sidebar_position: 2
---

This contract allows users to submit their votes.

The main functions of the contract are as follows:

- `publishMessage` - This function allows anyone to publish a message, and it accepts the message object as well as an ephemeral public key. This key together with the coordinator public key will be used to generate a shared ECDH key that will encrypt the message.
Before saving the message, the function will check that the voting deadline has not passed, as well as the max number of messages was not reached.
- `publisMessageBatch` - This function allows to submit a batch of messages, and it accepts an array of messages with their corresponding public keys used in the encryption step. It will call the `publishMessage` function for each message in the array.

## PublishMessage

The `publishMessage` function looks as follows:

```js
function publishMessage(Message memory _message, PubKey calldata _encPubKey) public virtual isWithinVotingDeadline {
// we check that we do not exceed the max number of messages
if (numMessages >= maxValues.maxMessages) revert TooManyMessages();

// check if the public key is on the curve
if (!CurveBabyJubJub.isOnCurve(_encPubKey.x, _encPubKey.y)) {
revert InvalidPubKey();
}

// cannot realistically overflow
unchecked {
numMessages++;
}

uint256 messageLeaf = hashMessageAndEncPubKey(_message, _encPubKey);
extContracts.messageAq.enqueue(messageLeaf);

emit PublishMessage(_message, _encPubKey);
}
```

## MergeMaciState

After a Poll's voting period ends, the coordinator's job is to store the main state root, as well as some more information on the Poll contract using `mergeMaciState`:

```js
function mergeMaciState() public isAfterVotingDeadline {
// This function can only be called once per Poll after the voting
// deadline
if (stateMerged) revert StateAlreadyMerged();

// set merged to true so it cannot be called again
stateMerged = true;

mergedStateRoot = extContracts.maci.getStateTreeRoot();

// Set currentSbCommitment
uint256[3] memory sb;
sb[0] = mergedStateRoot;
sb[1] = emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1];
sb[2] = uint256(0);

currentSbCommitment = hash3(sb);

// get number of signups and cache in a var for later use
uint256 _numSignups = extContracts.maci.numSignUps();
numSignups = _numSignups;

// dynamically determine the actual depth of the state tree
uint8 depth = 1;
while (uint40(2) ** uint40(depth) < _numSignups) {
depth++;
}

actualStateTreeDepth = depth;

emit MergeMaciState(mergedStateRoot, numSignups);
}
```

The function will store the state root from the MACI contract, create a commitment by hashing this merkle root, an empty ballot root stored in the `emptyBallotRoots` mapping, and a zero as salt. The commitment will be stored in the `currentSbCommitment` variable. Finally, it will store the total number of signups, and calculate the actual depth of the state tree. This information will be used when processing messages and tally to ensure proof validity.

The `emptyBallotRoots` mapping is used to store the empty ballot roots for each vote option tree depth. For instance, if the vote option tree depth is 5, a build script will generate the following values (this assumes that the state tree depth is 10):

```javascript
emptyBallotRoots[0] = uint256(16015576667038038422103932363190100635991292382181099511410843174865570503661);
emptyBallotRoots[1] = uint256(166510078825589460025300915201657086611944528317298994959376081297530246971);
emptyBallotRoots[2] = uint256(10057734083972610459557695472359628128485394923403014377687504571662791937025);
emptyBallotRoots[3] = uint256(4904828619307091008204672239231377290495002626534171783829482835985709082773);
emptyBallotRoots[4] = uint256(18694062287284245784028624966421731916526814537891066525886866373016385890569);
```

At the same time, the coordinator can merge the message accumulator queue and generate its merkle root. This is achieved by calling the following functions:

- `mergeMessageAqSubRoots` - merges the Poll's messages tree subroot
- `mergeMessageAq` - merges the Poll's messages tree
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
title: Poll Factory Smart Contract
description: Poll Factory smart contract
sidebar_label: PollFactory
sidebar_position: 3
---

`PollFactory` is a smart contract that is used to deploy new Polls. This is used by MACI inside the `deployPoll` function.

```ts
function deploy(
_duration,
MaxValues calldata _maxValues,
TreeDepths calldata _treeDepths,
PubKey calldata _coordinatorPubKey,
address _maci
) public virtual returns (address pollAddr) {
/// @notice Validate _maxValues
/// maxVoteOptions must be less than 2 ** 50 due to circuit limitations;
/// it will be packed as a 50-bit value along with other values as one
/// of the inputs (aka packedVal)
if (_maxValues.maxVoteOptions >= (2 ** 50)) {
revert InvalidMaxValues();
}

/// @notice deploy a new AccQueue contract to store messages
AccQueue messageAq = new AccQueueQuinaryMaci(_treeDepths.messageTreeSubDepth);

/// @notice the smart contracts that a Poll would interact with
ExtContracts memory extContracts = ExtContracts({ maci: IMACI(_maci), messageAq: messageAq });

// deploy the poll
Poll poll = new Poll(_duration, _maxValues, _treeDepths, _coordinatorPubKey, extContracts);

// Make the Poll contract own the messageAq contract, so only it can
// run enqueue/merge
messageAq.transferOwnership(address(poll));

// init Poll
poll.init();

pollAddr = address(poll);
}
```

Upon deployment, the following will happen:

- ownership of the `messageAq` contract is transferred to the deployed poll contract
Loading

0 comments on commit c8e1530

Please sign in to comment.