cosmos-sdk/x/distribution/simulation/invariants.go

66 lines
1.8 KiB
Go
Raw Normal View History

package simulation
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
distr "github.com/cosmos/cosmos-sdk/x/distribution"
"github.com/cosmos/cosmos-sdk/x/mock/simulation"
2019-01-11 12:08:01 -08:00
"github.com/cosmos/cosmos-sdk/x/staking"
)
// AllInvariants runs all invariants of the distribution module
2019-01-11 12:08:01 -08:00
func AllInvariants(d distr.Keeper, stk staking.Keeper) simulation.Invariant {
return func(ctx sdk.Context) error {
2019-01-16 13:38:05 -08:00
err := CanWithdrawInvariant(d, stk)(ctx)
if err != nil {
return err
}
2019-01-16 13:38:05 -08:00
err = NonNegativeOutstandingInvariant(d)(ctx)
if err != nil {
return err
}
return nil
}
}
2019-01-16 13:38:05 -08:00
// NonNegativeOutstandingInvariant checks that outstanding unwithdrawn fees are never negative
func NonNegativeOutstandingInvariant(k distr.Keeper) simulation.Invariant {
return func(ctx sdk.Context) error {
2019-01-16 13:38:05 -08:00
outstanding := k.GetOutstandingRewards(ctx)
if outstanding.HasNegative() {
return fmt.Errorf("Negative outstanding coins: %v", outstanding)
}
return nil
}
}
// CanWithdrawInvariant checks that current rewards can be completely withdrawn
2019-01-11 12:08:01 -08:00
func CanWithdrawInvariant(k distr.Keeper, sk staking.Keeper) simulation.Invariant {
return func(ctx sdk.Context) error {
2019-01-16 13:38:05 -08:00
// cache, we don't want to write changes
ctx, _ = ctx.CacheContext()
2019-01-16 13:38:05 -08:00
// iterate over all bonded validators, withdraw commission
sk.IterateValidators(ctx, func(_ int64, val sdk.Validator) (stop bool) {
_ = k.WithdrawValidatorCommission(ctx, val.GetOperator())
return false
2019-01-16 13:38:05 -08:00
})
2019-01-16 13:38:05 -08:00
// iterate over all current delegations, withdraw rewards
dels := sk.GetAllDelegations(ctx)
for _, delegation := range dels {
_ = k.WithdrawDelegationRewards(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr)
}
2019-01-16 13:38:05 -08:00
remaining := k.GetOutstandingRewards(ctx)
if len(remaining) > 0 && remaining[0].Amount.LT(sdk.ZeroDec()) {
return fmt.Errorf("Negative remaining coins: %v", remaining)
}
return nil
}
}