-
Notifications
You must be signed in to change notification settings - Fork 168
/
abci.go
165 lines (141 loc) · 5.4 KB
/
abci.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
package oracle
import (
"strings"
"time"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/umee-network/umee/v6/x/oracle/keeper"
"github.com/umee-network/umee/v6/x/oracle/types"
)
// EndBlocker is called at the end of every block
func EndBlocker(ctx sdk.Context, k keeper.Keeper) error {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)
params := k.GetParams(ctx)
if k.IsPeriodLastBlock(ctx, params.VotePeriod) {
if err := CalcPrices(ctx, params, k); err != nil {
return err
}
}
// Slash oracle providers who missed voting over the threshold and
// reset miss counters of all validators at the last block of slash window
if k.IsPeriodLastBlock(ctx, params.SlashWindow) {
k.SlashAndResetMissCounters(ctx)
}
k.PruneAllPrices(ctx)
return nil
}
func CalcPrices(ctx sdk.Context, params types.Params, k keeper.Keeper) error {
// Build claim map over all validators in active set
validatorClaimMap := make(map[string]types.Claim)
powerReduction := k.StakingKeeper.PowerReduction(ctx)
// Calculate total validator power
var totalBondedPower int64
for _, v := range k.StakingKeeper.GetBondedValidatorsByPower(ctx) {
addr := v.GetOperator()
power := v.GetConsensusPower(powerReduction)
totalBondedPower += power
validatorClaimMap[addr.String()] = types.NewClaim(power, 0, 0, addr)
}
// voteTargets defines the symbol (ticker) denoms that we require votes on
voteTargets := make(map[string]bool, 0)
voteTargetDenoms := make([]string, 0)
for _, v := range params.AcceptList {
voteTargets[v.SymbolDenom] = true // unique symbol denoms <Note: we are allowing duplicate symbol denoms>
voteTargetDenoms = append(voteTargetDenoms, v.BaseDenom)
}
// NOTE: it filters out inactive or jailed validators
// ballotDenomSlice is oracle votes of the symbol denoms, those are stored by AggregateExchangeRateVote
ballotDenomSlice := k.OrganizeBallotByDenom(ctx, validatorClaimMap)
threshold := k.VoteThreshold(ctx).MulInt64(types.MaxVoteThresholdMultiplier).TruncateInt64()
// Iterate through ballots and update exchange rates; drop if not enough votes have been achieved.
for _, ballotDenom := range ballotDenomSlice {
// Calculate the portion of votes received as an integer, scaled up using the
// same multiplier as the `threshold` computed above
support := ballotDenom.Ballot.Power() * types.MaxVoteThresholdMultiplier / totalBondedPower
if support < threshold {
ctx.Logger().Info("Ballot voting power is under vote threshold, dropping ballot", "denom", ballotDenom)
continue
}
denom := strings.ToUpper(ballotDenom.Denom)
// Get weighted median of exchange rates
exchangeRate, err := Tally(ballotDenom.Ballot, params.RewardBand, validatorClaimMap)
if err != nil {
return err
}
// save the exchange rate to store with denom and timestamp
k.SetExchangeRate(ctx, denom, exchangeRate)
}
if k.IsPeriodLastBlock(ctx, params.HistoricStampPeriod) {
k.IterateExchangeRates(ctx, func(denom string, exgRate sdk.Dec, _ time.Time) (stop bool) {
k.AddHistoricPrice(ctx, denom, exgRate)
return false
})
}
// Calculate and stamp median/median deviation if median stamp period has passed
if k.IsPeriodLastBlock(ctx, params.MedianStampPeriod) {
var err error
k.IterateExchangeRates(ctx, func(denom string, _ sdk.Dec, _ time.Time) (stop bool) {
err = k.CalcAndSetHistoricMedian(ctx, denom)
return err != nil
})
if err != nil {
return err
}
}
// update miss counting & slashing
voteTargetsLen := len(voteTargets)
claimSlice := types.ClaimMapToSlice(validatorClaimMap)
for _, claim := range claimSlice {
// Skip valid voters
// in MsgAggregateExchangeRateVote we filter tokens from the AcceptList.
if int(claim.TokensVoted) == voteTargetsLen {
continue
}
// Increase miss counter
k.SetMissCounter(ctx, claim.Validator, k.GetMissCounter(ctx, claim.Validator)+1)
}
// Distribute rewards to ballot winners
k.RewardBallotWinners(
ctx,
int64(params.VotePeriod),
int64(params.RewardDistributionWindow),
voteTargetDenoms,
claimSlice,
)
k.ClearVotes(ctx, params.VotePeriod)
return nil
}
// Tally calculates and returns the median. It sets the set of voters to be
// rewarded, i.e. voted within a reasonable spread from the weighted median to
// the store. Note, the ballot is sorted by ExchangeRate.
func Tally(
ballot types.ExchangeRateBallot,
rewardBand sdk.Dec,
validatorClaimMap map[string]types.Claim,
) (sdk.Dec, error) {
weightedMedian, err := ballot.WeightedMedian()
if err != nil {
return sdk.ZeroDec(), err
}
standardDeviation, err := ballot.StandardDeviation()
if err != nil {
return sdk.ZeroDec(), err
}
// rewardSpread is the MAX((weightedMedian * (rewardBand/2)), standardDeviation)
rewardSpread := weightedMedian.Mul(rewardBand.QuoInt64(2))
rewardSpread = sdk.MaxDec(rewardSpread, standardDeviation)
for _, tallyVote := range ballot {
// Filter ballot winners. For voters, we filter out the tally vote iff:
// (weightedMedian - rewardSpread) <= ExchangeRate <= (weightedMedian + rewardSpread)
if (tallyVote.ExchangeRate.GTE(weightedMedian.Sub(rewardSpread)) &&
tallyVote.ExchangeRate.LTE(weightedMedian.Add(rewardSpread))) ||
!tallyVote.ExchangeRate.IsPositive() {
key := tallyVote.Voter.String()
claim := validatorClaimMap[key]
claim.Weight += tallyVote.Power
claim.TokensVoted++
validatorClaimMap[key] = claim
}
}
return weightedMedian, nil
}