-
Notifications
You must be signed in to change notification settings - Fork 75
/
DKG.sol
491 lines (421 loc) · 18.1 KB
/
DKG.sol
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@keep-network/sortition-pools/contracts/SortitionPool.sol";
import "./BytesLib.sol";
import "../DKGValidator.sol";
library DKG {
using BytesLib for bytes;
using ECDSA for bytes32;
struct Parameters {
// Time in blocks during which a submitted result can be challenged.
uint256 resultChallengePeriodLength;
// Time in blocks after which the next group member is eligible
// to submit DKG result.
uint256 resultSubmissionEligibilityDelay;
}
struct Data {
// Address of the Sortition Pool contract.
SortitionPool sortitionPool;
// Address of the DKGValidator contract.
DKGValidator dkgValidator;
// DKG parameters. The parameters should persist between DKG executions.
// They should be updated with dedicated set functions only when DKG is not
// in progress.
Parameters parameters;
// Time in blocks at which DKG started.
uint256 startBlock;
// Seed used to start DKG.
uint256 seed;
// Time in blocks that should be added to result submission eligibility
// delay calculation. It is used in case of a challenge to adjust
// block calculation for members submission eligibility.
uint256 resultSubmissionStartBlockOffset;
// Hash of submitted DKG result.
bytes32 submittedResultHash;
// Block number from the moment of the DKG result submission.
uint256 submittedResultBlock;
}
/// @notice DKG result.
struct Result {
// Claimed submitter candidate group member index.
// Must be in range [1, 64].
uint256 submitterMemberIndex;
// Generated candidate group public key
bytes groupPubKey;
// Array of misbehaved members indices (disqualified or inactive).
// Indices must be in range [1, 64], unique, and sorted in ascending
// order.
uint8[] misbehavedMembersIndices;
// Concatenation of signatures from members supporting the result.
// The message to be signed by each member is keccak256 hash of the
// calculated group public key, misbehaved members indices and DKG
// start block. The calculated hash should be prefixed with prefixed with
// `\x19Ethereum signed message:\n` before signing, so the message to
// sign is:
// `\x19Ethereum signed message:\n${keccak256(
// groupPubKey, misbehavedMembersIndices, dkgStartBlock
// )}`
bytes signatures;
// Indices of members corresponding to each signature. Indices must be
// be in range [1, 64], unique, and sorted in ascending order.
uint256[] signingMembersIndices;
// Identifiers of candidate group members as outputted by the group
// selection protocol.
uint32[] members;
}
/// @notice States for phases of group creation. The states doesn't include
/// timeouts which should be tracked and notified individually.
enum State {
// Group creation is not in progress. It is a state set after group creation
// completion either by timeout or by a result approval.
IDLE,
// Group creation is awaiting the seed and sortition pool is locked.
AWAITING_SEED,
// Off-chain DKG protocol execution is in progress. A result is being calculated
// by the clients in this state. It's not yet possible to submit the result.
KEY_GENERATION,
// After off-chain DKG protocol execution the contract awaits result submission.
// This is a state to which group creation returns in case of a result
// challenge notification.
AWAITING_RESULT,
// DKG result was submitted and awaits an approval or a challenge. If a result
// gets challenge the state returns to `AWAITING_RESULT`. If a result gets
// approval the state changes to `IDLE`.
CHALLENGE
}
/// @dev Size of a group in the threshold relay.
uint256 public constant groupSize = 64;
/// @dev The minimum number of group members needed to interact according to
/// the protocol to produce a relay entry. The adversary can not learn
/// anything about the key as long as it does not break into
/// groupThreshold+1 of members.
uint256 public constant groupThreshold = 33;
/// @dev The minimum number of active and properly behaving group members
/// during the DKG needed to accept the result. This number is higher
/// than `groupThreshold` to keep a safety margin for members becoming
/// inactive after DKG so that the group can still produce a relay
/// entry.
uint256 public constant activeThreshold = 58; // 90% of groupSize
/// @notice Time in blocks after which DKG result is complete and ready to be
// published by clients.
uint256 public constant offchainDkgTime = 5 * (1 + 5) + 2 * (1 + 10) + 20;
event DkgStarted(uint256 indexed seed);
event DkgResultSubmitted(
bytes32 indexed resultHash,
uint256 indexed seed,
uint256 submitterMemberIndex,
bytes indexed groupPubKey,
uint8[] misbehavedMembersIndices,
bytes signatures,
uint256[] signingMembersIndices,
uint32[] members
);
event DkgTimedOut();
event DkgResultApproved(
bytes32 indexed resultHash,
address indexed approver
);
event DkgResultChallenged(
bytes32 indexed resultHash,
address indexed challenger,
string reason
);
event DkgStateLocked();
event DkgSeedTimedOut();
/// @notice Initializes SortitionPool and DKGValidator addresses.
/// Can be performed only once.
/// @param _sortitionPool Sortition Pool reference
/// @param _dkgValidator DKGValidator reference
function init(
Data storage self,
SortitionPool _sortitionPool,
DKGValidator _dkgValidator
) internal {
require(
address(self.sortitionPool) == address(0),
"Sortition Pool address already set"
);
require(
address(self.dkgValidator) == address(0),
"DKG Validator address already set"
);
self.sortitionPool = _sortitionPool;
self.dkgValidator = _dkgValidator;
}
/// @notice Determines the current state of group creation. It doesn't take
/// timeouts into consideration. The timeouts should be tracked and
/// notified separately.
function currentState(Data storage self)
internal
view
returns (State state)
{
state = State.IDLE;
if (self.sortitionPool.isLocked()) {
state = State.AWAITING_SEED;
if (self.startBlock > 0) {
state = State.KEY_GENERATION;
if (block.number > self.startBlock + offchainDkgTime) {
state = State.AWAITING_RESULT;
if (self.submittedResultBlock > 0) {
state = State.CHALLENGE;
}
}
}
}
}
/// @notice Locks the sortition pool and starts awaiting for the
/// group creation seed.
function lockState(Data storage self) internal {
require(currentState(self) == State.IDLE, "current state is not IDLE");
emit DkgStateLocked();
self.sortitionPool.lock();
}
function start(Data storage self, uint256 seed) internal {
require(
currentState(self) == State.AWAITING_SEED,
"current state is not AWAITING_SEED"
);
self.startBlock = block.number;
self.seed = seed;
// slither-disable-next-line reentrancy-events
emit DkgStarted(seed);
}
/// @notice Allows to submit DKG result. The submitted result does not go
/// through a validation and before it gets accepted, it needs to
/// wait through the challenge period during which everyone has
/// a chance to challenge the result as invalid one. Submitter of
/// the result needs to be in the sortition pool and if the result
/// gets challenged, the submitter will get slashed.
function submitResult(Data storage self, Result calldata result) external {
require(
currentState(self) == State.AWAITING_RESULT,
"current state is not AWAITING_RESULT"
);
require(!hasDkgTimedOut(self), "dkg timeout already passed");
// Check submitter's eligibility to call this function
uint256 T_init = self.startBlock +
offchainDkgTime +
self.resultSubmissionStartBlockOffset;
require(
block.number >=
(T_init +
(result.submitterMemberIndex - 1) *
self.parameters.resultSubmissionEligibilityDelay),
"Submitter not eligible"
);
SortitionPool sortitionPool = self.sortitionPool;
// Submitter must be an operator in the sortition pool.
// Declared submitter's member index in the DKG result needs to match
// the address calling this function.
require(
sortitionPool.isOperatorInPool(msg.sender),
"Submitter not in the sortition pool"
);
require(
sortitionPool.getIDOperator(
result.members[result.submitterMemberIndex - 1]
) == msg.sender,
"Unexpected submitter index"
);
self.submittedResultHash = keccak256(abi.encode(result));
self.submittedResultBlock = block.number;
emit DkgResultSubmitted(
self.submittedResultHash,
self.seed,
result.submitterMemberIndex,
result.groupPubKey,
result.misbehavedMembersIndices,
result.signatures,
result.signingMembersIndices,
result.members
);
}
/// @notice Checks if DKG timed out. The DKG timeout period includes time required
/// for off-chain protocol execution and time for the result publication
/// for all group members. After this time result cannot be submitted
/// and DKG can be notified about the timeout. DKG period is adjusted
/// by result submission offset that include blocks that were mined
/// while invalid result has been registered until it got challenged.
/// @return True if DKG timed out, false otherwise.
function hasDkgTimedOut(Data storage self) internal view returns (bool) {
return
currentState(self) == State.AWAITING_RESULT &&
block.number >
(self.startBlock +
offchainDkgTime +
self.resultSubmissionStartBlockOffset +
groupSize *
self.parameters.resultSubmissionEligibilityDelay);
}
/// @notice Notifies about DKG timeout.
function notifyTimeout(Data storage self) internal {
require(hasDkgTimedOut(self), "dkg has not timed out");
emit DkgTimedOut();
}
/// @notice Notifies about the seed was not delivered and restores the
/// initial DKG state (IDLE).
function notifySeedTimedOut(Data storage self) internal {
require(
currentState(self) == State.AWAITING_SEED,
"current state is not AWAITING_SEED"
);
emit DkgSeedTimedOut();
self.sortitionPool.unlock();
}
/// @notice Approves DKG result. Can be called when the challenge period for
/// the submitted result is finished. Considers the submitted result
/// as valid. For the first `resultSubmissionEligibilityDelay`
/// blocks after the end of the challenge period can be called only
/// by the DKG result submitter. After that time, can be called by
/// anyone.
/// @dev Can be called after a challenge period for the submitted result.
/// @param result Result to approve. Must match the submitted result stored
/// during `submitResult`.
/// @return misbehavedMembers Identifiers of members who misbehaved during DKG.
function approveResult(Data storage self, Result calldata result)
external
returns (uint32[] memory misbehavedMembers)
{
require(
currentState(self) == State.CHALLENGE,
"current state is not CHALLENGE"
);
uint256 challengePeriodEnd = self.submittedResultBlock +
self.parameters.resultChallengePeriodLength;
require(
block.number > challengePeriodEnd,
"challenge period has not passed yet"
);
require(
keccak256(abi.encode(result)) == self.submittedResultHash,
"result under approval is different than the submitted one"
);
// Extract submitter member address. Submitter member index is in
// range [1, 64] so we need to -1 when fetching identifier from members
// array.
address submitterMember = self.sortitionPool.getIDOperator(
result.members[result.submitterMemberIndex - 1]
);
require(
msg.sender == submitterMember ||
block.number >
challengePeriodEnd +
self.parameters.resultSubmissionEligibilityDelay,
"Only the DKG result submitter can approve the result at this moment"
);
// Extract misbehaved members identifiers. Misbehaved members indices
// are in range [1, 64], so we need to -1 when fetching identifiers from
// members array.
misbehavedMembers = new uint32[](
result.misbehavedMembersIndices.length
);
for (uint256 i = 0; i < result.misbehavedMembersIndices.length; i++) {
misbehavedMembers[i] = result.members[
result.misbehavedMembersIndices[i] - 1
];
}
emit DkgResultApproved(self.submittedResultHash, msg.sender);
return misbehavedMembers;
}
/// @notice Challenges DKG result. If the submitted result is proved to be
/// invalid it reverts the DKG back to the result submission phase.
/// @dev Can be called during a challenge period for the submitted result.
/// @param result Result to challenge. Must match the submitted result
/// stored during `submitResult`.
/// @return maliciousResultHash Hash of the malicious result.
/// @return maliciousSubmitter Identifier of the malicious submitter.
function challengeResult(Data storage self, Result calldata result)
external
returns (bytes32 maliciousResultHash, uint32 maliciousSubmitter)
{
require(
currentState(self) == State.CHALLENGE,
"current state is not CHALLENGE"
);
require(
block.number <=
self.submittedResultBlock +
self.parameters.resultChallengePeriodLength,
"challenge period has already passed"
);
require(
keccak256(abi.encode(result)) == self.submittedResultHash,
"result under challenge is different than the submitted one"
);
try
self.dkgValidator.validate(result, self.seed, self.startBlock)
returns (bool isValid, string memory errorMsg) {
if (isValid) {
revert("unjustified challenge");
}
emit DkgResultChallenged(
self.submittedResultHash,
msg.sender,
errorMsg
);
} catch {
// if the validation reverted we consider the DKG result as invalid
emit DkgResultChallenged(
self.submittedResultHash,
msg.sender,
"validation reverted"
);
}
// Consider result hash as malicious.
maliciousResultHash = self.submittedResultHash;
maliciousSubmitter = result.members[result.submitterMemberIndex - 1];
// Adjust DKG result submission block start, so submission eligibility
// starts from the beginning.
self.resultSubmissionStartBlockOffset =
block.number -
self.startBlock -
offchainDkgTime;
submittedResultCleanup(self);
return (maliciousResultHash, maliciousSubmitter);
}
/// @notice Set resultChallengePeriodLength parameter.
function setResultChallengePeriodLength(
Data storage self,
uint256 newResultChallengePeriodLength
) internal {
require(currentState(self) == State.IDLE, "current state is not IDLE");
require(
newResultChallengePeriodLength > 0,
"new value should be greater than zero"
);
self
.parameters
.resultChallengePeriodLength = newResultChallengePeriodLength;
}
/// @notice Set resultSubmissionEligibilityDelay parameter.
function setResultSubmissionEligibilityDelay(
Data storage self,
uint256 newResultSubmissionEligibilityDelay
) internal {
require(currentState(self) == State.IDLE, "current state is not IDLE");
require(
newResultSubmissionEligibilityDelay > 0,
"new value should be greater than zero"
);
self
.parameters
.resultSubmissionEligibilityDelay = newResultSubmissionEligibilityDelay;
}
/// @notice Completes DKG by cleaning up state.
/// @dev Should be called after DKG times out or a result is approved.
function complete(Data storage self) internal {
delete self.startBlock;
delete self.seed;
delete self.resultSubmissionStartBlockOffset;
submittedResultCleanup(self);
self.sortitionPool.unlock();
}
/// @notice Cleans up submitted result state either after DKG completion
/// (as part of `complete` method) or after justified challenge.
function submittedResultCleanup(Data storage self) private {
delete self.submittedResultHash;
delete self.submittedResultBlock;
}
}