Repository navigation
Expand file tree
/
Copy pathSharpFactsAggregator.sol
More file actions
375 lines (312 loc) · 14.1 KB
/
Copy pathSharpFactsAggregator.sol
File metadata and controls
375 lines (312 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Initializable} from "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {AccessControlUpgradeable} from "openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import {IFactsRegistry} from "./interfaces/IFactsRegistry.sol";
import {IStarknet} from "./interfaces/IStarknet.sol";
import {Uint256Splitter} from "./lib/Uint256Splitter.sol";
/// @title SharpFactsAggregator
/// @dev Aggregator contract to handle SHARP job outputs and update the global aggregator state.
/// @author Herodotus Dev Ltd
/// ------------------
/// Example:
/// Blocks inside brackets are the ones processed during their SHARP job execution
// 7 [8 9 10] 11
/// n = 10
/// r = 3
/// `r` is the number of blocks processed on a single SHARP job execution
/// `blockNMinusRPlusOneParentHash` = 8.parentHash (oldestHash)
/// `blockNPlusOneParentHash` = 11.parentHash (newestHash)
/// ------------------
contract SharpFactsAggregator is Initializable, AccessControlUpgradeable {
// Using inline library for efficient splitting and joining of uint256 values
using Uint256Splitter for uint256;
// Role definitions for access control
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 public constant UNLOCKER_ROLE = keccak256("UNLOCKER_ROLE");
uint256 public constant MINIMUM_BLOCKS_CONFIRMATIONS = 20;
uint256 public constant MAXIMUM_BLOCKS_CONFIRMATIONS = 255;
// Sharp Facts Registry
IFactsRegistry public immutable FACTS_REGISTRY;
// Starknet core contract
IStarknet public immutable STARKNET;
// Cairo program hash calculated with Poseidon (i.e., the off-chain block headers accumulator program)
bytes32 public constant PROGRAM_HASH =
bytes32(
uint256(
0x5dc00f4bec4077d7f511008cff02c0688efb11cfabb6029d084e5e309dcf014
)
);
// Global aggregator state
struct AggregatorState {
bytes32 poseidonMmrRoot;
uint256 mmrSize;
bytes32 continuableParentHash;
}
// Current __global__ state of this aggregator
AggregatorState public aggregatorState;
// Mapping to keep track of block number to its parent hash
mapping(uint256 => bytes32) public blockNumberToParentHash;
// Flag to control operator role requirements
bool public isOperatorRequired;
// Representation of the Cairo program's output (raw unpacked)
struct JobOutput {
uint256 fromBlockNumberHigh;
uint256 toBlockNumberLow;
bytes32 blockNPlusOneParentHash;
bytes32 blockNMinusRPlusOneParentHash;
bytes32 mmrPreviousRootPoseidon;
uint256 mmrPreviousSize;
bytes32 mmrNewRootPoseidon;
uint256 mmrNewSize;
}
// Custom errors for better error handling and clarity
error NotEnoughBlockConfirmations();
error TooManyBlocksConfirmations();
error NotEnoughJobs();
error TargetBlockInFuture();
error UnknownParentHash();
error AggregationError(string message); // Generic error with a message
error AggregationBlockMismatch(string message);
error GenesisBlockReached();
error InvalidFact();
// Event emitted when a new range is registered
// (i.e, when we want to allow aggregating from a more recent block)
event NewRangeRegistered(
uint256 targetBlock,
bytes32 targetBlockParentHash
);
// Event emitted when __at least__ one SHARP job is aggregated
event Aggregate(
uint256 fromBlockNumberHigh,
uint256 toBlockNumberLow,
bytes32 poseidonMmrRoot,
uint256 mmrSize,
bytes32 continuableParentHash
);
event OperatorRequirementChange(bool newRequirement);
constructor(IFactsRegistry factsRegistry, IStarknet starknet) {
FACTS_REGISTRY = factsRegistry;
STARKNET = starknet;
}
/**
* @notice Initializes the contract with given parameters.
* @param initialAggregatorState Initial state of the aggregator (i.e., initial trees state).
*/
function initialize(
AggregatorState calldata initialAggregatorState
) public initializer {
__AccessControl_init();
aggregatorState = initialAggregatorState;
_setRoleAdmin(OPERATOR_ROLE, OPERATOR_ROLE);
_setRoleAdmin(UNLOCKER_ROLE, OPERATOR_ROLE);
// Grant operator role to the contract deployer
// to be able to define new aggregate ranges
_grantRole(OPERATOR_ROLE, _msgSender());
_grantRole(UNLOCKER_ROLE, _msgSender());
// Set operator role requirement to true by default
isOperatorRequired = true;
}
/// @notice Reverts if the caller is not an operator and the operator role requirement is enabled
modifier onlyOperator() {
if (isOperatorRequired) {
require(
hasRole(OPERATOR_ROLE, _msgSender()),
"Caller is not an operator"
);
}
_;
}
/// @notice Reverts if the caller is not an unlocker
modifier onlyUnlocker() {
require(
hasRole(UNLOCKER_ROLE, _msgSender()),
"Caller is not an unlocker"
);
_;
}
/// @dev Modifies the contract's operator requirement
function setOperatorRequired(
bool _isOperatorRequired
) external onlyUnlocker {
isOperatorRequired = _isOperatorRequired;
emit OperatorRequirementChange(_isOperatorRequired);
}
/// Registers a new range to aggregate from
function registerNewRange() external onlyOperator {
// From the starknet core contract get the latest settled block number
uint256 latestSettledStarknetBlock = uint256(
STARKNET.stateBlockNumber()
);
// Extract its parent hash.
bytes32 latestSettledStarknetBlockhash = bytes32(
STARKNET.stateBlockHash()
);
// Cache the parent hash so that we can later on continue accumlating from it
blockNumberToParentHash[
latestSettledStarknetBlock + 1
] = latestSettledStarknetBlockhash;
// If we cannot aggregate further in the past (e.g., genesis block is reached or it's a new tree)
if (aggregatorState.continuableParentHash == bytes32(0)) {
// Set the aggregator state's `continuableParentHash` to the target block's parent hash
// so we can easily continue aggregating from it without specifying `rightBoundStartBlock` in `aggregateSharpJobs`
aggregatorState
.continuableParentHash = latestSettledStarknetBlockhash;
}
emit NewRangeRegistered(
latestSettledStarknetBlock + 1,
latestSettledStarknetBlockhash
);
}
/// @notice Aggregate SHARP jobs outputs (min. 1) to update the global aggregator state
/// @param outputs Array of SHARP jobs outputs (packed for Solidity)
function aggregateSharpJobs(
JobOutput[] calldata outputs
) external onlyOperator {
// Ensuring at least one job output is provided
if (outputs.length < 1) {
revert NotEnoughJobs();
}
JobOutput calldata firstOutput = outputs[0];
uint256 fromBlock = firstOutput.fromBlockNumberHigh;
// Retrieve from cache the parent hash of the block to start from
bytes32 fromBlockPlusOneParentHash = blockNumberToParentHash[
fromBlock + 1
];
// Ensure the first job is continuable
ensureContinuable(fromBlockPlusOneParentHash, firstOutput);
uint256 limit = outputs.length - 1;
// Iterate over the jobs outputs (aside from the last one)
// and ensure jobs are correctly linked and valid
for (uint256 i = 0; i < limit; ++i) {
JobOutput calldata curOutput = outputs[i];
JobOutput calldata nextOutput = outputs[i + 1];
ensureValidFact(curOutput);
ensureConsecutiveJobs(curOutput, nextOutput);
}
JobOutput calldata lastOutput = outputs[limit];
ensureValidFact(lastOutput);
// We save the latest output in the contract state for future calls
uint256 mmrNewSize = lastOutput.mmrNewSize;
aggregatorState.poseidonMmrRoot = lastOutput.mmrNewRootPoseidon;
aggregatorState.mmrSize = mmrNewSize;
aggregatorState.continuableParentHash = lastOutput
.blockNMinusRPlusOneParentHash;
uint256 toBlock = lastOutput.toBlockNumberLow;
blockNumberToParentHash[toBlock] = lastOutput
.blockNMinusRPlusOneParentHash;
emit NewRangeRegistered(
toBlock,
lastOutput.blockNMinusRPlusOneParentHash
);
emit Aggregate(
fromBlock,
toBlock,
lastOutput.mmrNewRootPoseidon,
mmrNewSize,
lastOutput.blockNMinusRPlusOneParentHash
);
}
/// @notice Ensures the fact is registered on SHARP Facts Registry
/// @param output SHARP job output (packed for Solidity)
function ensureValidFact(JobOutput memory output) internal view {
// We assemble the outputs in a uint256 array
uint256[] memory outputs = new uint256[](8);
outputs[0] = uint256(output.fromBlockNumberHigh);
outputs[1] = uint256(output.toBlockNumberLow);
outputs[2] = uint256(output.blockNPlusOneParentHash);
outputs[3] = uint256(output.blockNMinusRPlusOneParentHash);
outputs[4] = uint256(output.mmrPreviousRootPoseidon);
outputs[5] = uint256(output.mmrPreviousSize);
outputs[6] = uint256(output.mmrNewRootPoseidon);
outputs[7] = uint256(output.mmrNewSize);
// We hash the outputs
bytes32 outputHash = keccak256(abi.encodePacked(outputs));
// We compute the deterministic fact bytes32 value
bytes32 fact = keccak256(abi.encode(PROGRAM_HASH, outputHash));
// We ensure this fact has been registered on SHARP Facts Registry
if (!FACTS_REGISTRY.isValid(fact)) {
revert InvalidFact();
}
}
/// @notice Ensures the job output is cryptographically sound to continue from
/// @param fromBlockPlusOneParentHash The parent hash of the block to start from
/// @param output The job output to check
function ensureContinuable(
bytes32 fromBlockPlusOneParentHash,
JobOutput memory output
) internal view {
uint256 mmrPreviousSize = output.mmrPreviousSize;
// Check that the job's previous Poseidon MMR root is the same as the one stored in the contract state
if (output.mmrPreviousRootPoseidon != aggregatorState.poseidonMmrRoot)
revert AggregationError("Poseidon root mismatch");
// Check that the job's previous MMR size is the same as the one stored in the contract state
if (mmrPreviousSize != aggregatorState.mmrSize)
revert AggregationError("MMR size mismatch");
if (fromBlockPlusOneParentHash == bytes32(0)) {
// If the right bound start parent hash __is not__ specified,
// we check that the job's `blockN + 1 parent hash` is matching with the previously stored parent hash
if (
output.blockNPlusOneParentHash !=
aggregatorState.continuableParentHash
) {
revert AggregationError("Parent hash mismatch: Global state");
}
} else {
// If the right bound start parent hash __is__ specified,
// we check that the job's `blockN + 1 parent hash` is matching with a previously stored parent hash
if (output.blockNPlusOneParentHash != fromBlockPlusOneParentHash) {
revert AggregationError(
"Parent hash mismatch: ensureContinuable"
);
}
}
}
/// @notice Ensures the job outputs are correctly linked
/// @param output The job output to check
/// @param nextOutput The next job output to check
function ensureConsecutiveJobs(
JobOutput memory output,
JobOutput memory nextOutput
) internal pure {
uint256 toBlock = output.toBlockNumberLow;
// We cannot aggregate further past the genesis block
if (toBlock == 0) {
revert GenesisBlockReached();
}
uint256 nextFromBlock = nextOutput.fromBlockNumberHigh;
// We check that the next job's `from block` is the same as the previous job's `to block + 1`
if (toBlock - 1 != nextFromBlock)
revert AggregationBlockMismatch("ensureConsecutiveJobs");
uint256 outputMmrNewSize = output.mmrNewSize;
uint256 nextOutputMmrPreviousSize = nextOutput.mmrPreviousSize;
// We check that the previous job's new Poseidon MMR root matches the next job's previous Poseidon MMR root
if (output.mmrNewRootPoseidon != nextOutput.mmrPreviousRootPoseidon)
revert AggregationError("Poseidon root mismatch");
// We check that the previous job's new MMR size matches the next job's previous MMR size
if (outputMmrNewSize != nextOutputMmrPreviousSize)
revert AggregationError("MMR size mismatch");
// We check that the previous job's lowest block hash matches the next job's highest block hash
if (
output.blockNMinusRPlusOneParentHash !=
nextOutput.blockNPlusOneParentHash
)
revert AggregationError(
"Parent hash mismatch: ensureConsecutiveJobs"
);
}
/// @dev Helper function to verify a fact based on a job output
function verifyFact(uint256[] memory outputs) external view returns (bool) {
bytes32 outputHash = keccak256(abi.encodePacked(outputs));
bytes32 fact = keccak256(abi.encode(PROGRAM_HASH, outputHash));
return FACTS_REGISTRY.isValid(fact);
}
/// @notice Returns the current root hash of the Poseidon Merkle Mountain Range (MMR) tree
function getMMRPoseidonRoot() external view returns (bytes32) {
return aggregatorState.poseidonMmrRoot;
}
/// @notice Returns the current size of the Merkle Mountain Range (MMR) trees
function getMMRSize() external view returns (uint256) {
return aggregatorState.mmrSize;
}
}