-
Notifications
You must be signed in to change notification settings - Fork 107
/
generator-impl-v6-rolling.go
643 lines (550 loc) · 25.4 KB
/
generator-impl-v6-rolling.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
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/rocketpool"
tnsettings "github.com/rocket-pool/rocketpool-go/settings/trustednode"
"github.com/rocket-pool/rocketpool-go/utils/eth"
"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"
)
// Implementation for tree generator ruleset v6 with rolling record support
type treeGeneratorImpl_v6_rolling 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
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
zero *big.Int
rollingRecord *RollingRecord
nodeDetails map[common.Address]*NodeSmoothingDetails
}
// Create a new tree generator
func newTreeGeneratorImpl_v6_rolling(log *log.ColorLogger, logPrefix string, index uint64, startTime time.Time, endTime time.Time, consensusBlock uint64, elSnapshotHeader *types.Header, intervalsPassed uint64, state *state.NetworkState, rollingRecord *RollingRecord) *treeGeneratorImpl_v6_rolling {
return &treeGeneratorImpl_v6_rolling{
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{},
},
},
validatorIndexMap: map[string]*MinipoolInfo{},
elSnapshotHeader: elSnapshotHeader,
log: log,
logPrefix: logPrefix,
networkState: state,
rollingRecord: rollingRecord,
}
}
// Get the version of the ruleset used by this generator
func (r *treeGeneratorImpl_v6_rolling) getRulesetVersion() uint64 {
return r.rewardsFile.RulesetVersion
}
func (r *treeGeneratorImpl_v6_rolling) 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
// 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_rolling) 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
// 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_rolling) 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_rolling) 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)
}
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_rolling) 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 EL block for the start of this interval
startElBlockHeader, err := r.getStartBlocksForInterval()
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))
// Process the attestation performance for each minipool during this interval
r.intervalDutiesInfo = &IntervalDutiesInfo{
Index: r.rewardsFile.Index,
Slots: map[uint64]*SlotInfo{},
}
// 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 nodeAddress, nodeInfo := range r.nodeDetails {
if nodeInfo.SmoothingPoolEth.Cmp(r.zero) > 0 {
rewardsForNode, exists := r.rewardsFile.NodeRewards[nodeAddress]
if !exists {
network := nodeInfo.RewardsNetwork
validNetwork, err := r.validateNetwork(network)
if err != nil {
return err
}
if !validNetwork {
r.rewardsFile.InvalidNetworkNodes[nodeAddress] = network
network = 0
}
rewardsForNode = &NodeRewardsInfo_v1{
RewardNetwork: network,
CollateralRpl: NewQuotedBigInt(0),
OracleDaoRpl: NewQuotedBigInt(0),
SmoothingPoolEth: NewQuotedBigInt(0),
}
r.rewardsFile.NodeRewards[nodeAddress] = 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(minipoolInfo.AttestationCount)
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_rolling) calculateNodeRewards() (*big.Int, *big.Int, error) {
// Get the list of cheaters
cheaters := r.getCheaters()
// Get the latest scores from the rolling record
minipools, totalScore, attestationCount := r.rollingRecord.GetScores(cheaters)
// If there weren't any successful attestations, everything goes to the pool stakers
if totalScore.Cmp(r.zero) == 0 || attestationCount == 0 {
r.log.Printlnf("WARNING: Total attestation score = %s, successful attestations = %d... sending the whole smoothing pool balance to the pool stakers.", totalScore.String(), attestationCount)
return r.smoothingPoolBalance, big.NewInt(0), nil
}
totalEthForMinipools := big.NewInt(0)
totalNodeOpShare := big.NewInt(0)
totalNodeOpShare.Mul(r.smoothingPoolBalance, totalScore)
totalNodeOpShare.Div(totalNodeOpShare, big.NewInt(int64(attestationCount)))
totalNodeOpShare.Div(totalNodeOpShare, eth.EthToWei(1))
r.nodeDetails = map[common.Address]*NodeSmoothingDetails{}
for _, minipool := range minipools {
// Get the node amount
nodeInfo, exists := r.nodeDetails[minipool.NodeAddress]
if !exists {
nodeInfo = &NodeSmoothingDetails{
Minipools: []*MinipoolInfo{},
SmoothingPoolEth: big.NewInt(0),
RewardsNetwork: r.networkState.NodeDetailsByAddress[minipool.NodeAddress].RewardNetwork.Uint64(),
}
r.nodeDetails[minipool.NodeAddress] = nodeInfo
}
nodeInfo.Minipools = append(nodeInfo.Minipools, minipool)
// Add the minipool's score to the total node score
minipoolEth := big.NewInt(0).Set(totalNodeOpShare)
minipoolEth.Mul(minipoolEth, &minipool.AttestationScore.Int)
minipoolEth.Div(minipoolEth, totalScore)
minipool.MinipoolShare = minipoolEth
nodeInfo.SmoothingPoolEth.Add(nodeInfo.SmoothingPoolEth, minipoolEth)
}
// Add the node amounts to the total
for _, nodeInfo := range r.nodeDetails {
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
}
// Validates that the provided network is legal
func (r *treeGeneratorImpl_v6_rolling) validateNetwork(network uint64) (bool, error) {
valid, exists := r.validNetworkCache[network]
if !exists {
var err error
valid, err = tnsettings.GetNetworkEnabled(r.rp, big.NewInt(int64(network)), r.opts)
if err != nil {
return false, err
}
r.validNetworkCache[network] = valid
}
return valid, nil
}
// Gets the EL header for the given interval's start block
func (r *treeGeneratorImpl_v6_rolling) getStartBlocksForInterval() (*types.Header, error) {
// Get the Beacon block for the start slot of the record
r.rewardsFile.ConsensusStartBlock = r.rollingRecord.StartSlot
r.rewardsFile.MinipoolPerformanceFile.ConsensusStartBlock = r.rollingRecord.StartSlot
beaconBlock, exists, err := r.bc.GetBeaconBlock(fmt.Sprint(r.rollingRecord.StartSlot))
if err != nil {
return nil, fmt.Errorf("error verifying block from previous interval: %w", err)
}
if !exists {
return nil, fmt.Errorf("couldn't retrieve CL block from previous interval (slot %d); this likely means you checkpoint sync'd your Beacon Node and it has not backfilled to the previous interval yet so it cannot be used for tree generation", r.rollingRecord.StartSlot)
}
// Get the EL block for that Beacon block
elBlockNumber := beaconBlock.ExecutionBlockNumber
r.rewardsFile.ExecutionStartBlock = elBlockNumber
r.rewardsFile.MinipoolPerformanceFile.ExecutionStartBlock = r.rewardsFile.ExecutionStartBlock
startElHeader, err := r.rp.Client.HeaderByNumber(context.Background(), big.NewInt(int64(elBlockNumber)))
if err != nil {
return nil, fmt.Errorf("error getting EL header for block %d: %w", elBlockNumber, err)
}
return startElHeader, nil
}
// Detect and flag any cheaters
func (r *treeGeneratorImpl_v6_rolling) getCheaters() map[common.Address]bool {
cheatingNodes := map[common.Address]bool{}
three := big.NewInt(3)
for _, nd := range r.networkState.NodeDetails {
for _, mpd := range r.networkState.MinipoolDetailsByNode[nd.NodeAddress] {
if mpd.PenaltyCount.Cmp(three) >= 0 {
// If any minipool has 3+ penalties, ban the entire node
cheatingNodes[nd.NodeAddress] = true
break
}
}
}
return cheatingNodes
}