-
Notifications
You must be signed in to change notification settings - Fork 374
/
Copy pathValidators.sol
1401 lines (1308 loc) · 56.8 KB
/
Validators.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
pragma solidity ^0.5.13;
import "openzeppelin-solidity/contracts/math/Math.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";
import "./interfaces/IValidators.sol";
import "../common/CalledByVm.sol";
import "../common/Initializable.sol";
import "../common/FixidityLib.sol";
import "../common/linkedlists/AddressLinkedList.sol";
import "../common/UsingRegistry.sol";
import "../common/UsingPrecompiles.sol";
import "../common/interfaces/ICeloVersionedContract.sol";
import "../common/libraries/ReentrancyGuard.sol";
/**
* @title A contract for registering and electing Validator Groups and Validators.
*/
contract Validators is
IValidators,
ICeloVersionedContract,
Ownable,
ReentrancyGuard,
Initializable,
UsingRegistry,
UsingPrecompiles,
CalledByVm
{
using FixidityLib for FixidityLib.Fraction;
using AddressLinkedList for LinkedList.List;
using SafeMath for uint256;
using BytesLib for bytes;
// For Validators, these requirements must be met in order to:
// 1. Register a validator
// 2. Affiliate with and be added to a group
// 3. Receive epoch payments (note that the group must meet the group requirements as well)
// Accounts may de-register their Validator `duration` seconds after they were last a member of a
// group, after which no restrictions on Locked Gold will apply to the account.
//
// For Validator Groups, these requirements must be met in order to:
// 1. Register a group
// 2. Add a member to a group
// 3. Receive epoch payments
// Note that for groups, the requirement value is multiplied by the number of members, and is
// enforced for `duration` seconds after the group last had that number of members.
// Accounts may de-register their Group `duration` seconds after they were last non-empty, after
// which no restrictions on Locked Gold will apply to the account.
struct LockedGoldRequirements {
uint256 value;
// In seconds.
uint256 duration;
}
struct ValidatorGroup {
bool exists;
LinkedList.List members;
FixidityLib.Fraction commission;
FixidityLib.Fraction nextCommission;
uint256 nextCommissionBlock;
// sizeHistory[i] contains the last time the group contained i members.
uint256[] sizeHistory;
SlashingInfo slashInfo;
}
// Stores the epoch number at which a validator joined a particular group.
struct MembershipHistoryEntry {
uint256 epochNumber;
address group;
}
// Stores the per-epoch membership history of a validator, used to determine which group
// commission should be paid to at the end of an epoch.
// Stores a timestamp of the last time the validator was removed from a group, used to determine
// whether or not a group can de-register.
struct MembershipHistory {
// The key to the most recent entry in the entries mapping.
uint256 tail;
// The number of entries in this validators membership history.
uint256 numEntries;
mapping(uint256 => MembershipHistoryEntry) entries;
uint256 lastRemovedFromGroupTimestamp;
}
struct SlashingInfo {
FixidityLib.Fraction multiplier;
uint256 lastSlashed;
}
struct PublicKeys {
bytes ecdsa;
bytes bls;
}
struct Validator {
PublicKeys publicKeys;
address affiliation;
FixidityLib.Fraction score;
MembershipHistory membershipHistory;
}
// Parameters that govern the calculation of validator's score.
struct ValidatorScoreParameters {
uint256 exponent;
FixidityLib.Fraction adjustmentSpeed;
}
mapping(address => ValidatorGroup) private groups;
mapping(address => Validator) private validators;
address[] private registeredGroups;
address[] private registeredValidators;
LockedGoldRequirements public validatorLockedGoldRequirements;
LockedGoldRequirements public groupLockedGoldRequirements;
ValidatorScoreParameters private validatorScoreParameters;
uint256 public membershipHistoryLength;
uint256 public maxGroupSize;
// The number of blocks to delay a ValidatorGroup's commission update
uint256 public commissionUpdateDelay;
uint256 public slashingMultiplierResetPeriod;
uint256 public downtimeGracePeriod;
event MaxGroupSizeSet(uint256 size);
event CommissionUpdateDelaySet(uint256 delay);
event ValidatorScoreParametersSet(uint256 exponent, uint256 adjustmentSpeed);
event GroupLockedGoldRequirementsSet(uint256 value, uint256 duration);
event ValidatorLockedGoldRequirementsSet(uint256 value, uint256 duration);
event MembershipHistoryLengthSet(uint256 length);
event ValidatorRegistered(address indexed validator);
event ValidatorDeregistered(address indexed validator);
event ValidatorAffiliated(address indexed validator, address indexed group);
event ValidatorDeaffiliated(address indexed validator, address indexed group);
event ValidatorEcdsaPublicKeyUpdated(address indexed validator, bytes ecdsaPublicKey);
event ValidatorBlsPublicKeyUpdated(address indexed validator, bytes blsPublicKey);
event ValidatorScoreUpdated(address indexed validator, uint256 score, uint256 epochScore);
event ValidatorGroupRegistered(address indexed group, uint256 commission);
event ValidatorGroupDeregistered(address indexed group);
event ValidatorGroupMemberAdded(address indexed group, address indexed validator);
event ValidatorGroupMemberRemoved(address indexed group, address indexed validator);
event ValidatorGroupMemberReordered(address indexed group, address indexed validator);
event ValidatorGroupCommissionUpdateQueued(
address indexed group,
uint256 commission,
uint256 activationBlock
);
event ValidatorGroupCommissionUpdated(address indexed group, uint256 commission);
event ValidatorEpochPaymentDistributed(
address indexed validator,
uint256 validatorPayment,
address indexed group,
uint256 groupPayment
);
modifier onlySlasher() {
require(getLockedGold().isSlasher(msg.sender), "Only registered slasher can call");
_;
}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return Storage version of the contract.
* @return Major version of the contract.
* @return Minor version of the contract.
* @return Patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 2, 0, 5);
}
/**
* @notice Sets initialized == true on implementation contracts
* @param test Set to true to skip implementation initialization
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param registryAddress The address of the registry core smart contract.
* @param groupRequirementValue The Locked Gold requirement amount for groups.
* @param groupRequirementDuration The Locked Gold requirement duration for groups.
* @param validatorRequirementValue The Locked Gold requirement amount for validators.
* @param validatorRequirementDuration The Locked Gold requirement duration for validators.
* @param validatorScoreExponent The exponent used in calculating validator scores.
* @param validatorScoreAdjustmentSpeed The speed at which validator scores are adjusted.
* @param _membershipHistoryLength The max number of entries for validator membership history.
* @param _maxGroupSize The maximum group size.
* @param _commissionUpdateDelay The number of blocks to delay a ValidatorGroup's commission
* update.
* @dev Should be called only once.
*/
function initialize(
address registryAddress,
uint256 groupRequirementValue,
uint256 groupRequirementDuration,
uint256 validatorRequirementValue,
uint256 validatorRequirementDuration,
uint256 validatorScoreExponent,
uint256 validatorScoreAdjustmentSpeed,
uint256 _membershipHistoryLength,
uint256 _slashingMultiplierResetPeriod,
uint256 _maxGroupSize,
uint256 _commissionUpdateDelay,
uint256 _downtimeGracePeriod
) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setGroupLockedGoldRequirements(groupRequirementValue, groupRequirementDuration);
setValidatorLockedGoldRequirements(validatorRequirementValue, validatorRequirementDuration);
setValidatorScoreParameters(validatorScoreExponent, validatorScoreAdjustmentSpeed);
setMaxGroupSize(_maxGroupSize);
setCommissionUpdateDelay(_commissionUpdateDelay);
setMembershipHistoryLength(_membershipHistoryLength);
setSlashingMultiplierResetPeriod(_slashingMultiplierResetPeriod);
setDowntimeGracePeriod(_downtimeGracePeriod);
}
/**
* @notice Updates the block delay for a ValidatorGroup's commission udpdate
* @param delay Number of blocks to delay the update
*/
function setCommissionUpdateDelay(uint256 delay) public onlyOwner {
require(delay != commissionUpdateDelay, "commission update delay not changed");
commissionUpdateDelay = delay;
emit CommissionUpdateDelaySet(delay);
}
/**
* @notice Updates the maximum number of members a group can have.
* @param size The maximum group size.
* @return True upon success.
*/
function setMaxGroupSize(uint256 size) public onlyOwner returns (bool) {
require(0 < size, "Max group size cannot be zero");
require(size != maxGroupSize, "Max group size not changed");
maxGroupSize = size;
emit MaxGroupSizeSet(size);
return true;
}
/**
* @notice Updates the number of validator group membership entries to store.
* @param length The number of validator group membership entries to store.
* @return True upon success.
*/
function setMembershipHistoryLength(uint256 length) public onlyOwner returns (bool) {
require(0 < length, "Membership history length cannot be zero");
require(length != membershipHistoryLength, "Membership history length not changed");
membershipHistoryLength = length;
emit MembershipHistoryLengthSet(length);
return true;
}
/**
* @notice Updates the validator score parameters.
* @param exponent The exponent used in calculating the score.
* @param adjustmentSpeed The speed at which the score is adjusted.
* @return True upon success.
*/
function setValidatorScoreParameters(uint256 exponent, uint256 adjustmentSpeed)
public
onlyOwner
returns (bool)
{
require(
adjustmentSpeed <= FixidityLib.fixed1().unwrap(),
"Adjustment speed cannot be larger than 1"
);
require(
exponent != validatorScoreParameters.exponent ||
!FixidityLib.wrap(adjustmentSpeed).equals(validatorScoreParameters.adjustmentSpeed),
"Adjustment speed and exponent not changed"
);
validatorScoreParameters = ValidatorScoreParameters(
exponent,
FixidityLib.wrap(adjustmentSpeed)
);
emit ValidatorScoreParametersSet(exponent, adjustmentSpeed);
return true;
}
/**
* @notice Returns the maximum number of members a group can add.
* @return The maximum number of members a group can add.
*/
function getMaxGroupSize() external view returns (uint256) {
return maxGroupSize;
}
/**
* @notice Returns the block delay for a ValidatorGroup's commission udpdate.
* @return The block delay for a ValidatorGroup's commission udpdate.
*/
function getCommissionUpdateDelay() external view returns (uint256) {
return commissionUpdateDelay;
}
/**
* @notice Updates the Locked Gold requirements for Validator Groups.
* @param value The per-member amount of Locked Gold required.
* @param duration The time (in seconds) that these requirements persist for.
* @return True upon success.
*/
function setGroupLockedGoldRequirements(uint256 value, uint256 duration)
public
onlyOwner
returns (bool)
{
LockedGoldRequirements storage requirements = groupLockedGoldRequirements;
require(
value != requirements.value || duration != requirements.duration,
"Group requirements not changed"
);
groupLockedGoldRequirements = LockedGoldRequirements(value, duration);
emit GroupLockedGoldRequirementsSet(value, duration);
return true;
}
/**
* @notice Updates the Locked Gold requirements for Validators.
* @param value The amount of Locked Gold required.
* @param duration The time (in seconds) that these requirements persist for.
* @return True upon success.
*/
function setValidatorLockedGoldRequirements(uint256 value, uint256 duration)
public
onlyOwner
returns (bool)
{
LockedGoldRequirements storage requirements = validatorLockedGoldRequirements;
require(
value != requirements.value || duration != requirements.duration,
"Validator requirements not changed"
);
validatorLockedGoldRequirements = LockedGoldRequirements(value, duration);
emit ValidatorLockedGoldRequirementsSet(value, duration);
return true;
}
/**
* @notice Registers a validator unaffiliated with any validator group.
* @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus, should
* match the validator signer. 64 bytes.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @return True upon success.
* @dev Fails if the account is already a validator or validator group.
* @dev Fails if the account does not have sufficient Locked Gold.
*/
function registerValidator(
bytes calldata ecdsaPublicKey,
bytes calldata blsPublicKey,
bytes calldata blsPop
) external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
_isRegistrationAllowed(account);
require(!isValidator(account) && !isValidatorGroup(account), "Already registered");
uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account);
require(lockedGoldBalance >= validatorLockedGoldRequirements.value, "Deposit too small");
Validator storage validator = validators[account];
address signer = getAccounts().getValidatorSigner(account);
require(
_updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey),
"Error updating ECDSA public key"
);
require(
_updateBlsPublicKey(validator, account, blsPublicKey, blsPop),
"Error updating BLS public key"
);
registeredValidators.push(account);
updateMembershipHistory(account, address(0));
emit ValidatorRegistered(account);
return true;
}
/**
* @notice Returns the parameters that govern how a validator's score is calculated.
* @return The exponent that governs how a validator's score is calculated.
* @return The adjustment speed that governs how a validator's score is calculated.
*/
function getValidatorScoreParameters() external view returns (uint256, uint256) {
return (validatorScoreParameters.exponent, validatorScoreParameters.adjustmentSpeed.unwrap());
}
/**
* @notice Returns the group membership history of a validator.
* @param account The validator whose membership history to return.
* @return epochs The epochs of a validator.
* @return The membership groups of a validator.
* @return The last removed from group timestamp of a validator.
* @return The tail of a validator.
*/
function getMembershipHistory(address account)
external
view
returns (uint256[] memory, address[] memory, uint256, uint256)
{
MembershipHistory storage history = validators[account].membershipHistory;
uint256[] memory epochs = new uint256[](history.numEntries);
address[] memory membershipGroups = new address[](history.numEntries);
for (uint256 i = 0; i < history.numEntries; i = i.add(1)) {
uint256 index = history.tail.add(i);
epochs[i] = history.entries[index].epochNumber;
membershipGroups[i] = history.entries[index].group;
}
return (epochs, membershipGroups, history.lastRemovedFromGroupTimestamp, history.tail);
}
/**
* @notice Calculates the validator score for an epoch from the uptime value for the epoch.
* @param uptime The Fixidity representation of the validator's uptime, between 0 and 1.
* @dev epoch_score = uptime ** exponent
* @return Fixidity representation of the epoch score between 0 and 1.
*/
function calculateEpochScore(uint256 uptime) public view returns (uint256) {
require(uptime <= FixidityLib.fixed1().unwrap(), "Uptime cannot be larger than one");
uint256 numerator;
uint256 denominator;
uptime = Math.min(uptime.add(downtimeGracePeriod), FixidityLib.fixed1().unwrap());
(numerator, denominator) = fractionMulExp(
FixidityLib.fixed1().unwrap(),
FixidityLib.fixed1().unwrap(),
uptime,
FixidityLib.fixed1().unwrap(),
validatorScoreParameters.exponent,
18
);
return FixidityLib.newFixedFraction(numerator, denominator).unwrap();
}
/**
* @notice Calculates the aggregate score of a group for an epoch from individual uptimes.
* @param uptimes Array of Fixidity representations of the validators' uptimes, between 0 and 1.
* @dev group_score = average(uptimes ** exponent)
* @return Fixidity representation of the group epoch score between 0 and 1.
*/
function calculateGroupEpochScore(uint256[] calldata uptimes) external view returns (uint256) {
require(uptimes.length > 0, "Uptime array empty");
require(uptimes.length <= maxGroupSize, "Uptime array larger than maximum group size");
FixidityLib.Fraction memory sum;
for (uint256 i = 0; i < uptimes.length; i = i.add(1)) {
sum = sum.add(FixidityLib.wrap(calculateEpochScore(uptimes[i])));
}
return sum.divide(FixidityLib.newFixed(uptimes.length)).unwrap();
}
/**
* @notice Updates a validator's score based on its uptime for the epoch.
* @param signer The validator signer of the validator account whose score needs updating.
* @param uptime The Fixidity representation of the validator's uptime, between 0 and 1.
* @return True upon success.
*/
function updateValidatorScoreFromSigner(address signer, uint256 uptime) external onlyVm() {
_updateValidatorScoreFromSigner(signer, uptime);
}
/**
* @notice Updates a validator's score based on its uptime for the epoch.
* @param signer The validator signer of the validator whose score needs updating.
* @param uptime The Fixidity representation of the validator's uptime, between 0 and 1.
* @dev new_score = uptime ** exponent * adjustmentSpeed + old_score * (1 - adjustmentSpeed)
* @return True upon success.
*/
function _updateValidatorScoreFromSigner(address signer, uint256 uptime) internal {
address account = getAccounts().signerToAccount(signer);
require(isValidator(account), "Not a validator");
FixidityLib.Fraction memory epochScore = FixidityLib.wrap(calculateEpochScore(uptime));
FixidityLib.Fraction memory newComponent = validatorScoreParameters.adjustmentSpeed.multiply(
epochScore
);
FixidityLib.Fraction memory currentComponent = FixidityLib.fixed1().subtract(
validatorScoreParameters.adjustmentSpeed
);
currentComponent = currentComponent.multiply(validators[account].score);
validators[account].score = FixidityLib.wrap(
Math.min(epochScore.unwrap(), newComponent.add(currentComponent).unwrap())
);
emit ValidatorScoreUpdated(account, validators[account].score.unwrap(), epochScore.unwrap());
}
/**
* @notice Distributes epoch payments to the account associated with `signer` and its group.
* @param signer The validator signer of the account to distribute the epoch payment to.
* @param maxPayment The maximum payment to the validator. Actual payment is based on score and
* group commission.
* @return The total payment paid to the validator and their group.
*/
function distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment)
external
onlyVm()
returns (uint256)
{
return _distributeEpochPaymentsFromSigner(signer, maxPayment);
}
/**
* @notice Distributes epoch payments to the account associated with `signer` and its group.
* @param signer The validator signer of the validator to distribute the epoch payment to.
* @param maxPayment The maximum payment to the validator. Actual payment is based on score and
* group commission.
* @return The total payment paid to the validator and their group.
*/
function _distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment)
internal
returns (uint256)
{
address account = getAccounts().signerToAccount(signer);
require(isValidator(account), "Not a validator");
// The group that should be paid is the group that the validator was a member of at the
// time it was elected.
address group = getMembershipInLastEpoch(account);
require(group != address(0), "Validator not registered with a group");
// Both the validator and the group must maintain the minimum locked gold balance in order to
// receive epoch payments.
if (meetsAccountLockedGoldRequirements(account) && meetsAccountLockedGoldRequirements(group)) {
FixidityLib.Fraction memory totalPayment = FixidityLib
.newFixed(maxPayment)
.multiply(validators[account].score)
.multiply(groups[group].slashInfo.multiplier);
uint256 groupPayment = totalPayment.multiply(groups[group].commission).fromFixed();
FixidityLib.Fraction memory remainingPayment = FixidityLib.newFixed(
totalPayment.fromFixed().sub(groupPayment)
);
(address beneficiary, uint256 fraction) = getAccounts().getPaymentDelegation(account);
uint256 delegatedPayment = remainingPayment.multiply(FixidityLib.wrap(fraction)).fromFixed();
uint256 validatorPayment = remainingPayment.fromFixed().sub(delegatedPayment);
IStableToken stableToken = getStableToken();
require(stableToken.mint(group, groupPayment), "mint failed to validator group");
require(stableToken.mint(account, validatorPayment), "mint failed to validator account");
if (fraction != 0) {
require(stableToken.mint(beneficiary, delegatedPayment), "mint failed to delegatee");
}
emit ValidatorEpochPaymentDistributed(account, validatorPayment, group, groupPayment);
return totalPayment.fromFixed();
} else {
return 0;
}
}
/**
* @notice De-registers a validator.
* @param index The index of this validator in the list of all registered validators.
* @return True upon success.
* @dev Fails if the account is not a validator.
* @dev Fails if the validator has been a member of a group too recently.
*/
function deregisterValidator(uint256 index) external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
// Require that the validator has not been a member of a validator group for
// `validatorLockedGoldRequirements.duration` seconds.
Validator storage validator = validators[account];
if (validator.affiliation != address(0)) {
require(
!groups[validator.affiliation].members.contains(account),
"Has been group member recently"
);
}
uint256 requirementEndTime = validator.membershipHistory.lastRemovedFromGroupTimestamp.add(
validatorLockedGoldRequirements.duration
);
require(requirementEndTime < now, "Not yet requirement end time");
// Remove the validator.
deleteElement(registeredValidators, account, index);
delete validators[account];
emit ValidatorDeregistered(account);
return true;
}
/**
* @notice Affiliates a validator with a group, allowing it to be added as a member.
* @param group The validator group with which to affiliate.
* @return True upon success.
* @dev De-affiliates with the previously affiliated group if present.
*/
function affiliate(address group) external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
require(isValidatorGroup(group), "Not a validator group");
require(meetsAccountLockedGoldRequirements(account), "Validator doesn't meet requirements");
require(meetsAccountLockedGoldRequirements(group), "Group doesn't meet requirements");
Validator storage validator = validators[account];
if (validator.affiliation != address(0)) {
_deaffiliate(validator, account);
}
validator.affiliation = group;
emit ValidatorAffiliated(account, group);
return true;
}
/**
* @notice De-affiliates a validator, removing it from the group for which it is a member.
* @return True upon success.
* @dev Fails if the account is not a validator with non-zero affiliation.
*/
function deaffiliate() external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(validator.affiliation != address(0), "deaffiliate: not affiliated");
_deaffiliate(validator, account);
return true;
}
/**
* @notice Updates a validator's BLS key.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 48 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @return True upon success.
*/
function updateBlsPublicKey(bytes calldata blsPublicKey, bytes calldata blsPop)
external
returns (bool)
{
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(
_updateBlsPublicKey(validator, account, blsPublicKey, blsPop),
"Error updating BLS public key"
);
return true;
}
/**
* @notice Updates a validator's BLS key.
* @param validator The validator whose BLS public key should be updated.
* @param account The address under which the validator is registered.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @return True upon success.
*/
function _updateBlsPublicKey(
Validator storage validator,
address account,
bytes memory blsPublicKey,
bytes memory blsPop
) private returns (bool) {
require(blsPublicKey.length == 96, "Wrong BLS public key length");
require(blsPop.length == 48, "Wrong BLS PoP length");
require(checkProofOfPossession(account, blsPublicKey, blsPop), "Invalid BLS PoP");
validator.publicKeys.bls = blsPublicKey;
emit ValidatorBlsPublicKeyUpdated(account, blsPublicKey);
return true;
}
/**
* @notice Updates a validator's ECDSA key.
* @param account The address under which the validator is registered.
* @param signer The address which the validator is using to sign consensus messages.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @return True upon success.
*/
function updateEcdsaPublicKey(address account, address signer, bytes calldata ecdsaPublicKey)
external
onlyRegisteredContract(ACCOUNTS_REGISTRY_ID)
returns (bool)
{
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(
_updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey),
"Error updating ECDSA public key"
);
return true;
}
/**
* @notice Updates a validator's ECDSA key.
* @param validator The validator whose ECDSA public key should be updated.
* @param signer The address with which the validator is signing consensus messages.
* @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus. Should
* match `signer`. 64 bytes.
* @return True upon success.
*/
function _updateEcdsaPublicKey(
Validator storage validator,
address account,
address signer,
bytes memory ecdsaPublicKey
) private returns (bool) {
require(ecdsaPublicKey.length == 64, "Wrong ECDSA public key length");
require(
address(uint160(uint256(keccak256(ecdsaPublicKey)))) == signer,
"ECDSA key does not match signer"
);
validator.publicKeys.ecdsa = ecdsaPublicKey;
emit ValidatorEcdsaPublicKeyUpdated(account, ecdsaPublicKey);
return true;
}
/**
* @notice Updates a validator's ECDSA and BLS keys.
* @param account The address under which the validator is registered.
* @param signer The address which the validator is using to sign consensus messages.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @return True upon success.
*/
function updatePublicKeys(
address account,
address signer,
bytes calldata ecdsaPublicKey,
bytes calldata blsPublicKey,
bytes calldata blsPop
) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) {
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(
_updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey),
"Error updating ECDSA public key"
);
require(
_updateBlsPublicKey(validator, account, blsPublicKey, blsPop),
"Error updating BLS public key"
);
return true;
}
/**
* @notice Registers a validator group with no member validators.
* @param commission Fixidity representation of the commission this group receives on epoch
* payments made to its members.
* @return True upon success.
* @dev Fails if the account is already a validator or validator group.
* @dev Fails if the account does not have sufficient weight.
*/
function registerValidatorGroup(uint256 commission) external nonReentrant returns (bool) {
require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%");
address account = getAccounts().validatorSignerToAccount(msg.sender);
_isRegistrationAllowed(account);
require(!isValidator(account), "Already registered as validator");
require(!isValidatorGroup(account), "Already registered as group");
uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account);
require(lockedGoldBalance >= groupLockedGoldRequirements.value, "Not enough locked gold");
ValidatorGroup storage group = groups[account];
group.exists = true;
group.commission = FixidityLib.wrap(commission);
group.slashInfo = SlashingInfo(FixidityLib.fixed1(), 0);
registeredGroups.push(account);
emit ValidatorGroupRegistered(account, commission);
return true;
}
function _isRegistrationAllowed(address account) private returns (bool) {
require(
!getElection().allowedToVoteOverMaxNumberOfGroups(account),
"Cannot vote for more than max number of groups"
);
require(
// Validator could avoid getting slashed by delegating Celo to delegatees that would be voting
// for lots of proposals. Such transaction could run out of gas.
getLockedGold().getAccountTotalDelegatedFraction(account) == 0,
"Cannot delegate governance power"
);
}
/**
* @notice De-registers a validator group.
* @param index The index of this validator group in the list of all validator groups.
* @return True upon success.
* @dev Fails if the account is not a validator group with no members.
* @dev Fails if the group has had members too recently.
*/
function deregisterValidatorGroup(uint256 index) external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
// Only Validator Groups that have never had members or have been empty for at least
// `groupLockedGoldRequirements.duration` seconds can be deregistered.
require(isValidatorGroup(account), "Not a validator group");
require(groups[account].members.numElements == 0, "Validator group not empty");
uint256[] storage sizeHistory = groups[account].sizeHistory;
if (sizeHistory.length > 1) {
require(
sizeHistory[1].add(groupLockedGoldRequirements.duration) < now,
"Hasn't been empty for long enough"
);
}
delete groups[account];
deleteElement(registeredGroups, account, index);
emit ValidatorGroupDeregistered(account);
return true;
}
/**
* @notice Adds a member to the end of a validator group's list of members.
* @param validator The validator to add to the group
* @return True upon success.
* @dev Fails if `validator` has not set their affiliation to this account.
* @dev Fails if the group has zero members.
*/
function addMember(address validator) external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(groups[account].members.numElements > 0, "Validator group empty");
return _addMember(account, validator, address(0), address(0));
}
/**
* @notice Adds the first member to a group's list of members and marks it eligible for election.
* @param validator The validator to add to the group
* @param lesser The address of the group that has received fewer votes than this group.
* @param greater The address of the group that has received more votes than this group.
* @return True upon success.
* @dev Fails if `validator` has not set their affiliation to this account.
* @dev Fails if the group has > 0 members.
*/
function addFirstMember(address validator, address lesser, address greater)
external
nonReentrant
returns (bool)
{
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(groups[account].members.numElements == 0, "Validator group not empty");
return _addMember(account, validator, lesser, greater);
}
/**
* @notice Adds a member to the end of a validator group's list of members.
* @param group The address of the validator group.
* @param validator The validator to add to the group.
* @param lesser The address of the group that has received fewer votes than this group.
* @param greater The address of the group that has received more votes than this group.
* @return True upon success.
* @dev Fails if `validator` has not set their affiliation to this account.
* @dev Fails if the group has > 0 members.
*/
function _addMember(address group, address validator, address lesser, address greater)
private
returns (bool)
{
require(isValidatorGroup(group) && isValidator(validator), "Not validator and group");
ValidatorGroup storage _group = groups[group];
require(_group.members.numElements < maxGroupSize, "group would exceed maximum size");
require(validators[validator].affiliation == group, "Not affiliated to group");
require(!_group.members.contains(validator), "Already in group");
uint256 numMembers = _group.members.numElements.add(1);
_group.members.push(validator);
require(meetsAccountLockedGoldRequirements(group), "Group requirements not met");
require(meetsAccountLockedGoldRequirements(validator), "Validator requirements not met");
if (numMembers == 1) {
getElection().markGroupEligible(group, lesser, greater);
}
updateMembershipHistory(validator, group);
updateSizeHistory(group, numMembers.sub(1));
emit ValidatorGroupMemberAdded(group, validator);
return true;
}
/**
* @notice Removes a member from a validator group.
* @param validator The validator to remove from the group
* @return True upon success.
* @dev Fails if `validator` is not a member of the account's group.
*/
function removeMember(address validator) external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidatorGroup(account) && isValidator(validator), "is not group and validator");
return _removeMember(account, validator);
}
/**
* @notice Reorders a member within a validator group.
* @param validator The validator to reorder.
* @param lesserMember The member who will be behind `validator`, or 0 if `validator` will be the
* last member.
* @param greaterMember The member who will be ahead of `validator`, or 0 if `validator` will be
* the first member.
* @return True upon success.
* @dev Fails if `validator` is not a member of the account's validator group.
*/
function reorderMember(address validator, address lesserMember, address greaterMember)
external
nonReentrant
returns (bool)
{
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidatorGroup(account), "Not a group");
require(isValidator(validator), "Not a validator");
ValidatorGroup storage group = groups[account];
require(group.members.contains(validator), "Not a member of the group");
group.members.update(validator, lesserMember, greaterMember);
emit ValidatorGroupMemberReordered(account, validator);
return true;
}
/**
* @notice Queues an update to a validator group's commission.
* If there was a previously scheduled update, that is overwritten.
* @param commission Fixidity representation of the commission this group receives on epoch
* payments made to its members. Must be in the range [0, 1.0].
*/
function setNextCommissionUpdate(uint256 commission) external {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidatorGroup(account), "Not a validator group");
ValidatorGroup storage group = groups[account];
require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%");
require(commission != group.commission.unwrap(), "Commission must be different");
group.nextCommission = FixidityLib.wrap(commission);
group.nextCommissionBlock = block.number.add(commissionUpdateDelay);
emit ValidatorGroupCommissionUpdateQueued(account, commission, group.nextCommissionBlock);
}
/**
* @notice Updates a validator group's commission based on the previously queued update
*/
function updateCommission() external {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidatorGroup(account), "Not a validator group");
ValidatorGroup storage group = groups[account];
require(group.nextCommissionBlock != 0, "No commission update queued");
require(group.nextCommissionBlock <= block.number, "Can't apply commission update yet");
group.commission = group.nextCommission;
delete group.nextCommission;
delete group.nextCommissionBlock;
emit ValidatorGroupCommissionUpdated(account, group.commission.unwrap());
}
/**
* @notice Returns the current locked gold balance requirement for the supplied account.
* @param account The account that may have to meet locked gold balance requirements.
* @return The current locked gold balance requirement for the supplied account.
*/
function getAccountLockedGoldRequirement(address account) public view returns (uint256) {
if (isValidator(account)) {
return validatorLockedGoldRequirements.value;
} else if (isValidatorGroup(account)) {
uint256 multiplier = Math.max(1, groups[account].members.numElements);
uint256[] storage sizeHistory = groups[account].sizeHistory;
if (sizeHistory.length > 0) {
for (uint256 i = sizeHistory.length.sub(1); i > 0; i = i.sub(1)) {
if (sizeHistory[i].add(groupLockedGoldRequirements.duration) >= now) {
multiplier = Math.max(i, multiplier);
break;
}
}
}
return groupLockedGoldRequirements.value.mul(multiplier);
}
return 0;
}
/**
* @notice Returns whether or not an account meets its Locked Gold requirements.
* @param account The address of the account.
* @return Whether or not an account meets its Locked Gold requirements.
*/
function meetsAccountLockedGoldRequirements(address account) public view returns (bool) {
uint256 balance = getLockedGold().getAccountTotalLockedGold(account);
// Add a bit of "wiggle room" to accommodate the fact that vote activation can result in ~1
// wei rounding errors. Using 10 as an additional margin of safety.
return balance.add(10) >= getAccountLockedGoldRequirement(account);
}
/**
* @notice Returns the validator BLS key.
* @param signer The account that registered the validator or its authorized signing address.
* @return The validator BLS key.
*/
function getValidatorBlsPublicKeyFromSigner(address signer)
external
view
returns (bytes memory blsPublicKey)
{
address account = getAccounts().signerToAccount(signer);
require(isValidator(account), "Not a validator");
return validators[account].publicKeys.bls;
}
/**
* @notice Returns validator information.
* @param account The account that registered the validator.
* @return The unpacked validator struct.
*/
function getValidator(address account)
public
view
returns (
bytes memory ecdsaPublicKey,
bytes memory blsPublicKey,
address affiliation,
uint256 score,
address signer
)
{
require(isValidator(account), "Not a validator");