Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: modify DelegatorSharesInvariant for better performance #12170

Merged
merged 4 commits into from
Jun 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions x/staking/keeper/invariants.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,20 +164,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