-
Notifications
You must be signed in to change notification settings - Fork 194
/
NodeOperatorsRegistry.sol
1563 lines (1308 loc) · 78 KB
/
NodeOperatorsRegistry.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-FileCopyrightText: 2023 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
// See contracts/COMPILERS.md
pragma solidity 0.4.24;
import {AragonApp} from "@aragon/os/contracts/apps/AragonApp.sol";
import {SafeMath} from "@aragon/os/contracts/lib/math/SafeMath.sol";
import {UnstructuredStorage} from "@aragon/os/contracts/common/UnstructuredStorage.sol";
import {Math256} from "../../common/lib/Math256.sol";
import {MinFirstAllocationStrategy} from "../../common/lib/MinFirstAllocationStrategy.sol";
import {ILidoLocator} from "../../common/interfaces/ILidoLocator.sol";
import {IBurner} from "../../common/interfaces/IBurner.sol";
import {SigningKeys} from "../lib/SigningKeys.sol";
import {Packed64x4} from "../lib/Packed64x4.sol";
import {Versioned} from "../utils/Versioned.sol";
interface IStETH {
function sharesOf(address _account) external view returns (uint256);
function transferShares(address _recipient, uint256 _sharesAmount) external returns (uint256);
function approve(address _spender, uint256 _amount) external returns (bool);
}
/// @title Node Operator registry
/// @notice Node Operator registry manages signing keys and other node operator data.
/// @dev Must implement the full version of IStakingModule interface, not only the one declared locally.
/// It's also responsible for distributing rewards to node operators.
/// NOTE: the code below assumes moderate amount of node operators, i.e. up to `MAX_NODE_OPERATORS_COUNT`.
contract NodeOperatorsRegistry is AragonApp, Versioned {
using SafeMath for uint256;
using UnstructuredStorage for bytes32;
using SigningKeys for bytes32;
using Packed64x4 for Packed64x4.Packed;
//
// EVENTS
//
event NodeOperatorAdded(uint256 nodeOperatorId, string name, address rewardAddress, uint64 stakingLimit);
event NodeOperatorActiveSet(uint256 indexed nodeOperatorId, bool active);
event NodeOperatorNameSet(uint256 indexed nodeOperatorId, string name);
event NodeOperatorRewardAddressSet(uint256 indexed nodeOperatorId, address rewardAddress);
event NodeOperatorTotalKeysTrimmed(uint256 indexed nodeOperatorId, uint64 totalKeysTrimmed);
event KeysOpIndexSet(uint256 keysOpIndex);
event StakingModuleTypeSet(bytes32 moduleType);
event RewardsDistributed(address indexed rewardAddress, uint256 sharesAmount);
event RewardDistributionStateChanged(RewardDistributionState state);
event LocatorContractSet(address locatorAddress);
event VettedSigningKeysCountChanged(uint256 indexed nodeOperatorId, uint256 approvedValidatorsCount);
event DepositedSigningKeysCountChanged(uint256 indexed nodeOperatorId, uint256 depositedValidatorsCount);
event ExitedSigningKeysCountChanged(uint256 indexed nodeOperatorId, uint256 exitedValidatorsCount);
event TotalSigningKeysCountChanged(uint256 indexed nodeOperatorId, uint256 totalValidatorsCount);
event NonceChanged(uint256 nonce);
event StuckPenaltyDelayChanged(uint256 stuckPenaltyDelay);
event StuckPenaltyStateChanged(
uint256 indexed nodeOperatorId,
uint256 stuckValidatorsCount,
uint256 refundedValidatorsCount,
uint256 stuckPenaltyEndTimestamp
);
event TargetValidatorsCountChanged(uint256 indexed nodeOperatorId, uint256 targetValidatorsCount, uint256 targetLimitMode);
event NodeOperatorPenalized(address indexed recipientAddress, uint256 sharesPenalizedAmount);
// Enum to represent the state of the reward distribution process
enum RewardDistributionState {
TransferredToModule, // New reward portion minted and transferred to the module
ReadyForDistribution, // Operators' statistics updated, reward ready for distribution
Distributed // Reward distributed among operators
}
//
// ACL
//
// bytes32 public constant MANAGE_SIGNING_KEYS = keccak256("MANAGE_SIGNING_KEYS");
bytes32 public constant MANAGE_SIGNING_KEYS = 0x75abc64490e17b40ea1e66691c3eb493647b24430b358bd87ec3e5127f1621ee;
// bytes32 public constant SET_NODE_OPERATOR_LIMIT_ROLE = keccak256("SET_NODE_OPERATOR_LIMIT_ROLE");
bytes32 public constant SET_NODE_OPERATOR_LIMIT_ROLE = 0x07b39e0faf2521001ae4e58cb9ffd3840a63e205d288dc9c93c3774f0d794754;
// bytes32 public constant ACTIVATE_NODE_OPERATOR_ROLE = keccak256("MANAGE_NODE_OPERATOR_ROLE");
bytes32 public constant MANAGE_NODE_OPERATOR_ROLE = 0x78523850fdd761612f46e844cf5a16bda6b3151d6ae961fd7e8e7b92bfbca7f8;
// bytes32 public constant STAKING_ROUTER_ROLE = keccak256("STAKING_ROUTER_ROLE");
bytes32 public constant STAKING_ROUTER_ROLE = 0xbb75b874360e0bfd87f964eadd8276d8efb7c942134fc329b513032d0803e0c6;
//
// CONSTANTS
//
uint256 public constant MAX_NODE_OPERATORS_COUNT = 200;
uint256 public constant MAX_NODE_OPERATOR_NAME_LENGTH = 255;
uint256 public constant MAX_STUCK_PENALTY_DELAY = 365 days;
uint256 internal constant UINT64_MAX = 0xFFFFFFFFFFFFFFFF;
// SigningKeysStats
/// @dev Operator's max validator keys count approved for deposit by the DAO
uint8 internal constant TOTAL_VETTED_KEYS_COUNT_OFFSET = 0;
/// @dev Number of keys in the EXITED state of this operator for all time
uint8 internal constant TOTAL_EXITED_KEYS_COUNT_OFFSET = 1;
/// @dev Total number of keys of this operator for all time
uint8 internal constant TOTAL_KEYS_COUNT_OFFSET = 2;
/// @dev Number of keys of this operator which were in DEPOSITED state for all time
uint8 internal constant TOTAL_DEPOSITED_KEYS_COUNT_OFFSET = 3;
// TargetValidatorsStats
/// @dev Target limit mode, allows limiting target active validators count for operator (0 = disabled, 1 = soft mode, 2 = forced mode)
uint8 internal constant TARGET_LIMIT_MODE_OFFSET = 0;
/// @dev relative target active validators limit for operator, set by DAO
/// @notice used to check how many keys should go to exit, 0 - means all deposited keys would be exited
uint8 internal constant TARGET_VALIDATORS_COUNT_OFFSET = 1;
/// @dev actual operators's number of keys which could be deposited
uint8 internal constant MAX_VALIDATORS_COUNT_OFFSET = 2;
// StuckPenaltyStats
/// @dev stuck keys count from oracle report
uint8 internal constant STUCK_VALIDATORS_COUNT_OFFSET = 0;
/// @dev refunded keys count from dao
uint8 internal constant REFUNDED_VALIDATORS_COUNT_OFFSET = 1;
/// @dev extra penalty time after stuck keys resolved (refunded and/or exited)
/// @notice field is also used as flag for "half-cleaned" penalty status
/// Operator is PENALIZED if `STUCK_VALIDATORS_COUNT > REFUNDED_VALIDATORS_COUNT` or
/// `STUCK_VALIDATORS_COUNT <= REFUNDED_VALIDATORS_COUNT && STUCK_PENALTY_END_TIMESTAMP <= refund timestamp + STUCK_PENALTY_DELAY`
/// When operator refund all stuck validators and time has pass STUCK_PENALTY_DELAY, but STUCK_PENALTY_END_TIMESTAMP not zeroed,
/// then Operator can receive rewards but can't get new deposits until the new Oracle report or `clearNodeOperatorPenalty` is called.
uint8 internal constant STUCK_PENALTY_END_TIMESTAMP_OFFSET = 2;
// Summary SigningKeysStats
uint8 internal constant SUMMARY_MAX_VALIDATORS_COUNT_OFFSET = 0;
/// @dev Number of keys of all operators which were in the EXITED state for all time
uint8 internal constant SUMMARY_EXITED_KEYS_COUNT_OFFSET = 1;
/// @dev [deprecated] Total number of keys of all operators for all time
uint8 internal constant SUMMARY_TOTAL_KEYS_COUNT_OFFSET = 2;
/// @dev Number of keys of all operators which were in the DEPOSITED state for all time
uint8 internal constant SUMMARY_DEPOSITED_KEYS_COUNT_OFFSET = 3;
//
// UNSTRUCTURED STORAGE POSITIONS
//
// bytes32 internal constant SIGNING_KEYS_MAPPING_NAME = keccak256("lido.NodeOperatorsRegistry.signingKeysMappingName");
bytes32 internal constant SIGNING_KEYS_MAPPING_NAME = 0xeb2b7ad4d8ce5610cfb46470f03b14c197c2b751077c70209c5d0139f7c79ee9;
// bytes32 internal constant LIDO_LOCATOR_POSITION = keccak256("lido.NodeOperatorsRegistry.lidoLocator");
bytes32 internal constant LIDO_LOCATOR_POSITION = 0xfb2059fd4b64256b64068a0f57046c6d40b9f0e592ba8bcfdf5b941910d03537;
/// @dev Total number of operators
// bytes32 internal constant TOTAL_OPERATORS_COUNT_POSITION = keccak256("lido.NodeOperatorsRegistry.totalOperatorsCount");
bytes32 internal constant TOTAL_OPERATORS_COUNT_POSITION =
0xe2a589ae0816b289a9d29b7c085f8eba4b5525accca9fa8ff4dba3f5a41287e8;
/// @dev Cached number of active operators
// bytes32 internal constant ACTIVE_OPERATORS_COUNT_POSITION = keccak256("lido.NodeOperatorsRegistry.activeOperatorsCount");
bytes32 internal constant ACTIVE_OPERATORS_COUNT_POSITION =
0x6f5220989faafdc182d508d697678366f4e831f5f56166ad69bfc253fc548fb1;
/// @dev link to the index of operations with keys
// bytes32 internal constant KEYS_OP_INDEX_POSITION = keccak256("lido.NodeOperatorsRegistry.keysOpIndex");
bytes32 internal constant KEYS_OP_INDEX_POSITION = 0xcd91478ac3f2620f0776eacb9c24123a214bcb23c32ae7d28278aa846c8c380e;
/// @dev module type
// bytes32 internal constant TYPE_POSITION = keccak256("lido.NodeOperatorsRegistry.type");
bytes32 internal constant TYPE_POSITION = 0xbacf4236659a602d72c631ba0b0d67ec320aaf523f3ae3590d7faee4f42351d0;
// bytes32 internal constant STUCK_PENALTY_DELAY_POSITION = keccak256("lido.NodeOperatorsRegistry.stuckPenaltyDelay");
bytes32 internal constant STUCK_PENALTY_DELAY_POSITION = 0x8e3a1f3826a82c1116044b334cae49f3c3d12c3866a1c4b18af461e12e58a18e;
// bytes32 internal constant REWARD_DISTRIBUTION_STATE = keccak256("lido.NodeOperatorsRegistry.rewardDistributionState");
bytes32 internal constant REWARD_DISTRIBUTION_STATE = 0x4ddbb0dcdc5f7692e494c15a7fca1f9eb65f31da0b5ce1c3381f6a1a1fd579b6;
//
// DATA TYPES
//
/// @dev Node Operator parameters and internal state
struct NodeOperator {
/// @dev Flag indicating if the operator can participate in further staking and reward distribution
bool active;
/// @dev Ethereum address on Execution Layer which receives stETH rewards for this operator
address rewardAddress;
/// @dev Human-readable name
string name;
/// @dev The below variables store the signing keys info of the node operator.
/// signingKeysStats - contains packed variables: uint64 exitedSigningKeysCount, uint64 depositedSigningKeysCount,
/// uint64 vettedSigningKeysCount, uint64 totalSigningKeysCount
///
/// These variables can take values in the following ranges:
///
/// 0 <= exitedSigningKeysCount <= depositedSigningKeysCount
/// exitedSigningKeysCount <= depositedSigningKeysCount <= vettedSigningKeysCount
/// depositedSigningKeysCount <= vettedSigningKeysCount <= totalSigningKeysCount
/// depositedSigningKeysCount <= totalSigningKeysCount <= UINT64_MAX
///
/// Additionally, the exitedSigningKeysCount and depositedSigningKeysCount values are monotonically increasing:
/// : : : : :
/// [....exitedSigningKeysCount....]-------->: : :
/// [....depositedSigningKeysCount :.........]-------->: :
/// [....vettedSigningKeysCount....:.........:<--------]-------->:
/// [....totalSigningKeysCount.....:.........:<--------:---------]------->
/// : : : : :
Packed64x4.Packed signingKeysStats;
Packed64x4.Packed stuckPenaltyStats;
Packed64x4.Packed targetValidatorsStats;
}
struct NodeOperatorSummary {
Packed64x4.Packed summarySigningKeysStats;
}
//
// STORAGE VARIABLES
//
/// @dev Mapping of all node operators. Mapping is used to be able to extend the struct.
mapping(uint256 => NodeOperator) internal _nodeOperators;
NodeOperatorSummary internal _nodeOperatorSummary;
//
// METHODS
//
function initialize(address _locator, bytes32 _type, uint256 _stuckPenaltyDelay) public onlyInit {
// Initializations for v1 --> v2
_initialize_v2(_locator, _type, _stuckPenaltyDelay);
// Initializations for v2 --> v3
_initialize_v3();
initialized();
}
/// @notice A function to finalize upgrade to v2 (from v1). Can be called only once
/// For more details see https://github.com/lidofinance/lido-improvement-proposals/blob/develop/LIPS/lip-10.md
function finalizeUpgrade_v2(address _locator, bytes32 _type, uint256 _stuckPenaltyDelay) external {
require(hasInitialized(), "CONTRACT_NOT_INITIALIZED");
_checkContractVersion(0);
_initialize_v2(_locator, _type, _stuckPenaltyDelay);
uint256 totalOperators = getNodeOperatorsCount();
Packed64x4.Packed memory signingKeysStats;
Packed64x4.Packed memory operatorTargetStats;
Packed64x4.Packed memory summarySigningKeysStats = Packed64x4.Packed(0);
uint256 vettedSigningKeysCountBefore;
uint256 totalSigningKeysCount;
uint256 depositedSigningKeysCount;
for (uint256 nodeOperatorId; nodeOperatorId < totalOperators; ++nodeOperatorId) {
signingKeysStats = _loadOperatorSigningKeysStats(nodeOperatorId);
vettedSigningKeysCountBefore = signingKeysStats.get(TOTAL_VETTED_KEYS_COUNT_OFFSET);
totalSigningKeysCount = signingKeysStats.get(TOTAL_KEYS_COUNT_OFFSET);
depositedSigningKeysCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
uint256 vettedSigningKeysCountAfter;
if (!_nodeOperators[nodeOperatorId].active) {
// trim vetted signing keys count when node operator is not active
vettedSigningKeysCountAfter = depositedSigningKeysCount;
} else {
vettedSigningKeysCountAfter = Math256.min(
totalSigningKeysCount,
Math256.max(depositedSigningKeysCount, vettedSigningKeysCountBefore)
);
}
if (vettedSigningKeysCountBefore != vettedSigningKeysCountAfter) {
signingKeysStats.set(TOTAL_VETTED_KEYS_COUNT_OFFSET, vettedSigningKeysCountAfter);
_saveOperatorSigningKeysStats(nodeOperatorId, signingKeysStats);
emit VettedSigningKeysCountChanged(nodeOperatorId, vettedSigningKeysCountAfter);
}
operatorTargetStats = _loadOperatorTargetValidatorsStats(nodeOperatorId);
operatorTargetStats.set(MAX_VALIDATORS_COUNT_OFFSET, vettedSigningKeysCountAfter);
_saveOperatorTargetValidatorsStats(nodeOperatorId, operatorTargetStats);
summarySigningKeysStats.add(SUMMARY_MAX_VALIDATORS_COUNT_OFFSET, vettedSigningKeysCountAfter);
summarySigningKeysStats.add(SUMMARY_DEPOSITED_KEYS_COUNT_OFFSET, depositedSigningKeysCount);
summarySigningKeysStats.add(
SUMMARY_EXITED_KEYS_COUNT_OFFSET,
signingKeysStats.get(TOTAL_EXITED_KEYS_COUNT_OFFSET)
);
}
_saveSummarySigningKeysStats(summarySigningKeysStats);
_increaseValidatorsKeysNonce();
}
function _initialize_v2(address _locator, bytes32 _type, uint256 _stuckPenaltyDelay) internal {
_onlyNonZeroAddress(_locator);
LIDO_LOCATOR_POSITION.setStorageAddress(_locator);
TYPE_POSITION.setStorageBytes32(_type);
_setContractVersion(2);
_setStuckPenaltyDelay(_stuckPenaltyDelay);
// set unlimited allowance for burner from staking router
// to burn stuck keys penalized shares
IStETH(getLocator().lido()).approve(getLocator().burner(), ~uint256(0));
emit LocatorContractSet(_locator);
emit StakingModuleTypeSet(_type);
}
function finalizeUpgrade_v3() external {
require(hasInitialized(), "CONTRACT_NOT_INITIALIZED");
_checkContractVersion(2);
_initialize_v3();
// clear deprecated total keys count storage
Packed64x4.Packed memory summarySigningKeysStats = _loadSummarySigningKeysStats();
summarySigningKeysStats.set(SUMMARY_TOTAL_KEYS_COUNT_OFFSET, 0);
_saveSummarySigningKeysStats(summarySigningKeysStats);
}
function _initialize_v3() internal {
_setContractVersion(3);
_updateRewardDistributionState(RewardDistributionState.Distributed);
}
/// @notice Add node operator named `name` with reward address `rewardAddress` and staking limit = 0 validators
/// @param _name Human-readable name
/// @param _rewardAddress Ethereum 1 address which receives stETH rewards for this operator
/// @return id a unique key of the added operator
function addNodeOperator(string _name, address _rewardAddress) external returns (uint256 id) {
_onlyValidNodeOperatorName(_name);
_onlyValidRewardAddress(_rewardAddress);
_auth(MANAGE_NODE_OPERATOR_ROLE);
id = getNodeOperatorsCount();
require(id < MAX_NODE_OPERATORS_COUNT, "MAX_OPERATORS_COUNT_EXCEEDED");
TOTAL_OPERATORS_COUNT_POSITION.setStorageUint256(id + 1);
NodeOperator storage operator = _nodeOperators[id];
uint256 activeOperatorsCount = getActiveNodeOperatorsCount();
ACTIVE_OPERATORS_COUNT_POSITION.setStorageUint256(activeOperatorsCount + 1);
operator.active = true;
operator.name = _name;
operator.rewardAddress = _rewardAddress;
emit NodeOperatorAdded(id, _name, _rewardAddress, 0);
}
/// @notice Activates deactivated node operator with given id
/// @param _nodeOperatorId Node operator id to activate
function activateNodeOperator(uint256 _nodeOperatorId) external {
_onlyExistedNodeOperator(_nodeOperatorId);
_auth(MANAGE_NODE_OPERATOR_ROLE);
_onlyCorrectNodeOperatorState(!getNodeOperatorIsActive(_nodeOperatorId));
ACTIVE_OPERATORS_COUNT_POSITION.setStorageUint256(getActiveNodeOperatorsCount() + 1);
_nodeOperators[_nodeOperatorId].active = true;
emit NodeOperatorActiveSet(_nodeOperatorId, true);
_increaseValidatorsKeysNonce();
}
/// @notice Deactivates active node operator with given id
/// @param _nodeOperatorId Node operator id to deactivate
function deactivateNodeOperator(uint256 _nodeOperatorId) external {
_onlyExistedNodeOperator(_nodeOperatorId);
_auth(MANAGE_NODE_OPERATOR_ROLE);
_onlyCorrectNodeOperatorState(getNodeOperatorIsActive(_nodeOperatorId));
uint256 activeOperatorsCount = getActiveNodeOperatorsCount();
ACTIVE_OPERATORS_COUNT_POSITION.setStorageUint256(activeOperatorsCount.sub(1));
_nodeOperators[_nodeOperatorId].active = false;
emit NodeOperatorActiveSet(_nodeOperatorId, false);
Packed64x4.Packed memory signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorId);
uint256 vettedSigningKeysCount = signingKeysStats.get(TOTAL_VETTED_KEYS_COUNT_OFFSET);
uint256 depositedSigningKeysCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
// reset vetted keys count to the deposited validators count
if (vettedSigningKeysCount > depositedSigningKeysCount) {
signingKeysStats.set(TOTAL_VETTED_KEYS_COUNT_OFFSET, depositedSigningKeysCount);
_saveOperatorSigningKeysStats(_nodeOperatorId, signingKeysStats);
emit VettedSigningKeysCountChanged(_nodeOperatorId, depositedSigningKeysCount);
_updateSummaryMaxValidatorsCount(_nodeOperatorId);
}
_increaseValidatorsKeysNonce();
}
/// @notice Change human-readable name of the node operator with given id
/// @param _nodeOperatorId Node operator id to set name for
/// @param _name New human-readable name of the node operator
function setNodeOperatorName(uint256 _nodeOperatorId, string _name) external {
_onlyValidNodeOperatorName(_name);
_onlyExistedNodeOperator(_nodeOperatorId);
_auth(MANAGE_NODE_OPERATOR_ROLE);
_requireNotSameValue(keccak256(bytes(_nodeOperators[_nodeOperatorId].name)) != keccak256(bytes(_name)));
_nodeOperators[_nodeOperatorId].name = _name;
emit NodeOperatorNameSet(_nodeOperatorId, _name);
}
/// @notice Change reward address of the node operator with given id
/// @param _nodeOperatorId Node operator id to set reward address for
/// @param _rewardAddress Execution layer Ethereum address to set as reward address
function setNodeOperatorRewardAddress(uint256 _nodeOperatorId, address _rewardAddress) external {
_onlyValidRewardAddress(_rewardAddress);
_onlyExistedNodeOperator(_nodeOperatorId);
_auth(MANAGE_NODE_OPERATOR_ROLE);
_requireNotSameValue(_nodeOperators[_nodeOperatorId].rewardAddress != _rewardAddress);
_nodeOperators[_nodeOperatorId].rewardAddress = _rewardAddress;
emit NodeOperatorRewardAddressSet(_nodeOperatorId, _rewardAddress);
}
/// @notice Set the maximum number of validators to stake for the node operator with given id
/// @dev Current implementation preserves invariant: depositedSigningKeysCount <= vettedSigningKeysCount <= totalSigningKeysCount.
/// If _vettedSigningKeysCount out of range [depositedSigningKeysCount, totalSigningKeysCount], the new vettedSigningKeysCount
/// value will be set to the nearest range border.
/// @param _nodeOperatorId Node operator id to set staking limit for
/// @param _vettedSigningKeysCount New staking limit of the node operator
function setNodeOperatorStakingLimit(uint256 _nodeOperatorId, uint64 _vettedSigningKeysCount) external {
_onlyExistedNodeOperator(_nodeOperatorId);
_authP(SET_NODE_OPERATOR_LIMIT_ROLE, arr(uint256(_nodeOperatorId), uint256(_vettedSigningKeysCount)));
_onlyCorrectNodeOperatorState(getNodeOperatorIsActive(_nodeOperatorId));
_updateVettedSingingKeysCount(_nodeOperatorId, _vettedSigningKeysCount, true /* _allowIncrease */);
_increaseValidatorsKeysNonce();
}
/// @notice Called by StakingRouter to decrease the number of vetted keys for node operator with given id
/// @param _nodeOperatorIds bytes packed array of the node operators id
/// @param _vettedSigningKeysCounts bytes packed array of the new number of vetted keys for the node operators
function decreaseVettedSigningKeysCount(
bytes _nodeOperatorIds,
bytes _vettedSigningKeysCounts
) external {
_auth(STAKING_ROUTER_ROLE);
uint256 nodeOperatorsCount = _checkReportPayload(_nodeOperatorIds.length, _vettedSigningKeysCounts.length);
uint256 totalNodeOperatorsCount = getNodeOperatorsCount();
uint256 nodeOperatorId;
uint256 vettedKeysCount;
uint256 _nodeOperatorIdsOffset;
uint256 _vettedKeysCountsOffset;
/// @dev calldata layout:
/// | func sig (4 bytes) | ABI-enc data |
///
/// ABI-enc data:
///
/// | 32 bytes | 32 bytes | 32 bytes | ... | 32 bytes | ...... |
/// | ids len offset | counts len offset | ids len | ids | counts len | counts |
assembly {
_nodeOperatorIdsOffset := add(calldataload(4), 36) // arg1 calldata offset + 4 (signature len) + 32 (length slot)
_vettedKeysCountsOffset := add(calldataload(36), 36) // arg2 calldata offset + 4 (signature len) + 32 (length slot))
}
for (uint256 i; i < nodeOperatorsCount;) {
/// @solidity memory-safe-assembly
assembly {
nodeOperatorId := shr(192, calldataload(add(_nodeOperatorIdsOffset, mul(i, 8))))
vettedKeysCount := shr(128, calldataload(add(_vettedKeysCountsOffset, mul(i, 16))))
i := add(i, 1)
}
_requireValidRange(nodeOperatorId < totalNodeOperatorsCount);
_updateVettedSingingKeysCount(nodeOperatorId, vettedKeysCount, false /* only decrease */);
}
_increaseValidatorsKeysNonce();
}
function _updateVettedSingingKeysCount(
uint256 _nodeOperatorId,
uint256 _vettedSigningKeysCount,
bool _allowIncrease
) internal {
Packed64x4.Packed memory signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorId);
uint256 vettedSigningKeysCountBefore = signingKeysStats.get(TOTAL_VETTED_KEYS_COUNT_OFFSET);
uint256 depositedSigningKeysCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
uint256 totalSigningKeysCount = signingKeysStats.get(TOTAL_KEYS_COUNT_OFFSET);
uint256 vettedSigningKeysCountAfter = Math256.min(
totalSigningKeysCount, Math256.max(_vettedSigningKeysCount, depositedSigningKeysCount)
);
if (vettedSigningKeysCountAfter == vettedSigningKeysCountBefore) return;
require(
_allowIncrease || vettedSigningKeysCountAfter < vettedSigningKeysCountBefore,
"VETTED_KEYS_COUNT_INCREASED"
);
signingKeysStats.set(TOTAL_VETTED_KEYS_COUNT_OFFSET, vettedSigningKeysCountAfter);
_saveOperatorSigningKeysStats(_nodeOperatorId, signingKeysStats);
emit VettedSigningKeysCountChanged(_nodeOperatorId, vettedSigningKeysCountAfter);
_updateSummaryMaxValidatorsCount(_nodeOperatorId);
}
/// @notice Called by StakingRouter to signal that stETH rewards were minted for this module.
function onRewardsMinted(uint256 /* _totalShares */) external {
_auth(STAKING_ROUTER_ROLE);
_updateRewardDistributionState(RewardDistributionState.TransferredToModule);
}
function _checkReportPayload(uint256 idsLength, uint256 countsLength) internal pure returns (uint256 count) {
count = idsLength / 8;
require(countsLength / 16 == count && idsLength % 8 == 0 && countsLength % 16 == 0, "INVALID_REPORT_DATA");
}
/// @notice Called by StakingRouter to update the number of the validators of the given node
/// operator that were requested to exit but failed to do so in the max allowed time
///
/// @param _nodeOperatorIds bytes packed array of the node operators id
/// @param _stuckValidatorsCounts bytes packed array of the new number of stuck validators for the node operators
function updateStuckValidatorsCount(bytes _nodeOperatorIds, bytes _stuckValidatorsCounts) external {
_auth(STAKING_ROUTER_ROLE);
uint256 nodeOperatorsCount = _checkReportPayload(_nodeOperatorIds.length, _stuckValidatorsCounts.length);
uint256 totalNodeOperatorsCount = getNodeOperatorsCount();
uint256 nodeOperatorId;
uint256 validatorsCount;
uint256 _nodeOperatorIdsOffset;
uint256 _stuckValidatorsCountsOffset;
/// @dev calldata layout:
/// | func sig (4 bytes) | ABI-enc data |
///
/// ABI-enc data:
///
/// | 32 bytes | 32 bytes | 32 bytes | ... | 32 bytes | ...... |
/// | ids len offset | counts len offset | ids len | ids | counts len | counts |
assembly {
_nodeOperatorIdsOffset := add(calldataload(4), 36) // arg1 calldata offset + 4 (signature len) + 32 (length slot)
_stuckValidatorsCountsOffset := add(calldataload(36), 36) // arg2 calldata offset + 4 (signature len) + 32 (length slot))
}
for (uint256 i; i < nodeOperatorsCount;) {
/// @solidity memory-safe-assembly
assembly {
nodeOperatorId := shr(192, calldataload(add(_nodeOperatorIdsOffset, mul(i, 8))))
validatorsCount := shr(128, calldataload(add(_stuckValidatorsCountsOffset, mul(i, 16))))
i := add(i, 1)
}
_requireValidRange(nodeOperatorId < totalNodeOperatorsCount);
_updateStuckValidatorsCount(nodeOperatorId, validatorsCount);
}
_increaseValidatorsKeysNonce();
}
/// @notice Called by StakingRouter to update the number of the validators in the EXITED state
/// for node operator with given id
///
/// @param _nodeOperatorIds bytes packed array of the node operators id
/// @param _exitedValidatorsCounts bytes packed array of the new number of EXITED validators for the node operators
function updateExitedValidatorsCount(
bytes _nodeOperatorIds,
bytes _exitedValidatorsCounts
)
external
{
_auth(STAKING_ROUTER_ROLE);
uint256 nodeOperatorsCount = _checkReportPayload(_nodeOperatorIds.length, _exitedValidatorsCounts.length);
uint256 totalNodeOperatorsCount = getNodeOperatorsCount();
uint256 nodeOperatorId;
uint256 validatorsCount;
uint256 _nodeOperatorIdsOffset;
uint256 _exitedValidatorsCountsOffset;
/// @dev see comments for `updateStuckValidatorsCount`
assembly {
_nodeOperatorIdsOffset := add(calldataload(4), 36) // arg1 calldata offset + 4 (signature len) + 32 (length slot)
_exitedValidatorsCountsOffset := add(calldataload(36), 36) // arg2 calldata offset + 4 (signature len) + 32 (length slot))
}
for (uint256 i; i < nodeOperatorsCount;) {
/// @solidity memory-safe-assembly
assembly {
nodeOperatorId := shr(192, calldataload(add(_nodeOperatorIdsOffset, mul(i, 8))))
validatorsCount := shr(128, calldataload(add(_exitedValidatorsCountsOffset, mul(i, 16))))
i := add(i, 1)
}
_requireValidRange(nodeOperatorId < totalNodeOperatorsCount);
_updateExitedValidatorsCount(nodeOperatorId, validatorsCount, false);
}
_increaseValidatorsKeysNonce();
}
/// @notice Updates the number of the refunded validators for node operator with the given id
/// @param _nodeOperatorId Id of the node operator
/// @param _refundedValidatorsCount New number of refunded validators of the node operator
function updateRefundedValidatorsCount(uint256 _nodeOperatorId, uint256 _refundedValidatorsCount) external {
_onlyExistedNodeOperator(_nodeOperatorId);
_auth(STAKING_ROUTER_ROLE);
_updateRefundValidatorsKeysCount(_nodeOperatorId, _refundedValidatorsCount);
}
/// @notice Permissionless method for distributing all accumulated module rewards among node operators
/// based on the latest accounting report.
///
/// @dev Rewards can be distributed after all necessary data required to distribute rewards among operators
/// has been delivered, including exited and stuck keys.
///
/// The reward distribution lifecycle:
///
/// 1. TransferredToModule: Rewards are transferred to the module during an oracle main report.
/// 2. ReadyForDistribution: All necessary data required to distribute rewards among operators has been delivered.
/// 3. Distributed: Rewards have been successfully distributed.
///
/// The function can only be called when the state is ReadyForDistribution.
///
/// @dev Rewards can be distributed after node operators' statistics are updated until the next reward
/// is transferred to the module during the next oracle frame.
function distributeReward() external {
require(getRewardDistributionState() == RewardDistributionState.ReadyForDistribution, "DISTRIBUTION_NOT_READY");
_updateRewardDistributionState(RewardDistributionState.Distributed);
_distributeRewards();
}
/// @notice Called by StakingRouter after it finishes updating exited and stuck validators
/// counts for this module's node operators.
///
/// Guaranteed to be called after an oracle report is applied, regardless of whether any node
/// operator in this module has actually received any updated counts as a result of the report
/// but given that the total number of exited validators returned from getStakingModuleSummary
/// is the same as StakingRouter expects based on the total count received from the oracle.
function onExitedAndStuckValidatorsCountsUpdated() external {
_auth(STAKING_ROUTER_ROLE);
_updateRewardDistributionState(RewardDistributionState.ReadyForDistribution);
}
/// @notice Unsafely updates the number of validators in the EXITED/STUCK states for node operator with given id
/// 'unsafely' means that this method can both increase and decrease exited and stuck counters
/// @param _nodeOperatorId Id of the node operator
/// @param _exitedValidatorsCount New number of EXITED validators for the node operator
/// @param _stuckValidatorsCount New number of STUCK validator for the node operator
function unsafeUpdateValidatorsCount(
uint256 _nodeOperatorId,
uint256 _exitedValidatorsCount,
uint256 _stuckValidatorsCount
) external {
_onlyExistedNodeOperator(_nodeOperatorId);
_auth(STAKING_ROUTER_ROLE);
_updateStuckValidatorsCount(_nodeOperatorId, _stuckValidatorsCount);
_updateExitedValidatorsCount(_nodeOperatorId, _exitedValidatorsCount, true /* _allowDecrease */ );
_increaseValidatorsKeysNonce();
}
function _updateExitedValidatorsCount(uint256 _nodeOperatorId, uint256 _exitedValidatorsCount, bool _allowDecrease)
internal
{
Packed64x4.Packed memory signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorId);
uint256 oldExitedValidatorsCount = signingKeysStats.get(TOTAL_EXITED_KEYS_COUNT_OFFSET);
if (_exitedValidatorsCount == oldExitedValidatorsCount) return;
require(
_allowDecrease || _exitedValidatorsCount > oldExitedValidatorsCount,
"EXITED_VALIDATORS_COUNT_DECREASED"
);
uint256 depositedValidatorsCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
uint256 stuckValidatorsCount =
_loadOperatorStuckPenaltyStats(_nodeOperatorId).get(STUCK_VALIDATORS_COUNT_OFFSET);
// sustain invariant exited + stuck <= deposited
assert(depositedValidatorsCount >= stuckValidatorsCount);
_requireValidRange(_exitedValidatorsCount <= depositedValidatorsCount - stuckValidatorsCount);
signingKeysStats.set(TOTAL_EXITED_KEYS_COUNT_OFFSET, _exitedValidatorsCount);
_saveOperatorSigningKeysStats(_nodeOperatorId, signingKeysStats);
emit ExitedSigningKeysCountChanged(_nodeOperatorId, _exitedValidatorsCount);
Packed64x4.Packed memory summarySigningKeysStats = _loadSummarySigningKeysStats();
uint256 exitedValidatorsAbsDiff = Math256.absDiff(_exitedValidatorsCount, oldExitedValidatorsCount);
if (_exitedValidatorsCount > oldExitedValidatorsCount) {
summarySigningKeysStats.add(SUMMARY_EXITED_KEYS_COUNT_OFFSET, exitedValidatorsAbsDiff);
} else {
summarySigningKeysStats.sub(SUMMARY_EXITED_KEYS_COUNT_OFFSET, exitedValidatorsAbsDiff);
}
_saveSummarySigningKeysStats(summarySigningKeysStats);
_updateSummaryMaxValidatorsCount(_nodeOperatorId);
}
/// @notice Updates the limit of the validators that can be used for deposit by DAO
/// @param _nodeOperatorId Id of the node operator
/// @param _isTargetLimitActive Flag indicating if the soft target limit is active
/// @param _targetLimit Target limit of the node operator
/// @dev This function is deprecated, use updateTargetValidatorsLimits instead
function updateTargetValidatorsLimits(uint256 _nodeOperatorId, bool _isTargetLimitActive, uint256 _targetLimit) public {
updateTargetValidatorsLimits(_nodeOperatorId, _isTargetLimitActive ? 1 : 0, _targetLimit);
}
/// @notice Updates the limit of the validators that can be used for deposit by DAO
/// @param _nodeOperatorId Id of the node operator
/// @param _targetLimitMode target limit mode (0 = disabled, 1 = soft mode, 2 = forced mode)
/// @param _targetLimit Target limit of the node operator
function updateTargetValidatorsLimits(uint256 _nodeOperatorId, uint256 _targetLimitMode, uint256 _targetLimit) public {
_onlyExistedNodeOperator(_nodeOperatorId);
_auth(STAKING_ROUTER_ROLE);
_requireValidRange(_targetLimit <= UINT64_MAX);
Packed64x4.Packed memory operatorTargetStats = _loadOperatorTargetValidatorsStats(_nodeOperatorId);
operatorTargetStats.set(TARGET_LIMIT_MODE_OFFSET, _targetLimitMode);
if (_targetLimitMode == 0) {
_targetLimit = 0;
}
operatorTargetStats.set(TARGET_VALIDATORS_COUNT_OFFSET, _targetLimit);
_saveOperatorTargetValidatorsStats(_nodeOperatorId, operatorTargetStats);
emit TargetValidatorsCountChanged(_nodeOperatorId, _targetLimit, _targetLimitMode);
_updateSummaryMaxValidatorsCount(_nodeOperatorId);
_increaseValidatorsKeysNonce();
}
/**
* @notice Set the stuck signings keys count
*/
function _updateStuckValidatorsCount(uint256 _nodeOperatorId, uint256 _stuckValidatorsCount) internal {
Packed64x4.Packed memory stuckPenaltyStats = _loadOperatorStuckPenaltyStats(_nodeOperatorId);
uint256 curStuckValidatorsCount = stuckPenaltyStats.get(STUCK_VALIDATORS_COUNT_OFFSET);
if (_stuckValidatorsCount == curStuckValidatorsCount) return;
Packed64x4.Packed memory signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorId);
uint256 exitedValidatorsCount = signingKeysStats.get(TOTAL_EXITED_KEYS_COUNT_OFFSET);
uint256 depositedValidatorsCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
// sustain invariant exited + stuck <= deposited
assert(depositedValidatorsCount >= exitedValidatorsCount);
_requireValidRange(_stuckValidatorsCount <= depositedValidatorsCount - exitedValidatorsCount);
uint256 curRefundedValidatorsCount = stuckPenaltyStats.get(REFUNDED_VALIDATORS_COUNT_OFFSET);
if (_stuckValidatorsCount <= curRefundedValidatorsCount && curStuckValidatorsCount > curRefundedValidatorsCount) {
stuckPenaltyStats.set(STUCK_PENALTY_END_TIMESTAMP_OFFSET, block.timestamp + getStuckPenaltyDelay());
}
stuckPenaltyStats.set(STUCK_VALIDATORS_COUNT_OFFSET, _stuckValidatorsCount);
_saveOperatorStuckPenaltyStats(_nodeOperatorId, stuckPenaltyStats);
emit StuckPenaltyStateChanged(
_nodeOperatorId,
_stuckValidatorsCount,
curRefundedValidatorsCount,
stuckPenaltyStats.get(STUCK_PENALTY_END_TIMESTAMP_OFFSET)
);
_updateSummaryMaxValidatorsCount(_nodeOperatorId);
}
function _updateRefundValidatorsKeysCount(uint256 _nodeOperatorId, uint256 _refundedValidatorsCount) internal {
Packed64x4.Packed memory stuckPenaltyStats = _loadOperatorStuckPenaltyStats(_nodeOperatorId);
uint256 curRefundedValidatorsCount = stuckPenaltyStats.get(REFUNDED_VALIDATORS_COUNT_OFFSET);
if (_refundedValidatorsCount == curRefundedValidatorsCount) return;
Packed64x4.Packed memory signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorId);
_requireValidRange(_refundedValidatorsCount <= signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET));
uint256 curStuckValidatorsCount = stuckPenaltyStats.get(STUCK_VALIDATORS_COUNT_OFFSET);
if (_refundedValidatorsCount >= curStuckValidatorsCount && curRefundedValidatorsCount < curStuckValidatorsCount) {
stuckPenaltyStats.set(STUCK_PENALTY_END_TIMESTAMP_OFFSET, block.timestamp + getStuckPenaltyDelay());
}
stuckPenaltyStats.set(REFUNDED_VALIDATORS_COUNT_OFFSET, _refundedValidatorsCount);
_saveOperatorStuckPenaltyStats(_nodeOperatorId, stuckPenaltyStats);
emit StuckPenaltyStateChanged(
_nodeOperatorId,
curStuckValidatorsCount,
_refundedValidatorsCount,
stuckPenaltyStats.get(STUCK_PENALTY_END_TIMESTAMP_OFFSET)
);
_updateSummaryMaxValidatorsCount(_nodeOperatorId);
}
// @dev Recalculate and update the max validator count for operator and summary stats
function _updateSummaryMaxValidatorsCount(uint256 _nodeOperatorId) internal {
(uint256 oldMaxSigningKeysCount, uint256 newMaxSigningKeysCount) = _applyNodeOperatorLimits(_nodeOperatorId);
if (newMaxSigningKeysCount == oldMaxSigningKeysCount) return;
Packed64x4.Packed memory summarySigningKeysStats = _loadSummarySigningKeysStats();
uint256 maxSigningKeysCountAbsDiff = Math256.absDiff(newMaxSigningKeysCount, oldMaxSigningKeysCount);
if (newMaxSigningKeysCount > oldMaxSigningKeysCount) {
summarySigningKeysStats.add(SUMMARY_MAX_VALIDATORS_COUNT_OFFSET, maxSigningKeysCountAbsDiff);
} else {
summarySigningKeysStats.sub(SUMMARY_MAX_VALIDATORS_COUNT_OFFSET, maxSigningKeysCountAbsDiff);
}
_saveSummarySigningKeysStats(summarySigningKeysStats);
}
/// @notice Invalidates all unused deposit data for all node operators
function onWithdrawalCredentialsChanged() external {
_auth(STAKING_ROUTER_ROLE);
uint256 operatorsCount = getNodeOperatorsCount();
if (operatorsCount > 0) {
_invalidateReadyToDepositKeysRange(0, operatorsCount - 1);
}
}
/// @notice Invalidates all unused validators keys for node operators in the given range
/// @param _indexFrom the first index (inclusive) of the node operator to invalidate keys for
/// @param _indexTo the last index (inclusive) of the node operator to invalidate keys for
function invalidateReadyToDepositKeysRange(uint256 _indexFrom, uint256 _indexTo) external {
_auth(MANAGE_NODE_OPERATOR_ROLE);
_invalidateReadyToDepositKeysRange(_indexFrom, _indexTo);
}
function _invalidateReadyToDepositKeysRange(uint256 _indexFrom, uint256 _indexTo) internal {
_requireValidRange(_indexFrom <= _indexTo && _indexTo < getNodeOperatorsCount());
uint256 trimmedKeysCount;
uint256 totalTrimmedKeysCount;
uint256 totalSigningKeysCount;
uint256 depositedSigningKeysCount;
Packed64x4.Packed memory signingKeysStats;
for (uint256 nodeOperatorId = _indexFrom; nodeOperatorId <= _indexTo; ++nodeOperatorId) {
signingKeysStats = _loadOperatorSigningKeysStats(nodeOperatorId);
totalSigningKeysCount = signingKeysStats.get(TOTAL_KEYS_COUNT_OFFSET);
depositedSigningKeysCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
if (totalSigningKeysCount == depositedSigningKeysCount) continue;
assert(totalSigningKeysCount > depositedSigningKeysCount);
trimmedKeysCount = totalSigningKeysCount - depositedSigningKeysCount;
totalTrimmedKeysCount += trimmedKeysCount;
signingKeysStats.set(TOTAL_KEYS_COUNT_OFFSET, depositedSigningKeysCount);
signingKeysStats.set(TOTAL_VETTED_KEYS_COUNT_OFFSET, depositedSigningKeysCount);
_saveOperatorSigningKeysStats(nodeOperatorId, signingKeysStats);
_updateSummaryMaxValidatorsCount(nodeOperatorId);
emit TotalSigningKeysCountChanged(nodeOperatorId, depositedSigningKeysCount);
emit VettedSigningKeysCountChanged(nodeOperatorId, depositedSigningKeysCount);
emit NodeOperatorTotalKeysTrimmed(nodeOperatorId, uint64(trimmedKeysCount));
}
if (totalTrimmedKeysCount > 0) {
_increaseValidatorsKeysNonce();
}
}
/// @notice Obtains deposit data to be used by StakingRouter to deposit to the Ethereum Deposit
/// contract
/// @param _depositsCount Number of deposits to be done
/// @return publicKeys Batch of the concatenated public validators keys
/// @return signatures Batch of the concatenated deposit signatures for returned public keys
function obtainDepositData(
uint256 _depositsCount,
bytes /* _depositCalldata */
) external returns (bytes memory publicKeys, bytes memory signatures) {
_auth(STAKING_ROUTER_ROLE);
if (_depositsCount == 0) return (new bytes(0), new bytes(0));
(
uint256 allocatedKeysCount,
uint256[] memory nodeOperatorIds,
uint256[] memory activeKeysCountAfterAllocation
) = _getSigningKeysAllocationData(_depositsCount);
require(allocatedKeysCount == _depositsCount, "INVALID_ALLOCATED_KEYS_COUNT");
(publicKeys, signatures) = _loadAllocatedSigningKeys(
allocatedKeysCount,
nodeOperatorIds,
activeKeysCountAfterAllocation
);
_increaseValidatorsKeysNonce();
}
function _getNodeOperator(uint256 _nodeOperatorId)
internal
view
returns (uint256 exitedSigningKeysCount, uint256 depositedSigningKeysCount, uint256 maxSigningKeysCount)
{
Packed64x4.Packed memory signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorId);
Packed64x4.Packed memory operatorTargetStats = _loadOperatorTargetValidatorsStats(_nodeOperatorId);
exitedSigningKeysCount = signingKeysStats.get(TOTAL_EXITED_KEYS_COUNT_OFFSET);
depositedSigningKeysCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
maxSigningKeysCount = operatorTargetStats.get(MAX_VALIDATORS_COUNT_OFFSET);
// Validate data boundaries invariants here to not use SafeMath in caller methods
assert(maxSigningKeysCount >= depositedSigningKeysCount && depositedSigningKeysCount >= exitedSigningKeysCount);
}
function _applyNodeOperatorLimits(uint256 _nodeOperatorId)
internal
returns (uint256 oldMaxSigningKeysCount, uint256 newMaxSigningKeysCount)
{
Packed64x4.Packed memory signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorId);
Packed64x4.Packed memory operatorTargetStats = _loadOperatorTargetValidatorsStats(_nodeOperatorId);
uint256 depositedSigningKeysCount = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
// It's expected that validators don't suffer from penalties most of the time,
// so optimistically, set the count of max validators equal to the vetted validators count.
newMaxSigningKeysCount = signingKeysStats.get(TOTAL_VETTED_KEYS_COUNT_OFFSET);
if (!isOperatorPenaltyCleared(_nodeOperatorId)) {
// when the node operator is penalized zeroing its depositable validators count
newMaxSigningKeysCount = depositedSigningKeysCount;
} else if (operatorTargetStats.get(TARGET_LIMIT_MODE_OFFSET) != 0) {
// apply target limit when it's active and the node operator is not penalized
newMaxSigningKeysCount = Math256.max(
// max validators count can't be less than the deposited validators count
// even when the target limit is less than the current active validators count
depositedSigningKeysCount,
Math256.min(
// max validators count can't be greater than the vetted validators count
newMaxSigningKeysCount,
// SafeMath.add() isn't used below because the sum is always
// less or equal to 2 * UINT64_MAX
signingKeysStats.get(TOTAL_EXITED_KEYS_COUNT_OFFSET)
+ operatorTargetStats.get(TARGET_VALIDATORS_COUNT_OFFSET)
)
);
}
oldMaxSigningKeysCount = operatorTargetStats.get(MAX_VALIDATORS_COUNT_OFFSET);
if (oldMaxSigningKeysCount != newMaxSigningKeysCount) {
operatorTargetStats.set(MAX_VALIDATORS_COUNT_OFFSET, newMaxSigningKeysCount);
_saveOperatorTargetValidatorsStats(_nodeOperatorId, operatorTargetStats);
}
}
function _getSigningKeysAllocationData(uint256 _keysCount)
internal
view
returns (uint256 allocatedKeysCount, uint256[] memory nodeOperatorIds, uint256[] memory activeKeyCountsAfterAllocation)
{
uint256 activeNodeOperatorsCount = getActiveNodeOperatorsCount();
nodeOperatorIds = new uint256[](activeNodeOperatorsCount);
activeKeyCountsAfterAllocation = new uint256[](activeNodeOperatorsCount);
uint256[] memory activeKeysCapacities = new uint256[](activeNodeOperatorsCount);
uint256 activeNodeOperatorIndex;
uint256 nodeOperatorsCount = getNodeOperatorsCount();
uint256 maxSigningKeysCount;
uint256 depositedSigningKeysCount;
uint256 exitedSigningKeysCount;
for (uint256 nodeOperatorId; nodeOperatorId < nodeOperatorsCount; ++nodeOperatorId) {
(exitedSigningKeysCount, depositedSigningKeysCount, maxSigningKeysCount)
= _getNodeOperator(nodeOperatorId);
// the node operator has no available signing keys
if (depositedSigningKeysCount == maxSigningKeysCount) continue;
nodeOperatorIds[activeNodeOperatorIndex] = nodeOperatorId;
activeKeyCountsAfterAllocation[activeNodeOperatorIndex] = depositedSigningKeysCount - exitedSigningKeysCount;
activeKeysCapacities[activeNodeOperatorIndex] = maxSigningKeysCount - exitedSigningKeysCount;
++activeNodeOperatorIndex;
}
if (activeNodeOperatorIndex == 0) return (0, new uint256[](0), new uint256[](0));
/// @dev shrink the length of the resulting arrays if some active node operators have no available keys to be deposited
if (activeNodeOperatorIndex < activeNodeOperatorsCount) {
assembly {
mstore(nodeOperatorIds, activeNodeOperatorIndex)
mstore(activeKeyCountsAfterAllocation, activeNodeOperatorIndex)
mstore(activeKeysCapacities, activeNodeOperatorIndex)
}
}
(allocatedKeysCount, activeKeyCountsAfterAllocation) =
MinFirstAllocationStrategy.allocate(activeKeyCountsAfterAllocation, activeKeysCapacities, _keysCount);
/// @dev method NEVER allocates more keys than was requested
assert(_keysCount >= allocatedKeysCount);
}
function _loadAllocatedSigningKeys(
uint256 _keysCountToLoad,
uint256[] memory _nodeOperatorIds,
uint256[] memory _activeKeyCountsAfterAllocation
) internal returns (bytes memory pubkeys, bytes memory signatures) {
(pubkeys, signatures) = SigningKeys.initKeysSigsBuf(_keysCountToLoad);
uint256 loadedKeysCount = 0;
uint256 depositedSigningKeysCountBefore;
uint256 depositedSigningKeysCountAfter;
uint256 keysCount;
Packed64x4.Packed memory signingKeysStats;
for (uint256 i; i < _nodeOperatorIds.length; ++i) {
signingKeysStats = _loadOperatorSigningKeysStats(_nodeOperatorIds[i]);
depositedSigningKeysCountBefore = signingKeysStats.get(TOTAL_DEPOSITED_KEYS_COUNT_OFFSET);
depositedSigningKeysCountAfter =
signingKeysStats.get(TOTAL_EXITED_KEYS_COUNT_OFFSET) + _activeKeyCountsAfterAllocation[i];
if (depositedSigningKeysCountAfter == depositedSigningKeysCountBefore) continue;
// For gas savings SafeMath.add() wasn't used on depositedSigningKeysCountAfter
// calculation, so below we check that operation finished without overflow
// In case of overflow:
// depositedSigningKeysCountAfter < signingKeysStats.get(TOTAL_EXITED_KEYS_COUNT_OFFSET)
// what violates invariant:
// depositedSigningKeysCount >= exitedSigningKeysCount
assert(depositedSigningKeysCountAfter > depositedSigningKeysCountBefore);
keysCount = depositedSigningKeysCountAfter - depositedSigningKeysCountBefore;
SIGNING_KEYS_MAPPING_NAME.loadKeysSigs(
_nodeOperatorIds[i], depositedSigningKeysCountBefore, keysCount, pubkeys, signatures, loadedKeysCount