Skip to content

Commit

Permalink
perf: modify DelegatorSharesInvariant for better performance (cosmos#…
Browse files Browse the repository at this point in the history
  • Loading branch information
mergify[bot] authored and randy75828 committed Aug 10, 2022
1 parent 07b14c4 commit 5fc2642
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 5fc2642

Please sign in to comment.