-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathValidatorManager.sol
587 lines (505 loc) · 25.6 KB
/
ValidatorManager.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
// (c) 2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
// SPDX-License-Identifier: Ecosystem
pragma solidity 0.8.25;
import {ValidatorMessages} from "./ValidatorMessages.sol";
import {
InitialValidator,
IValidatorManager,
PChainOwner,
ConversionData,
Validator,
ValidatorChurnPeriod,
ValidatorManagerSettings,
ValidatorRegistrationInput,
ValidatorStatus
} from "./interfaces/IValidatorManager.sol";
import {
IWarpMessenger,
WarpMessage
} from "@avalabs/subnet-evm-contracts@1.2.0/contracts/interfaces/IWarpMessenger.sol";
import {ContextUpgradeable} from
"@openzeppelin/contracts-upgradeable@5.0.2/utils/ContextUpgradeable.sol";
import {Initializable} from
"@openzeppelin/contracts-upgradeable@5.0.2/proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IValidatorManager} interface.
*
* @custom:security-contact https://github.com/ava-labs/icm-contracts/blob/main/SECURITY.md
*/
abstract contract ValidatorManager is Initializable, ContextUpgradeable, IValidatorManager {
// solhint-disable private-vars-leading-underscore
/// @custom:storage-location erc7201:avalanche-icm.storage.ValidatorManager
struct ValidatorManagerStorage {
/// @notice The subnetID associated with this validator manager.
bytes32 _subnetID;
/// @notice The number of seconds after which to reset the churn tracker.
uint64 _churnPeriodSeconds;
/// @notice The maximum churn rate allowed per churn period.
uint8 _maximumChurnPercentage;
/// @notice The churn tracker used to track the amount of stake added or removed in the churn period.
ValidatorChurnPeriod _churnTracker;
/// @notice Maps the validationID to the registration message such that the message can be re-sent if needed.
mapping(bytes32 => bytes) _pendingRegisterValidationMessages;
/// @notice Maps the validationID to the validator information.
mapping(bytes32 => Validator) _validationPeriods;
/// @notice Maps the nodeID to the validationID for validation periods that have not ended.
mapping(bytes => bytes32) _registeredValidators;
/// @notice Boolean that indicates if the initial validator set has been set.
bool _initializedValidatorSet;
}
// solhint-enable private-vars-leading-underscore
// keccak256(abi.encode(uint256(keccak256("avalanche-icm.storage.ValidatorManager")) - 1)) & ~bytes32(uint256(0xff));
bytes32 public constant VALIDATOR_MANAGER_STORAGE_LOCATION =
0xe92546d698950ddd38910d2e15ed1d923cd0a7b3dde9e2a6a3f380565559cb00;
uint8 public constant MAXIMUM_CHURN_PERCENTAGE_LIMIT = 20;
uint64 public constant MAXIMUM_REGISTRATION_EXPIRY_LENGTH = 2 days;
uint32 public constant ADDRESS_LENGTH = 20; // This is only used as a packed uint32
uint8 public constant BLS_PUBLIC_KEY_LENGTH = 48;
bytes32 public constant P_CHAIN_BLOCKCHAIN_ID = bytes32(0);
error InvalidValidatorManagerAddress(address validatorManagerAddress);
error InvalidWarpOriginSenderAddress(address senderAddress);
error InvalidValidatorManagerBlockchainID(bytes32 blockchainID);
error InvalidWarpSourceChainID(bytes32 sourceChainID);
error InvalidRegistrationExpiry(uint64 registrationExpiry);
error InvalidInitializationStatus();
error InvalidMaximumChurnPercentage(uint8 maximumChurnPercentage);
error InvalidBLSKeyLength(uint256 length);
error InvalidNodeID(bytes nodeID);
error InvalidConversionID(bytes32 encodedConversionID, bytes32 expectedConversionID);
error InvalidTotalWeight(uint64 weight);
error InvalidValidationID(bytes32 validationID);
error InvalidValidatorStatus(ValidatorStatus status);
error InvalidWarpMessage();
error MaxChurnRateExceeded(uint64 churnAmount);
error NodeAlreadyRegistered(bytes nodeID);
error UnexpectedRegistrationStatus(bool validRegistration);
error InvalidPChainOwnerThreshold(uint256 threshold, uint256 addressesLength);
error PChainOwnerAddressesNotSorted();
// solhint-disable ordering
/**
* @dev This storage is visible to child contracts for convenience.
* External getters would be better practice, but code size limitations are preventing this.
* Child contracts should probably never write to this storage.
*/
function _getValidatorManagerStorage()
internal
pure
returns (ValidatorManagerStorage storage $)
{
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := VALIDATOR_MANAGER_STORAGE_LOCATION
}
}
/**
* @notice Warp precompile used for sending and receiving Warp messages.
*/
IWarpMessenger public constant WARP_MESSENGER =
IWarpMessenger(0x0200000000000000000000000000000000000005);
// solhint-disable-next-line func-name-mixedcase
function __ValidatorManager_init(ValidatorManagerSettings calldata settings)
internal
onlyInitializing
{
__Context_init();
__ValidatorManager_init_unchained(settings);
}
// solhint-disable-next-line func-name-mixedcase
function __ValidatorManager_init_unchained(ValidatorManagerSettings calldata settings)
internal
onlyInitializing
{
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
$._subnetID = settings.subnetID;
if (
settings.maximumChurnPercentage > MAXIMUM_CHURN_PERCENTAGE_LIMIT
|| settings.maximumChurnPercentage == 0
) {
revert InvalidMaximumChurnPercentage(settings.maximumChurnPercentage);
}
$._maximumChurnPercentage = settings.maximumChurnPercentage;
$._churnPeriodSeconds = settings.churnPeriodSeconds;
}
modifier initializedValidatorSet() {
if (!_getValidatorManagerStorage()._initializedValidatorSet) {
revert InvalidInitializationStatus();
}
_;
}
/**
* @notice See {IValidatorManager-initializeValidatorSet}.
*/
function initializeValidatorSet(
ConversionData calldata conversionData,
uint32 messageIndex
) external {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
if ($._initializedValidatorSet) {
revert InvalidInitializationStatus();
}
// Check that the blockchainID and validator manager address in the ConversionData correspond to this contract.
// Other validation checks are done by the P-Chain when converting the L1, so are not required here.
if (conversionData.validatorManagerBlockchainID != WARP_MESSENGER.getBlockchainID()) {
revert InvalidValidatorManagerBlockchainID(conversionData.validatorManagerBlockchainID);
}
if (address(conversionData.validatorManagerAddress) != address(this)) {
revert InvalidValidatorManagerAddress(address(conversionData.validatorManagerAddress));
}
uint256 numInitialValidators = conversionData.initialValidators.length;
uint64 totalWeight;
for (uint32 i; i < numInitialValidators; ++i) {
InitialValidator memory initialValidator = conversionData.initialValidators[i];
if ($._registeredValidators[initialValidator.nodeID] != bytes32(0)) {
revert NodeAlreadyRegistered(initialValidator.nodeID);
}
// Validation ID of the initial validators is the sha256 hash of the
// convert subnet to L1 tx ID and the index of the initial validator.
bytes32 validationID = sha256(abi.encodePacked(conversionData.subnetID, i));
// Save the initial validator as an active validator.
$._registeredValidators[initialValidator.nodeID] = validationID;
$._validationPeriods[validationID].status = ValidatorStatus.Active;
$._validationPeriods[validationID].nodeID = initialValidator.nodeID;
$._validationPeriods[validationID].startingWeight = initialValidator.weight;
$._validationPeriods[validationID].messageNonce = 0;
$._validationPeriods[validationID].weight = initialValidator.weight;
$._validationPeriods[validationID].startedAt = uint64(block.timestamp);
$._validationPeriods[validationID].endedAt = 0;
totalWeight += initialValidator.weight;
emit InitialValidatorCreated(
validationID, initialValidator.weight, initialValidator.nodeID
);
}
$._churnTracker.totalWeight = totalWeight;
// Rearranged equation for totalWeight < (100 / $._maximumChurnPercentage)
// Total weight must be above this value in order to not trigger churn limits with an added/removed weight of 1.
if (totalWeight * $._maximumChurnPercentage < 100) {
revert InvalidTotalWeight(totalWeight);
}
// Verify that the sha256 hash of the L1 conversion data matches with the Warp message's conversionID.
bytes32 conversionID = ValidatorMessages.unpackSubnetToL1ConversionMessage(
_getPChainWarpMessage(messageIndex).payload
);
bytes memory encodedConversion = ValidatorMessages.packConversionData(conversionData);
bytes32 encodedConversionID = sha256(encodedConversion);
if (encodedConversionID != conversionID) {
revert InvalidConversionID(encodedConversionID, conversionID);
}
$._initializedValidatorSet = true;
}
function _validatePChainOwner(PChainOwner calldata pChainOwner) internal pure {
// If threshold is 0, addresses must be empty.
if (pChainOwner.threshold == 0 && pChainOwner.addresses.length != 0) {
revert InvalidPChainOwnerThreshold(pChainOwner.threshold, pChainOwner.addresses.length);
}
// Threshold must be less than or equal to the number of addresses.
if (pChainOwner.threshold > pChainOwner.addresses.length) {
revert InvalidPChainOwnerThreshold(pChainOwner.threshold, pChainOwner.addresses.length);
}
// Addresses must be sorted in ascending order
for (uint256 i = 1; i < pChainOwner.addresses.length; i++) {
// Compare current address with the previous one
if (pChainOwner.addresses[i] < pChainOwner.addresses[i - 1]) {
revert PChainOwnerAddressesNotSorted();
}
}
}
/**
* @notice Begins the validator registration process, and sets the initial weight for the validator.
* This is the only method related to validator registration and removal that needs the initializedValidatorSet
* modifier. All others are guarded by checking the validator status changes initialized in this function.
* @param input The inputs for a validator registration.
* @param weight The weight of the validator being registered.
*/
function _initializeValidatorRegistration(
ValidatorRegistrationInput calldata input,
uint64 weight
) internal virtual initializedValidatorSet returns (bytes32) {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
if (
input.registrationExpiry <= block.timestamp
|| input.registrationExpiry >= block.timestamp + MAXIMUM_REGISTRATION_EXPIRY_LENGTH
) {
revert InvalidRegistrationExpiry(input.registrationExpiry);
}
// Ensure the new validator doesn't overflow the total weight
if (uint256(weight) + uint256($._churnTracker.totalWeight) > type(uint64).max) {
revert InvalidTotalWeight(weight);
}
_validatePChainOwner(input.remainingBalanceOwner);
_validatePChainOwner(input.disableOwner);
// Ensure the nodeID is not the zero address, and is not already an active validator.
if (input.blsPublicKey.length != BLS_PUBLIC_KEY_LENGTH) {
revert InvalidBLSKeyLength(input.blsPublicKey.length);
}
if (input.nodeID.length == 0) {
revert InvalidNodeID(input.nodeID);
}
if ($._registeredValidators[input.nodeID] != bytes32(0)) {
revert NodeAlreadyRegistered(input.nodeID);
}
// Check that adding this validator would not exceed the maximum churn rate.
_checkAndUpdateChurnTracker(weight, 0);
(bytes32 validationID, bytes memory registerL1ValidatorMessage) = ValidatorMessages
.packRegisterL1ValidatorMessage(
ValidatorMessages.ValidationPeriod({
subnetID: $._subnetID,
nodeID: input.nodeID,
blsPublicKey: input.blsPublicKey,
remainingBalanceOwner: input.remainingBalanceOwner,
disableOwner: input.disableOwner,
registrationExpiry: input.registrationExpiry,
weight: weight
})
);
$._pendingRegisterValidationMessages[validationID] = registerL1ValidatorMessage;
$._registeredValidators[input.nodeID] = validationID;
// Submit the message to the Warp precompile.
bytes32 messageID = WARP_MESSENGER.sendWarpMessage(registerL1ValidatorMessage);
$._validationPeriods[validationID].status = ValidatorStatus.PendingAdded;
$._validationPeriods[validationID].nodeID = input.nodeID;
$._validationPeriods[validationID].startingWeight = weight;
$._validationPeriods[validationID].messageNonce = 0;
$._validationPeriods[validationID].weight = weight;
$._validationPeriods[validationID].startedAt = 0; // The validation period only starts once the registration is acknowledged.
$._validationPeriods[validationID].endedAt = 0;
emit ValidationPeriodCreated(
validationID, messageID, weight, input.nodeID, input.registrationExpiry
);
return validationID;
}
/**
* @notice See {IValidatorManager-resendRegisterValidatorMessage}.
*/
function resendRegisterValidatorMessage(bytes32 validationID) external {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
// The initial validator set must have been set already to have pending register validation messages.
if ($._pendingRegisterValidationMessages[validationID].length == 0) {
revert InvalidValidationID(validationID);
}
if ($._validationPeriods[validationID].status != ValidatorStatus.PendingAdded) {
revert InvalidValidatorStatus($._validationPeriods[validationID].status);
}
// Submit the message to the Warp precompile.
WARP_MESSENGER.sendWarpMessage($._pendingRegisterValidationMessages[validationID]);
}
/**
* @notice See {IValidatorManager-completeValidatorRegistration}.
*/
function completeValidatorRegistration(uint32 messageIndex) external {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
(bytes32 validationID, bool validRegistration) = ValidatorMessages
.unpackL1ValidatorRegistrationMessage(_getPChainWarpMessage(messageIndex).payload);
if (!validRegistration) {
revert UnexpectedRegistrationStatus(validRegistration);
}
// The initial validator set must have been set already to have pending register validation messages.
if ($._pendingRegisterValidationMessages[validationID].length == 0) {
revert InvalidValidationID(validationID);
}
if ($._validationPeriods[validationID].status != ValidatorStatus.PendingAdded) {
revert InvalidValidatorStatus($._validationPeriods[validationID].status);
}
delete $._pendingRegisterValidationMessages[validationID];
$._validationPeriods[validationID].status = ValidatorStatus.Active;
$._validationPeriods[validationID].startedAt = uint64(block.timestamp);
emit ValidationPeriodRegistered(
validationID, $._validationPeriods[validationID].weight, block.timestamp
);
}
/**
* @notice Returns a validation ID registered to the given nodeID
* @param nodeID ID of the node associated with the validation ID
*/
function registeredValidators(bytes calldata nodeID) public view returns (bytes32) {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
return $._registeredValidators[nodeID];
}
/**
* @notice Returns a validator registered to the given validationID
* @param validationID ID of the validation period associated with the validator
*/
function getValidator(bytes32 validationID) public view returns (Validator memory) {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
return $._validationPeriods[validationID];
}
/**
* @notice Begins the process of ending an active validation period. The validation period must have been previously
* started by a successful call to {completeValidatorRegistration} with the given validationID.
* Any rewards for this validation period will stop accruing when this function is called.
* @param validationID The ID of the validation period being ended.
*/
function _initializeEndValidation(bytes32 validationID)
internal
virtual
returns (Validator memory)
{
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
// Ensure the validation period is active.
// The initial validator set must have been set already to have active validators.
Validator memory validator = $._validationPeriods[validationID];
if (validator.status != ValidatorStatus.Active) {
revert InvalidValidatorStatus($._validationPeriods[validationID].status);
}
// Update the validator status to pending removal.
// They are not removed from the active validators mapping until the P-Chain acknowledges the removal.
validator.status = ValidatorStatus.PendingRemoved;
// Set the end time of the validation period, since it is no longer known to be an active validator
// on the P-Chain.
validator.endedAt = uint64(block.timestamp);
// Save the validator updates.
$._validationPeriods[validationID] = validator;
(, bytes32 messageID) = _setValidatorWeight(validationID, 0);
// Emit the event to signal the start of the validator removal process.
emit ValidatorRemovalInitialized(validationID, messageID, validator.weight, block.timestamp);
return validator;
}
/**
* @notice See {IValidatorManager-resendEndValidatorMessage}.
*/
function resendEndValidatorMessage(bytes32 validationID) external {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
Validator memory validator = $._validationPeriods[validationID];
// The initial validator set must have been set already to have pending end validation messages.
if (validator.status != ValidatorStatus.PendingRemoved) {
revert InvalidValidatorStatus($._validationPeriods[validationID].status);
}
WARP_MESSENGER.sendWarpMessage(
ValidatorMessages.packL1ValidatorWeightMessage(validationID, validator.messageNonce, 0)
);
}
/**
* @notice Completes the process of ending a validation period by receiving an acknowledgement from the P-Chain
* that the validation ID is not active and will never be active in the future.
* Note: that this function can be used for successful validation periods that have been explicitly
* ended by calling {initializeEndValidation} or for validation periods that never began on the P-Chain due to the
* {registrationExpiry} being reached.
* @return (Validation ID, Validator instance) representing the completed validation period.
*/
function _completeEndValidation(uint32 messageIndex)
internal
returns (bytes32, Validator memory)
{
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
// Get the Warp message.
(bytes32 validationID, bool validRegistration) = ValidatorMessages
.unpackL1ValidatorRegistrationMessage(_getPChainWarpMessage(messageIndex).payload);
if (validRegistration) {
revert UnexpectedRegistrationStatus(validRegistration);
}
Validator memory validator = $._validationPeriods[validationID];
// The validation status is PendingRemoved if validator removal was initiated with a call to {initiateEndValidation}.
// The validation status is PendingAdded if the validator was never registered on the P-Chain.
// The initial validator set must have been set already to have pending validation messages.
if (
validator.status != ValidatorStatus.PendingRemoved
&& validator.status != ValidatorStatus.PendingAdded
) {
revert InvalidValidatorStatus(validator.status);
}
if (validator.status == ValidatorStatus.PendingRemoved) {
validator.status = ValidatorStatus.Completed;
} else {
validator.status = ValidatorStatus.Invalidated;
}
// Remove the validator from the registered validators mapping.
delete $._registeredValidators[validator.nodeID];
// Update the validator.
$._validationPeriods[validationID] = validator;
// Emit event.
emit ValidationPeriodEnded(validationID, validator.status);
return (validationID, validator);
}
function _incrementAndGetNonce(bytes32 validationID) internal returns (uint64) {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
return ++$._validationPeriods[validationID].messageNonce;
}
function _getPChainWarpMessage(uint32 messageIndex)
internal
view
returns (WarpMessage memory)
{
(WarpMessage memory warpMessage, bool valid) =
WARP_MESSENGER.getVerifiedWarpMessage(messageIndex);
if (!valid) {
revert InvalidWarpMessage();
}
// Must match to P-Chain blockchain id, which is 0.
if (warpMessage.sourceChainID != P_CHAIN_BLOCKCHAIN_ID) {
revert InvalidWarpSourceChainID(warpMessage.sourceChainID);
}
if (warpMessage.originSenderAddress != address(0)) {
revert InvalidWarpOriginSenderAddress(warpMessage.originSenderAddress);
}
return warpMessage;
}
function _setValidatorWeight(
bytes32 validationID,
uint64 newWeight
) internal returns (uint64, bytes32) {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
uint64 validatorWeight = $._validationPeriods[validationID].weight;
// Check that changing the validator weight would not exceed the maximum churn rate.
_checkAndUpdateChurnTracker(newWeight, validatorWeight);
uint64 nonce = _incrementAndGetNonce(validationID);
$._validationPeriods[validationID].weight = newWeight;
// Submit the message to the Warp precompile.
bytes32 messageID = WARP_MESSENGER.sendWarpMessage(
ValidatorMessages.packL1ValidatorWeightMessage(validationID, nonce, newWeight)
);
emit ValidatorWeightUpdate({
validationID: validationID,
nonce: nonce,
weight: newWeight,
setWeightMessageID: messageID
});
return (nonce, messageID);
}
function _getChurnPeriodSeconds() internal view returns (uint64) {
return _getValidatorManagerStorage()._churnPeriodSeconds;
}
/**
* @dev Helper function to check if the stake weight to be added or removed would exceed the maximum stake churn
* rate for the past churn period. If the churn rate is exceeded, the function will revert. If the churn rate is
* not exceeded, the function will update the churn tracker with the new weight.
*/
function _checkAndUpdateChurnTracker(
uint64 newValidatorWeight,
uint64 oldValidatorWeight
) private {
ValidatorManagerStorage storage $ = _getValidatorManagerStorage();
uint64 weightChange;
if (newValidatorWeight > oldValidatorWeight) {
weightChange = newValidatorWeight - oldValidatorWeight;
} else {
weightChange = oldValidatorWeight - newValidatorWeight;
}
uint256 currentTime = block.timestamp;
ValidatorChurnPeriod memory churnTracker = $._churnTracker;
if (
churnTracker.startedAt == 0
|| currentTime >= churnTracker.startedAt + $._churnPeriodSeconds
) {
churnTracker.churnAmount = weightChange;
churnTracker.startedAt = currentTime;
churnTracker.initialWeight = churnTracker.totalWeight;
} else {
// Churn is always additive whether the weight is being added or removed.
churnTracker.churnAmount += weightChange;
}
// Rearranged equation of maximumChurnPercentage >= currentChurnPercentage to avoid integer division truncation.
if ($._maximumChurnPercentage * churnTracker.initialWeight < churnTracker.churnAmount * 100)
{
revert MaxChurnRateExceeded(churnTracker.churnAmount);
}
// Two separate calculations because we're using uints and (newValidatorWeight - oldValidatorWeight) could underflow.
churnTracker.totalWeight += newValidatorWeight;
churnTracker.totalWeight -= oldValidatorWeight;
// Rearranged equation for totalWeight < (100 / $._maximumChurnPercentage)
// Total weight must be above this value in order to not trigger churn limits with an added/removed weight of 1.
if (churnTracker.totalWeight * $._maximumChurnPercentage < 100) {
revert InvalidTotalWeight(churnTracker.totalWeight);
}
$._churnTracker = churnTracker;
}
}