-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathWalletRegistry.sol
More file actions
1521 lines (1356 loc) · 66.8 KB
/
Copy pathWalletRegistry.sol
File metadata and controls
1521 lines (1356 loc) · 66.8 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
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 "./Allowlist.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;
/// @notice Allowlist contract for weight-based operator authorization.
/// When set (non-zero address), takes precedence over legacy TokenStaking.
/// This enables gradual migration from T staking to allowlist-based
/// authorization following TIP-092, while maintaining backward
/// compatibility with existing deployments.
/// @dev Set via initializeV2() during proxy upgrade. When allowlist is zero
/// address (default), the legacy TokenStaking authorization path is used.
Allowlist public allowlist;
// 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
);
// Custom Errors
// Authorization Errors
/// @notice Raised when caller is not the staking contract or allowlist contract.
error CallerNotStakingContract();
/// @notice Raised when caller is not the designated wallet owner contract.
error CallerNotWalletOwner();
/// @notice Raised when caller is not the governance address.
error CallerNotGovernance();
/// @notice Raised when caller is not the authorized random beacon contract.
error CallerNotRandomBeacon();
// Validation Errors
/// @notice Raised when allowlist address provided is zero address.
error AllowlistAddressZero();
/// @notice Raised when querying an operator that has not been registered.
error UnknownOperator();
/// @notice Raised when provided nonce does not match the expected inactivity claim nonce.
error InvalidNonce();
/// @notice Raised when the hash of provided group members does not match wallet's stored hash.
error InvalidGroupMembers();
/// @notice Raised when the hash of provided wallet member IDs does not match stored hash.
error InvalidWalletMembersIdentifiers();
/// @notice Raised when querying with an address that is not a sortition pool operator.
error NotSortitionPoolOperator();
/// @notice Raised when provided wallet member index is outside valid range [1, length].
error WalletMemberIndexOutOfRange();
// State Errors
/// @notice Raised when DKG parameter update attempted while DKG state is not IDLE.
error CurrentStateNotIdle();
// Configuration Errors
/// @notice Raised when insufficient gas remains after challengeDkgResult execution.
error NotEnoughExtraGasLeft();
/// @notice Dual-mode authorization modifier supporting both Allowlist and
/// legacy TokenStaking authorization paths.
/// @dev Authorization precedence:
/// 1. If allowlist is set (non-zero), only allowlist contract can call
/// 2. If allowlist is NOT set (zero), only legacy staking contract can call
/// This ensures a clean migration path while maintaining backward compatibility.
/// The address is cached in a local variable to minimize gas costs from
/// storage reads (SLOAD operation).
modifier onlyStakingContract() {
address _allowlist = address(allowlist);
if (_allowlist != address(0)) {
// Allowlist authorization path (post-TIP-092)
if (msg.sender != _allowlist) revert CallerNotStakingContract();
} else {
// Legacy staking authorization path (pre-TIP-092, backward compatible)
if (msg.sender != address(staking))
revert CallerNotStakingContract();
}
_;
}
/// @notice Reverts if called not by the Wallet Owner.
modifier onlyWalletOwner() {
if (msg.sender != address(walletOwner)) revert CallerNotWalletOwner();
_;
}
/// @notice Reverts if called not by the governance.
modifier onlyReimbursableAdmin() override {
if (msg.sender != governance) revert CallerNotGovernance();
_;
}
/// @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 Upgrades WalletRegistry to support allowlist-based authorization.
/// This function enables the migration from legacy TokenStaking to the
/// new Allowlist contract following TIP-092 governance decision.
/// Once called, the allowlist contract becomes the sole authority for
/// operator authorization, replacing the TokenStaking contract.
/// @param _allowlist Address of the Allowlist contract
/// @dev Uses reinitializer(2) for proxy upgrade compatibility. Can only be
/// called once per proxy upgrade. The zero address check prevents
/// misconfiguration that would break authorization.
/// After successful execution, the onlyStakingContract modifier will
/// only accept calls from the allowlist contract.
///
/// SECURITY ASSUMPTION (Audit ISSUE #2 - Bytecode Optimization):
/// Front-running protection is provided by atomic upgradeToAndCall pattern,
/// not by governance modifier (removed to save ~42 bytes). The governance
/// process MUST enforce atomic upgrades via upgradeToAndCall and prohibit
/// separate upgradeTo followed by initializeV2 calls. The reinitializer(2)
/// modifier prevents re-initialization after successful atomic upgrade.
///
/// Atomic Upgrade Requirement:
/// - Proxy admin MUST use upgradeToAndCall (single transaction)
/// - Upgrade implementation + initialize MUST be atomic
/// - No front-running window between upgrade and initialization
/// - Violation of this assumption creates front-running vulnerability
function initializeV2(address _allowlist) external reinitializer(2) {
if (_allowlist == address(0)) revert AllowlistAddressZero();
allowlist = Allowlist(_allowlist);
}
/// @notice Withdraws application rewards for the given staking provider.
/// Rewards are withdrawn to the beneficiary returned by
/// `rolesOf(stakingProvider)` on the current authorization source.
/// Reverts if the staking provider has not registered the operator
/// address.
/// @dev Emits `RewardsWithdrawn` event.
///
/// Beneficiary lookup uses `_currentAuthorizationSource()` (Allowlist
/// when set, otherwise legacy TokenStaking), consistent with other
/// authorization reads. For delegated setups, Allowlist.rolesOf() and
/// TokenStaking.rolesOf() can disagree on beneficiary; mainnet has
/// shown at least one live provider where the two sources diverge.
///
/// Historical context (TIP-092/100 - February 15, 2025):
/// - Sortition pool DKG participation rewards halted; TokenStaking notification
/// rewards halted for ECDSA/RandomBeacon; only TACo application rewards were
/// in a transition window. Today this path returns 0 for ECDSA operators (no
/// rewards), so immediate impact is bounded; the next redeploy still encodes
/// the beneficiary routing above if rewards are ever re-enabled.
///
/// If rewards are reactivated: Allowlist.rolesOf() always returns the staking
/// provider as beneficiary (no owner-vs-beneficiary delegation), while
/// TokenStaking.rolesOf() returns the configured beneficiary when delegation
/// applies. Operators should align expectations with whichever source is active.
function withdrawRewards(address stakingProvider) external {
address operator = stakingProviderToOperator(stakingProvider);
if (operator == address(0)) revert UnknownOperator();
(, address beneficiary, ) = _currentAuthorizationSource().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(
_currentAuthorizationSource(),
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(
_currentAuthorizationSource(),
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.
///
/// IMPLEMENTATION NOTE: This function does NOT require authorization
/// source routing (no _currentAuthorizationSource() parameter) because
/// it operates solely on internal library state.
///
/// Technical Rationale:
/// - Records authorization decrease request in internal mappings only
/// - Does NOT query external contracts for authorization amounts
/// - Does NOT apply the decrease (approval happens later via separate call)
/// - Contrast with involuntaryAuthorizationDecrease() which MUST query
/// current authorization amounts and therefore requires routing parameter
///
/// Post-Migration Behavior: Unchanged - requests are recorded without
/// querying authorization source (TokenStaking or Allowlist).
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(
_currentAuthorizationSource(),
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(
_currentAuthorizationSource(),
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 {
// Consolidated state validation for all DKG parameter setters. Since all
// setters are called exclusively from this function, we perform the state
// check once here instead of in each individual setter to reduce bytecode size.
if (dkg.currentState() != DKG.State.IDLE) revert CurrentStateNotIdle();
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 {
if (msg.sender != address(randomBeacon)) {
revert CallerNotRandomBeacon();
}
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.
///
/// This function is EIP-7702 compatible - it does not restrict
/// callers to EOAs, allowing accounts with delegated code execution
/// to participate in DKG result challenges. Gas manipulation
/// protection is enforced via inline gas check regardless of caller
/// type.
function challengeDkgResult(DKG.Result calldata dkgResult) external {
(
bytes32 maliciousDkgResultHash,
uint32 maliciousDkgResultSubmitterId
) = dkg.challengeResult(dkgResult);
address maliciousDkgResultSubmitterAddress = sortitionPool
.getIDOperator(maliciousDkgResultSubmitterId);
address[] memory operatorWrapper = new address[](1);
operatorWrapper[0] = operatorToStakingProvider(
maliciousDkgResultSubmitterAddress
);
// NOT MIGRATED: Slashing call remains on TokenStaking for pragmatic
// reasons, not functional requirements.
//
// Critical Context - TokenStaking.seize() is a STUB (TIP-100):
// - Function ONLY emits NotificationReceived event
// - NO token operations, NO storage mutations, NO economic penalty
// - Both TokenStaking.seize() and Allowlist.seize() provide symbolic
// slashing only (event emission for monitoring)
// - Actual enforcement mechanism: DAO governance via requestWeightDecrease()
//
// Migration Decision Rationale:
// - Bytecode cost: 100-200 bytes to route through Allowlist
// - Benefit: Zero (both contracts provide identical symbolic behavior)
// - Event preservation: TokenStaking event includes amount/rewardMultiplier
// fields for monitoring continuity (though values are symbolic)
// - Risk: Zero implementation risk (no code changes = no bugs)
//
// Historical Note: The presence of staking.seize() may create a false
// impression of economic slashing. In reality, economic slashing was
// removed in TIP-100 implementation. This call exists for event telemetry
// and DAO governance coordination only.
//
// Stakeholder Decision: Pragmatic choice to save bytecode and avoid
// implementation risk for functionally equivalent routing options.
// Attempt to slash malicious submitter. Slashing may fail silently
// if the staking contract reverts, but challenge must complete
// regardless. Bytecode optimization: empty catch block reduces
// contract size by ~800 bytes (see commit 412a8e6d).
// slither-disable-next-line reentrancy-events
try