-
Notifications
You must be signed in to change notification settings - Fork 12
/
rewards.go
366 lines (295 loc) · 16.1 KB
/
rewards.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
package performance
import (
"github.com/iotaledger/hive.go/ads"
"github.com/iotaledger/hive.go/core/safemath"
"github.com/iotaledger/hive.go/ierrors"
"github.com/iotaledger/hive.go/lo"
"github.com/iotaledger/iota-core/pkg/model"
iotago "github.com/iotaledger/iota.go/v4"
)
func (t *Tracker) RewardsRoot(epoch iotago.EpochIndex) (iotago.Identifier, error) {
t.mutex.RLock()
defer t.mutex.RUnlock()
m, err := t.rewardsMap(epoch)
if err != nil {
return iotago.Identifier{}, err
}
return m.Root(), nil
}
func (t *Tracker) ValidatorReward(validatorID iotago.AccountID, stakingFeature *iotago.StakingFeature, claimingEpoch iotago.EpochIndex) (validatorReward iotago.Mana, firstRewardEpoch iotago.EpochIndex, lastRewardEpoch iotago.EpochIndex, err error) {
t.mutex.RLock()
defer t.mutex.RUnlock()
validatorReward = 0
stakedAmount := stakingFeature.StakedAmount
firstRewardEpoch = stakingFeature.StartEpoch
// Start Epoch = 0 is unmodified as a special case for the initial validators that bootstrap the network to get their rewards.
// Otherwise, the earliest rewards can be in the epoch for which a validator could have been selected, which is start epoch + 1.
if firstRewardEpoch != 0 {
firstRewardEpoch = stakingFeature.StartEpoch + 1
}
lastRewardEpoch = stakingFeature.EndEpoch
// Limit reward fetching only to committed epochs.
if lastRewardEpoch > t.latestAppliedEpoch {
lastRewardEpoch = t.latestAppliedEpoch
}
decayEndEpoch := t.decayEndEpoch(claimingEpoch, lastRewardEpoch)
// Only fetch unexpired rewards from epochs by determining the earliest epoch
// for which rewards are still retained or available.
firstRewardEpoch = t.earliestRewardEpoch(firstRewardEpoch, claimingEpoch)
for epoch := firstRewardEpoch; epoch <= lastRewardEpoch; epoch++ {
rewardsForAccountInEpoch, exists, err := t.rewardsForAccount(validatorID, epoch)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to get rewards for account %s in epoch %d", validatorID, epoch)
}
if !exists || rewardsForAccountInEpoch.PoolStake == 0 {
// updating epoch start for beginning epochs without the reward
if epoch < lastRewardEpoch && firstRewardEpoch == epoch {
firstRewardEpoch = epoch + 1
}
continue
}
poolStats, err := t.poolStatsStore.Load(epoch)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to get pool stats for epoch %d and validator accountID %s", epoch, validatorID)
}
if poolStats == nil {
return 0, 0, 0, ierrors.Errorf("pool stats for epoch %d and validator accountID %s are nil", epoch, validatorID)
}
// If a validator's fixed cost is greater than the earned reward, all rewards go to the delegators.
if rewardsForAccountInEpoch.PoolRewards < rewardsForAccountInEpoch.FixedCost {
continue
}
poolRewardsNoFixedCost := rewardsForAccountInEpoch.PoolRewards - rewardsForAccountInEpoch.FixedCost
profitMarginExponent := t.apiProvider.APIForEpoch(epoch).ProtocolParameters().RewardsParameters().ProfitMarginExponent
profitMarginComplement, err := scaleUpComplement(poolStats.ProfitMargin, profitMarginExponent)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate profit margin factor due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
result, err := safemath.SafeMul(poolStats.ProfitMargin, uint64(poolRewardsNoFixedCost))
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate profit margin factor due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
profitMarginFactor := result >> profitMarginExponent
result, err = safemath.SafeMul(profitMarginComplement, uint64(poolRewardsNoFixedCost))
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate profit margin factor due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
residualValidatorFactor, err := safemath.Safe64MulDiv(result>>profitMarginExponent, uint64(stakedAmount), uint64(rewardsForAccountInEpoch.PoolStake))
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate residual validator factor due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
result, err = safemath.SafeAdd(uint64(rewardsForAccountInEpoch.FixedCost), profitMarginFactor)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate un-decayed epoch reward due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
undecayedEpochRewards, err := safemath.SafeAdd(result, residualValidatorFactor)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate un-decayed epoch rewards due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
decayProvider := t.apiProvider.APIForEpoch(epoch).ManaDecayProvider()
decayedEpochRewards, err := decayProvider.DecayManaByEpochs(iotago.Mana(undecayedEpochRewards), epoch, decayEndEpoch)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate rewards with decay for epoch %d and validator accountID %s", epoch, validatorID)
}
validatorReward, err = safemath.SafeAdd(validatorReward, decayedEpochRewards)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate validator reward due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
}
return validatorReward, firstRewardEpoch, lastRewardEpoch, nil
}
func (t *Tracker) DelegatorReward(validatorID iotago.AccountID, delegatedAmount iotago.BaseToken, epochStart iotago.EpochIndex, epochEnd iotago.EpochIndex, claimingEpoch iotago.EpochIndex) (delegatorReward iotago.Mana, firstRewardEpoch iotago.EpochIndex, lastRewardEpoch iotago.EpochIndex, err error) {
t.mutex.RLock()
defer t.mutex.RUnlock()
var delegatorsReward iotago.Mana
firstRewardEpoch = epochStart
lastRewardEpoch = epochEnd
// limit looping to committed epochs
if lastRewardEpoch > t.latestAppliedEpoch {
lastRewardEpoch = t.latestAppliedEpoch
}
decayEndEpoch := t.decayEndEpoch(claimingEpoch, lastRewardEpoch)
// Only fetch unexpired rewards from epochs by determining the earliest epoch
// for which rewards are still retained or available.
firstRewardEpoch = t.earliestRewardEpoch(firstRewardEpoch, claimingEpoch)
for epoch := firstRewardEpoch; epoch <= lastRewardEpoch; epoch++ {
rewardsForAccountInEpoch, exists, err := t.rewardsForAccount(validatorID, epoch)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to get rewards for account %s in epoch %d", validatorID, epoch)
}
if !exists || rewardsForAccountInEpoch.PoolStake == 0 {
// updating epoch start for beginning epochs without the reward
if firstRewardEpoch == epoch {
firstRewardEpoch = epoch + 1
}
continue
}
poolStats, err := t.poolStatsStore.Load(epoch)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to get pool stats for epoch %d and validator account ID %s", epoch, validatorID)
}
if poolStats == nil {
return 0, 0, 0, ierrors.Errorf("pool stats for epoch %d and validator accountID %s are nil", epoch, validatorID)
}
profitMarginExponent := t.apiProvider.APIForEpoch(epoch).ProtocolParameters().RewardsParameters().ProfitMarginExponent
profitMarginComplement, err := scaleUpComplement(poolStats.ProfitMargin, profitMarginExponent)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate profit margin factor due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
// if pool reward was lower than fixed cost, the whole reward goes to delegators
poolReward := rewardsForAccountInEpoch.PoolRewards
// fixed cost was not too high, no punishment for the validator
if rewardsForAccountInEpoch.PoolRewards >= rewardsForAccountInEpoch.FixedCost {
poolReward = rewardsForAccountInEpoch.PoolRewards - rewardsForAccountInEpoch.FixedCost
}
result, err := safemath.SafeMul(profitMarginComplement, uint64(poolReward))
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to multiply profitMarginComplement and poolReward for unDecayedEpochRewards due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
result, err = safemath.SafeDiv(result>>profitMarginExponent, uint64(rewardsForAccountInEpoch.PoolStake))
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to divide by PoolStake for unDecayedEpochRewards due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
undecayedEpochRewards, err := safemath.SafeMul(result, uint64(delegatedAmount))
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to multiply by delegatedAmmount for unDecayedEpochRewards due to overflow for epoch %d and validator accountID %s", epoch, validatorID)
}
decayProvider := t.apiProvider.APIForEpoch(epoch).ManaDecayProvider()
decayedEpochRewards, err := decayProvider.DecayManaByEpochs(iotago.Mana(undecayedEpochRewards), epoch, decayEndEpoch)
if err != nil {
return 0, 0, 0, ierrors.Wrapf(err, "failed to calculate rewards with decay for epoch %d and validator accountID %s", epoch, validatorID)
}
delegatorsReward += decayedEpochRewards
}
return delegatorsReward, firstRewardEpoch, lastRewardEpoch, nil
}
func (t *Tracker) PoolRewardsForAccount(accountID iotago.AccountID) (
poolRewardsForAccount iotago.Mana,
exists bool,
err error,
) {
rewards, exists, err := t.rewardsForAccount(accountID, t.latestAppliedEpoch)
if err != nil || !exists {
return 0, exists, err
}
return rewards.PoolRewards, exists, err
}
// Returns the epoch until which rewards are decayed.
//
// When claiming rewards in epoch X for epoch X-1, decay of X-(X-1) = 1 would be applied. Since epoch X is the
// very first epoch in which one can claim those rewards, decaying by 1 is odd, as one could never claim the full reward then.
// Hence, one epoch worth of decay is deducted in general.
//
// The decay end epoch must however be greater or equal than the last epoch for which rewards are claimed, otherwise
// the decay operation would fail since the amount of epochs to decay would be negative.
// Hence, the smallest returned decay end epoch will be the lastRewardEpoch.
func (t *Tracker) decayEndEpoch(claimingEpoch iotago.EpochIndex, lastRewardEpoch iotago.EpochIndex) iotago.EpochIndex {
if claimingEpoch >= 1 {
claimingEpoch--
}
return lo.Max(claimingEpoch, lastRewardEpoch)
}
// Returns the earliest epoch for which rewards are retained or available, whichever is later.
func (t *Tracker) earliestRewardEpoch(firstRewardEpoch iotago.EpochIndex, claimingEpoch iotago.EpochIndex) iotago.EpochIndex {
retentionPeriod := iotago.EpochIndex(t.apiProvider.APIForEpoch(claimingEpoch).ProtocolParameters().RewardsParameters().RetentionPeriod)
var earliestRetainedRewardEpoch iotago.EpochIndex
if retentionPeriod < claimingEpoch {
earliestRetainedRewardEpoch = claimingEpoch - retentionPeriod
}
return lo.Max(earliestRetainedRewardEpoch, firstRewardEpoch)
}
func (t *Tracker) rewardsMap(epoch iotago.EpochIndex) (ads.Map[iotago.Identifier, iotago.AccountID, *model.PoolRewards], error) {
kv, err := t.rewardsStorePerEpochFunc(epoch)
if err != nil {
return nil, ierrors.Wrapf(err, "failed to get rewards store for epoch %d", epoch)
}
return ads.NewMap[iotago.Identifier](kv,
iotago.Identifier.Bytes,
iotago.IdentifierFromBytes,
iotago.AccountID.Bytes,
iotago.AccountIDFromBytes,
(*model.PoolRewards).Bytes,
model.PoolRewardsFromBytes,
), nil
}
func (t *Tracker) rewardsForAccount(accountID iotago.AccountID, epoch iotago.EpochIndex) (rewardsForAccount *model.PoolRewards, exists bool, err error) {
m, err := t.rewardsMap(epoch)
if err != nil {
return nil, false, err
}
return m.Get(accountID)
}
func (t *Tracker) poolReward(slot iotago.SlotIndex, totalValidatorsStake iotago.BaseToken, totalStake iotago.BaseToken, poolStake iotago.BaseToken, validatorStake iotago.BaseToken, performanceFactor uint64) (iotago.Mana, error) {
apiForSlot := t.apiProvider.APIForSlot(slot)
epoch := apiForSlot.TimeProvider().EpochFromSlot(slot)
params := apiForSlot.ProtocolParameters()
targetReward, err := params.RewardsParameters().TargetReward(epoch, apiForSlot)
if err != nil {
return 0, ierrors.Wrapf(err, "failed to calculate target reward for slot %d", slot)
}
// Notice that, since both pool stake and validator stake use at most 53 bits of the variable,
// to not overflow the calculation, PoolCoefficientExponent must be at most 11. Pool Coefficient will then use at most PoolCoefficientExponent + 1 bits.
poolCoefficient, err := t.calculatePoolCoefficient(poolStake, totalStake, validatorStake, totalValidatorsStake, slot)
if err != nil {
return 0, ierrors.Wrapf(err, "failed to calculate pool coefficient for slot %d", slot)
}
// Since `Pool Coefficient` uses at most 12 bits and `Target Reward(n)` uses at most 50 bits
// this multiplication will not overflow using uint64 variables.
result, err := safemath.SafeMul(poolCoefficient, uint64(targetReward))
if err != nil {
return 0, ierrors.Wrapf(err, "failed to calculate pool scaled reward due to overflow for slot %d", slot)
}
result >>= params.RewardsParameters().PoolCoefficientExponent
// Since the result above uses at most 50 bits and `Performance Factor` uses at most 8 bits,
// this multiplication will not overflow using uint64 variables.
scaledPoolReward, err := safemath.SafeMul(result, performanceFactor)
if err != nil {
return 0, ierrors.Wrapf(err, "failed to calculate pool reward without fixed costs due to overflow for slot %d", slot)
}
result, err = safemath.SafeDiv(scaledPoolReward, uint64(params.ValidationBlocksPerSlot()))
if err != nil {
return 0, ierrors.Wrapf(err, "failed to calculate result reward due division by zero for slot %d", slot)
}
poolRewardFixedCost := iotago.Mana(result >> 1)
return poolRewardFixedCost, nil
}
func (t *Tracker) calculatePoolCoefficient(poolStake iotago.BaseToken, totalStake iotago.BaseToken, validatorStake iotago.BaseToken, totalValidatorStake iotago.BaseToken, slot iotago.SlotIndex) (uint64, error) {
poolCoeffExponent := t.apiProvider.APIForSlot(slot).ProtocolParameters().RewardsParameters().PoolCoefficientExponent
scaledUpPoolStake, err := safemath.SafeLeftShift(poolStake, poolCoeffExponent)
if err != nil {
return 0, ierrors.Wrapf(err, "failed in step 1 of pool coefficient calculation due to overflow for slot %d", slot)
}
result1, err := safemath.SafeDiv(scaledUpPoolStake, totalStake)
if err != nil {
return 0, ierrors.Wrapf(err, "failed in step 2 of pool coefficient calculation due to overflow for slot %d", slot)
}
scaledUpValidatorStake, err := safemath.SafeLeftShift(validatorStake, poolCoeffExponent)
if err != nil {
return 0, ierrors.Wrapf(err, "failed in step 3 of pool coefficient calculation due to overflow for slot %d", slot)
}
result2, err := safemath.SafeDiv(scaledUpValidatorStake, totalValidatorStake)
if err != nil {
return 0, ierrors.Wrapf(err, "failed in step 4 of pool coefficient calculation due to overflow for slot %d", slot)
}
poolCoeff, err := safemath.SafeAdd(result1, result2)
if err != nil {
return 0, ierrors.Wrapf(err, "failed in step 5 of pool coefficient calculation due to overflow for slot %d", slot)
}
return uint64(poolCoeff), nil
}
// calculateProfitMargin calculates a common profit margin for all validators by firstly increasing the accuracy of the given value, so the profit margin is moved to the power of 2^accuracyShift.
func (t *Tracker) calculateProfitMargin(totalValidatorsStake iotago.BaseToken, totalPoolStake iotago.BaseToken, epoch iotago.EpochIndex) (uint64, error) {
scaledUpTotalValidatorStake, err := safemath.SafeLeftShift(totalValidatorsStake, t.apiProvider.APIForEpoch(epoch).ProtocolParameters().RewardsParameters().ProfitMarginExponent)
if err != nil {
return 0, ierrors.Wrapf(err, "failed to calculate profit margin due to overflow for epoch %d", epoch)
}
return uint64(scaledUpTotalValidatorStake / (totalValidatorsStake + totalPoolStake)), nil
}
// scaleUpComplement returns the 'shifted' completition to "one" for the shifted value where one is the 2^accuracyShift.
func scaleUpComplement[V iotago.BaseToken | iotago.Mana | uint64](val V, shift uint8) (V, error) {
shiftedOne, err := safemath.SafeLeftShift(V(1), shift)
if err != nil {
return 0, err
}
return safemath.SafeSub(shiftedOne, val)
}