@crisp-e3/contracts 0.2.2-test → 0.3.0-test

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.
@@ -5,177 +5,262 @@
5
5
  // or FITNESS FOR A PARTICULAR PURPOSE.
6
6
  pragma solidity >=0.8.27;
7
7
 
8
- import {IRiscZeroVerifier} from "risc0/IRiscZeroVerifier.sol";
9
- import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
10
- import {IE3Program} from "@enclave-e3/contracts/contracts/interfaces/IE3Program.sol";
11
- import {IInputValidator} from "@enclave-e3/contracts/contracts/interfaces/IInputValidator.sol";
12
- import {IEnclave} from "@enclave-e3/contracts/contracts/interfaces/IEnclave.sol";
13
- import {E3} from "@enclave-e3/contracts/contracts/interfaces/IE3.sol";
14
- import {CRISPInputValidatorFactory} from "./CRISPInputValidatorFactory.sol";
15
- import {HonkVerifier} from "./CRISPVerifier.sol";
8
+ import { IRiscZeroVerifier } from 'risc0/IRiscZeroVerifier.sol';
9
+ import { Ownable } from '@openzeppelin/contracts/access/Ownable.sol';
10
+ import { IE3Program } from '@enclave-e3/contracts/contracts/interfaces/IE3Program.sol';
11
+ import { IEnclave } from '@enclave-e3/contracts/contracts/interfaces/IEnclave.sol';
12
+ import { E3 } from '@enclave-e3/contracts/contracts/interfaces/IE3.sol';
13
+ import { LazyIMTData, InternalLazyIMT, PoseidonT3 } from '@zk-kit/lazy-imt.sol/InternalLazyIMT.sol';
14
+
15
+ import { HonkVerifier } from './CRISPVerifier.sol';
16
16
 
17
17
  contract CRISPProgram is IE3Program, Ownable {
18
- // Constants
19
- bytes32 public constant ENCRYPTION_SCHEME_ID = keccak256("fhe.rs:BFV");
20
-
21
- // State variables
22
- IEnclave public enclave;
23
- IRiscZeroVerifier public verifier;
24
- CRISPInputValidatorFactory private immutable INPUT_VALIDATOR_FACTORY;
25
- HonkVerifier private immutable HONK_VERIFIER;
26
- bytes32 public imageId;
27
-
28
- /// @notice Half of the largest minimum degree used to fit votes
29
- /// inside the plaintext polynomial
30
- uint256 public constant HALF_LARGEST_MINIMUM_DEGREE = 28;
31
-
32
- // Mappings
33
- mapping(address => bool) public authorizedContracts;
34
- mapping(uint256 e3Id => bytes32 paramsHash) public paramsHashes;
35
-
36
- // Events
37
- event InputValidatorUpdated(address indexed newValidator);
38
-
39
- // Errors
40
- error CallerNotAuthorized();
41
- error E3AlreadyInitialized();
42
- error E3DoesNotExist();
43
- error EnclaveAddressZero();
44
- error VerifierAddressZero();
45
- error InvalidInputValidatorFactory();
46
- error InvalidHonkVerifier();
47
-
48
- /// @notice Initialize the contract, binding it to a specified RISC Zero verifier.
49
- /// @param _enclave The enclave address
50
- /// @param _verifier The RISC Zero verifier address
51
- /// @param _inputValidatorFactory The input validator factory address
52
- /// @param _honkVerifier The honk verifier address
53
- /// @param _imageId The image ID for the guest program
54
- constructor(
55
- IEnclave _enclave,
56
- IRiscZeroVerifier _verifier,
57
- CRISPInputValidatorFactory _inputValidatorFactory,
58
- HonkVerifier _honkVerifier,
59
- bytes32 _imageId
60
- ) Ownable(msg.sender) {
61
- require(address(_enclave) != address(0), EnclaveAddressZero());
62
- require(address(_verifier) != address(0), VerifierAddressZero());
63
- require(address(_inputValidatorFactory) != address(0), InvalidInputValidatorFactory());
64
- require(address(_honkVerifier) != address(0), InvalidHonkVerifier());
65
-
66
- enclave = _enclave;
67
- verifier = _verifier;
68
- INPUT_VALIDATOR_FACTORY = _inputValidatorFactory;
69
- HONK_VERIFIER = _honkVerifier;
70
- authorizedContracts[address(_enclave)] = true;
71
- imageId = _imageId;
72
- }
18
+ using InternalLazyIMT for LazyIMTData;
19
+ /// @notice a structure that holds the round data
20
+ struct RoundData {
21
+ /// @notice The governance token address.
22
+ address token;
23
+ /// @notice The minimum balance required to pass the validation.
24
+ uint256 balanceThreshold;
25
+ /// @notice The Merkle root of the census.
26
+ uint256 censusMerkleRoot;
27
+ }
73
28
 
74
- /// @notice Set the Image ID for the guest program
75
- /// @param _imageId The new image ID.
76
- function setImageId(bytes32 _imageId) external onlyOwner {
77
- imageId = _imageId;
78
- }
29
+ // Constants
30
+ bytes32 public constant ENCRYPTION_SCHEME_ID = keccak256('fhe.rs:BFV');
31
+
32
+ // The depth of the input merkle tree
33
+ uint8 public constant TREE_DEPTH = 20;
34
+
35
+ // State variables
36
+ IEnclave public enclave;
37
+ IRiscZeroVerifier public verifier;
38
+ HonkVerifier private immutable HONK_VERIFIER;
39
+ bytes32 public imageId;
40
+
41
+ /// @notice the round data
42
+ mapping(uint256 e3Id => RoundData roundData) public roundsData;
43
+ /// @notice whether the round data has been set
44
+ mapping(uint256 e3Id => bool isDataSet) public isRoundsDataSet;
45
+
46
+ /// @notice Half of the largest minimum degree used to fit votes
47
+ /// inside the plaintext polynomial
48
+ uint256 public constant HALF_LARGEST_MINIMUM_DEGREE = 28;
49
+
50
+ // Mappings
51
+ mapping(address => bool) public authorizedContracts;
52
+ mapping(uint256 e3Id => bytes32 paramsHash) public paramsHashes;
53
+ /// @notice Mapping to store votes slot indices. Each eligible voter has their own slot
54
+ /// to store their vote inside the merkle tree.
55
+ mapping(uint256 e3Id => mapping(address slot => uint40 index)) public voteSlots;
56
+ mapping(uint256 e3Id => LazyIMTData) public votes;
57
+
58
+ // Errors
59
+ error CallerNotAuthorized();
60
+ error E3AlreadyInitialized();
61
+ error E3DoesNotExist();
62
+ error EnclaveAddressZero();
63
+ error VerifierAddressZero();
64
+
65
+ /// @notice The error emitted when the honk verifier address is invalid.
66
+ error InvalidHonkVerifier();
67
+ /// @notice The error emitted when the input data is empty.
68
+ error EmptyInputData();
69
+ /// @notice The error emitted when the input data is invalid.
70
+ error InvalidInputData(bytes reason);
71
+ /// @notice The error emitted when the Noir proof is invalid.
72
+ error InvalidNoirProof();
73
+ /// @notice The error emitted when the round data is not set.
74
+ error RoundDataNotSet();
75
+ /// @notice The error emitted when trying to set the round data more than once.
76
+ error RoundDataAlreadySet();
77
+
78
+ /// @notice The event emitted when an input is published.
79
+ event InputPublished(uint256 indexed e3Id, bytes vote, uint256 index);
80
+
81
+ /// @notice Initialize the contract, binding it to a specified RISC Zero verifier.
82
+ /// @param _enclave The enclave address
83
+ /// @param _verifier The RISC Zero verifier address
84
+ /// @param _honkVerifier The honk verifier address
85
+ /// @param _imageId The image ID for the guest program
86
+ constructor(IEnclave _enclave, IRiscZeroVerifier _verifier, HonkVerifier _honkVerifier, bytes32 _imageId) Ownable(msg.sender) {
87
+ require(address(_enclave) != address(0), EnclaveAddressZero());
88
+ require(address(_verifier) != address(0), VerifierAddressZero());
89
+ require(address(_honkVerifier) != address(0), InvalidHonkVerifier());
90
+
91
+ enclave = _enclave;
92
+ verifier = _verifier;
93
+ HONK_VERIFIER = _honkVerifier;
94
+ authorizedContracts[address(_enclave)] = true;
95
+ imageId = _imageId;
96
+ }
97
+
98
+ /// @notice Sets the Round data. Can only be set once.
99
+ /// @param _root The Merkle root to set.
100
+ /// @param _token The governance token address.
101
+ /// @param _balanceThreshold The minimum balance required.
102
+ function setRoundData(uint256 _e3Id, uint256 _root, address _token, uint256 _balanceThreshold) external onlyOwner {
103
+ if (isRoundsDataSet[_e3Id]) revert RoundDataAlreadySet();
104
+
105
+ isRoundsDataSet[_e3Id] = true;
106
+
107
+ roundsData[_e3Id] = RoundData({ token: _token, balanceThreshold: _balanceThreshold, censusMerkleRoot: _root });
108
+ }
109
+
110
+ /// @notice Set the Image ID for the guest program
111
+ /// @param _imageId The new image ID.
112
+ function setImageId(bytes32 _imageId) external onlyOwner {
113
+ imageId = _imageId;
114
+ }
115
+
116
+ /// @notice Set the RISC Zero verifier address
117
+ /// @param _verifier The new RISC Zero verifier address
118
+ function setVerifier(IRiscZeroVerifier _verifier) external onlyOwner {
119
+ if (address(_verifier) == address(0)) revert VerifierAddressZero();
120
+ verifier = _verifier;
121
+ }
122
+
123
+ /// @notice Get the params hash for an E3 program
124
+ /// @param e3Id The E3 program ID
125
+ /// @return The params hash
126
+ function getParamsHash(uint256 e3Id) public view returns (bytes32) {
127
+ return paramsHashes[e3Id];
128
+ }
129
+
130
+ /// @notice Validate the E3 program parameters
131
+ /// @param e3Id The E3 program ID
132
+ /// @param e3ProgramParams The E3 program parameters
133
+ function validate(uint256 e3Id, uint256, bytes calldata e3ProgramParams, bytes calldata) external returns (bytes32) {
134
+ require(authorizedContracts[msg.sender] || msg.sender == owner(), CallerNotAuthorized());
135
+ require(paramsHashes[e3Id] == bytes32(0), E3AlreadyInitialized());
136
+ paramsHashes[e3Id] = keccak256(e3ProgramParams);
79
137
 
80
- /// @notice Set the RISC Zero verifier address
81
- /// @param _verifier The new RISC Zero verifier address
82
- function setVerifier(IRiscZeroVerifier _verifier) external onlyOwner {
83
- verifier = _verifier;
138
+ // we need to init the inputs merkle tree for this e3Id
139
+ votes[e3Id]._init(TREE_DEPTH);
140
+
141
+ return ENCRYPTION_SCHEME_ID;
142
+ }
143
+
144
+ /// @inheritdoc IE3Program
145
+ function validateInput(uint256 e3Id, address, bytes memory data) external {
146
+ // it should only be called via Enclave for now
147
+ require(authorizedContracts[msg.sender] || msg.sender == owner(), CallerNotAuthorized());
148
+ // We need to ensure that the CRISP admin set the merkle root of the census.
149
+ if (!isRoundsDataSet[e3Id]) revert RoundDataNotSet();
150
+
151
+ if (data.length == 0) revert EmptyInputData();
152
+
153
+ (bytes memory noirProof, bytes32[] memory vote, address slotAddress) = abi.decode(data, (bytes, bytes32[], address));
154
+
155
+ bytes memory voteBytes = abi.encode(vote);
156
+
157
+ (uint40 voteIndex, bool isFirstVote) = _processVote(e3Id, slotAddress, voteBytes);
158
+
159
+ bytes32[] memory noirPublicInputs = new bytes32[](2 + vote.length);
160
+
161
+ // Set public inputs for the proof. Order must match Noir circuit.
162
+ noirPublicInputs[0] = bytes32(uint256(uint160(slotAddress)));
163
+ // Pass isFirstVote flag to verifier (1 = first vote, 0 = re-vote)
164
+ noirPublicInputs[1] = bytes32(uint256(isFirstVote ? 1 : 0));
165
+
166
+ // Set the encrypted vote to the noir public inputs.
167
+ for (uint256 i = 0; i < vote.length; i++) {
168
+ noirPublicInputs[i + 2] = vote[i];
84
169
  }
85
170
 
86
- /// @notice Get the params hash for an E3 program
87
- /// @param e3Id The E3 program ID
88
- /// @return The params hash
89
- function getParamsHash(uint256 e3Id) public view returns (bytes32) {
90
- return paramsHashes[e3Id];
171
+ // Check if the ciphertext was encrypted correctly
172
+ if (!HONK_VERIFIER.verify(noirProof, noirPublicInputs)) {
173
+ revert InvalidNoirProof();
91
174
  }
92
175
 
93
- /// @notice Validate the E3 program parameters
94
- /// @param e3Id The E3 program ID
95
- /// @param e3ProgramParams The E3 program parameters
96
- function validate(uint256 e3Id, uint256, bytes calldata e3ProgramParams, bytes calldata)
97
- external
98
- returns (bytes32, IInputValidator inputValidator)
99
- {
100
- require(authorizedContracts[msg.sender] || msg.sender == owner(), CallerNotAuthorized());
101
- require(paramsHashes[e3Id] == bytes32(0), E3AlreadyInitialized());
102
- paramsHashes[e3Id] = keccak256(e3ProgramParams);
103
-
104
- // Deploy a new input validator
105
- inputValidator = IInputValidator(INPUT_VALIDATOR_FACTORY.deploy(address(HONK_VERIFIER), owner()));
106
-
107
- return (ENCRYPTION_SCHEME_ID, inputValidator);
176
+ emit InputPublished(e3Id, voteBytes, voteIndex);
177
+ }
178
+
179
+ /// @notice Process a vote: insert or update in the merkle tree depending
180
+ /// on whether it's the first vote or an override.
181
+ function _processVote(uint256 e3Id, address slotAddress, bytes memory vote) internal returns (uint40 voteIndex, bool isFirstVote) {
182
+ uint40 storedIndexPlusOne = voteSlots[e3Id][slotAddress];
183
+
184
+ // we treat the index 0 as not voted yet
185
+ // any valid index will be index + 1
186
+ if (storedIndexPlusOne == 0) {
187
+ // FIRST VOTE
188
+ isFirstVote = true;
189
+ voteIndex = votes[e3Id].numberOfLeaves;
190
+ voteSlots[e3Id][slotAddress] = voteIndex + 1;
191
+ votes[e3Id]._insert(PoseidonT3.hash([uint256(keccak256(vote)), voteIndex]));
192
+ } else {
193
+ // RE-VOTE
194
+ isFirstVote = false;
195
+ voteIndex = storedIndexPlusOne - 1;
196
+ votes[e3Id]._update(PoseidonT3.hash([uint256(keccak256(vote)), voteIndex]), voteIndex);
108
197
  }
198
+ }
199
+
200
+ /// @notice Decode the tally from the plaintext output
201
+ /// @param e3Id The E3 program ID
202
+ /// @return yes The number of yes votes
203
+ /// @return no The number of no votes
204
+ function decodeTally(uint256 e3Id) public view returns (uint256 yes, uint256 no) {
205
+ // fetch from enclave
206
+ E3 memory e3 = enclave.getE3(e3Id);
207
+
208
+ // abi decode it into an array of uint256
209
+ uint256[] memory tally = abi.decode(e3.plaintextOutput, (uint256[]));
210
+
211
+ /// @notice We want to completely ignore anything outside of the coefficients
212
+ /// we agreed to store out votes on.
213
+ uint256 halfD = tally.length / 2;
214
+ uint256 START_INDEX_Y = halfD - HALF_LARGEST_MINIMUM_DEGREE;
215
+ uint256 START_INDEX_N = tally.length - HALF_LARGEST_MINIMUM_DEGREE;
216
+
217
+ // first weight (we are converting back from bits to integer)
218
+ uint256 weight = 2 ** (HALF_LARGEST_MINIMUM_DEGREE - 1);
109
219
 
110
- /// @notice Decode the tally from the plaintext output
111
- /// @param e3Id The E3 program ID
112
- /// @return yes The number of yes votes
113
- /// @return no The number of no votes
114
- function decodeTally(uint256 e3Id) public view returns (uint256 yes, uint256 no) {
115
- // fetch from enclave
116
- E3 memory e3 = enclave.getE3(e3Id);
117
-
118
- // abi decode it into an array of uint256
119
- uint256[] memory tally = abi.decode(e3.plaintextOutput, (uint256[]));
120
-
121
- /// @notice We want to completely ignore anything outside of the coefficients
122
- /// we agreed to store out votes on.
123
- uint256 halfD = tally.length / 2;
124
- uint256 START_INDEX_Y = halfD - HALF_LARGEST_MINIMUM_DEGREE;
125
- uint256 START_INDEX_N = tally.length - HALF_LARGEST_MINIMUM_DEGREE;
126
-
127
- // first weight (we are converting back from bits to integer)
128
- uint256 weight = 2 ** (HALF_LARGEST_MINIMUM_DEGREE - 1);
129
-
130
- // Convert yes votes
131
- for (uint256 i = START_INDEX_Y; i < halfD; i++) {
132
- yes += tally[i] * weight;
133
- weight /= 2; // Right shift equivalent
134
- }
135
-
136
- // Reset weight for no votes
137
- weight = 2 ** (HALF_LARGEST_MINIMUM_DEGREE - 1);
138
-
139
- // Convert no votes
140
- for (uint256 i = START_INDEX_N; i < tally.length; i++) {
141
- no += tally[i] * weight;
142
- weight /= 2;
143
- }
144
-
145
- return (yes, no);
220
+ // Convert yes votes
221
+ for (uint256 i = START_INDEX_Y; i < halfD; i++) {
222
+ yes += tally[i] * weight;
223
+ weight /= 2; // Right shift equivalent
146
224
  }
147
225
 
148
- /// @notice Verify the proof
149
- /// @param e3Id The E3 program ID
150
- /// @param ciphertextOutputHash The hash of the ciphertext output
151
- /// @param proof The proof to verify
152
- function verify(uint256 e3Id, bytes32 ciphertextOutputHash, bytes memory proof)
153
- external
154
- view
155
- override
156
- returns (bool)
157
- {
158
- require(paramsHashes[e3Id] != bytes32(0), E3DoesNotExist());
159
- bytes32 inputRoot = bytes32(enclave.getInputRoot(e3Id));
160
- bytes memory journal = new bytes(396); // (32 + 1) * 4 * 3
161
-
162
- encodeLengthPrefixAndHash(journal, 0, ciphertextOutputHash);
163
- encodeLengthPrefixAndHash(journal, 132, paramsHashes[e3Id]);
164
- encodeLengthPrefixAndHash(journal, 264, inputRoot);
165
-
166
- verifier.verify(proof, imageId, sha256(journal));
167
- return true;
226
+ // Reset weight for no votes
227
+ weight = 2 ** (HALF_LARGEST_MINIMUM_DEGREE - 1);
228
+
229
+ // Convert no votes
230
+ for (uint256 i = START_INDEX_N; i < tally.length; i++) {
231
+ no += tally[i] * weight;
232
+ weight /= 2;
168
233
  }
169
234
 
170
- /// @notice Encode length prefix and hash
171
- /// @param journal The journal to encode into
172
- /// @param startIndex The start index in the journal
173
- /// @param hashVal The hash value to encode
174
- function encodeLengthPrefixAndHash(bytes memory journal, uint256 startIndex, bytes32 hashVal) internal pure {
175
- journal[startIndex] = 0x20;
176
- startIndex += 4;
177
- for (uint256 i = 0; i < 32; i++) {
178
- journal[startIndex + i * 4] = hashVal[i];
179
- }
235
+ return (yes, no);
236
+ }
237
+
238
+ /// @notice Verify the proof
239
+ /// @param e3Id The E3 program ID
240
+ /// @param ciphertextOutputHash The hash of the ciphertext output
241
+ /// @param proof The proof to verify
242
+ function verify(uint256 e3Id, bytes32 ciphertextOutputHash, bytes memory proof) external view override returns (bool) {
243
+ require(paramsHashes[e3Id] != bytes32(0), E3DoesNotExist());
244
+ bytes32 inputRoot = bytes32(votes[e3Id]._root(TREE_DEPTH));
245
+ bytes memory journal = new bytes(396); // (32 + 1) * 4 * 3
246
+
247
+ encodeLengthPrefixAndHash(journal, 0, ciphertextOutputHash);
248
+ encodeLengthPrefixAndHash(journal, 132, paramsHashes[e3Id]);
249
+ encodeLengthPrefixAndHash(journal, 264, inputRoot);
250
+
251
+ verifier.verify(proof, imageId, sha256(journal));
252
+ return true;
253
+ }
254
+
255
+ /// @notice Encode length prefix and hash
256
+ /// @param journal The journal to encode into
257
+ /// @param startIndex The start index in the journal
258
+ /// @param hashVal The hash value to encode
259
+ function encodeLengthPrefixAndHash(bytes memory journal, uint256 startIndex, bytes32 hashVal) internal pure {
260
+ journal[startIndex] = 0x20;
261
+ startIndex += 4;
262
+ for (uint256 i = 0; i < 32; i++) {
263
+ journal[startIndex + i * 4] = hashVal[i];
180
264
  }
265
+ }
181
266
  }