Skip to content

Commit

Permalink
perf: modify DelegatorSharesInvariant for better performance (#12170)
Browse files Browse the repository at this point in the history
(cherry picked from commit f052877)
  • Loading branch information
catShaark authored and mergify[bot] committed Jun 7, 2022
1 parent d721a76 commit be892cc
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions x/staking/keeper/invariants.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,20 +166,30 @@ func DelegatorSharesInvariant(k Keeper) sdk.Invariant {
)

validators := k.GetAllValidators(ctx)
validatorsDelegationShares := map[string]sdk.Dec{}

// initialize a map: validator -> its delegation shares
for _, validator := range validators {
valTotalDelShares := validator.GetDelegatorShares()
totalDelShares := sdk.ZeroDec()
validatorsDelegationShares[validator.GetOperator().String()] = sdk.ZeroDec()
}

delegations := k.GetValidatorDelegations(ctx, validator.GetOperator())
for _, delegation := range delegations {
totalDelShares = totalDelShares.Add(delegation.Shares)
}
// iterate through all the delegations to calculate the total delegation shares for each validator
delegations := k.GetAllDelegations(ctx)
for _, delegation := range delegations {
delegationValidatorAddr := delegation.GetValidatorAddr().String()
validatorDelegationShares := validatorsDelegationShares[delegationValidatorAddr]
validatorsDelegationShares[delegationValidatorAddr] = validatorDelegationShares.Add(delegation.Shares)
}

if !valTotalDelShares.Equal(totalDelShares) {
// for each validator, check if its total delegation shares calculated from the step above equals to its expected delegation shares
for _, validator := range validators {
expValTotalDelShares := validator.GetDelegatorShares()
calculatedValTotalDelShares := validatorsDelegationShares[validator.GetOperator().String()]
if !calculatedValTotalDelShares.Equal(expValTotalDelShares) {
broken = true
msg += fmt.Sprintf("broken delegator shares invariance:\n"+
"\tvalidator.DelegatorShares: %v\n"+
"\tsum of Delegator.Shares: %v\n", valTotalDelShares, totalDelShares)
"\tsum of Delegator.Shares: %v\n", expValTotalDelShares, calculatedValTotalDelShares)
}
}

Expand Down

0 comments on commit be892cc

Please sign in to comment.