-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathWalletRegistry.sol
1303 lines (1160 loc) · 55.4 KB
/
WalletRegistry.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-3.0-only
//
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
pragma solidity 0.8.17;
import "./api/IWalletRegistry.sol";
import "./api/IWalletOwner.sol";
import "./libraries/Wallets.sol";
import {EcdsaAuthorization as Authorization} from "./libraries/EcdsaAuthorization.sol";
import {EcdsaDkg as DKG} from "./libraries/EcdsaDkg.sol";
import {EcdsaInactivity as Inactivity} from "./libraries/EcdsaInactivity.sol";
import {EcdsaDkgValidator as DKGValidator} from "./EcdsaDkgValidator.sol";
import "@keep-network/sortition-pools/contracts/SortitionPool.sol";
import "@keep-network/random-beacon/contracts/api/IRandomBeacon.sol";
import "@keep-network/random-beacon/contracts/api/IRandomBeaconConsumer.sol";
import "@keep-network/random-beacon/contracts/Reimbursable.sol";
import "@keep-network/random-beacon/contracts/ReimbursementPool.sol";
import "@keep-network/random-beacon/contracts/Governable.sol";
import "@threshold-network/solidity-contracts/contracts/staking/IApplication.sol";
import "@threshold-network/solidity-contracts/contracts/staking/IStaking.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract WalletRegistry is
IWalletRegistry,
IRandomBeaconConsumer,
IApplication,
Governable,
Reimbursable,
Initializable
{
using Authorization for Authorization.Data;
using DKG for DKG.Data;
using Wallets for Wallets.Data;
// Libraries data storages
Authorization.Data internal authorization;
DKG.Data internal dkg;
Wallets.Data internal wallets;
/// @notice Slashing amount for submitting a malicious DKG result. Every
/// DKG result submitted can be challenged for the time of
/// `dkg.resultChallengePeriodLength`. If the DKG result submitted
/// is challenged and proven to be malicious, the operator who
/// submitted the malicious result is slashed for
/// `_maliciousDkgResultSlashingAmount`.
uint96 internal _maliciousDkgResultSlashingAmount;
/// @notice Percentage of the staking contract malicious behavior
/// notification reward which will be transferred to the notifier
/// reporting about a malicious DKG result. Notifiers are rewarded
/// from a notifiers treasury pool. For example, if
/// notification reward is 1000 and the value of the multiplier is
/// 5, the notifier will receive: 5% of 1000 = 50 per each
/// operator affected.
uint256 internal _maliciousDkgResultNotificationRewardMultiplier;
/// @notice Duration of the sortition pool rewards ban imposed on operators
/// who missed their turn for DKG result submission or who failed
/// a heartbeat.
uint256 internal _sortitionPoolRewardsBanDuration;
/// @notice Calculated max gas cost for submitting a DKG result. This will
/// be refunded as part of the DKG approval process. It is in the
/// submitter's interest to not skip his priority turn on the approval,
/// otherwise the refund of the DKG submission will be refunded to
/// another group member that will call the DKG approve function.
uint256 internal _dkgResultSubmissionGas;
/// @notice Gas that is meant to balance the DKG result approval's overall
/// cost. It can be updated by the governance based on the current
/// market conditions.
uint256 internal _dkgResultApprovalGasOffset;
/// @notice Gas that is meant to balance the notification of an operator
/// inactivity. It can be updated by the governance based on the
/// current market conditions.
uint256 internal _notifyOperatorInactivityGasOffset;
/// @notice Gas that is meant to balance the notification of a seed for DKG
/// delivery timeout. It can be updated by the governance based on the
/// current market conditions.
uint256 internal _notifySeedTimeoutGasOffset;
/// @notice Gas that is meant to balance the notification of a DKG protocol
/// execution timeout. It can be updated by the governance based on the
/// current market conditions.
/// @dev The value is subtracted for the refundable gas calculation, as the
/// DKG timeout notification transaction recovers some gas when cleaning
/// up the storage.
uint256 internal _notifyDkgTimeoutNegativeGasOffset;
/// @notice Stores current operator inactivity claim nonce for the given
/// wallet signing group. Each claim is made with a unique nonce
/// which protects against claim replay.
mapping(bytes32 => uint256) public inactivityClaimNonce; // walletID -> nonce
// Address that is set as owner of all wallets. Only this address can request
// new wallets creation and manage their state.
IWalletOwner public walletOwner;
// External dependencies
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
SortitionPool public immutable sortitionPool;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IStaking public immutable staking;
IRandomBeacon public randomBeacon;
// Events
event DkgStarted(uint256 indexed seed);
event DkgResultSubmitted(
bytes32 indexed resultHash,
uint256 indexed seed,
DKG.Result result
);
event DkgTimedOut();
event DkgResultApproved(
bytes32 indexed resultHash,
address indexed approver
);
event DkgResultChallenged(
bytes32 indexed resultHash,
address indexed challenger,
string reason
);
event DkgStateLocked();
event DkgSeedTimedOut();
event WalletCreated(
bytes32 indexed walletID,
bytes32 indexed dkgResultHash
);
event WalletClosed(bytes32 indexed walletID);
event DkgMaliciousResultSlashed(
bytes32 indexed resultHash,
uint256 slashingAmount,
address maliciousSubmitter
);
event DkgMaliciousResultSlashingFailed(
bytes32 indexed resultHash,
uint256 slashingAmount,
address maliciousSubmitter
);
event AuthorizationParametersUpdated(
uint96 minimumAuthorization,
uint64 authorizationDecreaseDelay,
uint64 authorizationDecreaseChangePeriod
);
event RewardParametersUpdated(
uint256 maliciousDkgResultNotificationRewardMultiplier,
uint256 sortitionPoolRewardsBanDuration
);
event SlashingParametersUpdated(uint256 maliciousDkgResultSlashingAmount);
event DkgParametersUpdated(
uint256 seedTimeout,
uint256 resultChallengePeriodLength,
uint256 resultChallengeExtraGas,
uint256 resultSubmissionTimeout,
uint256 resultSubmitterPrecedencePeriodLength
);
event GasParametersUpdated(
uint256 dkgResultSubmissionGas,
uint256 dkgResultApprovalGasOffset,
uint256 notifyOperatorInactivityGasOffset,
uint256 notifySeedTimeoutGasOffset,
uint256 notifyDkgTimeoutNegativeGasOffset
);
event RandomBeaconUpgraded(address randomBeacon);
event WalletOwnerUpdated(address walletOwner);
event OperatorRegistered(
address indexed stakingProvider,
address indexed operator
);
event AuthorizationIncreased(
address indexed stakingProvider,
address indexed operator,
uint96 fromAmount,
uint96 toAmount
);
event AuthorizationDecreaseRequested(
address indexed stakingProvider,
address indexed operator,
uint96 fromAmount,
uint96 toAmount,
uint64 decreasingAt
);
event AuthorizationDecreaseApproved(address indexed stakingProvider);
event InvoluntaryAuthorizationDecreaseFailed(
address indexed stakingProvider,
address indexed operator,
uint96 fromAmount,
uint96 toAmount
);
event OperatorJoinedSortitionPool(
address indexed stakingProvider,
address indexed operator
);
event OperatorStatusUpdated(
address indexed stakingProvider,
address indexed operator
);
event InactivityClaimed(
bytes32 indexed walletID,
uint256 nonce,
address notifier
);
modifier onlyStakingContract() {
require(
msg.sender == address(staking),
"Caller is not the staking contract"
);
_;
}
/// @notice Reverts if called not by the Wallet Owner.
modifier onlyWalletOwner() {
require(
msg.sender == address(walletOwner),
"Caller is not the Wallet Owner"
);
_;
}
modifier onlyReimbursableAdmin() override {
require(governance == msg.sender, "Caller is not the governance");
_;
}
/// @dev Used to initialize immutable variables only, use `initialize` function
/// for upgradable contract initialization on deployment.
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(SortitionPool _sortitionPool, IStaking _staking) {
sortitionPool = _sortitionPool;
staking = _staking;
_disableInitializers();
}
/// @dev Initializes upgradable contract on deployment.
function initialize(
DKGValidator _ecdsaDkgValidator,
IRandomBeacon _randomBeacon,
ReimbursementPool _reimbursementPool
) external initializer {
randomBeacon = _randomBeacon;
reimbursementPool = _reimbursementPool;
_transferGovernance(msg.sender);
//
// All parameters set in the constructor are initial ones, used at the
// moment contracts were deployed for the first time. Parameters are
// governable and values assigned in the constructor do not need to
// reflect the current ones.
//
// Minimum authorization is 40k T.
//
// Authorization decrease delay is 45 days.
//
// Authorization decrease change period is 45 days. It means pending
// authorization decrease can be overwritten all the time.
authorization.setMinimumAuthorization(40_000e18);
authorization.setAuthorizationDecreaseDelay(3_888_000);
authorization.setAuthorizationDecreaseChangePeriod(3_888_000);
// Malicious DKG result slashing amount is set initially to 1% of the
// minimum authorization (400 T). This values needs to be increased
// significantly once the system is fully launched.
//
// Notifier of a malicious DKG result receives 100% of the notifier
// reward from the staking contract.
//
// Inactive operators are set as ineligible for rewards for 2 weeks.
_maliciousDkgResultSlashingAmount = 400e18;
_maliciousDkgResultNotificationRewardMultiplier = 100;
_sortitionPoolRewardsBanDuration = 2 weeks;
// DKG seed timeout is set to 48h assuming 15s block time. The same
// value is used by the Random Beacon as a relay entry hard timeout.
//
// DKG result challenge period length is set to 48h as well, assuming
// 15s block time.
//
// DKG result submission timeout covers:
// - 20 blocks required to confirm the DkgStarted event off-chain
// - 1 attempt of the off-chain protocol that takes 216 blocks at most
// - 3 blocks to submit the result for each of the 100 members
// That gives: 20 + (1 * 216) + (3 * 100) = 536
//
//
// The original DKG result submitter has 20 blocks to approve it before
// anyone else can do that.
//
// With these parameters, the happy path takes no more than 104 hours.
// In practice, it should take about 48 hours (just the challenge time).
dkg.init(sortitionPool, _ecdsaDkgValidator);
dkg.setSeedTimeout(11_520);
dkg.setResultChallengePeriodLength(11_520);
dkg.setResultChallengeExtraGas(50_000);
dkg.setResultSubmissionTimeout(536);
dkg.setSubmitterPrecedencePeriodLength(20);
// Gas parameters were adjusted based on Ethereum state in April 2022.
// If the cost of EVM opcodes change over time, these parameters will
// have to be updated.
_dkgResultSubmissionGas = 290_000;
_dkgResultApprovalGasOffset = 72_000;
_notifyOperatorInactivityGasOffset = 93_000;
_notifySeedTimeoutGasOffset = 7_250;
_notifyDkgTimeoutNegativeGasOffset = 2_300;
}
/// @notice Withdraws application rewards for the given staking provider.
/// Rewards are withdrawn to the staking provider's beneficiary
/// address set in the staking contract. Reverts if staking provider
/// has not registered the operator address.
/// @dev Emits `RewardsWithdrawn` event.
function withdrawRewards(address stakingProvider) external {
address operator = stakingProviderToOperator(stakingProvider);
require(operator != address(0), "Unknown operator");
(, address beneficiary, ) = staking.rolesOf(stakingProvider);
uint96 amount = sortitionPool.withdrawRewards(operator, beneficiary);
// slither-disable-next-line reentrancy-events
emit RewardsWithdrawn(stakingProvider, amount);
}
/// @notice Withdraws rewards belonging to operators marked as ineligible
/// for sortition pool rewards.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract.
/// @param recipient Recipient of withdrawn rewards.
function withdrawIneligibleRewards(address recipient)
external
onlyGovernance
{
sortitionPool.withdrawIneligible(recipient);
}
/// @notice Used by staking provider to set operator address that will
/// operate ECDSA node. The given staking provider can set operator
/// address only one time. The operator address can not be changed
/// and must be unique. Reverts if the operator is already set for
/// the staking provider or if the operator address is already in
/// use. Reverts if there is a pending authorization decrease for
/// the staking provider.
function registerOperator(address operator) external {
authorization.registerOperator(operator);
}
/// @notice Lets the operator join the sortition pool. The operator address
/// must be known - before calling this function, it has to be
/// appointed by the staking provider by calling `registerOperator`.
/// Also, the operator must have the minimum authorization required
/// by ECDSA. Function reverts if there is no minimum stake
/// authorized or if the operator is not known. If there was an
/// authorization decrease requested, it is activated by starting
/// the authorization decrease delay.
function joinSortitionPool() external {
authorization.joinSortitionPool(staking, sortitionPool);
}
/// @notice Updates status of the operator in the sortition pool. If there
/// was an authorization decrease requested, it is activated by
/// starting the authorization decrease delay.
/// Function reverts if the operator is not known.
function updateOperatorStatus(address operator) external {
authorization.updateOperatorStatus(staking, sortitionPool, operator);
}
/// @notice Used by T staking contract to inform the application that the
/// authorized stake amount for the given staking provider increased.
///
/// Reverts if the authorization amount is below the minimum.
///
/// The function is not updating the sortition pool. Sortition pool
/// state needs to be updated by the operator with a call to
/// `joinSortitionPool` or `updateOperatorStatus`.
///
/// @dev Can only be called by T staking contract.
function authorizationIncreased(
address stakingProvider,
uint96 fromAmount,
uint96 toAmount
) external onlyStakingContract {
authorization.authorizationIncreased(
stakingProvider,
fromAmount,
toAmount
);
}
/// @notice Used by T staking contract to inform the application that the
/// authorization decrease for the given staking provider has been
/// requested.
///
/// Reverts if the amount after deauthorization would be non-zero
/// and lower than the minimum authorization.
///
/// If the operator is not known (`registerOperator` was not called)
/// it lets to `approveAuthorizationDecrease` immediatelly. If the
/// operator is known (`registerOperator` was called), the operator
/// needs to update state of the sortition pool with a call to
/// `joinSortitionPool` or `updateOperatorStatus`. After the
/// sortition pool state is in sync, authorization decrease delay
/// starts.
///
/// After authorization decrease delay passes, authorization
/// decrease request needs to be approved with a call to
/// `approveAuthorizationDecrease` function.
///
/// If there is a pending authorization decrease request, it is
/// overwritten.
///
/// @dev Can only be called by T staking contract.
function authorizationDecreaseRequested(
address stakingProvider,
uint96 fromAmount,
uint96 toAmount
) external onlyStakingContract {
authorization.authorizationDecreaseRequested(
stakingProvider,
fromAmount,
toAmount
);
}
/// @notice Approves the previously registered authorization decrease
/// request. Reverts if authorization decrease delay has not passed
/// yet or if the authorization decrease was not requested for the
/// given staking provider.
function approveAuthorizationDecrease(address stakingProvider) external {
authorization.approveAuthorizationDecrease(staking, stakingProvider);
}
/// @notice Used by T staking contract to inform the application the
/// authorization has been decreased for the given staking provider
/// involuntarily, as a result of slashing.
///
/// If the operator is not known (`registerOperator` was not called)
/// the function does nothing. The operator was never in a sortition
/// pool so there is nothing to update.
///
/// If the operator is known, sortition pool is unlocked, and the
/// operator is in the sortition pool, the sortition pool state is
/// updated. If the sortition pool is locked, update needs to be
/// postponed. Every other staker is incentivized to call
/// `updateOperatorStatus` for the problematic operator to increase
/// their own rewards in the pool.
function involuntaryAuthorizationDecrease(
address stakingProvider,
uint96 fromAmount,
uint96 toAmount
) external onlyStakingContract {
authorization.involuntaryAuthorizationDecrease(
staking,
sortitionPool,
stakingProvider,
fromAmount,
toAmount
);
}
/// @notice Updates address of the Random Beacon.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract. The caller is responsible for
/// validating parameters.
/// @param _randomBeacon Random Beacon address.
function upgradeRandomBeacon(IRandomBeacon _randomBeacon)
external
onlyGovernance
{
randomBeacon = _randomBeacon;
emit RandomBeaconUpgraded(address(_randomBeacon));
}
/// @notice Updates the wallet owner.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract. The caller is responsible for
/// validating parameters. The wallet owner has to implement `IWalletOwner`
/// interface.
/// @param _walletOwner New wallet owner address.
function updateWalletOwner(IWalletOwner _walletOwner)
external
onlyGovernance
{
walletOwner = _walletOwner;
emit WalletOwnerUpdated(address(_walletOwner));
}
/// @notice Updates the values of authorization parameters.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract. The caller is responsible for
/// validating parameters.
/// @param _minimumAuthorization New minimum authorization amount.
/// @param _authorizationDecreaseDelay New authorization decrease delay in
/// seconds.
/// @param _authorizationDecreaseChangePeriod New authorization decrease
/// change period in seconds.
function updateAuthorizationParameters(
uint96 _minimumAuthorization,
uint64 _authorizationDecreaseDelay,
uint64 _authorizationDecreaseChangePeriod
) external onlyGovernance {
authorization.setMinimumAuthorization(_minimumAuthorization);
authorization.setAuthorizationDecreaseDelay(
_authorizationDecreaseDelay
);
authorization.setAuthorizationDecreaseChangePeriod(
_authorizationDecreaseChangePeriod
);
emit AuthorizationParametersUpdated(
_minimumAuthorization,
_authorizationDecreaseDelay,
_authorizationDecreaseChangePeriod
);
}
/// @notice Updates the values of DKG parameters.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract. The caller is responsible for
/// validating parameters.
/// @param _seedTimeout New seed timeout.
/// @param _resultChallengePeriodLength New DKG result challenge period
/// length.
/// @param _resultChallengeExtraGas New extra gas value required to be left
/// at the end of the DKG result challenge transaction.
/// @param _resultSubmissionTimeout New DKG result submission timeout.
/// @param _submitterPrecedencePeriodLength New submitter precedence period
/// length.
function updateDkgParameters(
uint256 _seedTimeout,
uint256 _resultChallengePeriodLength,
uint256 _resultChallengeExtraGas,
uint256 _resultSubmissionTimeout,
uint256 _submitterPrecedencePeriodLength
) external onlyGovernance {
dkg.setSeedTimeout(_seedTimeout);
dkg.setResultChallengePeriodLength(_resultChallengePeriodLength);
dkg.setResultChallengeExtraGas(_resultChallengeExtraGas);
dkg.setResultSubmissionTimeout(_resultSubmissionTimeout);
dkg.setSubmitterPrecedencePeriodLength(
_submitterPrecedencePeriodLength
);
// slither-disable-next-line reentrancy-events
emit DkgParametersUpdated(
_seedTimeout,
_resultChallengePeriodLength,
_resultChallengeExtraGas,
_resultSubmissionTimeout,
_submitterPrecedencePeriodLength
);
}
/// @notice Updates the values of reward parameters.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract. The caller is responsible for
/// validating parameters.
/// @param maliciousDkgResultNotificationRewardMultiplier New value of the
/// DKG malicious result notification reward multiplier.
/// @param sortitionPoolRewardsBanDuration New sortition pool rewards
/// ban duration in seconds.
function updateRewardParameters(
uint256 maliciousDkgResultNotificationRewardMultiplier,
uint256 sortitionPoolRewardsBanDuration
) external onlyGovernance {
_maliciousDkgResultNotificationRewardMultiplier = maliciousDkgResultNotificationRewardMultiplier;
_sortitionPoolRewardsBanDuration = sortitionPoolRewardsBanDuration;
emit RewardParametersUpdated(
maliciousDkgResultNotificationRewardMultiplier,
sortitionPoolRewardsBanDuration
);
}
/// @notice Updates the values of slashing parameters.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract. The caller is responsible for
/// validating parameters.
/// @param maliciousDkgResultSlashingAmount New malicious DKG result
/// slashing amount.
function updateSlashingParameters(uint96 maliciousDkgResultSlashingAmount)
external
onlyGovernance
{
_maliciousDkgResultSlashingAmount = maliciousDkgResultSlashingAmount;
emit SlashingParametersUpdated(maliciousDkgResultSlashingAmount);
}
/// @notice Updates the values of gas-related parameters.
/// @dev Can be called only by the contract guvnor, which should be the
/// wallet registry governance contract. The caller is responsible for
/// validating parameters.
/// @param dkgResultSubmissionGas New DKG result submission gas.
/// @param dkgResultApprovalGasOffset New DKG result approval gas offset.
/// @param notifyOperatorInactivityGasOffset New operator inactivity
/// notification gas offset.
/// @param notifySeedTimeoutGasOffset New seed for DKG delivery timeout
/// notification gas offset.
/// @param notifyDkgTimeoutNegativeGasOffset New DKG timeout notification gas
/// offset.
function updateGasParameters(
uint256 dkgResultSubmissionGas,
uint256 dkgResultApprovalGasOffset,
uint256 notifyOperatorInactivityGasOffset,
uint256 notifySeedTimeoutGasOffset,
uint256 notifyDkgTimeoutNegativeGasOffset
) external onlyGovernance {
_dkgResultSubmissionGas = dkgResultSubmissionGas;
_dkgResultApprovalGasOffset = dkgResultApprovalGasOffset;
_notifyOperatorInactivityGasOffset = notifyOperatorInactivityGasOffset;
_notifySeedTimeoutGasOffset = notifySeedTimeoutGasOffset;
_notifyDkgTimeoutNegativeGasOffset = notifyDkgTimeoutNegativeGasOffset;
emit GasParametersUpdated(
dkgResultSubmissionGas,
dkgResultApprovalGasOffset,
notifyOperatorInactivityGasOffset,
_notifySeedTimeoutGasOffset,
_notifyDkgTimeoutNegativeGasOffset
);
}
/// @notice Requests a new wallet creation.
/// @dev Can be called only by the owner of wallets.
/// It locks the DKG and request a new relay entry. It expects
/// that the DKG process will be started once a new relay entry
/// gets generated.
function requestNewWallet() external onlyWalletOwner {
dkg.lockState();
randomBeacon.requestRelayEntry(this);
}
/// @notice Closes an existing wallet. Reverts if wallet with the given ID
/// does not exist or if it has already been closed.
/// @param walletID ID of the wallet.
/// @dev Only a Wallet Owner can call this function.
function closeWallet(bytes32 walletID) external onlyWalletOwner {
wallets.deleteWallet(walletID);
emit WalletClosed(walletID);
}
/// @notice A callback that is executed once a new relay entry gets
/// generated. It starts the DKG process.
/// @dev Can be called only by the random beacon contract.
/// @param relayEntry Relay entry.
function __beaconCallback(uint256 relayEntry, uint256) external {
require(
msg.sender == address(randomBeacon),
"Caller is not the Random Beacon"
);
dkg.start(relayEntry);
}
/// @notice Submits result of DKG protocol.
/// The DKG result consists of result submitting member index,
/// calculated group public key, bytes array of misbehaved members,
/// concatenation of signatures from group members, indices of members
/// corresponding to each signature and the list of group members.
/// The result is registered optimistically and waits for an approval.
/// The result can be challenged when it is believed to be incorrect.
/// The challenge verifies the registered result i.a. it checks if members
/// list corresponds to the expected set of members determined
/// by the sortition pool.
/// @dev The message to be signed by each member is keccak256 hash of the
/// chain ID, calculated group public key, misbehaved members indices
/// and DKG start block. The calculated hash should be prefixed with
/// `\x19Ethereum signed message:\n` before signing, so the message to
/// sign is:
/// `\x19Ethereum signed message:\n${keccak256(chainID,groupPubKey,misbehavedIndices,startBlock)}`
/// @param dkgResult DKG result.
function submitDkgResult(DKG.Result calldata dkgResult) external {
wallets.validatePublicKey(dkgResult.groupPubKey);
dkg.submitResult(dkgResult);
}
/// @notice Approves DKG result. Can be called when the challenge period for
/// the submitted result is finished. Considers the submitted result
/// as valid, bans misbehaved group members from the sortition pool
/// rewards, and completes the group creation by activating the
/// candidate group. For the first `resultSubmissionTimeout` 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.
/// A new wallet based on the DKG result details.
/// @param dkgResult Result to approve. Must match the submitted result
/// stored during `submitDkgResult`.
function approveDkgResult(DKG.Result calldata dkgResult) external {
uint256 gasStart = gasleft();
uint32[] memory misbehavedMembers = dkg.approveResult(dkgResult);
(bytes32 walletID, bytes32 publicKeyX, bytes32 publicKeyY) = wallets
.addWallet(dkgResult.membersHash, dkgResult.groupPubKey);
emit WalletCreated(walletID, keccak256(abi.encode(dkgResult)));
if (misbehavedMembers.length > 0) {
sortitionPool.setRewardIneligibility(
misbehavedMembers,
// solhint-disable-next-line not-rely-on-time
block.timestamp + _sortitionPoolRewardsBanDuration
);
}
walletOwner.__ecdsaWalletCreatedCallback(
walletID,
publicKeyX,
publicKeyY
);
dkg.complete();
// Refund msg.sender's ETH for DKG result submission and result approval
reimbursementPool.refund(
_dkgResultSubmissionGas +
(gasStart - gasleft()) +
_dkgResultApprovalGasOffset,
msg.sender
);
}
/// @notice Notifies about seed for DKG delivery timeout. It is expected
/// that a seed is delivered by the Random Beacon as a relay entry in a
/// callback function.
function notifySeedTimeout() external {
uint256 gasStart = gasleft();
dkg.notifySeedTimeout();
reimbursementPool.refund(
(gasStart - gasleft()) + _notifySeedTimeoutGasOffset,
msg.sender
);
}
/// @notice Notifies about DKG timeout.
function notifyDkgTimeout() external {
uint256 gasStart = gasleft();
dkg.notifyDkgTimeout();
// Note that the offset is subtracted as it is expected that the cleanup
// performed on DKG timeout notification removes data from the storage
// which is recovering gas for the transaction.
reimbursementPool.refund(
(gasStart - gasleft()) - _notifyDkgTimeoutNegativeGasOffset,
msg.sender
);
}
/// @notice Challenges DKG result. If the submitted result is proved to be
/// invalid it reverts the DKG back to the result submission phase.
/// @param dkgResult Result to challenge. Must match the submitted result
/// stored during `submitDkgResult`.
/// @dev Due to EIP-150 1/64 of the gas is not forwarded to the call, and
/// will be kept to execute the remaining operations in the function
/// after the call inside the try-catch. To eliminate a class of
/// attacks related to the gas limit manipulation, this function
/// requires an extra amount of gas to be left at the end of the
/// execution.
function challengeDkgResult(DKG.Result calldata dkgResult) external {
// solhint-disable-next-line avoid-tx-origin
require(msg.sender == tx.origin, "Not EOA");
(
bytes32 maliciousDkgResultHash,
uint32 maliciousDkgResultSubmitterId
) = dkg.challengeResult(dkgResult);
address maliciousDkgResultSubmitterAddress = sortitionPool
.getIDOperator(maliciousDkgResultSubmitterId);
address[] memory operatorWrapper = new address[](1);
operatorWrapper[0] = operatorToStakingProvider(
maliciousDkgResultSubmitterAddress
);
try
staking.seize(
_maliciousDkgResultSlashingAmount,
_maliciousDkgResultNotificationRewardMultiplier,
msg.sender,
operatorWrapper
)
{
// slither-disable-next-line reentrancy-events
emit DkgMaliciousResultSlashed(
maliciousDkgResultHash,
_maliciousDkgResultSlashingAmount,
maliciousDkgResultSubmitterAddress
);
} catch {
// Should never happen but we want to ensure a non-critical path
// failure from an external contract does not stop the challenge
// to complete.
emit DkgMaliciousResultSlashingFailed(
maliciousDkgResultHash,
_maliciousDkgResultSlashingAmount,
maliciousDkgResultSubmitterAddress
);
}
// Due to EIP-150, 1/64 of the gas is not forwarded to the call, and
// will be kept to execute the remaining operations in the function
// after the call inside the try-catch.
//
// To ensure there is no way for the caller to manipulate gas limit in
// such a way that the call inside try-catch fails with out-of-gas and
// the rest of the function is executed with the remaining 1/64 of gas,
// we require an extra gas amount to be left at the end of the call to
// `challengeDkgResult`.
dkg.requireChallengeExtraGas();
}
/// @notice Notifies about operators who are inactive. Using this function,
/// a majority of the wallet signing group can decide about
/// punishing specific group members who constantly fail doing their
/// job. If the provided claim is proved to be valid and signed by
/// sufficient number of group members, operators of members deemed
/// as inactive are banned from sortition pool rewards for the
/// duration specified by `sortitionPoolRewardsBanDuration` parameter.
/// The function allows to signal about single operators being
/// inactive as well as to signal wallet-wide heartbeat failures
/// that are propagated to the wallet owner who should begin the
/// procedure of moving responsibilities to another wallet given
/// that the wallet who failed the heartbeat may soon be not able to
/// function and provide new signatures.
/// The sender of the claim must be one of the claim signers. This
/// function can be called only for registered wallets
/// @param claim Operator inactivity claim.
/// @param nonce Current inactivity claim nonce for the given wallet signing
/// group. Must be the same as the stored one.
/// @param groupMembers Identifiers of the wallet signing group members.
function notifyOperatorInactivity(
Inactivity.Claim calldata claim,
uint256 nonce,
uint32[] calldata groupMembers
) external {
uint256 gasStart = gasleft();
bytes32 walletID = claim.walletID;
require(nonce == inactivityClaimNonce[walletID], "Invalid nonce");
(bytes32 pubKeyX, bytes32 pubKeyY) = wallets
.getWalletPublicKeyCoordinates(walletID);
bytes32 memberIdsHash = wallets.getWalletMembersIdsHash(walletID);
require(
memberIdsHash == keccak256(abi.encode(groupMembers)),
"Invalid group members"
);
uint32[] memory ineligibleOperators = Inactivity.verifyClaim(
sortitionPool,
claim,
bytes.concat(pubKeyX, pubKeyY),
nonce,
groupMembers
);
inactivityClaimNonce[walletID]++;
emit InactivityClaimed(walletID, nonce, msg.sender);
sortitionPool.setRewardIneligibility(
ineligibleOperators,
// solhint-disable-next-line not-rely-on-time
block.timestamp + _sortitionPoolRewardsBanDuration
);
if (claim.heartbeatFailed) {
walletOwner.__ecdsaWalletHeartbeatFailedCallback(
walletID,
pubKeyX,
pubKeyY
);
}
reimbursementPool.refund(
(gasStart - gasleft()) + _notifyOperatorInactivityGasOffset,
msg.sender
);
}
/// @notice Allows the wallet owner to add all signing group members of the
/// wallet with the given ID to the slashing queue of the staking .
/// contract. The notifier will receive reward per each group member
/// from the staking contract notifiers treasury. The reward is
/// scaled by the `rewardMultiplier` provided as a parameter.
/// @param amount Amount of tokens to seize from each signing group member.
/// @param rewardMultiplier Fraction of the staking contract notifiers
/// reward the notifier should receive; should be between [0, 100].
/// @param notifier Address of the misbehavior notifier.
/// @param walletID ID of the wallet.
/// @param walletMembersIDs Identifiers of the wallet signing group members.
/// @dev Requirements:
/// - The expression `keccak256(abi.encode(walletMembersIDs))` must
/// be exactly the same as the hash stored under `membersIdsHash`
/// for the given `walletID`. Those IDs are not directly stored
/// in the contract for gas efficiency purposes but they can be
/// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`
/// events.
/// - `rewardMultiplier` must be between [0, 100].
/// - This function does revert if staking contract call reverts.
/// The calling code needs to handle the potential revert.
function seize(
uint96 amount,
uint256 rewardMultiplier,
address notifier,
bytes32 walletID,
uint32[] calldata walletMembersIDs
) external onlyWalletOwner {
bytes32 memberIdsHash = wallets.getWalletMembersIdsHash(walletID);
require(
memberIdsHash == keccak256(abi.encode(walletMembersIDs)),
"Invalid wallet members identifiers"
);
address[] memory groupMembersAddresses = sortitionPool.getIDOperators(
walletMembersIDs
);
address[] memory stakingProvidersAddresses = new address[](
walletMembersIDs.length
);
for (uint256 i = 0; i < groupMembersAddresses.length; i++) {
stakingProvidersAddresses[i] = operatorToStakingProvider(
groupMembersAddresses[i]
);
}
staking.seize(
amount,
rewardMultiplier,
notifier,
stakingProvidersAddresses
);
}
/// @notice Checks if DKG result is valid for the current DKG.
/// @param result DKG result.
/// @return True if the result is valid. If the result is invalid it returns
/// false and an error message.
function isDkgResultValid(DKG.Result calldata result)
external
view
returns (bool, string memory)
{
return dkg.isResultValid(result);
}
/// @notice Check current wallet creation state.
function getWalletCreationState() external view returns (DKG.State) {
return dkg.currentState();
}
/// @notice Checks whether the given operator is a member of the given
/// wallet signing group.
/// @param walletID ID of the wallet.