forked from prysmaticlabs/prysm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rewards_penalties.go
432 lines (386 loc) · 16 KB
/
rewards_penalties.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
// Package balances contains libraries to calculate reward and
// penalty quotients. It computes new validator balances
// for justifications, crosslinks and attestation inclusions. It
// also computes penalties for the inactive validators.
package balances
import (
"errors"
"fmt"
"github.com/prysmaticlabs/prysm/beacon-chain/core/epoch"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/mathutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/sliceutil"
)
// ExpectedFFGSource applies rewards or penalties
// for an expected FFG source. It uses total justified
// attesting balances, total validator balances and base
// reward quotient to calculate the reward amount.
// Validators who voted for previous justified hash
// will get a reward, everyone else will get a penalty.
//
// Spec pseudocode definition:
// Any validator index in previous_epoch_justified_attester_indices
// gains base_reward(state, index) * previous_epoch_justified_attesting_balance // total_balance.
// Any active validator v not in previous_epoch_justified_attester_indices
// loses base_reward(state, index).
func ExpectedFFGSource(
state *pb.BeaconState,
justifiedAttesterIndices []uint64,
justifiedAttestingBalance uint64,
totalBalance uint64) *pb.BeaconState {
baseRewardQuotient := baseRewardQuotient(totalBalance)
for _, index := range justifiedAttesterIndices {
state.ValidatorBalances[index] +=
baseReward(state, index, baseRewardQuotient) *
justifiedAttestingBalance /
totalBalance
}
activeValidatorIndices := helpers.ActiveValidatorIndices(state.ValidatorRegistry, state.Slot)
didNotAttestIndices := sliceutil.Not(justifiedAttesterIndices, activeValidatorIndices)
for _, index := range didNotAttestIndices {
state.ValidatorBalances[index] -=
baseReward(state, index, baseRewardQuotient)
}
return state
}
// ExpectedFFGTarget applies rewards or penalties
// for an expected FFG target. It uses total boundary
// attesting balances, total validator balances and base
// reward quotient to calculate the reward amount.
// Validators who voted for epoch boundary block
// will get a reward, everyone else will get a penalty.
//
// Spec pseudocode definition:
// Any validator index in previous_epoch_boundary_attester_indices gains
// base_reward(state, index) * previous_epoch_boundary_attesting_balance // total_balance.
// Any active validator index not in previous_epoch_boundary_attester_indices loses
// base_reward(state, index).
func ExpectedFFGTarget(
state *pb.BeaconState,
boundaryAttesterIndices []uint64,
boundaryAttestingBalance uint64,
totalBalance uint64) *pb.BeaconState {
baseRewardQuotient := baseRewardQuotient(totalBalance)
for _, index := range boundaryAttesterIndices {
state.ValidatorBalances[index] +=
baseReward(state, index, baseRewardQuotient) *
boundaryAttestingBalance /
totalBalance
}
activeValidatorIndices := helpers.ActiveValidatorIndices(state.ValidatorRegistry, state.Slot)
didNotAttestIndices := sliceutil.Not(boundaryAttesterIndices, activeValidatorIndices)
for _, index := range didNotAttestIndices {
state.ValidatorBalances[index] -=
baseReward(state, index, baseRewardQuotient)
}
return state
}
// ExpectedBeaconChainHead applies rewards or penalties
// for an expected beacon chain head. It uses total head
// attesting balances, total validator balances and base
// reward quotient to calculate the reward amount.
// Validators who voted for the canonical head block
// will get a reward, everyone else will get a penalty.
//
// Spec pseudocode definition:
// Any validator index in previous_epoch_head_attester_indices gains
// base_reward(state, index) * previous_epoch_head_attesting_balance // total_balance).
// Any active validator index not in previous_epoch_head_attester_indices loses
// base_reward(state, index).
func ExpectedBeaconChainHead(
state *pb.BeaconState,
headAttesterIndices []uint64,
headAttestingBalance uint64,
totalBalance uint64) *pb.BeaconState {
baseRewardQuotient := baseRewardQuotient(totalBalance)
for _, index := range headAttesterIndices {
state.ValidatorBalances[index] +=
baseReward(state, index, baseRewardQuotient) *
headAttestingBalance /
totalBalance
}
activeValidatorIndices := helpers.ActiveValidatorIndices(state.ValidatorRegistry, state.Slot)
didNotAttestIndices := sliceutil.Not(headAttesterIndices, activeValidatorIndices)
for _, index := range didNotAttestIndices {
state.ValidatorBalances[index] -=
baseReward(state, index, baseRewardQuotient)
}
return state
}
// InclusionDistance applies rewards based on
// inclusion distance. It uses calculated inclusion distance
// and base reward quotient to calculate the reward amount.
//
// Spec pseudocode definition:
// Any validator index in previous_epoch_attester_indices gains
// base_reward(state, index) * MIN_ATTESTATION_INCLUSION_DELAY //
// inclusion_distance(state, index)
func InclusionDistance(
state *pb.BeaconState,
attesterIndices []uint64,
totalBalance uint64) (*pb.BeaconState, error) {
baseRewardQuotient := baseRewardQuotient(totalBalance)
for _, index := range attesterIndices {
inclusionDistance, err := epoch.InclusionDistance(state, index)
if err != nil {
return nil, fmt.Errorf("could not get inclusion distance: %v", err)
}
if inclusionDistance == 0 {
return nil, errors.New("could not process inclusion distance: 0")
}
state.ValidatorBalances[index] +=
baseReward(state, index, baseRewardQuotient) *
params.BeaconConfig().MinAttestationInclusionDelay /
inclusionDistance
}
return state, nil
}
// InactivityFFGSource applies penalties to inactive
// validators that missed to vote FFG source over an
// extended of time. (epochs_since_finality > 4)
//
// Spec pseudocode definition:
// Any active validator index not in previous_epoch_justified_attester_indices,
// loses inactivity_penalty(state, index, epochs_since_finality)
func InactivityFFGSource(
state *pb.BeaconState,
justifiedAttesterIndices []uint64,
totalBalance uint64,
epochsSinceFinality uint64) *pb.BeaconState {
baseRewardQuotient := baseRewardQuotient(totalBalance)
activeValidatorIndices := helpers.ActiveValidatorIndices(state.ValidatorRegistry, state.Slot)
didNotAttestIndices := sliceutil.Not(justifiedAttesterIndices, activeValidatorIndices)
for _, index := range didNotAttestIndices {
state.ValidatorBalances[index] -=
inactivityPenalty(state, index, baseRewardQuotient, epochsSinceFinality)
}
return state
}
// InactivityFFGTarget applies penalties to inactive
// validators that missed to vote FFG target over an
// extended of time. (epochs_since_finality > 4)
//
// Spec pseudocode definition:
// Any active validator index not in previous_epoch_boundary_attester_indices,
// loses inactivity_penalty(state, index, epochs_since_finality)
func InactivityFFGTarget(
state *pb.BeaconState,
boundaryAttesterIndices []uint64,
totalBalance uint64,
epochsSinceFinality uint64) *pb.BeaconState {
baseRewardQuotient := baseRewardQuotient(totalBalance)
activeValidatorIndices := helpers.ActiveValidatorIndices(state.ValidatorRegistry, state.Slot)
didNotAttestIndices := sliceutil.Not(boundaryAttesterIndices, activeValidatorIndices)
for _, index := range didNotAttestIndices {
state.ValidatorBalances[index] -=
inactivityPenalty(state, index, baseRewardQuotient, epochsSinceFinality)
}
return state
}
// InactivityChainHead applies penalties to inactive validators
// that missed to vote on canonical head over an extended of time.
// (epochs_since_finality > 4)
//
// Spec pseudocode definition:
// Any active validator index not in previous_epoch_head_attester_indices,
// loses base_reward(state, index)
func InactivityChainHead(
state *pb.BeaconState,
headAttesterIndices []uint64,
totalBalance uint64) *pb.BeaconState {
baseRewardQuotient := baseRewardQuotient(totalBalance)
activeValidatorIndices := helpers.ActiveValidatorIndices(state.ValidatorRegistry, state.Slot)
didNotAttestIndices := sliceutil.Not(headAttesterIndices, activeValidatorIndices)
for _, index := range didNotAttestIndices {
state.ValidatorBalances[index] -=
baseReward(state, index, baseRewardQuotient)
}
return state
}
// InactivityExitedPenalties applies additional (2x) penalties
// to inactive validators with status EXITED_WITH_PENALTY.
//
// Spec pseudocode definition:
// Any active_validator index with validator.penalized_epoch <= current_epoch,
// loses 2 * inactivity_penalty(state, index, epochs_since_finality) +
// base_reward(state, index).
func InactivityExitedPenalties(
state *pb.BeaconState,
totalBalance uint64,
epochsSinceFinality uint64) *pb.BeaconState {
baseRewardQuotient := baseRewardQuotient(totalBalance)
activeValidatorIndices := helpers.ActiveValidatorIndices(state.ValidatorRegistry, state.Slot)
for _, index := range activeValidatorIndices {
if state.ValidatorRegistry[index].PenalizedEpoch <= helpers.CurrentEpoch(state) {
state.ValidatorBalances[index] -=
2*inactivityPenalty(state, index, baseRewardQuotient, epochsSinceFinality) +
baseReward(state, index, baseRewardQuotient)
}
}
return state
}
// InactivityInclusionDistance applies penalties in relation with
// inclusion delay to inactive validators.
//
// Spec pseudocode definition:
// Any validator index in previous_epoch_attester_indices loses
// base_reward(state, index) - base_reward(state, index) *
// MIN_ATTESTATION_INCLUSION_DELAY // inclusion_distance(state, index)
func InactivityInclusionDistance(
state *pb.BeaconState,
attesterIndices []uint64,
totalBalance uint64) (*pb.BeaconState, error) {
baseRewardQuotient := baseRewardQuotient(totalBalance)
for _, index := range attesterIndices {
inclusionDistance, err := epoch.InclusionDistance(state, index)
if err != nil {
return nil, fmt.Errorf("could not get inclusion distance: %v", err)
}
baseReward := baseReward(state, index, baseRewardQuotient)
state.ValidatorBalances[index] -= baseReward -
baseReward*params.BeaconConfig().MinAttestationInclusionDelay/
inclusionDistance
}
return state, nil
}
// AttestationInclusion awards the the beacon
// proposers who included previous epoch attestations.
//
// Spec pseudocode definition:
// For each index in previous_epoch_attester_indices,
// we determine the proposer proposer_index =
// get_beacon_proposer_index(state, inclusion_slot(state, index))
// and set state.validator_balances[proposer_index] +=
// base_reward(state, index) // INCLUDER_REWARD_QUOTIENT
func AttestationInclusion(
state *pb.BeaconState,
totalBalance uint64,
prevEpochAttesterIndices []uint64) (*pb.BeaconState, error) {
baseRewardQuotient := baseRewardQuotient(totalBalance)
for _, index := range prevEpochAttesterIndices {
slot, err := epoch.InclusionSlot(state, index)
if err != nil {
return nil, fmt.Errorf("could not get inclusion slot: %v", err)
}
proposerIndex, err := validators.BeaconProposerIdx(state, slot)
if err != nil {
return nil, fmt.Errorf("could not get propoer index: %v", err)
}
state.ValidatorBalances[proposerIndex] +=
baseReward(state, proposerIndex, baseRewardQuotient) /
params.BeaconConfig().IncluderRewardQuotient
}
return state, nil
}
// Crosslinks awards or penalizes attesters
// for attesting shard cross links.
//
// Spec pseudocode definition:
// For slot in range(get_epoch_start_slot(previous_epoch), get_epoch_start_slot(current_epoch)),
// let crosslink_committees_at_slot = get_crosslink_committees_at_slot(slot).
// For every (crosslink_committee, shard) in crosslink_committee_at_slot, compute:
//
// Let shard_block_root be state.latest_crosslinks[shard].shard_block_root
// Let attesting_validator_indices(shard_committee, shard_block_root)
// be the union of the validator index sets given by [get_attestation_participants(
// state, a.data, a.participation_bitfield) for a in current_epoch_attestations +
// previous_epoch_attestations if a.shard == shard and a.shard_block_root == shard_block_root].
// Let winning_root(shard_committee)
// be equal to the value of shard_block_root such that sum([get_effective_balance(state, i)
// for i in attesting_validator_indices(shard_committee, shard_block_root)])
// is maximized (ties broken by favoring lower shard_block_root values).
// Let attesting_validators(shard_committee)
// be equal to attesting_validator_indices(
// shard_committee, winning_root(shard_committee)) for convenience.
// Let total_attesting_balance(shard_committee) =
// sum([get_effective_balance(state, i) for i in attesting_validators(shard_committee)]).
// Let total_balance(shard_committee) =
// sum([get_effective_balance(state, i) for i in shard_committee]).
func Crosslinks(
state *pb.BeaconState,
thisEpochAttestations []*pb.PendingAttestationRecord,
prevEpochAttestations []*pb.PendingAttestationRecord) (*pb.BeaconState, error) {
prevEpoch := helpers.PrevEpoch(state)
currentEpoch := helpers.CurrentEpoch(state)
startSlot := helpers.StartSlot(prevEpoch)
endSlot := helpers.StartSlot(currentEpoch)
for i := startSlot; i < endSlot; i++ {
crosslinkCommittees, err := helpers.CrosslinkCommitteesAtSlot(state, i, false)
if err != nil {
return nil, fmt.Errorf("could not get shard committees for slot %d: %v", i, err)
}
for _, crosslinkCommittee := range crosslinkCommittees {
shard := crosslinkCommittee.Shard
committee := crosslinkCommittee.Committee
totalAttestingBalance, err :=
epoch.TotalAttestingBalance(state, shard, thisEpochAttestations, prevEpochAttestations)
if err != nil {
return nil,
fmt.Errorf("could not get attesting balance for shard committee %d: %v", shard, err)
}
totalBalance := epoch.TotalBalance(state, committee)
baseRewardQuotient := baseRewardQuotient(totalBalance)
attestingIndices, err := epoch.AttestingValidators(
state,
shard,
thisEpochAttestations,
prevEpochAttestations)
if err != nil {
return nil,
fmt.Errorf("could not get attesting indices for shard committee %d: %v", shard, err)
}
for _, index := range committee {
baseReward := baseReward(state, index, baseRewardQuotient)
if sliceutil.IsIn(index, attestingIndices) {
state.ValidatorBalances[index] +=
baseReward * totalAttestingBalance / totalBalance
} else {
state.ValidatorBalances[index] -=
baseReward * totalAttestingBalance / totalBalance
}
}
}
}
return state, nil
}
// baseRewardQuotient takes the total balance and calculates for
// the quotient of the base reward.
//
// Spec pseudocode definition:
// base_reward_quotient =
// integer_squareroot(total_balance) // BASE_REWARD_QUOTIENT
func baseRewardQuotient(totalBalance uint64) uint64 {
return mathutil.IntegerSquareRoot(totalBalance) / params.BeaconConfig().BaseRewardQuotient
}
// baseReward takes state and validator index to calculate for
// individual validator's base reward.
//
// Spec pseudocode definition:
// base_reward(state, index) =
// get_effective_balance(state, index) // base_reward_quotient // 5
func baseReward(
state *pb.BeaconState,
validatorIndex uint64,
baseRewardQuotient uint64) uint64 {
validatorBalance := validators.EffectiveBalance(state, validatorIndex)
return validatorBalance / baseRewardQuotient / 5
}
// inactivityPenalty takes state and validator index to calculate for
// individual validator's penalty for being offline.
//
// Spec pseudocode definition:
// inactivity_penalty(state, index, epochs_since_finality) =
// base_reward(state, index) + get_effective_balance(state, index)
// * epochs_since_finality // INACTIVITY_PENALTY_QUOTIENT // 2
func inactivityPenalty(
state *pb.BeaconState,
validatorIndex uint64,
baseRewardQuotient uint64,
epochsSinceFinality uint64) uint64 {
baseReward := baseReward(state, validatorIndex, baseRewardQuotient)
validatorBalance := validators.EffectiveBalance(state, validatorIndex)
return baseReward + validatorBalance*epochsSinceFinality/params.BeaconConfig().InactivityPenaltyQuotient/2
}