-
Notifications
You must be signed in to change notification settings - Fork 108
/
generator-impl-v6.go
1104 lines (951 loc) · 43.1 KB
/
generator-impl-v6.go
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
package rewards
import (
"context"
"fmt"
"math/big"
"sort"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/rocket-pool/rocketpool-go/rewards"
"github.com/rocket-pool/rocketpool-go/rocketpool"
tnsettings "github.com/rocket-pool/rocketpool-go/settings/trustednode"
rptypes "github.com/rocket-pool/rocketpool-go/types"
"github.com/rocket-pool/rocketpool-go/utils/eth"
rpstate "github.com/rocket-pool/rocketpool-go/utils/state"
"github.com/rocket-pool/smartnode/shared/services/beacon"
"github.com/rocket-pool/smartnode/shared/services/config"
"github.com/rocket-pool/smartnode/shared/services/state"
"github.com/rocket-pool/smartnode/shared/utils/log"
"golang.org/x/sync/errgroup"
)
// Implementation for tree generator ruleset v6
type treeGeneratorImpl_v6 struct {
networkState *state.NetworkState
rewardsFile *RewardsFile_v1
elSnapshotHeader *types.Header
log *log.ColorLogger
logPrefix string
rp *rocketpool.RocketPool
cfg *config.RocketPoolConfig
bc beacon.Client
opts *bind.CallOpts
nodeDetails []*NodeSmoothingDetails
smoothingPoolBalance *big.Int
intervalDutiesInfo *IntervalDutiesInfo
slotsPerEpoch uint64
validatorIndexMap map[string]*MinipoolInfo
elStartTime time.Time
elEndTime time.Time
validNetworkCache map[uint64]bool
epsilon *big.Int
intervalSeconds *big.Int
beaconConfig beacon.Eth2Config
validatorStatusMap map[rptypes.ValidatorPubkey]beacon.ValidatorStatus
totalAttestationScore *big.Int
successfulAttestations uint64
zero *big.Int
genesisTime time.Time
}
// Create a new tree generator
func newTreeGeneratorImpl_v6(log *log.ColorLogger, logPrefix string, index uint64, startTime time.Time, endTime time.Time, consensusBlock uint64, elSnapshotHeader *types.Header, intervalsPassed uint64, state *state.NetworkState) *treeGeneratorImpl_v6 {
return &treeGeneratorImpl_v6{
zero: big.NewInt(0),
rewardsFile: &RewardsFile_v1{
RewardsFileHeader: &RewardsFileHeader{
RewardsFileVersion: 1,
RulesetVersion: 6,
Index: index,
StartTime: startTime.UTC(),
EndTime: endTime.UTC(),
ConsensusEndBlock: consensusBlock,
ExecutionEndBlock: elSnapshotHeader.Number.Uint64(),
IntervalsPassed: intervalsPassed,
InvalidNetworkNodes: map[common.Address]uint64{},
TotalRewards: &TotalRewards{
ProtocolDaoRpl: NewQuotedBigInt(0),
TotalCollateralRpl: NewQuotedBigInt(0),
TotalOracleDaoRpl: NewQuotedBigInt(0),
TotalSmoothingPoolEth: NewQuotedBigInt(0),
PoolStakerSmoothingPoolEth: NewQuotedBigInt(0),
NodeOperatorSmoothingPoolEth: NewQuotedBigInt(0),
},
NetworkRewards: map[uint64]*NetworkRewardsInfo{},
},
NodeRewards: map[common.Address]*NodeRewardsInfo_v1{},
MinipoolPerformanceFile: MinipoolPerformanceFile_v1{
Index: index,
StartTime: startTime.UTC(),
EndTime: endTime.UTC(),
ConsensusEndBlock: consensusBlock,
ExecutionEndBlock: elSnapshotHeader.Number.Uint64(),
MinipoolPerformance: map[common.Address]*SmoothingPoolMinipoolPerformance_v1{},
},
},
validatorStatusMap: map[rptypes.ValidatorPubkey]beacon.ValidatorStatus{},
validatorIndexMap: map[string]*MinipoolInfo{},
elSnapshotHeader: elSnapshotHeader,
log: log,
logPrefix: logPrefix,
totalAttestationScore: big.NewInt(0),
networkState: state,
}
}
// Get the version of the ruleset used by this generator
func (r *treeGeneratorImpl_v6) getRulesetVersion() uint64 {
return r.rewardsFile.RulesetVersion
}
func (r *treeGeneratorImpl_v6) generateTree(rp *rocketpool.RocketPool, cfg *config.RocketPoolConfig, bc beacon.Client) (IRewardsFile, error) {
r.log.Printlnf("%s Generating tree using Ruleset v%d.", r.logPrefix, r.rewardsFile.RulesetVersion)
// Provision some struct params
r.rp = rp
r.cfg = cfg
r.bc = bc
r.validNetworkCache = map[uint64]bool{
0: true,
}
// Set the network name
r.rewardsFile.Network = fmt.Sprint(cfg.Smartnode.Network.Value)
r.rewardsFile.MinipoolPerformanceFile.Network = r.rewardsFile.Network
// Get the Beacon config
r.beaconConfig = r.networkState.BeaconConfig
r.slotsPerEpoch = r.beaconConfig.SlotsPerEpoch
r.genesisTime = time.Unix(int64(r.beaconConfig.GenesisTime), 0)
// Set the EL client call opts
r.opts = &bind.CallOpts{
BlockNumber: r.elSnapshotHeader.Number,
}
r.log.Printlnf("%s Creating tree for %d nodes", r.logPrefix, len(r.networkState.NodeDetails))
// Get the minipool count - this will be used for an error epsilon due to division truncation
minipoolCount := uint64(len(r.networkState.MinipoolDetails))
r.epsilon = big.NewInt(int64(minipoolCount))
// Calculate the RPL rewards
err := r.calculateRplRewards()
if err != nil {
return nil, fmt.Errorf("Error calculating RPL rewards: %w", err)
}
// Calculate the ETH rewards
err = r.calculateEthRewards(true)
if err != nil {
return nil, fmt.Errorf("Error calculating ETH rewards: %w", err)
}
// Calculate the network reward map and the totals
r.updateNetworksAndTotals()
// Generate the Merkle Tree
err = r.rewardsFile.generateMerkleTree()
if err != nil {
return nil, fmt.Errorf("Error generating Merkle tree: %w", err)
}
// Sort all of the missed attestations so the files are always generated in the same state
for _, minipoolInfo := range r.rewardsFile.MinipoolPerformanceFile.MinipoolPerformance {
sort.Slice(minipoolInfo.MissingAttestationSlots, func(i, j int) bool {
return minipoolInfo.MissingAttestationSlots[i] < minipoolInfo.MissingAttestationSlots[j]
})
}
return r.rewardsFile, nil
}
// Quickly calculates an approximate of the staker's share of the smoothing pool balance without processing Beacon performance
// Used for approximate returns in the rETH ratio update
func (r *treeGeneratorImpl_v6) approximateStakerShareOfSmoothingPool(rp *rocketpool.RocketPool, cfg *config.RocketPoolConfig, bc beacon.Client) (*big.Int, error) {
r.log.Printlnf("%s Approximating tree using Ruleset v%d.", r.logPrefix, r.rewardsFile.RulesetVersion)
r.rp = rp
r.cfg = cfg
r.bc = bc
r.validNetworkCache = map[uint64]bool{
0: true,
}
// Set the network name
r.rewardsFile.Network = fmt.Sprint(cfg.Smartnode.Network.Value)
r.rewardsFile.MinipoolPerformanceFile.Network = r.rewardsFile.Network
// Get the Beacon config
r.beaconConfig = r.networkState.BeaconConfig
r.slotsPerEpoch = r.beaconConfig.SlotsPerEpoch
r.genesisTime = time.Unix(int64(r.beaconConfig.GenesisTime), 0)
// Set the EL client call opts
r.opts = &bind.CallOpts{
BlockNumber: r.elSnapshotHeader.Number,
}
r.log.Printlnf("%s Creating tree for %d nodes", r.logPrefix, len(r.networkState.NodeDetails))
// Get the minipool count - this will be used for an error epsilon due to division truncation
minipoolCount := uint64(len(r.networkState.MinipoolDetails))
r.epsilon = big.NewInt(int64(minipoolCount))
// Calculate the ETH rewards
err := r.calculateEthRewards(false)
if err != nil {
return nil, fmt.Errorf("error calculating ETH rewards: %w", err)
}
return &r.rewardsFile.TotalRewards.PoolStakerSmoothingPoolEth.Int, nil
}
// Calculates the per-network distribution amounts and the total reward amounts
func (r *treeGeneratorImpl_v6) updateNetworksAndTotals() {
// Get the highest network index with valid rewards
highestNetworkIndex := uint64(0)
for network := range r.rewardsFile.NetworkRewards {
if network > highestNetworkIndex {
highestNetworkIndex = network
}
}
// Create the map for each network, including unused ones
for network := uint64(0); network <= highestNetworkIndex; network++ {
rewardsForNetwork, exists := r.rewardsFile.NetworkRewards[network]
if !exists {
rewardsForNetwork = &NetworkRewardsInfo{
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NetworkRewards[network] = rewardsForNetwork
}
}
}
// Calculates the RPL rewards for the given interval
func (r *treeGeneratorImpl_v6) calculateRplRewards() error {
pendingRewards := r.networkState.NetworkDetails.PendingRPLRewards
nodeOpPercent := r.networkState.NetworkDetails.NodeOperatorRewardsPercent
r.log.Printlnf("%s Pending RPL rewards: %s (%.3f)", r.logPrefix, pendingRewards.String(), eth.WeiToEth(pendingRewards))
totalNodeRewards := big.NewInt(0)
totalNodeRewards.Mul(pendingRewards, nodeOpPercent)
totalNodeRewards.Div(totalNodeRewards, eth.EthToWei(1))
r.log.Printlnf("%s Approx. total collateral RPL rewards: %s (%.3f)", r.logPrefix, totalNodeRewards.String(), eth.WeiToEth(totalNodeRewards))
// Calculate the effective stake of each node, scaling by their participation in this interval
trueNodeEffectiveStakes, totalNodeEffectiveStake, err := r.networkState.CalculateTrueEffectiveStakes(true, false)
if err != nil {
return fmt.Errorf("error calculating effective RPL stakes: %w", err)
}
r.log.Printlnf("%s Calculating individual collateral rewards...", r.logPrefix)
for i, nodeDetails := range r.networkState.NodeDetails {
// Get how much RPL goes to this node: (true effective stake) * (total node rewards) / (total true effective stake)
nodeRplRewards := big.NewInt(0)
nodeRplRewards.Mul(trueNodeEffectiveStakes[nodeDetails.NodeAddress], totalNodeRewards)
nodeRplRewards.Div(nodeRplRewards, totalNodeEffectiveStake)
// If there are pending rewards, add it to the map
if nodeRplRewards.Cmp(r.zero) == 1 {
rewardsForNode, exists := r.rewardsFile.NodeRewards[nodeDetails.NodeAddress]
if !exists {
// Get the network the rewards should go to
network := r.networkState.NodeDetails[i].RewardNetwork.Uint64()
validNetwork, err := r.validateNetwork(network)
if err != nil {
return err
}
if !validNetwork {
r.rewardsFile.InvalidNetworkNodes[nodeDetails.NodeAddress] = network
network = 0
}
rewardsForNode = &NodeRewardsInfo_v1{
RewardNetwork: network,
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NodeRewards[nodeDetails.NodeAddress] = rewardsForNode
}
rewardsForNode.CollateralRpl.Add(&rewardsForNode.CollateralRpl.Int, nodeRplRewards)
// Add the rewards to the running total for the specified network
rewardsForNetwork, exists := r.rewardsFile.NetworkRewards[rewardsForNode.RewardNetwork]
if !exists {
rewardsForNetwork = &NetworkRewardsInfo{
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NetworkRewards[rewardsForNode.RewardNetwork] = rewardsForNetwork
}
rewardsForNetwork.CollateralRpl.Add(&rewardsForNetwork.CollateralRpl.Int, nodeRplRewards)
}
}
// Sanity check to make sure we arrived at the correct total
delta := big.NewInt(0)
totalCalculatedNodeRewards := big.NewInt(0)
for _, networkRewards := range r.rewardsFile.NetworkRewards {
totalCalculatedNodeRewards.Add(totalCalculatedNodeRewards, &networkRewards.CollateralRpl.Int)
}
delta.Sub(totalNodeRewards, totalCalculatedNodeRewards).Abs(delta)
if delta.Cmp(r.epsilon) == 1 {
return fmt.Errorf("error calculating collateral RPL: total was %s, but expected %s; error was too large", totalCalculatedNodeRewards.String(), totalNodeRewards.String())
}
r.rewardsFile.TotalRewards.TotalCollateralRpl.Int = *totalCalculatedNodeRewards
r.log.Printlnf("%s Calculated rewards: %s (error = %s wei)", r.logPrefix, totalCalculatedNodeRewards.String(), delta.String())
// Handle Oracle DAO rewards
oDaoPercent := r.networkState.NetworkDetails.TrustedNodeOperatorRewardsPercent
totalODaoRewards := big.NewInt(0)
totalODaoRewards.Mul(pendingRewards, oDaoPercent)
totalODaoRewards.Div(totalODaoRewards, eth.EthToWei(1))
r.log.Printlnf("%s Total Oracle DAO RPL rewards: %s (%.3f)", r.logPrefix, totalODaoRewards.String(), eth.WeiToEth(totalODaoRewards))
oDaoDetails := r.networkState.OracleDaoMemberDetails
// Calculate the true effective time of each oDAO node based on their participation in this interval
totalODaoNodeTime := big.NewInt(0)
trueODaoNodeTimes := map[common.Address]*big.Int{}
for _, details := range oDaoDetails {
// Get the timestamp of the node joining the oDAO
joinTime := details.JoinedTime
// Get the actual effective time, scaled based on participation
intervalDuration := r.networkState.NetworkDetails.IntervalDuration
intervalDurationBig := big.NewInt(int64(intervalDuration.Seconds()))
participationTime := big.NewInt(0).Set(intervalDurationBig)
snapshotBlockTime := time.Unix(int64(r.elSnapshotHeader.Time), 0)
eligibleDuration := snapshotBlockTime.Sub(joinTime)
if eligibleDuration < intervalDuration {
participationTime = big.NewInt(int64(eligibleDuration.Seconds()))
}
trueODaoNodeTimes[details.Address] = participationTime
// Add it to the total
totalODaoNodeTime.Add(totalODaoNodeTime, participationTime)
}
for _, details := range oDaoDetails {
address := details.Address
// Calculate the oDAO rewards for the node: (participation time) * (total oDAO rewards) / (total participation time)
individualOdaoRewards := big.NewInt(0)
individualOdaoRewards.Mul(trueODaoNodeTimes[address], totalODaoRewards)
individualOdaoRewards.Div(individualOdaoRewards, totalODaoNodeTime)
rewardsForNode, exists := r.rewardsFile.NodeRewards[address]
if !exists {
// Get the network the rewards should go to
network := r.networkState.NodeDetailsByAddress[address].RewardNetwork.Uint64()
validNetwork, err := r.validateNetwork(network)
if err != nil {
return err
}
if !validNetwork {
r.rewardsFile.InvalidNetworkNodes[address] = network
network = 0
}
rewardsForNode = &NodeRewardsInfo_v1{
RewardNetwork: network,
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NodeRewards[address] = rewardsForNode
}
rewardsForNode.OracleDaoRpl.Add(&rewardsForNode.OracleDaoRpl.Int, individualOdaoRewards)
// Add the rewards to the running total for the specified network
rewardsForNetwork, exists := r.rewardsFile.NetworkRewards[rewardsForNode.RewardNetwork]
if !exists {
rewardsForNetwork = &NetworkRewardsInfo{
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NetworkRewards[rewardsForNode.RewardNetwork] = rewardsForNetwork
}
rewardsForNetwork.OracleDaoRpl.Add(&rewardsForNetwork.OracleDaoRpl.Int, individualOdaoRewards)
}
// Sanity check to make sure we arrived at the correct total
totalCalculatedOdaoRewards := big.NewInt(0)
delta = big.NewInt(0)
for _, networkRewards := range r.rewardsFile.NetworkRewards {
totalCalculatedOdaoRewards.Add(totalCalculatedOdaoRewards, &networkRewards.OracleDaoRpl.Int)
}
delta.Sub(totalODaoRewards, totalCalculatedOdaoRewards).Abs(delta)
if delta.Cmp(r.epsilon) == 1 {
return fmt.Errorf("error calculating ODao RPL: total was %s, but expected %s; error was too large", totalCalculatedOdaoRewards.String(), totalODaoRewards.String())
}
r.rewardsFile.TotalRewards.TotalOracleDaoRpl.Int = *totalCalculatedOdaoRewards
r.log.Printlnf("%s Calculated rewards: %s (error = %s wei)", r.logPrefix, totalCalculatedOdaoRewards.String(), delta.String())
// Get expected Protocol DAO rewards
pDaoPercent := r.networkState.NetworkDetails.ProtocolDaoRewardsPercent
pDaoRewards := NewQuotedBigInt(0)
pDaoRewards.Mul(pendingRewards, pDaoPercent)
pDaoRewards.Div(&pDaoRewards.Int, eth.EthToWei(1))
r.log.Printlnf("%s Expected Protocol DAO rewards: %s (%.3f)", r.logPrefix, pDaoRewards.String(), eth.WeiToEth(&pDaoRewards.Int))
// Get actual protocol DAO rewards
pDaoRewards.Sub(pendingRewards, totalCalculatedNodeRewards)
pDaoRewards.Sub(&pDaoRewards.Int, totalCalculatedOdaoRewards)
r.rewardsFile.TotalRewards.ProtocolDaoRpl = pDaoRewards
r.log.Printlnf("%s Actual Protocol DAO rewards: %s to account for truncation", r.logPrefix, pDaoRewards.String())
return nil
}
// Calculates the ETH rewards for the given interval
func (r *treeGeneratorImpl_v6) calculateEthRewards(checkBeaconPerformance bool) error {
// Get the Smoothing Pool contract's balance
r.smoothingPoolBalance = r.networkState.NetworkDetails.SmoothingPoolBalance
r.log.Printlnf("%s Smoothing Pool Balance: %s (%.3f)", r.logPrefix, r.smoothingPoolBalance.String(), eth.WeiToEth(r.smoothingPoolBalance))
// Ignore the ETH calculation if there are no rewards
if r.smoothingPoolBalance.Cmp(r.zero) == 0 {
return nil
}
if r.rewardsFile.Index == 0 {
// This is the first interval, Smoothing Pool rewards are ignored on the first interval since it doesn't have a discrete start time
return nil
}
// Get the start time of this interval based on the event from the previous one
//previousIntervalEvent, err := GetRewardSnapshotEvent(r.rp, r.cfg, r.rewardsFile.Index-1, r.opts) // This is immutable so querying at the head is fine and mitigates issues around calls for pruned EL state
previousIntervalEvent, err := GetRewardSnapshotEvent(r.rp, r.cfg, r.rewardsFile.Index-1, nil)
if err != nil {
return err
}
startElBlockHeader, err := r.getStartBlocksForInterval(previousIntervalEvent)
if err != nil {
return err
}
r.elStartTime = time.Unix(int64(startElBlockHeader.Time), 0)
r.elEndTime = time.Unix(int64(r.elSnapshotHeader.Time), 0)
r.intervalSeconds = big.NewInt(int64(r.elEndTime.Sub(r.elStartTime) / time.Second))
// Get the details for nodes eligible for Smoothing Pool rewards
// This should be all of the eth1 calls, so do them all at the start of Smoothing Pool calculation to prevent the need for an archive node during normal operations
err = r.getSmoothingPoolNodeDetails()
if err != nil {
return err
}
eligible := 0
for _, nodeInfo := range r.nodeDetails {
if nodeInfo.IsEligible {
eligible++
}
}
r.log.Printlnf("%s %d / %d nodes were eligible for Smoothing Pool rewards", r.logPrefix, eligible, len(r.nodeDetails))
// Process the attestation performance for each minipool during this interval
r.intervalDutiesInfo = &IntervalDutiesInfo{
Index: r.rewardsFile.Index,
Slots: map[uint64]*SlotInfo{},
}
if checkBeaconPerformance {
err = r.processAttestationsForInterval()
if err != nil {
return err
}
} else {
// Attestation processing is disabled, just give each minipool 1 good attestation and complete slot activity so they're all scored the same
// Used for approximating rETH's share during balances calculation
one := eth.EthToWei(1)
validatorReq := eth.EthToWei(32)
for _, nodeInfo := range r.nodeDetails {
// Check if the node is currently opted in for simplicity
if nodeInfo.IsEligible && nodeInfo.IsOptedIn && r.elEndTime.Sub(nodeInfo.OptInTime) > 0 {
for _, minipool := range nodeInfo.Minipools {
minipool.CompletedAttestations = map[uint64]bool{0: true}
// Make up an attestation
details := r.networkState.MinipoolDetailsByAddress[minipool.Address]
bond, fee := r.getMinipoolBondAndNodeFee(details, r.elEndTime)
minipoolScore := big.NewInt(0).Sub(one, fee) // 1 - fee
minipoolScore.Mul(minipoolScore, bond) // Multiply by bond
minipoolScore.Div(minipoolScore, validatorReq) // Divide by 32 to get the bond as a fraction of a total validator
minipoolScore.Add(minipoolScore, fee) // Total = fee + (bond/32)(1 - fee)
// Add it to the minipool's score and the total score
minipool.AttestationScore.Add(&minipool.AttestationScore.Int, minipoolScore)
r.totalAttestationScore.Add(r.totalAttestationScore, minipoolScore)
r.successfulAttestations++
}
}
}
}
// Determine how much ETH each node gets and how much the pool stakers get
poolStakerETH, nodeOpEth, err := r.calculateNodeRewards()
if err != nil {
return err
}
// Update the rewards maps
for _, nodeInfo := range r.nodeDetails {
if nodeInfo.IsEligible && nodeInfo.SmoothingPoolEth.Cmp(r.zero) > 0 {
rewardsForNode, exists := r.rewardsFile.NodeRewards[nodeInfo.Address]
if !exists {
network := nodeInfo.RewardsNetwork
validNetwork, err := r.validateNetwork(network)
if err != nil {
return err
}
if !validNetwork {
r.rewardsFile.InvalidNetworkNodes[nodeInfo.Address] = network
network = 0
}
rewardsForNode = &NodeRewardsInfo_v1{
RewardNetwork: network,
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NodeRewards[nodeInfo.Address] = rewardsForNode
}
rewardsForNode.SmoothingPoolEth.Add(&rewardsForNode.SmoothingPoolEth.Int, nodeInfo.SmoothingPoolEth)
rewardsForNode.SmoothingPoolEligibilityRate = float64(nodeInfo.EndSlot-nodeInfo.StartSlot) / float64(r.rewardsFile.ConsensusEndBlock-r.rewardsFile.ConsensusStartBlock)
// Add minipool rewards to the JSON
for _, minipoolInfo := range nodeInfo.Minipools {
successfulAttestations := uint64(len(minipoolInfo.CompletedAttestations))
missingAttestations := uint64(len(minipoolInfo.MissingAttestationSlots))
performance := &SmoothingPoolMinipoolPerformance_v1{
Pubkey: minipoolInfo.ValidatorPubkey.Hex(),
SuccessfulAttestations: successfulAttestations,
MissedAttestations: missingAttestations,
EthEarned: eth.WeiToEth(minipoolInfo.MinipoolShare),
MissingAttestationSlots: []uint64{},
}
if successfulAttestations+missingAttestations == 0 {
// Don't include minipools that have zero attestations
continue
} else {
performance.ParticipationRate = float64(successfulAttestations) / float64(successfulAttestations+missingAttestations)
}
for slot := range minipoolInfo.MissingAttestationSlots {
performance.MissingAttestationSlots = append(performance.MissingAttestationSlots, slot)
}
r.rewardsFile.MinipoolPerformanceFile.MinipoolPerformance[minipoolInfo.Address] = performance
}
// Add the rewards to the running total for the specified network
rewardsForNetwork, exists := r.rewardsFile.NetworkRewards[rewardsForNode.RewardNetwork]
if !exists {
rewardsForNetwork = &NetworkRewardsInfo{
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NetworkRewards[rewardsForNode.RewardNetwork] = rewardsForNetwork
}
rewardsForNetwork.SmoothingPoolEth.Add(&rewardsForNetwork.SmoothingPoolEth.Int, nodeInfo.SmoothingPoolEth)
}
}
// Set the totals
r.rewardsFile.TotalRewards.PoolStakerSmoothingPoolEth.Int = *poolStakerETH
r.rewardsFile.TotalRewards.NodeOperatorSmoothingPoolEth.Int = *nodeOpEth
r.rewardsFile.TotalRewards.TotalSmoothingPoolEth.Int = *r.smoothingPoolBalance
return nil
}
// Calculate the distribution of Smoothing Pool ETH to each node
func (r *treeGeneratorImpl_v6) calculateNodeRewards() (*big.Int, *big.Int, error) {
// If there weren't any successful attestations, everything goes to the pool stakers
if r.totalAttestationScore.Cmp(r.zero) == 0 || r.successfulAttestations == 0 {
r.log.Printlnf("WARNING: Total attestation score = %s, successful attestations = %d... sending the whole smoothing pool balance to the pool stakers.", r.totalAttestationScore.String(), r.successfulAttestations)
return r.smoothingPoolBalance, big.NewInt(0), nil
}
totalEthForMinipools := big.NewInt(0)
totalNodeOpShare := big.NewInt(0)
totalNodeOpShare.Mul(r.smoothingPoolBalance, r.totalAttestationScore)
totalNodeOpShare.Div(totalNodeOpShare, big.NewInt(int64(r.successfulAttestations)))
totalNodeOpShare.Div(totalNodeOpShare, eth.EthToWei(1))
for _, nodeInfo := range r.nodeDetails {
nodeInfo.SmoothingPoolEth = big.NewInt(0)
if nodeInfo.IsEligible {
for _, minipool := range nodeInfo.Minipools {
if len(minipool.CompletedAttestations)+len(minipool.MissingAttestationSlots) == 0 || !minipool.WasActive {
// Ignore minipools that weren't active for the interval
minipool.WasActive = false
minipool.MinipoolShare = big.NewInt(0)
continue
}
minipoolEth := big.NewInt(0).Set(totalNodeOpShare)
minipoolEth.Mul(minipoolEth, &minipool.AttestationScore.Int)
minipoolEth.Div(minipoolEth, r.totalAttestationScore)
minipool.MinipoolShare = minipoolEth
nodeInfo.SmoothingPoolEth.Add(nodeInfo.SmoothingPoolEth, minipoolEth)
}
}
totalEthForMinipools.Add(totalEthForMinipools, nodeInfo.SmoothingPoolEth)
}
// This is how much actually goes to the pool stakers - it should ideally be equal to poolStakerShare but this accounts for any cumulative floating point errors
truePoolStakerAmount := big.NewInt(0).Sub(r.smoothingPoolBalance, totalEthForMinipools)
// Sanity check to make sure we arrived at the correct total
delta := big.NewInt(0).Sub(totalEthForMinipools, totalNodeOpShare)
delta.Abs(delta)
if delta.Cmp(r.epsilon) == 1 {
return nil, nil, fmt.Errorf("error calculating smoothing pool ETH: total was %s, but expected %s; error was too large (%s wei)", totalEthForMinipools.String(), totalNodeOpShare.String(), delta.String())
}
// Calculate the staking pool share and the node op share
poolStakerShare := big.NewInt(0).Sub(r.smoothingPoolBalance, totalNodeOpShare)
r.log.Printlnf("%s Pool staker ETH: %s (%.3f)", r.logPrefix, poolStakerShare.String(), eth.WeiToEth(poolStakerShare))
r.log.Printlnf("%s Node Op ETH: %s (%.3f)", r.logPrefix, totalNodeOpShare.String(), eth.WeiToEth(totalNodeOpShare))
r.log.Printlnf("%s Calculated NO ETH: %s (error = %s wei)", r.logPrefix, totalEthForMinipools.String(), delta.String())
r.log.Printlnf("%s Adjusting pool staker ETH to %s to account for truncation", r.logPrefix, truePoolStakerAmount.String())
return truePoolStakerAmount, totalEthForMinipools, nil
}
// Get all of the duties for a range of epochs
func (r *treeGeneratorImpl_v6) processAttestationsForInterval() error {
startEpoch := r.rewardsFile.ConsensusStartBlock / r.beaconConfig.SlotsPerEpoch
endEpoch := r.rewardsFile.ConsensusEndBlock / r.beaconConfig.SlotsPerEpoch
// Determine the validator indices of each minipool
err := r.createMinipoolIndexMap()
if err != nil {
return err
}
// Check all of the attestations for each epoch
r.log.Printlnf("%s Checking participation of %d minipools for epochs %d to %d", r.logPrefix, len(r.validatorIndexMap), startEpoch, endEpoch)
r.log.Printlnf("%s NOTE: this will take a long time, progress is reported every 100 epochs", r.logPrefix)
epochsDone := 0
reportStartTime := time.Now()
for epoch := startEpoch; epoch < endEpoch+1; epoch++ {
if epochsDone == 100 {
timeTaken := time.Since(reportStartTime)
r.log.Printlnf("%s On Epoch %d of %d (%.2f%%)... (%s so far)", r.logPrefix, epoch, endEpoch, float64(epoch-startEpoch)/float64(endEpoch-startEpoch)*100.0, timeTaken)
epochsDone = 0
}
err := r.processEpoch(true, epoch)
if err != nil {
return err
}
epochsDone++
}
// Check the epoch after the end of the interval for any lingering attestations
epoch := endEpoch + 1
err = r.processEpoch(false, epoch)
if err != nil {
return err
}
r.log.Printlnf("%s Finished participation check (total time = %s)", r.logPrefix, time.Since(reportStartTime))
return nil
}
// Process an epoch, optionally getting the duties for all eligible minipools in it and checking each one's attestation performance
func (r *treeGeneratorImpl_v6) processEpoch(getDuties bool, epoch uint64) error {
// Get the committee info and attestation records for this epoch
var committeeData beacon.Committees
attestationsPerSlot := make([][]beacon.AttestationInfo, r.slotsPerEpoch)
var wg errgroup.Group
if getDuties {
wg.Go(func() error {
var err error
committeeData, err = r.bc.GetCommitteesForEpoch(&epoch)
return err
})
}
for i := uint64(0); i < r.slotsPerEpoch; i++ {
i := i
slot := epoch*r.slotsPerEpoch + i
wg.Go(func() error {
attestations, found, err := r.bc.GetAttestations(fmt.Sprint(slot))
if err != nil {
return err
}
if found {
attestationsPerSlot[i] = attestations
} else {
attestationsPerSlot[i] = []beacon.AttestationInfo{}
}
return nil
})
}
err := wg.Wait()
if err != nil {
return fmt.Errorf("Error getting committee and attestaion records for epoch %d: %w", epoch, err)
}
if getDuties {
// Get all of the expected duties for the epoch
err = r.getDutiesForEpoch(committeeData)
if err != nil {
return fmt.Errorf("Error getting duties for epoch %d: %w", epoch, err)
}
}
// Process all of the slots in the epoch
for i := uint64(0); i < r.slotsPerEpoch; i++ {
slot := epoch*r.slotsPerEpoch + i
attestations := attestationsPerSlot[i]
if len(attestations) > 0 {
r.checkDutiesForSlot(attestations, slot)
}
}
return nil
}
// Handle all of the attestations in the given slot
func (r *treeGeneratorImpl_v6) checkDutiesForSlot(attestations []beacon.AttestationInfo, slot uint64) error {
one := eth.EthToWei(1)
validatorReq := eth.EthToWei(32)
// Go through the attestations for the block
for _, attestation := range attestations {
// Get the RP committees for this attestation's slot and index
slotInfo, exists := r.intervalDutiesInfo.Slots[attestation.SlotIndex]
if !exists {
continue
}
rpCommittee, exists := slotInfo.Committees[attestation.CommitteeIndex]
if !exists {
continue
}
blockTime := r.genesisTime.Add(time.Second * time.Duration(r.networkState.BeaconConfig.SecondsPerSlot*attestation.SlotIndex))
// Check if each RP validator attested successfully
for position, validator := range rpCommittee.Positions {
if !attestation.AggregationBits.BitAt(uint64(position)) {
continue
}
// This was seen, so remove it from the missing attestations and add it to the completed ones
delete(rpCommittee.Positions, position)
if len(rpCommittee.Positions) == 0 {
delete(slotInfo.Committees, attestation.CommitteeIndex)
}
if len(slotInfo.Committees) == 0 {
delete(r.intervalDutiesInfo.Slots, attestation.SlotIndex)
}
delete(validator.MissingAttestationSlots, attestation.SlotIndex)
// Check if this minipool was opted into the SP for this block
nodeDetails := r.nodeDetails[validator.NodeIndex]
if blockTime.Sub(nodeDetails.OptInTime) < 0 || nodeDetails.OptOutTime.Sub(blockTime) < 0 {
// Not opted in
continue
}
// Mark this duty as completed
validator.CompletedAttestations[attestation.SlotIndex] = true
// Get the pseudoscore for this attestation
details := r.networkState.MinipoolDetailsByAddress[validator.Address]
bond, fee := r.getMinipoolBondAndNodeFee(details, blockTime)
minipoolScore := big.NewInt(0).Sub(one, fee) // 1 - fee
minipoolScore.Mul(minipoolScore, bond) // Multiply by bond
minipoolScore.Div(minipoolScore, validatorReq) // Divide by 32 to get the bond as a fraction of a total validator
minipoolScore.Add(minipoolScore, fee) // Total = fee + (bond/32)(1 - fee)
// Add it to the minipool's score and the total score
validator.AttestationScore.Add(&validator.AttestationScore.Int, minipoolScore)
r.totalAttestationScore.Add(r.totalAttestationScore, minipoolScore)
r.successfulAttestations++
}
}
return nil
}
// Maps out the attestaion duties for the given epoch
func (r *treeGeneratorImpl_v6) getDutiesForEpoch(committees beacon.Committees) error {
// Crawl the committees
for idx := 0; idx < committees.Count(); idx++ {
slotIndex := committees.Slot(idx)
if slotIndex < r.rewardsFile.ConsensusStartBlock || slotIndex > r.rewardsFile.ConsensusEndBlock {
// Ignore slots that are out of bounds
continue
}
blockTime := r.genesisTime.Add(time.Second * time.Duration(r.beaconConfig.SecondsPerSlot*slotIndex))
committeeIndex := committees.Index(idx)
// Check if there are any RP validators in this committee
rpValidators := map[int]*MinipoolInfo{}
for position, validator := range committees.Validators(idx) {
minipoolInfo, exists := r.validatorIndexMap[validator]
if !exists {
// This isn't an RP validator, so ignore it
continue
}
// Check if this minipool was opted into the SP for this block
nodeDetails := r.networkState.NodeDetailsByAddress[minipoolInfo.NodeAddress]
isOptedIn := nodeDetails.SmoothingPoolRegistrationState
spRegistrationTime := time.Unix(nodeDetails.SmoothingPoolRegistrationChanged.Int64(), 0)
if (isOptedIn && blockTime.Sub(spRegistrationTime) < 0) || // If this block occurred before the node opted in, ignore it
(!isOptedIn && spRegistrationTime.Sub(blockTime) < 0) { // If this block occurred after the node opted out, ignore it
continue
}
// Check if this minipool was in the `staking` state during this time
mpd := r.networkState.MinipoolDetailsByAddress[minipoolInfo.Address]
statusChangeTime := time.Unix(mpd.StatusTime.Int64(), 0)
if mpd.Status != rptypes.Staking || blockTime.Sub(statusChangeTime) < 0 {
continue
}
// This was a legal RP validator opted into the SP during this slot so add it
rpValidators[position] = minipoolInfo
minipoolInfo.MissingAttestationSlots[slotIndex] = true
}
// If there are some RP validators, add this committee to the map
if len(rpValidators) > 0 {
slotInfo, exists := r.intervalDutiesInfo.Slots[slotIndex]
if !exists {
slotInfo = &SlotInfo{
Index: slotIndex,
Committees: map[uint64]*CommitteeInfo{},
}
r.intervalDutiesInfo.Slots[slotIndex] = slotInfo
}
slotInfo.Committees[committeeIndex] = &CommitteeInfo{
Index: committeeIndex,
Positions: rpValidators,
}
}
}
return nil
}
// Maps all minipools to their validator indices and creates a map of indices to minipool info
func (r *treeGeneratorImpl_v6) createMinipoolIndexMap() error {
// Get the status for all uncached minipool validators and add them to the cache
r.validatorIndexMap = map[string]*MinipoolInfo{}
for _, details := range r.nodeDetails {
if details.IsEligible {
for _, minipoolInfo := range details.Minipools {
status, exists := r.networkState.ValidatorDetails[minipoolInfo.ValidatorPubkey]
if !exists {
// Remove minipools that don't have indices yet since they're not actually viable
//r.log.Printlnf("NOTE: minipool %s (pubkey %s) didn't exist at this slot; removing it", minipoolInfo.Address.Hex(), minipoolInfo.ValidatorPubkey.Hex())
minipoolInfo.WasActive = false
} else {
switch status.Status {
case beacon.ValidatorState_PendingInitialized, beacon.ValidatorState_PendingQueued:
// Remove minipools that don't have indices yet since they're not actually viable
//r.log.Printlnf("NOTE: minipool %s (index %s, pubkey %s) was in state %s; removing it", minipoolInfo.Address.Hex(), status.Index, minipoolInfo.ValidatorPubkey.Hex(), string(status.Status))
minipoolInfo.WasActive = false
default:
// Get the validator index
minipoolInfo.ValidatorIndex = status.Index
r.validatorIndexMap[minipoolInfo.ValidatorIndex] = minipoolInfo
// Get the validator's activation start and end slots
startSlot := status.ActivationEpoch * r.beaconConfig.SlotsPerEpoch
endSlot := status.ExitEpoch * r.beaconConfig.SlotsPerEpoch
// Verify this minipool has already started
if status.ActivationEpoch == FarEpoch {
//r.log.Printlnf("NOTE: minipool %s hasn't been scheduled for activation yet; removing it", minipoolInfo.Address.Hex())
minipoolInfo.WasActive = false
continue
} else if startSlot > r.rewardsFile.ConsensusEndBlock {
//r.log.Printlnf("NOTE: minipool %s activates on slot %d which is after interval end %d; removing it", minipoolInfo.Address.Hex(), startSlot, r.rewardsFile.ConsensusEndBlock)
minipoolInfo.WasActive = false
}
// Check if the minipool exited before this interval
if status.ExitEpoch != FarEpoch && endSlot < r.rewardsFile.ConsensusStartBlock {
//r.log.Printlnf("NOTE: minipool %s exited on slot %d which was before interval start %d; removing it", minipoolInfo.Address.Hex(), endSlot, r.rewardsFile.ConsensusStartBlock)
minipoolInfo.WasActive = false
continue
}
}
}
}
}
}
return nil
}
// Get the details for every node that was opted into the Smoothing Pool for at least some portion of this interval
func (r *treeGeneratorImpl_v6) getSmoothingPoolNodeDetails() error {
farFutureTime := time.Unix(1000000000000000000, 0) // Far into the future
farPastTime := time.Unix(0, 0)
// For each NO, get their opt-in status and time of last change in batches
r.log.Printlnf("%s Getting details of nodes for Smoothing Pool calculation...", r.logPrefix)
nodeCount := uint64(len(r.networkState.NodeDetails))
r.nodeDetails = make([]*NodeSmoothingDetails, nodeCount)
for batchStartIndex := uint64(0); batchStartIndex < nodeCount; batchStartIndex += SmoothingPoolDetailsBatchSize {
// Get batch start & end index
iterationStartIndex := batchStartIndex
iterationEndIndex := batchStartIndex + SmoothingPoolDetailsBatchSize
if iterationEndIndex > nodeCount {
iterationEndIndex = nodeCount
}
// Load details
var wg errgroup.Group
for iterationIndex := iterationStartIndex; iterationIndex < iterationEndIndex; iterationIndex++ {
iterationIndex := iterationIndex
wg.Go(func() error {
nativeNodeDetails := r.networkState.NodeDetails[iterationIndex]
nodeDetails := &NodeSmoothingDetails{
Address: nativeNodeDetails.NodeAddress,
Minipools: []*MinipoolInfo{},
SmoothingPoolEth: big.NewInt(0),
RewardsNetwork: nativeNodeDetails.RewardNetwork.Uint64(),
}
nodeDetails.IsOptedIn = nativeNodeDetails.SmoothingPoolRegistrationState
statusChangeTimeBig := nativeNodeDetails.SmoothingPoolRegistrationChanged
statusChangeTime := time.Unix(statusChangeTimeBig.Int64(), 0)
if nodeDetails.IsOptedIn {
nodeDetails.OptInTime = statusChangeTime
nodeDetails.OptOutTime = farFutureTime
} else {
nodeDetails.OptOutTime = statusChangeTime
nodeDetails.OptInTime = farPastTime
}
// Get the details for each minipool in the node
for _, mpd := range r.networkState.MinipoolDetailsByNode[nodeDetails.Address] {
if mpd.Exists && mpd.Status == rptypes.Staking {
nativeMinipoolDetails := r.networkState.MinipoolDetailsByAddress[mpd.MinipoolAddress]
penaltyCount := nativeMinipoolDetails.PenaltyCount.Uint64()
if penaltyCount >= 3 {
// This node is a cheater
nodeDetails.IsEligible = false
nodeDetails.Minipools = []*MinipoolInfo{}
r.nodeDetails[iterationIndex] = nodeDetails
return nil
}
// This minipool is below the penalty count, so include it
nodeDetails.Minipools = append(nodeDetails.Minipools, &MinipoolInfo{
Address: mpd.MinipoolAddress,
ValidatorPubkey: mpd.Pubkey,
NodeAddress: nodeDetails.Address,
NodeIndex: iterationIndex,
Fee: nativeMinipoolDetails.NodeFee,
//MissedAttestations: 0,
//GoodAttestations: 0,
MissingAttestationSlots: map[uint64]bool{},
CompletedAttestations: map[uint64]bool{},
WasActive: true,
AttestationScore: NewQuotedBigInt(0),
})
}
}
nodeDetails.IsEligible = len(nodeDetails.Minipools) > 0
r.nodeDetails[iterationIndex] = nodeDetails
return nil
})