diff --git a/codec/any_test.go b/codec/any_test.go index fff902c3d994..d9ea888c49fb 100644 --- a/codec/any_test.go +++ b/codec/any_test.go @@ -4,10 +4,9 @@ import ( "errors" "testing" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" ) diff --git a/codec/types/any.go b/codec/types/any.go index b879180481db..38fe4b42aa72 100644 --- a/codec/types/any.go +++ b/codec/types/any.go @@ -1,6 +1,7 @@ package types import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/gogo/protobuf/proto" ) @@ -98,6 +99,23 @@ func UnsafePackAny(x interface{}) *Any { return &Any{cachedValue: x} } +// PackAny is a checked and safe version of UnsafePackAny. It assures that +// `x` implements the proto.Message interface and uses it to serialize `x`. +// [DEPRECATED]: should be moved away: https://github.com/cosmos/cosmos-sdk/issues/7479 +func PackAny(x interface{}) (*Any, error) { + if x == nil { + return nil, nil + } + if intoany, ok := x.(IntoAny); ok { + return intoany.AsAny(), nil + } + protoMsg, ok := x.(proto.Message) + if !ok { + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting %T to implement proto.Message", x) + } + return NewAnyWithValue(protoMsg) +} + // GetCachedValue returns the cached value from the Any if present func (any *Any) GetCachedValue() interface{} { return any.cachedValue diff --git a/proto/cosmos/staking/v1beta1/tx.proto b/proto/cosmos/staking/v1beta1/tx.proto index c68e037dca3d..60aecd9513c8 100644 --- a/proto/cosmos/staking/v1beta1/tx.proto +++ b/proto/cosmos/staking/v1beta1/tx.proto @@ -5,6 +5,7 @@ import "gogoproto/gogo.proto"; import "cosmos/base/v1beta1/coin.proto"; import "google/protobuf/timestamp.proto"; import "cosmos/staking/v1beta1/staking.proto"; +import "google/protobuf/any.proto"; option go_package = "github.com/cosmos/cosmos-sdk/x/staking/types"; @@ -43,7 +44,7 @@ message MsgCreateValidator { ]; string delegator_address = 4 [(gogoproto.moretags) = "yaml:\"delegator_address\""]; string validator_address = 5 [(gogoproto.moretags) = "yaml:\"validator_address\""]; - string pubkey = 6; + google.protobuf.Any pubkey = 6; cosmos.base.v1beta1.Coin value = 7 [(gogoproto.nullable) = false]; } diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index d93953e1f4f5..d17e57fb95f7 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -204,7 +204,7 @@ func InitTestnet( genAccounts = append(genAccounts, authtypes.NewBaseAccount(addr, nil, 0, 0)) valTokens := sdk.TokensFromConsensusPower(100) - createValMsg := stakingtypes.NewMsgCreateValidator( + createValMsg, err := stakingtypes.NewMsgCreateValidator( sdk.ValAddress(addr), valPubKeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), @@ -212,6 +212,9 @@ func InitTestnet( stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()), sdk.OneInt(), ) + if err != nil { + return err + } txBuilder := clientCtx.TxConfig.NewTxBuilder() if err := txBuilder.SetMsgs(createValMsg); err != nil { diff --git a/testutil/network/network.go b/testutil/network/network.go index 914ed792dccc..1ab9006f8ea1 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -162,6 +162,7 @@ type ( } ) +// New creates a new Network for integration tests. func New(t *testing.T, cfg Config) *Network { // only one caller/test can create and use a network at a time t.Log("acquiring test network lock") @@ -293,7 +294,7 @@ func New(t *testing.T, cfg Config) *Network { commission, err := sdk.NewDecFromStr("0.5") require.NoError(t, err) - createValMsg := stakingtypes.NewMsgCreateValidator( + createValMsg, err := stakingtypes.NewMsgCreateValidator( sdk.ValAddress(addr), valPubKeys[i], sdk.NewCoin(sdk.DefaultBondDenom, cfg.BondedTokens), @@ -301,6 +302,7 @@ func New(t *testing.T, cfg Config) *Network { stakingtypes.NewCommissionRates(commission, sdk.OneDec(), sdk.OneDec()), sdk.OneInt(), ) + require.NoError(t, err) p2pURL, err := url.Parse(p2pAddr) require.NoError(t, err) diff --git a/types/address.go b/types/address.go index 8683a50fe38a..345c44fa8e1c 100644 --- a/types/address.go +++ b/types/address.go @@ -9,12 +9,15 @@ import ( "strings" "github.com/tendermint/tendermint/crypto" + tmed25519 "github.com/tendermint/tendermint/crypto/ed25519" yaml "gopkg.in/yaml.v2" "github.com/cosmos/cosmos-sdk/codec/legacy" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/types/bech32" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) const ( @@ -674,12 +677,32 @@ func GetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) (crypto.PubKey, return nil, err } - pk, err := cryptocodec.PubKeyFromBytes(bz) + aminoPk, err := cryptocodec.PubKeyFromBytes(bz) if err != nil { return nil, err } - return pk, nil + var protoPk crypto.PubKey + switch aminoPk.(type) { + + // We are bech32ifying some secp256k1 keys in tests. + case *secp256k1.PubKey: + protoPk = aminoPk + case *ed25519.PubKey: + protoPk = aminoPk + + // Real-life case. + case tmed25519.PubKey: + protoPk = &ed25519.PubKey{ + Key: aminoPk.Bytes(), + } + + default: + // We only allow ed25519 pubkeys to be bech32-ed right now. + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "bech32 pubkey does not support %T", aminoPk) + } + + return protoPk, nil } // MustGetPubKeyFromBech32 calls GetPubKeyFromBech32 except it panics on error. diff --git a/x/auth/types/account.go b/x/auth/types/account.go index 301a5af9e730..476e607c421c 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -14,7 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) var ( @@ -84,22 +83,11 @@ func (acc BaseAccount) GetPubKey() (pk crypto.PubKey) { // SetPubKey - Implements sdk.AccountI. func (acc *BaseAccount) SetPubKey(pubKey crypto.PubKey) error { - if pubKey == nil { - acc.PubKey = nil - } else { - protoMsg, ok := pubKey.(proto.Message) - if !ok { - return sdkerrors.ErrInvalidPubKey - } - - any, err := codectypes.NewAnyWithValue(protoMsg) - if err != nil { - return err - } - - acc.PubKey = any + any, err := codectypes.PackAny(pubKey) + if err != nil { + return err } - + acc.PubKey = any return nil } diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 617cf1d4e583..bcb9e62aa213 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -20,20 +20,11 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1234)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) - - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator with 50% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator( - sdk.ValAddress(addrs[0]), valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt(), - ) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidator(sdk.ValAddress(addrs[0]), valConsPk1, 100, true) val := app.StakingKeeper.Validator(ctx, valAddrs[0]) // allocate tokens @@ -56,27 +47,17 @@ func TestAllocateTokensToManyValidators(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - sh := staking.NewHandler(app.StakingKeeper) addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1234)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator with 50% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[0], valConsPk1, 100, true) // create second validator with 0% commission - commission = stakingtypes.NewCommissionRates(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) - msg = stakingtypes.NewMsgCreateValidator(valAddrs[1], valConsPk2, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[1], valConsPk2, 100, true) abciValA := abci.Validator{ Address: valConsPk1.Address(), @@ -101,7 +82,7 @@ func TestAllocateTokensToManyValidators(t *testing.T) { feeCollector := app.AccountKeeper.GetModuleAccount(ctx, types.FeeCollectorName) require.NotNil(t, feeCollector) - err = app.BankKeeper.SetBalances(ctx, feeCollector.GetAddress(), fees) + err := app.BankKeeper.SetBalances(ctx, feeCollector.GetAddress(), fees) require.NoError(t, err) app.AccountKeeper.SetAccount(ctx, feeCollector) @@ -138,31 +119,19 @@ func TestAllocateTokensTruncation(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1234)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator with 10% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(110)), stakingtypes.Description{}, commission, sdk.OneInt()) - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[0], valConsPk1, 110, true) // create second validator with 10% commission - commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg = stakingtypes.NewMsgCreateValidator(valAddrs[1], valConsPk2, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt()) - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[1], valConsPk2, 100, true) // create third validator with 10% commission - commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg = stakingtypes.NewMsgCreateValidator(valAddrs[2], valConsPk3, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt()) - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[2], valConsPk3, 100, true) abciValA := abci.Validator{ Address: valConsPk1.Address(), @@ -193,7 +162,7 @@ func TestAllocateTokensTruncation(t *testing.T) { feeCollector := app.AccountKeeper.GetModuleAccount(ctx, types.FeeCollectorName) require.NotNil(t, feeCollector) - err = app.BankKeeper.SetBalances(ctx, feeCollector.GetAddress(), fees) + err := app.BankKeeper.SetBalances(ctx, feeCollector.GetAddress(), fees) require.NoError(t, err) app.AccountKeeper.SetAccount(ctx, feeCollector) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 44135ce10ff5..e55acbe09137 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -9,33 +9,26 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestCalculateRewardsBasic(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) // create validator with 50% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator( - valAddrs[0], valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt(), - ) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[0], valConsPk1, 100, true) - // end block to bond validator + // end block to bond validator and start new block staking.EndBlocker(ctx, app.StakingKeeper) - - // next block ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + tstaking.Ctx = ctx // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) @@ -80,19 +73,12 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) - - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator with 50% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) valPower := int64(100) - valTokens := sdk.TokensFromConsensusPower(valPower) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true) // end block to bond validator staking.EndBlocker(ctx, app.StakingKeeper) @@ -148,20 +134,14 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + valPower := int64(100) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true) // end block to bond validator staking.EndBlocker(ctx, app.StakingKeeper) @@ -186,7 +166,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // slash the validator by 50% - app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) // fetch the validator again val = app.StakingKeeper.Validator(ctx, valAddrs[0]) @@ -200,7 +180,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // slash the validator by 50% again - app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1)) // fetch the validator again val = app.StakingKeeper.Validator(ctx, valAddrs[0]) @@ -229,19 +209,13 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - sh := staking.NewHandler(app.StakingKeeper) - + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) // create validator with 50% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[0], valConsPk1, 100, true) // end block to bond validator staking.EndBlocker(ctx, app.StakingKeeper) @@ -259,12 +233,8 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // second delegation - msg2 := stakingtypes.NewMsgDelegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.Ctx = ctx + tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], 100) del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) // fetch updated validator @@ -306,8 +276,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) - - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set module account coins distrAcc := app.DistrKeeper.GetDistributionAccount(ctx) @@ -316,17 +285,8 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { // create validator with 50% commission power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator( - valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - stakingtypes.Description{}, commission, sdk.OneInt(), - ) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + valTokens := tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, power, true) // assert correct initial balance expTokens := balanceTokens.Sub(valTokens) @@ -354,7 +314,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // withdraw rewards - _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) require.Nil(t, err) // historical count should still be 2 (added one record, cleared one) @@ -385,19 +345,12 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) - - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + valPower := int64(100) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true) // end block to bond validator staking.EndBlocker(ctx, app.StakingKeeper) @@ -427,10 +380,10 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // slash the validator by 50% - app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) // slash the validator by 50% again - app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1)) // fetch the validator again val = app.StakingKeeper.Validator(ctx, valAddrs[0]) @@ -457,21 +410,15 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - sh := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) // create validator with 50% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + valPower := int64(100) + tstaking.CreateValidatorWithValPower(valAddrs[0], valConsPk1, valPower, true) // end block to bond validator staking.EndBlocker(ctx, app.StakingKeeper) @@ -490,17 +437,11 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { // slash the validator ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // second delegation - delTokens := sdk.TokensFromConsensusPower(100) - msg2 := stakingtypes.NewMsgDelegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], - sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.DelegateWithPower(sdk.AccAddress(valAddrs[1]), valAddrs[0], 100) del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) @@ -515,7 +456,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { // slash the validator again ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // fetch updated validator @@ -544,11 +485,9 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - sh := staking.NewHandler(app.StakingKeeper) - + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addr) - initial := int64(20) // set module account coins @@ -560,13 +499,8 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))} // create validator with 50% commission - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator(valAddrs[0], valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[0], valConsPk1, 100, true) // end block to bond validator staking.EndBlocker(ctx, app.StakingKeeper) @@ -585,10 +519,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // second delegation - msg2 := stakingtypes.NewMsgDelegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], 100) // historical count should be 3 (second delegation init) require.Equal(t, uint64(3), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) diff --git a/x/distribution/keeper/grpc_query_test.go b/x/distribution/keeper/grpc_query_test.go index 92a9f3abb4b6..a101896feaa1 100644 --- a/x/distribution/keeper/grpc_query_test.go +++ b/x/distribution/keeper/grpc_query_test.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -340,15 +341,9 @@ func (suite *KeeperTestSuite) TestGRPCValidatorSlashes() { func (suite *KeeperTestSuite) TestGRPCDelegationRewards() { app, ctx, addrs, valAddrs := suite.app, suite.ctx, suite.addrs, suite.valAddrs - sh := staking.NewHandler(app.StakingKeeper) - comm := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator( - valAddrs[0], valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, comm, sdk.OneInt(), - ) - - res, err := sh(ctx, msg) - suite.Require().NoError(err) - suite.Require().NotNil(res) + tstaking := teststaking.NewHelper(suite.T(), ctx, app.StakingKeeper) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valAddrs[0], valConsPk1, 100, true) staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index e801a4311d7f..c749bf774213 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -169,15 +170,9 @@ func TestQueries(t *testing.T) { require.Equal(t, []types.ValidatorSlashEvent{slashOne, slashTwo}, slashes) // test delegation rewards query - sh := staking.NewHandler(app.StakingKeeper) - comm := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := stakingtypes.NewMsgCreateValidator( - valOpAddr1, valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), stakingtypes.Description{}, comm, sdk.OneInt(), - ) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) + tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + tstaking.CreateValidator(valOpAddr1, valConsPk1, 100, true) staking.EndBlocker(ctx, app.StakingKeeper) diff --git a/x/evidence/keeper/infraction_test.go b/x/evidence/keeper/infraction_test.go index 88f275c82d2a..0f1adee14f46 100644 --- a/x/evidence/keeper/infraction_test.go +++ b/x/evidence/keeper/infraction_test.go @@ -6,32 +6,19 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/evidence/types" "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" ) -func newTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) *stakingtypes.MsgCreateValidator { - commission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - return stakingtypes.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt), - stakingtypes.Description{}, commission, sdk.OneInt(), - ) -} - func (suite *KeeperTestSuite) TestHandleDoubleSign() { ctx := suite.ctx.WithIsCheckTx(false).WithBlockHeight(1) suite.populateValidators(ctx) power := int64(100) stakingParams := suite.app.StakingKeeper.GetParams(ctx) - selfDelegation := sdk.TokensFromConsensusPower(power) operatorAddr, val := valAddresses[0], pubkeys[0] + tstaking := teststaking.NewHelper(suite.T(), ctx, suite.app.StakingKeeper) - // create validator - res, err := staking.NewHandler(suite.app.StakingKeeper)(ctx, newTestMsgCreateValidator(operatorAddr, val, selfDelegation)) - suite.NoError(err) - suite.NotNil(res) + selfDelegation := tstaking.CreateValidatorWithValPower(operatorAddr, val, power, true) // execute end-blocker and verify validator attributes staking.EndBlocker(ctx, suite.app.StakingKeeper) @@ -79,10 +66,9 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign() { del, _ := suite.app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(operatorAddr), operatorAddr) validator, _ := suite.app.StakingKeeper.GetValidator(ctx, operatorAddr) totalBond := validator.TokensFromShares(del.GetShares()).TruncateInt() - msgUnbond := stakingtypes.NewMsgUndelegate(sdk.AccAddress(operatorAddr), operatorAddr, sdk.NewCoin(stakingParams.BondDenom, totalBond)) - res, err = staking.NewHandler(suite.app.StakingKeeper)(ctx, msgUnbond) - suite.NoError(err) - suite.NotNil(res) + tstaking.Ctx = ctx + tstaking.Denom = stakingParams.BondDenom + tstaking.Undelegate(sdk.AccAddress(operatorAddr), operatorAddr, totalBond, true) } func (suite *KeeperTestSuite) TestHandleDoubleSign_TooOld() { @@ -91,13 +77,10 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign_TooOld() { power := int64(100) stakingParams := suite.app.StakingKeeper.GetParams(ctx) - amt := sdk.TokensFromConsensusPower(power) operatorAddr, val := valAddresses[0], pubkeys[0] + tstaking := teststaking.NewHelper(suite.T(), ctx, suite.app.StakingKeeper) - // create validator - res, err := staking.NewHandler(suite.app.StakingKeeper)(ctx, newTestMsgCreateValidator(operatorAddr, val, amt)) - suite.NoError(err) - suite.NotNil(res) + amt := tstaking.CreateValidatorWithValPower(operatorAddr, val, power, true) // execute end-blocker and verify validator attributes staking.EndBlocker(ctx, suite.app.StakingKeeper) diff --git a/x/evidence/keeper/init_test.go b/x/evidence/keeper/init_test.go new file mode 100644 index 000000000000..d5854aab467e --- /dev/null +++ b/x/evidence/keeper/init_test.go @@ -0,0 +1,11 @@ +package keeper_test + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index 0017f12f25b8..65e52b30ed1d 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -3,7 +3,6 @@ package keeper_test import ( "encoding/hex" "fmt" - "testing" "time" "github.com/stretchr/testify/suite" @@ -19,6 +18,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/evidence/exported" "github.com/cosmos/cosmos-sdk/x/evidence/keeper" "github.com/cosmos/cosmos-sdk/x/evidence/types" + "github.com/cosmos/cosmos-sdk/x/staking" ) var ( @@ -49,7 +49,7 @@ func newPubKey(pk string) (res crypto.PubKey) { return pubkey } -func testEquivocationHandler(k interface{}) types.Handler { +func testEquivocationHandler(_ interface{}) types.Handler { return func(ctx sdk.Context, e exported.Evidence) error { if err := e.ValidateBasic(); err != nil { return err @@ -75,6 +75,7 @@ type KeeperTestSuite struct { app *simapp.SimApp queryClient types.QueryClient + stakingHdl sdk.Handler } func (suite *KeeperTestSuite) SetupTest() { @@ -103,6 +104,7 @@ func (suite *KeeperTestSuite) SetupTest() { queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, app.InterfaceRegistry()) types.RegisterQueryServer(queryHelper, app.EvidenceKeeper) suite.queryClient = types.NewQueryClient(queryHelper) + suite.stakingHdl = staking.NewHandler(app.StakingKeeper) } func (suite *KeeperTestSuite) populateEvidence(ctx sdk.Context, numEvidence int) []exported.Evidence { @@ -208,7 +210,3 @@ func (suite *KeeperTestSuite) TestGetEvidenceHandler() { suite.Error(err) suite.Nil(handler) } - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index c88d33fef956..671431ed9e56 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -29,10 +29,6 @@ var ( addr2 = sdk.AccAddress(pk2.Address()) desc = stakingtypes.NewDescription("testname", "", "", "", "") comm = stakingtypes.CommissionRates{} - msg1 = stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk1.Address()), pk1, - sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, sdk.OneInt()) - msg2 = stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk2.Address()), pk1, - sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, sdk.OneInt()) ) // GenTxTestSuite is a test suite to be used with gentx tests. @@ -42,6 +38,8 @@ type GenTxTestSuite struct { ctx sdk.Context app *simapp.SimApp encodingConfig simappparams.EncodingConfig + + msg1, msg2 *stakingtypes.MsgCreateValidator } func (suite *GenTxTestSuite) SetupTest() { @@ -49,8 +47,17 @@ func (suite *GenTxTestSuite) SetupTest() { app := simapp.Setup(checkTx) suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{}) suite.app = app - suite.encodingConfig = simapp.MakeEncodingConfig() + + var err error + amount := sdk.NewInt64Coin(sdk.DefaultBondDenom, 50) + one := sdk.OneInt() + suite.msg1, err = stakingtypes.NewMsgCreateValidator( + sdk.ValAddress(pk1.Address()), pk1, amount, desc, comm, one) + suite.NoError(err) + suite.msg2, err = stakingtypes.NewMsgCreateValidator( + sdk.ValAddress(pk2.Address()), pk1, amount, desc, comm, one) + suite.NoError(err) } func (suite *GenTxTestSuite) setAccountBalance(addr sdk.AccAddress, amount int64) json.RawMessage { @@ -83,7 +90,7 @@ func (suite *GenTxTestSuite) TestSetGenTxsInAppGenesisState() { { "one genesis transaction", func() { - err := txBuilder.SetMsgs(msg1) + err := txBuilder.SetMsgs(suite.msg1) suite.Require().NoError(err) tx := txBuilder.GetTx() genTxs = []sdk.Tx{tx} @@ -93,7 +100,7 @@ func (suite *GenTxTestSuite) TestSetGenTxsInAppGenesisState() { { "two genesis transactions", func() { - err := txBuilder.SetMsgs(msg1, msg2) + err := txBuilder.SetMsgs(suite.msg1, suite.msg2) suite.Require().NoError(err) tx := txBuilder.GetTx() genTxs = []sdk.Tx{tx} @@ -211,7 +218,7 @@ func (suite *GenTxTestSuite) TestDeliverGenTxs() { { "no signature supplied", func() { - err := txBuilder.SetMsgs(msg1) + err := txBuilder.SetMsgs(suite.msg1) suite.Require().NoError(err) genTxs = make([]json.RawMessage, 1) diff --git a/x/genutil/types/genesis_state_test.go b/x/genutil/types/genesis_state_test.go index 475a9478f2f1..ce0015420d0d 100644 --- a/x/genutil/types/genesis_state_test.go +++ b/x/genutil/types/genesis_state_test.go @@ -37,16 +37,17 @@ func TestValidateGenesisMultipleMessages(t *testing.T) { desc := stakingtypes.NewDescription("testname", "", "", "", "") comm := stakingtypes.CommissionRates{} - msg1 := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk1.Address()), pk1, + msg1, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk1.Address()), pk1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, sdk.OneInt()) + require.NoError(t, err) - msg2 := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk2.Address()), pk2, + msg2, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk2.Address()), pk2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, sdk.OneInt()) + require.NoError(t, err) txGen := simapp.MakeEncodingConfig().TxConfig txBuilder := txGen.NewTxBuilder() - err := txBuilder.SetMsgs(msg1, msg2) - require.NoError(t, err) + require.NoError(t, txBuilder.SetMsgs(msg1, msg2)) tx := txBuilder.GetTx() genesisState := types.NewGenesisStateFromTx(txGen.TxJSONEncoder(), []sdk.Tx{tx}) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 70a172ee1b7a..bfda1b3590b6 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -298,9 +298,7 @@ func TestProposalPassedEndblocker(t *testing.T) { proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))} newDepositMsg := types.NewMsgDeposit(addrs[0], proposal.ProposalId, proposalCoins) - res, err := handler(ctx, newDepositMsg) - require.NoError(t, err) - require.NotNil(t, res) + handleAndCheck(t, handler, ctx, newDepositMsg) macc = app.GovKeeper.GetGovernanceAccount(ctx) require.NotNil(t, macc) @@ -330,9 +328,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { SortAddresses(addrs) - handler := gov.NewHandler(app.GovKeeper) stakingHandler := staking.NewHandler(app.StakingKeeper) - header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -350,9 +346,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { proposalCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))) newDepositMsg := types.NewMsgDeposit(addrs[0], proposal.ProposalId, proposalCoins) - res, err := handler(ctx, newDepositMsg) - require.NoError(t, err) - require.NotNil(t, res) + handleAndCheck(t, gov.NewHandler(app.GovKeeper), ctx, newDepositMsg) err = app.GovKeeper.AddVote(ctx, proposal.ProposalId, addrs[0], types.OptionYes) require.NoError(t, err) diff --git a/x/gov/common_test.go b/x/gov/common_test.go index aef391d794aa..d8648b478adb 100644 --- a/x/gov/common_test.go +++ b/x/gov/common_test.go @@ -82,15 +82,18 @@ func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") for i := 0; i < len(addrs); i++ { - valTokens := sdk.TokensFromConsensusPower(powerAmt[i]) - valCreateMsg := stakingtypes.NewMsgCreateValidator( + valCreateMsg, err := stakingtypes.NewMsgCreateValidator( addrs[i], pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), TestDescription, TestCommissionRates, sdk.OneInt(), ) - - res, err := stakingHandler(ctx, valCreateMsg) require.NoError(t, err) - require.NotNil(t, res) + handleAndCheck(t, stakingHandler, ctx, valCreateMsg) } } + +func handleAndCheck(t *testing.T, h sdk.Handler, ctx sdk.Context, msg sdk.Msg) { + res, err := h(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) +} diff --git a/x/slashing/abci_test.go b/x/slashing/abci_test.go index 484870719bad..2d5430700c4e 100644 --- a/x/slashing/abci_test.go +++ b/x/slashing/abci_test.go @@ -11,8 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing" - slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -22,20 +22,15 @@ func TestBeginBlocker(t *testing.T) { pks := simapp.CreateTestPubKeys(1) simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200)) - - power := int64(100) - amt := sdk.TokensFromConsensusPower(power) addr, pk := sdk.ValAddress(pks[0].Address()), pks[0] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // bond the validator - res, err := staking.NewHandler(app.StakingKeeper)(ctx, slashingkeeper.NewTestMsgCreateValidator(addr, pk, amt)) - require.NoError(t, err) - require.NotNil(t, res) - + amt := tstaking.CreateValidatorWithValPower(addr, pk, 100, true) staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), - sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, slashingkeeper.InitTokens.Sub(amt))), + sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 3e4735e43adf..f16bfb36f11a 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -63,13 +63,14 @@ func TestSlashingMsgs(t *testing.T) { description := stakingtypes.NewDescription("foo_moniker", "", "", "", "") commission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - createValidatorMsg := stakingtypes.NewMsgCreateValidator( + createValidatorMsg, err := stakingtypes.NewMsgCreateValidator( sdk.ValAddress(addr1), valKey.PubKey(), bondCoin, description, commission, sdk.OneInt(), ) + require.NoError(t, err) header := tmproto.Header{Height: app.LastBlockHeight() + 1} txGen := simapp.MakeEncodingConfig().TxConfig - _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1) + _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin.Sub(bondCoin)}) diff --git a/x/slashing/genesis_test.go b/x/slashing/genesis_test.go index 8b9b9a4639c5..b9241f0246ca 100644 --- a/x/slashing/genesis_test.go +++ b/x/slashing/genesis_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing/testslashing" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -18,7 +18,7 @@ func TestExportAndInitGenesis(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) + app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.TokensFromConsensusPower(200)) @@ -31,7 +31,7 @@ func TestExportAndInitGenesis(t *testing.T) { app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1]), info2) genesisState := slashing.ExportGenesis(ctx, app.SlashingKeeper) - require.Equal(t, genesisState.Params, keeper.TestParams()) + require.Equal(t, genesisState.Params, testslashing.TestParams()) require.Len(t, genesisState.SigningInfos, 2) require.Equal(t, genesisState.SigningInfos[0].ValidatorSigningInfo, info1) diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index 3e5bba742c5d..c392bde58580 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -6,18 +6,18 @@ import ( "testing" "time" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - "github.com/cosmos/cosmos-sdk/testutil/testdata" - "github.com/stretchr/testify/require" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing/testslashing" "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -25,29 +25,23 @@ func TestCannotUnjailUnlessJailed(t *testing.T) { // initial setup app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - pks := simapp.CreateTestPubKeys(1) simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200)) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) slh := slashing.NewHandler(app.SlashingKeeper) - amt := sdk.TokensFromConsensusPower(100) addr, val := sdk.ValAddress(pks[0].Address()), pks[0] - msg := keeper.NewTestMsgCreateValidator(addr, val, amt) - res, err := staking.NewHandler(app.StakingKeeper)(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - + amt := tstaking.CreateValidatorWithValPower(addr, val, 100, true) staking.EndBlocker(ctx, app.StakingKeeper) - require.Equal( t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), - sdk.Coins{sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, keeper.InitTokens.Sub(amt))}, + sdk.Coins{sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))}, ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) // assert non-jailed validator can't be unjailed - res, err = slh(ctx, types.NewMsgUnjail(addr)) + res, err := slh(ctx, types.NewMsgUnjail(addr)) require.Error(t, err) require.Nil(t, res) require.True(t, errors.Is(types.ErrValidatorNotJailed, err)) @@ -60,33 +54,25 @@ func TestCannotUnjailUnlessMeetMinSelfDelegation(t *testing.T) { pks := simapp.CreateTestPubKeys(1) simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200)) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) slh := slashing.NewHandler(app.SlashingKeeper) - amtInt := int64(100) - addr, val, amt := sdk.ValAddress(pks[0].Address()), pks[0], sdk.TokensFromConsensusPower(amtInt) - msg := keeper.NewTestMsgCreateValidator(addr, val, amt) + addr, val := sdk.ValAddress(pks[0].Address()), pks[0] + amt := sdk.TokensFromConsensusPower(100) + msg := tstaking.CreateValidatorMsg(addr, val, amt.Int64()) msg.MinSelfDelegation = amt - - res, err := staking.NewHandler(app.StakingKeeper)(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msg, true) staking.EndBlocker(ctx, app.StakingKeeper) - require.Equal( t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), - sdk.Coins{sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, keeper.InitTokens.Sub(amt))}, + sdk.Coins{sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))}, ) - unbondAmt := sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, sdk.OneInt()) - undelegateMsg := stakingtypes.NewMsgUndelegate(sdk.AccAddress(addr), addr, unbondAmt) - res, err = staking.NewHandler(app.StakingKeeper)(ctx, undelegateMsg) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.Undelegate(sdk.AccAddress(addr), addr, sdk.OneInt(), true) require.True(t, app.StakingKeeper.Validator(ctx, addr).IsJailed()) // assert non-jailed validator can't be unjailed - res, err = slh(ctx, types.NewMsgUnjail(addr)) + res, err := slh(ctx, types.NewMsgUnjail(addr)) require.Error(t, err) require.Nil(t, res) require.True(t, errors.Is(types.ErrSelfDelegationTooLowToUnjail, err)) @@ -96,25 +82,17 @@ func TestJailedValidatorDelegations(t *testing.T) { // initial setup app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Unix(0, 0)}) - pks := simapp.CreateTestPubKeys(3) + simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(20)) - app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) + app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) stakingParams := app.StakingKeeper.GetParams(ctx) app.StakingKeeper.SetParams(ctx, stakingParams) - - // create a validator - bondAmount := sdk.TokensFromConsensusPower(10) - valPubKey := pks[1] valAddr, consAddr := sdk.ValAddress(pks[1].Address()), sdk.ConsAddress(pks[0].Address()) - msgCreateVal := keeper.NewTestMsgCreateValidator(valAddr, valPubKey, bondAmount) - res, err := staking.NewHandler(app.StakingKeeper)(ctx, msgCreateVal) - require.NoError(t, err) - require.NotNil(t, res) - - // end block + amt := tstaking.CreateValidatorWithValPower(valAddr, pks[1], 10, true) staking.EndBlocker(ctx, app.StakingKeeper) // set dummy signing info @@ -123,20 +101,12 @@ func TestJailedValidatorDelegations(t *testing.T) { // delegate tokens to the validator delAddr := sdk.AccAddress(pks[2].Address()) - msgDelegate := keeper.NewTestMsgDelegate(delAddr, valAddr, bondAmount) - res, err = staking.NewHandler(app.StakingKeeper)(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) - - unbondAmt := sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, bondAmount) + tstaking.Delegate(delAddr, valAddr, amt.Int64()) // unbond validator total self-delegations (which should jail the validator) - msgUndelegate := stakingtypes.NewMsgUndelegate(sdk.AccAddress(valAddr), valAddr, unbondAmt) - res, err = staking.NewHandler(app.StakingKeeper)(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) - - _, err = app.StakingKeeper.CompleteUnbonding(ctx, sdk.AccAddress(valAddr), valAddr) + valAcc := sdk.AccAddress(valAddr) + tstaking.Undelegate(valAcc, valAddr, amt, true) + _, err := app.StakingKeeper.CompleteUnbonding(ctx, sdk.AccAddress(valAddr), valAddr) require.Nil(t, err, "expected complete unbonding validator to be ok, got: %v", err) // verify validator still exists and is jailed @@ -145,15 +115,12 @@ func TestJailedValidatorDelegations(t *testing.T) { require.True(t, validator.IsJailed()) // verify the validator cannot unjail itself - res, err = slashing.NewHandler(app.SlashingKeeper)(ctx, types.NewMsgUnjail(valAddr)) + res, err := slashing.NewHandler(app.SlashingKeeper)(ctx, types.NewMsgUnjail(valAddr)) require.Error(t, err) require.Nil(t, res) // self-delegate to validator - msgSelfDelegate := keeper.NewTestMsgDelegate(sdk.AccAddress(valAddr), valAddr, bondAmount) - res, err = staking.NewHandler(app.StakingKeeper)(ctx, msgSelfDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Delegate(valAcc, valAddr, amt.Int64()) // verify the validator can now unjail itself res, err = slashing.NewHandler(app.SlashingKeeper)(ctx, types.NewMsgUnjail(valAddr)) @@ -177,26 +144,21 @@ func TestHandleAbsentValidator(t *testing.T) { // initial setup app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Unix(0, 0)}) - pks := simapp.CreateTestPubKeys(1) simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200)) - app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) + app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) power := int64(100) - amt := sdk.TokensFromConsensusPower(power) addr, val := sdk.ValAddress(pks[0].Address()), pks[0] - sh := staking.NewHandler(app.StakingKeeper) slh := slashing.NewHandler(app.SlashingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) - res, err := sh(ctx, keeper.NewTestMsgCreateValidator(addr, val, amt)) - require.NoError(t, err) - require.NotNil(t, res) - + amt := tstaking.CreateValidatorWithValPower(addr, val, power, true) staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), - sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, keeper.InitTokens.Sub(amt))), + sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) @@ -274,7 +236,7 @@ func TestHandleAbsentValidator(t *testing.T) { require.Equal(t, amt.Int64()-slashAmt, validator.GetTokens().Int64()) // unrevocation should fail prior to jail expiration - res, err = slh(ctx, types.NewMsgUnjail(addr)) + res, err := slh(ctx, types.NewMsgUnjail(addr)) require.Error(t, err) require.Nil(t, res) diff --git a/x/slashing/init_test.go b/x/slashing/init_test.go new file mode 100644 index 000000000000..25a38a2d5e53 --- /dev/null +++ b/x/slashing/init_test.go @@ -0,0 +1,9 @@ +package slashing_test + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + InitTokens = sdk.TokensFromConsensusPower(200) +) diff --git a/x/slashing/keeper/grpc_query_test.go b/x/slashing/keeper/grpc_query_test.go index 199fd9b05e24..d923b822c76c 100644 --- a/x/slashing/keeper/grpc_query_test.go +++ b/x/slashing/keeper/grpc_query_test.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing/testslashing" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -33,7 +33,7 @@ func (suite *SlashingTestSuite) SetupTest() { app.AccountKeeper.SetParams(ctx, authtypes.DefaultParams()) app.BankKeeper.SetParams(ctx, banktypes.DefaultParams()) - app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) + app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.TokensFromConsensusPower(200)) @@ -60,7 +60,7 @@ func (suite *SlashingTestSuite) TestGRPCQueryParams() { paramsResp, err := queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{}) suite.NoError(err) - suite.Equal(keeper.TestParams(), paramsResp.Params) + suite.Equal(testslashing.TestParams(), paramsResp.Params) } func (suite *SlashingTestSuite) TestGRPCSigningInfo() { diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index d8e49a11c503..035090341cf2 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -9,8 +9,9 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing/testslashing" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -22,19 +23,15 @@ func TestUnJailNotBonded(t *testing.T) { p.MaxValidators = 5 app.StakingKeeper.SetParams(ctx, p) - amt := sdk.TokensFromConsensusPower(100) - sh := staking.NewHandler(app.StakingKeeper) - addrDels := simapp.AddTestAddrsIncremental(app, ctx, 6, sdk.TokensFromConsensusPower(200)) valAddrs := simapp.ConvertAddrsToValAddrs(addrDels) pks := simapp.CreateTestPubKeys(6) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create max (5) validators all with the same power for i := uint32(0); i < p.MaxValidators; i++ { addr, val := valAddrs[i], pks[i] - res, err := sh(ctx, keeper.NewTestMsgCreateValidator(addr, val, amt)) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.CreateValidatorWithValPower(addr, val, 100, true) } staking.EndBlocker(ctx, app.StakingKeeper) @@ -42,45 +39,33 @@ func TestUnJailNotBonded(t *testing.T) { // create a 6th validator with less power than the cliff validator (won't be bonded) addr, val := valAddrs[5], pks[5] - createValMsg := keeper.NewTestMsgCreateValidator(addr, val, sdk.TokensFromConsensusPower(50)) - createValMsg.MinSelfDelegation = sdk.TokensFromConsensusPower(50) - res, err := sh(ctx, createValMsg) - require.NoError(t, err) - require.NotNil(t, res) + amt := sdk.TokensFromConsensusPower(50) + msg := tstaking.CreateValidatorMsg(addr, val, amt.Int64()) + msg.MinSelfDelegation = amt + tstaking.Handle(msg, true) staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - validator, ok := app.StakingKeeper.GetValidator(ctx, addr) - require.True(t, ok) - require.False(t, validator.Jailed) - require.Equal(t, stakingtypes.BondStatusUnbonded, validator.GetStatus().String()) + tstaking.CheckValidator(addr, stakingtypes.Unbonded, false) // unbond below minimum self-delegation - msgUnbond := stakingtypes.NewMsgUndelegate(sdk.AccAddress(addr), addr, sdk.NewCoin(p.BondDenom, sdk.TokensFromConsensusPower(1))) - res, err = sh(ctx, msgUnbond) - require.NoError(t, err) - require.NotNil(t, res) + require.Equal(t, p.BondDenom, tstaking.Denom) + tstaking.Undelegate(sdk.AccAddress(addr), addr, sdk.TokensFromConsensusPower(1), true) staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) // verify that validator is jailed - validator, ok = app.StakingKeeper.GetValidator(ctx, addr) - require.True(t, ok) - require.True(t, validator.Jailed) + tstaking.CheckValidator(addr, -1, true) // verify we cannot unjail (yet) require.Error(t, app.SlashingKeeper.Unjail(ctx, addr)) staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - // bond to meet minimum self-delegation - msgBond := stakingtypes.NewMsgDelegate(sdk.AccAddress(addr), addr, sdk.NewCoin(p.BondDenom, sdk.TokensFromConsensusPower(1))) - res, err = sh(ctx, msgBond) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.DelegateWithPower(sdk.AccAddress(addr), addr, 1) staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) @@ -88,9 +73,7 @@ func TestUnJailNotBonded(t *testing.T) { // verify we can immediately unjail require.NoError(t, app.SlashingKeeper.Unjail(ctx, addr)) - validator, ok = app.StakingKeeper.GetValidator(ctx, addr) - require.True(t, ok) - require.False(t, validator.Jailed) + tstaking.CheckValidator(addr, -1, false) } // Test a new validator entering the validator set @@ -103,20 +86,14 @@ func TestHandleNewValidator(t *testing.T) { addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200)) valAddrs := simapp.ConvertAddrsToValAddrs(addrDels) pks := simapp.CreateTestPubKeys(1) - addr, val := valAddrs[0], pks[0] - amt := sdk.TokensFromConsensusPower(100) - sh := staking.NewHandler(app.StakingKeeper) - + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(app.SlashingKeeper.SignedBlocksWindow(ctx) + 1) // Validator created - res, err := sh(ctx, keeper.NewTestMsgCreateValidator(addr, val, amt)) - require.NoError(t, err) - require.NotNil(t, res) + amt := tstaking.CreateValidatorWithValPower(addr, val, 100, true) staking.EndBlocker(ctx, app.StakingKeeper) - require.Equal( t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), @@ -149,18 +126,15 @@ func TestHandleAlreadyJailed(t *testing.T) { // initial setup app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - power := int64(100) - amt := sdk.TokensFromConsensusPower(power) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200)) valAddrs := simapp.ConvertAddrsToValAddrs(addrDels) pks := simapp.CreateTestPubKeys(1) - addr, val := valAddrs[0], pks[0] - sh := staking.NewHandler(app.StakingKeeper) - res, err := sh(ctx, keeper.NewTestMsgCreateValidator(addr, val, amt)) - require.NoError(t, err) - require.NotNil(t, res) + power := int64(100) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) + + amt := tstaking.CreateValidatorWithValPower(addr, val, power, true) staking.EndBlocker(ctx, app.StakingKeeper) @@ -206,7 +180,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // TestParams set the SignedBlocksWindow to 1000 and MaxMissedBlocksPerWindow to 500 app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) + app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) params := app.StakingKeeper.GetParams(ctx) params.MaxValidators = 1 @@ -216,14 +190,12 @@ func TestValidatorDippingInAndOut(t *testing.T) { pks := simapp.CreateTestPubKeys(3) simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200)) - amt := sdk.TokensFromConsensusPower(power) addr, val := pks[0].Address(), pks[0] consAddr := sdk.ConsAddress(addr) - sh := staking.NewHandler(app.StakingKeeper) - res, err := sh(ctx, keeper.NewTestMsgCreateValidator(sdk.ValAddress(addr), val, amt)) - require.NoError(t, err) - require.NotNil(t, res) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) + valAddr := sdk.ValAddress(addr) + tstaking.CreateValidatorWithValPower(valAddr, val, power, true) staking.EndBlocker(ctx, app.StakingKeeper) // 100 first blocks OK @@ -234,30 +206,21 @@ func TestValidatorDippingInAndOut(t *testing.T) { } // kick first validator out of validator set - newAmt := sdk.TokensFromConsensusPower(101) - res, err = sh(ctx, keeper.NewTestMsgCreateValidator(sdk.ValAddress(pks[1].Address()), pks[1], newAmt)) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.CreateValidatorWithValPower(sdk.ValAddress(pks[1].Address()), pks[1], 101, true) validatorUpdates := staking.EndBlocker(ctx, app.StakingKeeper) require.Equal(t, 2, len(validatorUpdates)) - validator, _ := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addr)) - require.Equal(t, stakingtypes.Unbonding, validator.Status) + tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, false) // 600 more blocks happened - height = int64(700) + height = 700 ctx = ctx.WithBlockHeight(height) // validator added back in - delTokens := sdk.TokensFromConsensusPower(50) - res, err = sh(ctx, keeper.NewTestMsgDelegate(sdk.AccAddress(pks[2].Address()), sdk.ValAddress(pks[0].Address()), delTokens)) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), sdk.ValAddress(pks[0].Address()), 50) validatorUpdates = staking.EndBlocker(ctx, app.StakingKeeper) require.Equal(t, 2, len(validatorUpdates)) - validator, _ = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addr)) - require.Equal(t, stakingtypes.Bonded, validator.Status) + tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) newPower := int64(150) // validator misses a block @@ -265,8 +228,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { height++ // shouldn't be jailed/kicked yet - validator, _ = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addr)) - require.Equal(t, stakingtypes.Bonded, validator.Status) + tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) // validator misses 500 more blocks, 501 total latest := height @@ -277,8 +239,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // should now be jailed & kicked staking.EndBlocker(ctx, app.StakingKeeper) - validator, _ = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addr)) - require.Equal(t, stakingtypes.Unbonding, validator.Status) + tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, true) // check all the signing information signInfo, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, consAddr) @@ -302,8 +263,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator should not be kicked since we reset counter/array when it was jailed staking.EndBlocker(ctx, app.StakingKeeper) - validator, _ = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addr)) - require.Equal(t, stakingtypes.Bonded, validator.Status) + tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) // validator misses 501 blocks latest = height @@ -314,6 +274,5 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator should now be jailed & kicked staking.EndBlocker(ctx, app.StakingKeeper) - validator, _ = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addr)) - require.Equal(t, stakingtypes.Unbonding, validator.Status) + tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, true) } diff --git a/x/slashing/keeper/querier_test.go b/x/slashing/keeper/querier_test.go index 004ae1e8541c..bda5fe4bc5f6 100644 --- a/x/slashing/keeper/querier_test.go +++ b/x/slashing/keeper/querier_test.go @@ -11,13 +11,14 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing/testslashing" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) func TestNewQuerier(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) + app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino()) querier := keeper.NewQuerier(app.SlashingKeeper, legacyQuerierCdc.LegacyAmino) @@ -35,7 +36,7 @@ func TestQueryParams(t *testing.T) { legacyQuerierCdc := codec.NewAminoCodec(cdc) app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) - app.SlashingKeeper.SetParams(ctx, keeper.TestParams()) + app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) querier := keeper.NewQuerier(app.SlashingKeeper, legacyQuerierCdc.LegacyAmino) diff --git a/x/slashing/keeper/test_common.go b/x/slashing/keeper/test_common.go deleted file mode 100644 index f9edb4febec7..000000000000 --- a/x/slashing/keeper/test_common.go +++ /dev/null @@ -1,41 +0,0 @@ -package keeper - -// DONTCOVER - -import ( - "github.com/tendermint/tendermint/crypto" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// TODO remove dependencies on staking (should only refer to validator set type from sdk) - -var ( - InitTokens = sdk.TokensFromConsensusPower(200) -) - -// Have to change these parameters for tests -// lest the tests take forever -func TestParams() types.Params { - params := types.DefaultParams() - params.SignedBlocksWindow = 1000 - params.DowntimeJailDuration = 60 * 60 - - return params -} - -func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) *stakingtypes.MsgCreateValidator { - commission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - - return stakingtypes.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt), - stakingtypes.Description{}, commission, sdk.OneInt(), - ) -} - -func NewTestMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, delAmount sdk.Int) *stakingtypes.MsgDelegate { - amount := sdk.NewCoin(sdk.DefaultBondDenom, delAmount) - return stakingtypes.NewMsgDelegate(delAddr, valAddr, amount) -} diff --git a/x/slashing/testslashing/params.go b/x/slashing/testslashing/params.go new file mode 100644 index 000000000000..dac3f23c5c5e --- /dev/null +++ b/x/slashing/testslashing/params.go @@ -0,0 +1,16 @@ +package testslashing + +import ( + "github.com/cosmos/cosmos-sdk/x/slashing/types" +) + +// TestParams construct default slashing params for tests. +// Have to change these parameters for tests +// lest the tests take forever +func TestParams() types.Params { + params := types.DefaultParams() + params.SignedBlocksWindow = 1000 + params.DowntimeJailDuration = 60 * 60 + + return params +} diff --git a/x/staking/app_test.go b/x/staking/app_test.go index 2f33961021a0..1c60ec50278d 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -65,13 +65,14 @@ func TestStakingMsgs(t *testing.T) { // create validator description := types.NewDescription("foo_moniker", "", "", "", "") - createValidatorMsg := types.NewMsgCreateValidator( + createValidatorMsg, err := types.NewMsgCreateValidator( sdk.ValAddress(addr1), valKey.PubKey(), bondCoin, description, commissionRates, sdk.OneInt(), ) + require.NoError(t, err) header := tmproto.Header{Height: app.LastBlockHeight() + 1} txGen := simapp.MakeEncodingConfig().TxConfig - _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1) + _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin.Sub(bondCoin)}) diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index fcd76ca8ffc8..ab486c5a9841 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -343,9 +343,12 @@ func NewBuildCreateValidatorMsg(clientCtx client.Context, txf tx.Factory, fs *fl return txf, nil, types.ErrMinSelfDelegationInvalid } - msg := types.NewMsgCreateValidator( + msg, err := types.NewMsgCreateValidator( sdk.ValAddress(valAddr), pk, amount, description, commissionRates, minSelfDelegation, ) + if err != nil { + return txf, nil, err + } if err := msg.ValidateBasic(); err != nil { return txf, nil, err } @@ -550,10 +553,12 @@ func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorC return txBldr, nil, types.ErrMinSelfDelegationInvalid } - msg := types.NewMsgCreateValidator( + msg, err := types.NewMsgCreateValidator( sdk.ValAddress(valAddr), pk, amount, description, commissionRates, minSelfDelegation, ) - + if err != nil { + return txBldr, msg, err + } if generateOnly { ip := config.IP nodeID := config.NodeID diff --git a/x/staking/common_test.go b/x/staking/common_test.go index f7bca291b869..30072c7b58ef 100644 --- a/x/staking/common_test.go +++ b/x/staking/common_test.go @@ -1,7 +1,6 @@ package staking_test import ( - "github.com/tendermint/tendermint/crypto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" @@ -28,17 +27,6 @@ var ( PKs = simapp.CreateTestPubKeys(500) ) -func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) *types.MsgCreateValidator { - return types.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt), types.Description{}, commissionRates, sdk.OneInt(), - ) -} - -func NewTestMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt sdk.Int) *types.MsgDelegate { - amount := sdk.NewCoin(sdk.DefaultBondDenom, amt) - return types.NewMsgDelegate(delAddr, valAddr, amount) -} - // getBaseSimappWithCustomKeeper Returns a simapp with custom StakingKeeper // to avoid messing with the hooks. func getBaseSimappWithCustomKeeper() (*codec.LegacyAmino, *simapp.SimApp, sdk.Context) { diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index 51a7323ca0ab..22c773339131 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -19,6 +19,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/golang/protobuf/proto" ) @@ -43,19 +44,12 @@ func bootstrapHandlerGenesisTest(t *testing.T, power int64, numAddrs int, accAmo func TestValidatorByPowerIndex(t *testing.T) { initPower := int64(1000000) - initBond := sdk.TokensFromConsensusPower(initPower) - app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 10, 10000000000000) - validatorAddr, validatorAddr3 := valAddrs[0], valAddrs[1] - - handler := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], initBond) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + initBond := tstaking.CreateValidatorWithValPower(validatorAddr, PKs[0], initPower, true) // must end-block updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -74,10 +68,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.True(t, keeper.ValidatorByPowerIndexExists(ctx, app.StakingKeeper, power)) // create a second validator keep it bonded - msgCreateValidator = NewTestMsgCreateValidator(validatorAddr3, PKs[2], initBond) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.CreateValidatorWithValPower(validatorAddr3, PKs[2], initPower, true) // must end-block updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -110,15 +101,10 @@ func TestValidatorByPowerIndex(t *testing.T) { // unbond self-delegation totalBond := validator.TokensFromShares(bond.GetShares()).TruncateInt() - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, totalBond) - msgUndelegate := types.NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt) - - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, totalBond, true) var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) ctx = ctx.WithBlockTime(resData.CompletionTime) @@ -135,22 +121,14 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { initPower := int64(1000000) app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 10, 10000000000000) - handler := staking.NewHandler(app.StakingKeeper) - addr1, addr2 := valAddrs[0], valAddrs[1] pk1, pk2 := PKs[0], PKs[1] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator1 := NewTestMsgCreateValidator(addr1, pk1, valTokens) - res, err := handler(ctx, msgCreateValidator1) - require.NoError(t, err) - require.NotNil(t, res) - + valTokens := tstaking.CreateValidatorWithValPower(addr1, pk1, 10, true) app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) - validator, found := app.StakingKeeper.GetValidator(ctx, addr1) - require.True(t, found) - assert.Equal(t, types.Bonded, validator.Status) + validator := tstaking.CheckValidator(addr1, types.Bonded, false) assert.Equal(t, addr1.String(), validator.OperatorAddress) assert.Equal(t, pk1.(cryptotypes.IntoTmPubKey).AsTmPubKey(), validator.GetConsPubKey()) assert.Equal(t, valTokens, validator.BondedTokens()) @@ -158,31 +136,19 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { assert.Equal(t, types.Description{}, validator.Description) // two validators can't have the same operator address - msgCreateValidator2 := NewTestMsgCreateValidator(addr1, pk2, valTokens) - res, err = handler(ctx, msgCreateValidator2) - require.Error(t, err) - require.Nil(t, res) + tstaking.CreateValidator(addr1, pk2, valTokens.Int64(), false) // two validators can't have the same pubkey - msgCreateValidator3 := NewTestMsgCreateValidator(addr2, pk1, valTokens) - res, err = handler(ctx, msgCreateValidator3) - require.Error(t, err) - require.Nil(t, res) + tstaking.CreateValidator(addr2, pk1, valTokens.Int64(), false) // must have different pubkey and operator - msgCreateValidator4 := NewTestMsgCreateValidator(addr2, pk2, valTokens) - res, err = handler(ctx, msgCreateValidator4) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.CreateValidator(addr2, pk2, valTokens.Int64(), true) // must end-block updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 1, len(updates)) - validator, found = app.StakingKeeper.GetValidator(ctx, addr2) - - require.True(t, found) - assert.Equal(t, types.Bonded, validator.Status) + validator = tstaking.CheckValidator(addr2, types.Bonded, false) assert.Equal(t, addr2.String(), validator.OperatorAddress) assert.Equal(t, pk2.(cryptotypes.IntoTmPubKey).AsTmPubKey(), validator.GetConsPubKey()) assert.True(sdk.IntEq(t, valTokens, validator.Tokens)) @@ -192,78 +158,59 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { func TestInvalidPubKeyTypeMsgCreateValidator(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 1, 1000) - handler := staking.NewHandler(app.StakingKeeper) ctx = ctx.WithConsensusParams(&abci.ConsensusParams{ Validator: &tmproto.ValidatorParams{PubKeyTypes: []string{tmtypes.ABCIPubKeyTypeEd25519}}, }) addr := valAddrs[0] invalidPk := secp256k1.GenPrivKey().PubKey() + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // invalid pukKey type should not be allowed - msgCreateValidator := NewTestMsgCreateValidator(addr, invalidPk, sdk.NewInt(10)) - res, err := handler(ctx, msgCreateValidator) - require.Error(t, err) - require.Nil(t, res) + tstaking.CreateValidator(addr, invalidPk, 10, false) } func TestLegacyValidatorDelegations(t *testing.T) { app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 2, 100000000) - handler := staking.NewHandler(app.StakingKeeper) - bondAmount := sdk.TokensFromConsensusPower(10) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) valAddr := valAddrs[0] valConsPubKey, valConsAddr := PKs[0], sdk.ConsAddress(PKs[0].Address()) delAddr := delAddrs[1] // create validator - msgCreateVal := NewTestMsgCreateValidator(valAddr, valConsPubKey, bondAmount) - res, err := handler(ctx, msgCreateVal) - require.NoError(t, err) - require.NotNil(t, res) + bondAmount := tstaking.CreateValidatorWithValPower(valAddr, valConsPubKey, 10, true) // must end-block updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 1, len(updates)) // verify the validator exists and has the correct attributes - validator, found := app.StakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - require.Equal(t, types.Bonded, validator.Status) + validator := tstaking.CheckValidator(valAddr, types.Bonded, false) require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt()) require.Equal(t, bondAmount, validator.BondedTokens()) // delegate tokens to the validator - msgDelegate := NewTestMsgDelegate(delAddr, valAddr, bondAmount) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Delegate(delAddr, valAddr, bondAmount.Int64()) // verify validator bonded shares - validator, found = app.StakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) + validator = tstaking.CheckValidator(valAddr, types.Bonded, false) require.Equal(t, bondAmount.MulRaw(2), validator.DelegatorShares.RoundInt()) require.Equal(t, bondAmount.MulRaw(2), validator.BondedTokens()) // unbond validator total self-delegations (which should jail the validator) - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, bondAmount) - msgUndelegate := types.NewMsgUndelegate(sdk.AccAddress(valAddr), valAddr, unbondAmt) - - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + res := tstaking.Undelegate(sdk.AccAddress(valAddr), valAddr, bondAmount, true) var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) ctx = ctx.WithBlockTime(resData.CompletionTime) + tstaking.Ctx = ctx staking.EndBlocker(ctx, app.StakingKeeper) // verify the validator record still exists, is jailed, and has correct tokens - validator, found = app.StakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - require.True(t, validator.Jailed) + validator = tstaking.CheckValidator(valAddr, -1, true) require.Equal(t, bondAmount, validator.Tokens) // verify delegation still exists @@ -273,10 +220,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt()) // verify the validator can still self-delegate - msgSelfDelegate := NewTestMsgDelegate(sdk.AccAddress(valAddr), valAddr, bondAmount) - res, err = handler(ctx, msgSelfDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Delegate(sdk.AccAddress(valAddr), valAddr, bondAmount.Int64()) // verify validator bonded shares validator, found = app.StakingKeeper.GetValidator(ctx, valAddr) @@ -288,10 +232,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { app.StakingKeeper.Unjail(ctx, valConsAddr) // verify the validator can now accept delegations - msgDelegate = NewTestMsgDelegate(delAddr, valAddr, bondAmount) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Delegate(delAddr, valAddr, bondAmount.Int64()) // verify validator bonded shares validator, found = app.StakingKeeper.GetValidator(ctx, valAddr) @@ -310,30 +251,22 @@ func TestIncrementsMsgDelegate(t *testing.T) { initPower := int64(1000) initBond := sdk.TokensFromConsensusPower(initPower) app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) params := app.StakingKeeper.GetParams(ctx) - - bondAmount := sdk.TokensFromConsensusPower(10) validatorAddr, delegatorAddr := valAddrs[0], delAddrs[1] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // first create validator - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], bondAmount) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + bondAmount := tstaking.CreateValidatorWithValPower(validatorAddr, PKs[0], 10, true) // apply TM updates app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) - validator, found := app.StakingKeeper.GetValidator(ctx, validatorAddr) - require.True(t, found) - require.Equal(t, types.Bonded, validator.Status) + validator := tstaking.CheckValidator(validatorAddr, types.Bonded, false) require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt()) require.Equal(t, bondAmount, validator.BondedTokens(), "validator: %v", validator) - _, found = app.StakingKeeper.GetDelegation(ctx, delegatorAddr, validatorAddr) - require.False(t, found) + tstaking.CheckDelegator(delegatorAddr, validatorAddr, false) bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found) @@ -342,15 +275,10 @@ func TestIncrementsMsgDelegate(t *testing.T) { bondedTokens := app.StakingKeeper.TotalBondedTokens(ctx) require.Equal(t, bondAmount.Int64(), bondedTokens.Int64()) - // just send the same msgbond multiple times - msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, bondAmount) - for i := int64(0); i < 5; i++ { ctx = ctx.WithBlockHeight(i) - - res, err := handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Ctx = ctx + tstaking.Delegate(delegatorAddr, validatorAddr, bondAmount.Int64()) //Check that the accounts and the bond account have the appropriate values validator, found := app.StakingKeeper.GetValidator(ctx, validatorAddr) @@ -384,14 +312,12 @@ func TestEditValidatorDecreaseMinSelfDelegation(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 1, 1000000000) validatorAddr := valAddrs[0] - handler := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], initBond) + msgCreateValidator := tstaking.CreateValidatorMsg(validatorAddr, PKs[0], initBond.Int64()) msgCreateValidator.MinSelfDelegation = sdk.NewInt(2) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgCreateValidator, true) // must end-block updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -407,9 +333,7 @@ func TestEditValidatorDecreaseMinSelfDelegation(t *testing.T) { newMinSelfDelegation := sdk.OneInt() msgEditValidator := types.NewMsgEditValidator(validatorAddr, types.Description{}, nil, &newMinSelfDelegation) - res, err = handler(ctx, msgEditValidator) - require.Error(t, err) - require.Nil(t, res) + tstaking.Handle(msgEditValidator, false) } func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) { @@ -418,15 +342,12 @@ func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 2, 1000000000) validatorAddr := valAddrs[0] - - handler := staking.NewHandler(app.StakingKeeper) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create validator - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], initBond) + msgCreateValidator := tstaking.CreateValidatorMsg(validatorAddr, PKs[0], initBond.Int64()) msgCreateValidator.MinSelfDelegation = sdk.NewInt(2) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgCreateValidator, true) // must end-block updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -442,36 +363,25 @@ func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) { newMinSelfDelegation := initBond.Add(sdk.OneInt()) msgEditValidator := types.NewMsgEditValidator(validatorAddr, types.Description{}, nil, &newMinSelfDelegation) - res, err = handler(ctx, msgEditValidator) - require.Error(t, err) - require.Nil(t, res) + tstaking.Handle(msgEditValidator, false) } func TestIncrementsMsgUnbond(t *testing.T) { initPower := int64(1000) - initBond := sdk.TokensFromConsensusPower(initPower) app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) params := app.StakingKeeper.GetParams(ctx) denom := params.BondDenom // create validator, delegate validatorAddr, delegatorAddr := valAddrs[0], delAddrs[1] - - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], initBond) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + initBond := tstaking.CreateValidatorWithValPower(validatorAddr, PKs[0], initPower, true) // initial balance amt1 := app.BankKeeper.GetBalance(ctx, delegatorAddr, denom).Amount - msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, initBond) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Delegate(delegatorAddr, validatorAddr, initBond.Int64()) // balance should have been subtracted after delegation amt2 := app.BankKeeper.GetBalance(ctx, delegatorAddr, denom).Amount @@ -492,15 +402,14 @@ func TestIncrementsMsgUnbond(t *testing.T) { numUnbonds := int64(5) for i := int64(0); i < numUnbonds; i++ { - res, err := handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + res := tstaking.Handle(msgUndelegate, true) var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) ctx = ctx.WithBlockTime(resData.CompletionTime) + tstaking.Ctx = ctx staking.EndBlocker(ctx, app.StakingKeeper) // check that the accounts and the bond account have the appropriate values @@ -538,21 +447,12 @@ func TestIncrementsMsgUnbond(t *testing.T) { } for _, c := range errorCases { - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, c) - msgUndelegate := types.NewMsgUndelegate(delegatorAddr, validatorAddr, unbondAmt) - res, err = handler(ctx, msgUndelegate) - require.Error(t, err) - require.Nil(t, res) + tstaking.Undelegate(delegatorAddr, validatorAddr, c, false) } - leftBonded := initBond.Sub(unbondAmt.Amount.Mul(sdk.NewInt(numUnbonds))) - // should be able to unbond remaining - unbondAmt = sdk.NewCoin(sdk.DefaultBondDenom, leftBonded) - msgUndelegate = types.NewMsgUndelegate(delegatorAddr, validatorAddr, unbondAmt) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err, "msgUnbond: %v\nshares: %s\nleftBonded: %s\n", msgUndelegate, unbondAmt, leftBonded) - require.NotNil(t, res, "msgUnbond: %v\nshares: %s\nleftBonded: %s\n", msgUndelegate, unbondAmt, leftBonded) + leftBonded := initBond.Sub(unbondAmt.Amount.Mul(sdk.NewInt(numUnbonds))) + tstaking.Undelegate(delegatorAddr, validatorAddr, leftBonded, true) } func TestMultipleMsgCreateValidator(t *testing.T) { @@ -560,11 +460,10 @@ func TestMultipleMsgCreateValidator(t *testing.T) { initTokens := sdk.TokensFromConsensusPower(initPower) app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 3, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - params := app.StakingKeeper.GetParams(ctx) blockTime := time.Now().UTC() ctx = ctx.WithBlockTime(blockTime) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) validatorAddrs := []sdk.ValAddress{ valAddrs[0], @@ -578,24 +477,19 @@ func TestMultipleMsgCreateValidator(t *testing.T) { } // bond them all + amt := sdk.TokensFromConsensusPower(10) for i, validatorAddr := range validatorAddrs { - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidatorOnBehalfOf := NewTestMsgCreateValidator(validatorAddr, PKs[i], valTokens) - - res, err := handler(ctx, msgCreateValidatorOnBehalfOf) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.CreateValidator(validatorAddr, PKs[i], amt.Int64(), true) // verify that the account is bonded validators := app.StakingKeeper.GetValidators(ctx, 100) require.Equal(t, (i + 1), len(validators)) val := validators[i] - balanceExpd := initTokens.Sub(valTokens) + balanceExpd := initTokens.Sub(amt) balanceGot := app.BankKeeper.GetBalance(ctx, delegatorAddrs[i], params.BondDenom).Amount require.Equal(t, i+1, len(validators), "expected %d validators got %d, validators: %v", i+1, len(validators), validators) - require.Equal(t, valTokens, val.DelegatorShares.RoundInt(), "expected %d shares, got %d", 10, val.DelegatorShares) + require.Equal(t, amt, val.DelegatorShares.RoundInt(), "expected %d shares, got %d", 10, val.DelegatorShares) require.Equal(t, balanceExpd, balanceGot, "expected account to have %d, got %d", balanceExpd, balanceGot) } @@ -606,14 +500,10 @@ func TestMultipleMsgCreateValidator(t *testing.T) { _, found := app.StakingKeeper.GetValidator(ctx, validatorAddr) require.True(t, found) - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10)) - msgUndelegate := types.NewMsgUndelegate(delegatorAddrs[i], validatorAddr, unbondAmt) // remove delegation - res, err := handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + res := tstaking.Undelegate(delegatorAddrs[i], validatorAddr, amt, true) var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) // adds validator into unbonding queue @@ -637,43 +527,30 @@ func TestMultipleMsgCreateValidator(t *testing.T) { func TestMultipleMsgDelegate(t *testing.T) { app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 50, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) validatorAddr, delegatorAddrs := valAddrs[0], delAddrs[1:] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) + var amount int64 = 10 // first make a validator - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], sdk.NewInt(10)) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.CreateValidator(validatorAddr, PKs[0], amount, true) // delegate multiple parties for _, delegatorAddr := range delegatorAddrs { - msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, sdk.NewInt(10)) - res, err := handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) - - // check that the account is bonded - bond, found := app.StakingKeeper.GetDelegation(ctx, delegatorAddr, validatorAddr) - require.True(t, found) - require.NotNil(t, bond, "expected delegatee bond %d to exist", bond) + tstaking.Delegate(delegatorAddr, validatorAddr, 10) + tstaking.CheckDelegator(delegatorAddr, validatorAddr, true) } // unbond them all for _, delegatorAddr := range delegatorAddrs { - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgUndelegate := types.NewMsgUndelegate(delegatorAddr, validatorAddr, unbondAmt) - - res, err := handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + res := tstaking.Undelegate(delegatorAddr, validatorAddr, sdk.NewInt(amount), true) var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) ctx = ctx.WithBlockTime(resData.CompletionTime) staking.EndBlocker(ctx, app.StakingKeeper) + tstaking.Ctx = ctx // check that the account is unbonded _, found := app.StakingKeeper.GetDelegation(ctx, delegatorAddr, validatorAddr) @@ -683,98 +560,67 @@ func TestMultipleMsgDelegate(t *testing.T) { func TestJailValidator(t *testing.T) { app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) validatorAddr, delegatorAddr := valAddrs[0], delAddrs[1] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) + var amt int64 = 10 - // create the validator - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], sdk.NewInt(10)) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - // bond a delegator - msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, sdk.NewInt(10)) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + // create the validator and delegate + tstaking.CreateValidator(validatorAddr, PKs[0], amt, true) + tstaking.Delegate(delegatorAddr, validatorAddr, amt) // unbond the validators bond portion - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgUndelegateValidator := types.NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt) - res, err = handler(ctx, msgUndelegateValidator) - require.NoError(t, err) - require.NotNil(t, res) + unamt := sdk.NewInt(amt) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, unamt, true) var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) ctx = ctx.WithBlockTime(resData.CompletionTime) staking.EndBlocker(ctx, app.StakingKeeper) + tstaking.Ctx = ctx - validator, found := app.StakingKeeper.GetValidator(ctx, validatorAddr) - require.True(t, found) - require.True(t, validator.Jailed, "%v", validator) + tstaking.CheckValidator(validatorAddr, -1, true) // test that the delegator can still withdraw their bonds - msgUndelegateDelegator := types.NewMsgUndelegate(delegatorAddr, validatorAddr, unbondAmt) - - res, err = handler(ctx, msgUndelegateDelegator) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Undelegate(delegatorAddr, validatorAddr, unamt, true) err = proto.Unmarshal(res.Data, &resData) require.NoError(t, err) ctx = ctx.WithBlockTime(resData.CompletionTime) staking.EndBlocker(ctx, app.StakingKeeper) + tstaking.Ctx = ctx // verify that the pubkey can now be reused - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.CreateValidator(validatorAddr, PKs[0], amt, true) } func TestValidatorQueue(t *testing.T) { app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) validatorAddr, delegatorAddr := valAddrs[0], delAddrs[1] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) params.UnbondingTime = 7 * time.Second app.StakingKeeper.SetParams(ctx, params) - // create the validator - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], valTokens) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - // bond a delegator - delTokens := sdk.TokensFromConsensusPower(10) - msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, delTokens) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) - + // create the validator and make a bond + amt := tstaking.CreateValidatorWithValPower(validatorAddr, PKs[0], 10, true) + tstaking.Delegate(delegatorAddr, validatorAddr, amt.Int64()) staking.EndBlocker(ctx, app.StakingKeeper) // unbond the all self-delegation to put validator in unbonding state - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, delTokens) - msgUndelegateValidator := types.NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt) - res, err = handler(ctx, msgUndelegateValidator) - require.NoError(t, err) - require.NotNil(t, res) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, amt, true) var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) - ctx = ctx.WithBlockTime(resData.CompletionTime) - staking.EndBlocker(ctx, app.StakingKeeper) + finishTime := resData.CompletionTime + ctx = tstaking.TurnBlock(finishTime) origHeader := ctx.BlockHeader() validator, found := app.StakingKeeper.GetValidator(ctx, validatorAddr) @@ -782,16 +628,14 @@ func TestValidatorQueue(t *testing.T) { require.True(t, validator.IsUnbonding(), "%v", validator) // should still be unbonding at time 6 seconds later - ctx = ctx.WithBlockTime(origHeader.Time.Add(time.Second * 6)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 6)) validator, found = app.StakingKeeper.GetValidator(ctx, validatorAddr) require.True(t, found) require.True(t, validator.IsUnbonding(), "%v", validator) // should be in unbonded state at time 7 seconds later - ctx = ctx.WithBlockTime(origHeader.Time.Add(time.Second * 7)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 7)) validator, found = app.StakingKeeper.GetValidator(ctx, validatorAddr) require.True(t, found) @@ -800,8 +644,8 @@ func TestValidatorQueue(t *testing.T) { func TestUnbondingPeriod(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 1, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) validatorAddr := valAddrs[0] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) @@ -809,20 +653,11 @@ func TestUnbondingPeriod(t *testing.T) { app.StakingKeeper.SetParams(ctx, params) // create the validator - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], valTokens) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - + amt := tstaking.CreateValidatorWithValPower(validatorAddr, PKs[0], 10, true) staking.EndBlocker(ctx, app.StakingKeeper) // begin unbonding - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10)) - msgUndelegate := types.NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, amt, true) origHeader := ctx.BlockHeader() @@ -835,59 +670,41 @@ func TestUnbondingPeriod(t *testing.T) { require.True(t, found, "should not have unbonded") // cannot complete unbonding at time 6 seconds later - ctx = ctx.WithBlockTime(origHeader.Time.Add(time.Second * 6)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 6)) _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found, "should not have unbonded") // can complete unbonding at time 7 seconds later - ctx = ctx.WithBlockTime(origHeader.Time.Add(time.Second * 7)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 7)) _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.False(t, found, "should have unbonded") } func TestUnbondingFromUnbondingValidator(t *testing.T) { app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) validatorAddr, delegatorAddr := valAddrs[0], delAddrs[1] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) - // create the validator - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], sdk.NewInt(10)) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - // bond a delegator - msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, sdk.NewInt(10)) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + // create the validator and delegate + tstaking.CreateValidator(validatorAddr, PKs[0], 10, true) + tstaking.Delegate(delegatorAddr, validatorAddr, 10) // unbond the validators bond portion - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgUndelegateValidator := types.NewMsgUndelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt) - res, err = handler(ctx, msgUndelegateValidator) - require.NoError(t, err) - require.NotNil(t, res) + unbondAmt := sdk.NewInt(10) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt, true) // change the ctx to Block Time one second before the validator would have unbonded var resData types.MsgUndelegateResponse - err = proto.Unmarshal(res.Data, &resData) + err := proto.Unmarshal(res.Data, &resData) require.NoError(t, err) ctx = ctx.WithBlockTime(resData.CompletionTime.Add(time.Second * -1)) // unbond the delegator from the validator - msgUndelegateDelegator := types.NewMsgUndelegate(delegatorAddr, validatorAddr, unbondAmt) - res, err = handler(ctx, msgUndelegateDelegator) - require.NoError(t, err) - require.NotNil(t, res) + res = tstaking.Undelegate(delegatorAddr, validatorAddr, unbondAmt, true) - ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(app.StakingKeeper.UnbondingTime(ctx))) - - // Run the EndBlocker - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlockTimeDiff(app.StakingKeeper.UnbondingTime(ctx)) + tstaking.Ctx = ctx // Check to make sure that the unbonding delegation is no longer in state // (meaning it was deleted in the above EndBlocker) @@ -897,42 +714,31 @@ func TestUnbondingFromUnbondingValidator(t *testing.T) { func TestRedelegationPeriod(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) validatorAddr, validatorAddr2 := valAddrs[0], valAddrs[1] denom := app.StakingKeeper.GetParams(ctx).BondDenom + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) params.UnbondingTime = 7 * time.Second app.StakingKeeper.SetParams(ctx, params) - - // create the validators - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], sdk.NewInt(10)) - // initial balance amt1 := app.BankKeeper.GetBalance(ctx, sdk.AccAddress(validatorAddr), denom).Amount - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + // create the validators + tstaking.CreateValidator(validatorAddr, PKs[0], 10, true) // balance should have been subtracted after creation amt2 := app.BankKeeper.GetBalance(ctx, sdk.AccAddress(validatorAddr), denom).Amount require.Equal(t, amt1.Sub(sdk.NewInt(10)).Int64(), amt2.Int64(), "expected coins to be subtracted") - msgCreateValidator = NewTestMsgCreateValidator(validatorAddr2, PKs[1], sdk.NewInt(10)) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.CreateValidator(validatorAddr2, PKs[1], 10, true) bal1 := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(validatorAddr)) // begin redelegate redAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) msgBeginRedelegate := types.NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2, redAmt) - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgBeginRedelegate, true) // origin account should not lose tokens as with a regular delegation bal2 := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(validatorAddr)) @@ -946,76 +752,54 @@ func TestRedelegationPeriod(t *testing.T) { require.True(t, found, "should not have unbonded") // cannot complete redelegation at time 6 seconds later - ctx = ctx.WithBlockTime(origHeader.Time.Add(time.Second * 6)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 6)) _, found = app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) require.True(t, found, "should not have unbonded") // can complete redelegation at time 7 seconds later - ctx = ctx.WithBlockTime(origHeader.Time.Add(time.Second * 7)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 7)) _, found = app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) require.False(t, found, "should have unbonded") } func TestTransitiveRedelegation(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 3, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - - validatorAddr := valAddrs[0] - validatorAddr2 := valAddrs[1] - validatorAddr3 := valAddrs[2] + val1, val2, val3 := valAddrs[0], valAddrs[1], valAddrs[2] blockTime := time.Now().UTC() ctx = ctx.WithBlockTime(blockTime) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // create the validators - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr, PKs[0], sdk.NewInt(10)) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - msgCreateValidator = NewTestMsgCreateValidator(validatorAddr2, PKs[1], sdk.NewInt(10)) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - msgCreateValidator = NewTestMsgCreateValidator(validatorAddr3, PKs[2], sdk.NewInt(10)) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.CreateValidator(val1, PKs[0], 10, true) + tstaking.CreateValidator(val2, PKs[1], 10, true) + tstaking.CreateValidator(val3, PKs[2], 10, true) // begin redelegate redAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgBeginRedelegate := types.NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2, redAmt) - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + msgBeginRedelegate := types.NewMsgBeginRedelegate(sdk.AccAddress(val1), val1, val2, redAmt) + tstaking.Handle(msgBeginRedelegate, true) // cannot redelegation to next validator while first delegation exists - msgBeginRedelegate = types.NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr2, validatorAddr3, redAmt) - res, err = handler(ctx, msgBeginRedelegate) - require.Error(t, err) - require.Nil(t, res) + msgBeginRedelegate = types.NewMsgBeginRedelegate(sdk.AccAddress(val1), val2, val3, redAmt) + tstaking.Handle(msgBeginRedelegate, false) params := app.StakingKeeper.GetParams(ctx) ctx = ctx.WithBlockTime(blockTime.Add(params.UnbondingTime)) + tstaking.Ctx = ctx // complete first redelegation staking.EndBlocker(ctx, app.StakingKeeper) // now should be able to redelegate from the second validator to the third - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgBeginRedelegate, true) } func TestMultipleRedelegationAtSameTime(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - valAddr := valAddrs[0] valAddr2 := valAddrs[1] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) @@ -1023,16 +807,8 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { app.StakingKeeper.SetParams(ctx, params) // create the validators - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator := NewTestMsgCreateValidator(valAddr, PKs[0], valTokens) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - msgCreateValidator = NewTestMsgCreateValidator(valAddr2, PKs[1], valTokens) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + valTokens := tstaking.CreateValidatorWithValPower(valAddr, PKs[0], 10, true) + tstaking.CreateValidator(valAddr2, PKs[1], valTokens.Int64(), true) // end block to bond them staking.EndBlocker(ctx, app.StakingKeeper) @@ -1041,9 +817,7 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) redAmt := sdk.NewCoin(sdk.DefaultBondDenom, valTokens.QuoRaw(2)) msgBeginRedelegate := types.NewMsgBeginRedelegate(selfDelAddr, valAddr, valAddr2, redAmt) - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgBeginRedelegate, true) // there should only be one entry in the redelegation object rd, found := app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) @@ -1051,9 +825,7 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { require.Len(t, rd.Entries, 1) // start a second redelegation at this same time as the first - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgBeginRedelegate, true) // now there should be two entries rd, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) @@ -1061,19 +833,16 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { require.Len(t, rd.Entries, 2) // move forward in time, should complete both redelegations - ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(1 * time.Second)) - staking.EndBlocker(ctx, app.StakingKeeper) - + ctx = tstaking.TurnBlockTimeDiff(1 * time.Second) rd, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) require.False(t, found) } func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 2, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - valAddr := valAddrs[0] valAddr2 := valAddrs[1] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) @@ -1081,16 +850,8 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { app.StakingKeeper.SetParams(ctx, params) // create the validators - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator := NewTestMsgCreateValidator(valAddr, PKs[0], valTokens) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - msgCreateValidator = NewTestMsgCreateValidator(valAddr2, PKs[1], valTokens) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + valTokens := tstaking.CreateValidatorWithValPower(valAddr, PKs[0], 10, true) + tstaking.CreateValidator(valAddr2, PKs[1], valTokens.Int64(), true) // end block to bond them staking.EndBlocker(ctx, app.StakingKeeper) @@ -1099,15 +860,12 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) redAmt := sdk.NewCoin(sdk.DefaultBondDenom, valTokens.QuoRaw(2)) msgBeginRedelegate := types.NewMsgBeginRedelegate(selfDelAddr, valAddr, valAddr2, redAmt) - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgBeginRedelegate, true) // move forward in time and start a second redelegation ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(5 * time.Second)) - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Ctx = ctx + tstaking.Handle(msgBeginRedelegate, true) // now there should be two entries rd, found := app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) @@ -1115,47 +873,36 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { require.Len(t, rd.Entries, 2) // move forward in time, should complete the first redelegation, but not the second - ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(5 * time.Second)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlockTimeDiff(5 * time.Second) rd, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) require.True(t, found) require.Len(t, rd.Entries, 1) // move forward in time, should complete the second redelegation - ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(5 * time.Second)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlockTimeDiff(5 * time.Second) rd, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) require.False(t, found) } func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 1, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - valAddr := valAddrs[0] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) params.UnbondingTime = 1 * time.Second app.StakingKeeper.SetParams(ctx, params) - // create the validator - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator := NewTestMsgCreateValidator(valAddr, PKs[0], valTokens) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + // create the validators + valTokens := tstaking.CreateValidatorWithValPower(valAddr, PKs[0], 10, true) // end block to bond staking.EndBlocker(ctx, app.StakingKeeper) // begin an unbonding delegation selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, valTokens.QuoRaw(2)) - msgUndelegate := types.NewMsgUndelegate(selfDelAddr, valAddr, unbondAmt) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Undelegate(selfDelAddr, valAddr, valTokens.QuoRaw(2), true) // there should only be one entry in the ubd object ubd, found := app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) @@ -1163,9 +910,7 @@ func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { require.Len(t, ubd.Entries, 1) // start a second ubd at this same time as the first - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Undelegate(selfDelAddr, valAddr, valTokens.QuoRaw(2), true) // now there should be two entries ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) @@ -1173,17 +918,15 @@ func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { require.Len(t, ubd.Entries, 2) // move forwaubd in time, should complete both ubds - ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(1 * time.Second)) - staking.EndBlocker(ctx, app.StakingKeeper) - + ctx = tstaking.TurnBlockTimeDiff(1 * time.Second) ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) require.False(t, found) } func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 1, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) valAddr := valAddrs[0] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) @@ -1191,22 +934,14 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { app.StakingKeeper.SetParams(ctx, params) // create the validator - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator := NewTestMsgCreateValidator(valAddr, PKs[0], valTokens) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + valTokens := tstaking.CreateValidatorWithValPower(valAddr, PKs[0], 10, true) // end block to bond staking.EndBlocker(ctx, app.StakingKeeper) // begin an unbonding delegation selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, valTokens.QuoRaw(2)) - msgUndelegate := types.NewMsgUndelegate(selfDelAddr, valAddr, unbondAmt) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Undelegate(selfDelAddr, valAddr, valTokens.QuoRaw(2), true) // there should only be one entry in the ubd object ubd, found := app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) @@ -1215,9 +950,8 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { // move forwaubd in time and start a second redelegation ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(5 * time.Second)) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Ctx = ctx + tstaking.Undelegate(selfDelAddr, valAddr, valTokens.QuoRaw(2), true) // now there should be two entries ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) @@ -1225,26 +959,23 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { require.Len(t, ubd.Entries, 2) // move forwaubd in time, should complete the first redelegation, but not the second - ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(5 * time.Second)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlockTimeDiff(5 * time.Second) ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) require.True(t, found) require.Len(t, ubd.Entries, 1) // move forwaubd in time, should complete the second redelegation - ctx = ctx.WithBlockTime(ctx.BlockHeader().Time.Add(5 * time.Second)) - staking.EndBlocker(ctx, app.StakingKeeper) + ctx = tstaking.TurnBlockTimeDiff(5 * time.Second) ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) require.False(t, found) } func TestUnbondingWhenExcessValidators(t *testing.T) { app, ctx, _, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 3, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - - validatorAddr1 := valAddrs[0] - validatorAddr2 := valAddrs[1] - validatorAddr3 := valAddrs[2] + val1 := valAddrs[0] + val2 := valAddrs[1] + val3 := valAddrs[2] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // set the unbonding time params := app.StakingKeeper.GetParams(ctx) @@ -1252,43 +983,21 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { app.StakingKeeper.SetParams(ctx, params) // add three validators - valTokens1 := sdk.TokensFromConsensusPower(50) - msgCreateValidator := NewTestMsgCreateValidator(validatorAddr1, PKs[0], valTokens1) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.CreateValidatorWithValPower(val1, PKs[0], 50, true) // apply TM updates app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 1, len(app.StakingKeeper.GetLastValidators(ctx))) - valTokens2 := sdk.TokensFromConsensusPower(30) - msgCreateValidator = NewTestMsgCreateValidator(validatorAddr2, PKs[1], valTokens2) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - // apply TM updates + valTokens2 := tstaking.CreateValidatorWithValPower(val2, PKs[1], 30, true) app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 2, len(app.StakingKeeper.GetLastValidators(ctx))) - valTokens3 := sdk.TokensFromConsensusPower(10) - msgCreateValidator = NewTestMsgCreateValidator(validatorAddr3, PKs[2], valTokens3) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - // apply TM updates + tstaking.CreateValidatorWithValPower(val3, PKs[2], 10, true) app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 2, len(app.StakingKeeper.GetLastValidators(ctx))) // unbond the validator-2 - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, valTokens2) - msgUndelegate := types.NewMsgUndelegate(sdk.AccAddress(validatorAddr2), validatorAddr2, unbondAmt) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) - + tstaking.Undelegate(sdk.AccAddress(val2), val2, valTokens2, true) // apply TM updates app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -1297,35 +1006,20 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { // the total number of validators should stay the same vals := app.StakingKeeper.GetLastValidators(ctx) require.Equal(t, 2, len(vals), "vals %v", vals) - val1, found := app.StakingKeeper.GetValidator(ctx, validatorAddr1) - require.True(t, found) - require.Equal(t, types.Bonded, val1.Status, "%v", val1) + tstaking.CheckValidator(val1, types.Bonded, false) } func TestBondUnbondRedelegateSlashTwice(t *testing.T) { app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 3, 1000000000) - - handler := staking.NewHandler(app.StakingKeeper) - valA, valB, del := valAddrs[0], valAddrs[1], delAddrs[2] consAddr0 := sdk.ConsAddress(PKs[0].Address()) + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) - valTokens := sdk.TokensFromConsensusPower(10) - msgCreateValidator := NewTestMsgCreateValidator(valA, PKs[0], valTokens) - res, err := handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) - - msgCreateValidator = NewTestMsgCreateValidator(valB, PKs[1], valTokens) - res, err = handler(ctx, msgCreateValidator) - require.NoError(t, err) - require.NotNil(t, res) + valTokens := tstaking.CreateValidatorWithValPower(valA, PKs[0], 10, true) + tstaking.CreateValidator(valB, PKs[1], valTokens.Int64(), true) // delegate 10 stake - msgDelegate := NewTestMsgDelegate(del, valA, valTokens) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Delegate(del, valA, valTokens.Int64()) // apply Tendermint updates updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -1333,20 +1027,16 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { // a block passes ctx = ctx.WithBlockHeight(1) + tstaking.Ctx = ctx // begin unbonding 4 stake - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(4)) - msgUndelegate := types.NewMsgUndelegate(del, valA, unbondAmt) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + unbondAmt := sdk.TokensFromConsensusPower(4) + tstaking.Undelegate(del, valA, unbondAmt, true) // begin redelegate 6 stake redAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(6)) msgBeginRedelegate := types.NewMsgBeginRedelegate(del, valA, valB, redAmt) - res, err = handler(ctx, msgBeginRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgBeginRedelegate, true) // destination delegation should have 6 shares delegation, found := app.StakingKeeper.GetDelegation(ctx, del, valB) @@ -1364,7 +1054,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { ubd, found := app.StakingKeeper.GetUnbondingDelegation(ctx, del, valA) require.True(t, found) require.Len(t, ubd.Entries, 1) - require.Equal(t, unbondAmt.Amount.QuoRaw(2), ubd.Entries[0].Balance) + require.Equal(t, unbondAmt.QuoRaw(2), ubd.Entries[0].Balance) // redelegation should have been slashed by half redelegation, found := app.StakingKeeper.GetRedelegation(ctx, del, valA, valB) @@ -1384,12 +1074,13 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { // slash the validator for an infraction committed after the unbonding and redelegation begin ctx = ctx.WithBlockHeight(3) app.StakingKeeper.Slash(ctx, consAddr0, 2, 10, sdk.NewDecWithPrec(5, 1)) + tstaking.Ctx = ctx // unbonding delegation should be unchanged ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, del, valA) require.True(t, found) require.Len(t, ubd.Entries, 1) - require.Equal(t, unbondAmt.Amount.QuoRaw(2), ubd.Entries[0].Balance) + require.Equal(t, unbondAmt.QuoRaw(2), ubd.Entries[0].Balance) // redelegation should be unchanged redelegation, found = app.StakingKeeper.GetRedelegation(ctx, del, valA, valB) @@ -1422,9 +1113,8 @@ func TestInvalidMsg(t *testing.T) { func TestInvalidCoinDenom(t *testing.T) { app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, 1000, 3, 1000000000) - handler := staking.NewHandler(app.StakingKeeper) - valA, valB, delAddr := valAddrs[0], valAddrs[1], delAddrs[2] + tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) valTokens := sdk.TokensFromConsensusPower(100) invalidCoin := sdk.NewCoin("churros", valTokens) @@ -1432,49 +1122,33 @@ func TestInvalidCoinDenom(t *testing.T) { oneCoin := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) commission := types.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.ZeroDec()) + msgCreate, err := types.NewMsgCreateValidator(valA, PKs[0], invalidCoin, types.Description{}, commission, sdk.OneInt()) + require.NoError(t, err) + tstaking.Handle(msgCreate, false) - msgCreate := types.NewMsgCreateValidator(valA, PKs[0], invalidCoin, types.Description{}, commission, sdk.OneInt()) - res, err := handler(ctx, msgCreate) - require.Error(t, err) - require.Nil(t, res) - - msgCreate = types.NewMsgCreateValidator(valA, PKs[0], validCoin, types.Description{}, commission, sdk.OneInt()) - res, err = handler(ctx, msgCreate) + msgCreate, err = types.NewMsgCreateValidator(valA, PKs[0], validCoin, types.Description{}, commission, sdk.OneInt()) require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgCreate, true) - msgCreate = types.NewMsgCreateValidator(valB, PKs[1], validCoin, types.Description{}, commission, sdk.OneInt()) - res, err = handler(ctx, msgCreate) + msgCreate, err = types.NewMsgCreateValidator(valB, PKs[1], validCoin, types.Description{}, commission, sdk.OneInt()) require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgCreate, true) msgDelegate := types.NewMsgDelegate(delAddr, valA, invalidCoin) - res, err = handler(ctx, msgDelegate) - require.Error(t, err) - require.Nil(t, res) + tstaking.Handle(msgDelegate, false) msgDelegate = types.NewMsgDelegate(delAddr, valA, validCoin) - res, err = handler(ctx, msgDelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgDelegate, true) msgUndelegate := types.NewMsgUndelegate(delAddr, valA, invalidCoin) - res, err = handler(ctx, msgUndelegate) - require.Error(t, err) - require.Nil(t, res) + tstaking.Handle(msgUndelegate, false) msgUndelegate = types.NewMsgUndelegate(delAddr, valA, oneCoin) - res, err = handler(ctx, msgUndelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgUndelegate, true) msgRedelegate := types.NewMsgBeginRedelegate(delAddr, valA, valB, invalidCoin) - res, err = handler(ctx, msgRedelegate) - require.Error(t, err) - require.Nil(t, res) + tstaking.Handle(msgRedelegate, false) msgRedelegate = types.NewMsgBeginRedelegate(delAddr, valA, valB, oneCoin) - res, err = handler(ctx, msgRedelegate) - require.NoError(t, err) - require.NotNil(t, res) + tstaking.Handle(msgRedelegate, true) } diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index d4084402265e..f5e859f04e93 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -7,6 +7,7 @@ import ( metrics "github.com/armon/go-metrics" tmstrings "github.com/tendermint/tendermint/libs/strings" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -38,9 +39,9 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa return nil, types.ErrValidatorOwnerExists } - pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, msg.Pubkey) - if err != nil { - return nil, err + pk, ok := msg.Pubkey.GetCachedValue().(cryptotypes.PubKey) + if !ok { + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting crypto.PubKey, got %T", pk) } if _, found := k.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(pk)); found { diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index ff54822aa339..131c4251fded 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -148,7 +148,10 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k simtypes.RandomDecAmount(r, maxCommission), ) - msg := types.NewMsgCreateValidator(address, simAccount.ConsKey.PubKey(), selfDelegation, description, commission, sdk.OneInt()) + msg, err := types.NewMsgCreateValidator(address, simAccount.ConsKey.PubKey(), selfDelegation, description, commission, sdk.OneInt()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to create CreateValidator message"), nil, err + } txGen := simappparams.MakeEncodingConfig().TxConfig tx, err := helpers.GenTx( diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index f077a4e50c2c..ff9d10436879 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -85,7 +85,7 @@ func TestSimulateMsgCreateValidator(t *testing.T) { require.Equal(t, "0.660000000000000000", msg.Commission.MaxRate.String()) require.Equal(t, "0.047464127245687382", msg.Commission.Rate.String()) require.Equal(t, types.TypeMsgCreateValidator, msg.Type()) - require.Equal(t, "cosmosvalconspub1zcjduepq280tm686ma80cva9z620dmknd9a858pd2zmq9ackfenfllecjxds0hg9n7", msg.Pubkey) + require.Equal(t, []byte{0xa, 0x20, 0x51, 0xde, 0xbd, 0xe8, 0xfa, 0xdf, 0x4e, 0xfc, 0x33, 0xa5, 0x16, 0x94, 0xf6, 0xee, 0xd3, 0x69, 0x7a, 0x7a, 0x1c, 0x2d, 0x50, 0xb6, 0x2, 0xf7, 0x16, 0x4e, 0x66, 0x9f, 0xff, 0x38, 0x91, 0x9b}, msg.Pubkey.Value) require.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress) require.Equal(t, "cosmosvaloper1ghekyjucln7y67ntx7cf27m9dpuxxemnsvnaes", msg.ValidatorAddress) require.Len(t, futureOperations, 0) diff --git a/x/staking/teststaking/helper.go b/x/staking/teststaking/helper.go new file mode 100644 index 000000000000..c0ba45bb1a98 --- /dev/null +++ b/x/staking/teststaking/helper.go @@ -0,0 +1,133 @@ +package teststaking + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// Helper is a structure which wraps the staking handler +// and provides methods useful in tests +type Helper struct { + t *testing.T + h sdk.Handler + k keeper.Keeper + + Ctx sdk.Context + Commission stakingtypes.CommissionRates + // Coin Denomination + Denom string +} + +// NewHelper creates staking Handler wrapper for tests +func NewHelper(t *testing.T, ctx sdk.Context, k keeper.Keeper) *Helper { + return &Helper{t, staking.NewHandler(k), k, ctx, ZeroCommission(), sdk.DefaultBondDenom} +} + +// CreateValidator calls handler to create a new staking validator +func (sh *Helper) CreateValidator(addr sdk.ValAddress, pk crypto.PubKey, stakeAmount int64, ok bool) { + coin := sdk.NewCoin(sh.Denom, sdk.NewInt(stakeAmount)) + sh.createValidator(addr, pk, coin, ok) +} + +// CreateValidatorWithValPower calls handler to create a new staking validator with zero +// commission +func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk crypto.PubKey, valPower int64, ok bool) sdk.Int { + amount := sdk.TokensFromConsensusPower(valPower) + coin := sdk.NewCoin(sh.Denom, amount) + sh.createValidator(addr, pk, coin, ok) + return amount +} + +// CreateValidatorMsg returns a message used to create validator in this service. +func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk crypto.PubKey, stakeAmount int64) *stakingtypes.MsgCreateValidator { + coin := sdk.NewCoin(sh.Denom, sdk.NewInt(stakeAmount)) + msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{}, sh.Commission, sdk.OneInt()) + require.NoError(sh.t, err) + return msg +} + +func (sh *Helper) createValidator(addr sdk.ValAddress, pk crypto.PubKey, coin sdk.Coin, ok bool) { + msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{}, sh.Commission, sdk.OneInt()) + require.NoError(sh.t, err) + sh.Handle(msg, ok) +} + +// Delegate calls handler to delegate stake for a validator +func (sh *Helper) Delegate(delegator sdk.AccAddress, val sdk.ValAddress, amount int64) { + coin := sdk.NewCoin(sh.Denom, sdk.NewInt(amount)) + msg := stakingtypes.NewMsgDelegate(delegator, val, coin) + sh.Handle(msg, true) +} + +// DelegateWithPower calls handler to delegate stake for a validator +func (sh *Helper) DelegateWithPower(delegator sdk.AccAddress, val sdk.ValAddress, power int64) { + coin := sdk.NewCoin(sh.Denom, sdk.TokensFromConsensusPower(power)) + msg := stakingtypes.NewMsgDelegate(delegator, val, coin) + sh.Handle(msg, true) +} + +// Undelegate calls handler to unbound some stake from a validator. +func (sh *Helper) Undelegate(delegator sdk.AccAddress, val sdk.ValAddress, amount sdk.Int, ok bool) *sdk.Result { + unbondAmt := sdk.NewCoin(sh.Denom, amount) + msg := stakingtypes.NewMsgUndelegate(delegator, val, unbondAmt) + return sh.Handle(msg, ok) +} + +// Handle calls staking handler on a given message +func (sh *Helper) Handle(msg sdk.Msg, ok bool) *sdk.Result { + res, err := sh.h(sh.Ctx, msg) + if ok { + require.NoError(sh.t, err) + require.NotNil(sh.t, res) + } else { + require.Error(sh.t, err) + require.Nil(sh.t, res) + } + return res +} + +// CheckValidator asserts that a validor exists and has a given status (if status!="") +// and if has a right jailed flag. +func (sh *Helper) CheckValidator(addr sdk.ValAddress, status stakingtypes.BondStatus, jailed bool) stakingtypes.Validator { + v, ok := sh.k.GetValidator(sh.Ctx, addr) + require.True(sh.t, ok) + require.Equal(sh.t, jailed, v.Jailed, "wrong Jalied status") + if status >= 0 { + require.Equal(sh.t, status, v.Status) + } + return v +} + +// CheckDelegator asserts that a delegator exists +func (sh *Helper) CheckDelegator(delegator sdk.AccAddress, val sdk.ValAddress, found bool) { + _, ok := sh.k.GetDelegation(sh.Ctx, delegator, val) + require.Equal(sh.t, ok, found) +} + +// TurnBlock calls EndBlocker and updates the block time +func (sh *Helper) TurnBlock(newTime time.Time) sdk.Context { + sh.Ctx = sh.Ctx.WithBlockTime(newTime) + staking.EndBlocker(sh.Ctx, sh.k) + return sh.Ctx +} + +// TurnBlockTimeDiff calls EndBlocker and updates the block time by adding the +// duration to the current block time +func (sh *Helper) TurnBlockTimeDiff(diff time.Duration) sdk.Context { + sh.Ctx = sh.Ctx.WithBlockTime(sh.Ctx.BlockHeader().Time.Add(diff)) + staking.EndBlocker(sh.Ctx, sh.k) + return sh.Ctx +} + +// ZeroCommission constructs a commission rates with all zeros. +func ZeroCommission() stakingtypes.CommissionRates { + return stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) +} diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index e7e8305ea097..51e19ac263f9 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -5,6 +5,7 @@ import ( "github.com/tendermint/tendermint/crypto" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -19,11 +20,13 @@ const ( ) var ( - _ sdk.Msg = &MsgCreateValidator{} - _ sdk.Msg = &MsgEditValidator{} - _ sdk.Msg = &MsgDelegate{} - _ sdk.Msg = &MsgUndelegate{} - _ sdk.Msg = &MsgBeginRedelegate{} + _ sdk.Msg = &MsgCreateValidator{} + _ codectypes.UnpackInterfacesMessage = (*MsgCreateValidator)(nil) + _ sdk.Msg = &MsgCreateValidator{} + _ sdk.Msg = &MsgEditValidator{} + _ sdk.Msg = &MsgDelegate{} + _ sdk.Msg = &MsgUndelegate{} + _ sdk.Msg = &MsgBeginRedelegate{} ) // NewMsgCreateValidator creates a new MsgCreateValidator instance. @@ -31,21 +34,20 @@ var ( func NewMsgCreateValidator( valAddr sdk.ValAddress, pubKey crypto.PubKey, selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation sdk.Int, -) *MsgCreateValidator { - var pkStr string - if pubKey != nil { - pkStr = sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pubKey) +) (*MsgCreateValidator, error) { + pkAny, err := codectypes.PackAny(pubKey) + if err != nil { + return nil, err } - return &MsgCreateValidator{ Description: description, DelegatorAddress: sdk.AccAddress(valAddr).String(), ValidatorAddress: valAddr.String(), - Pubkey: pkStr, + Pubkey: pkAny, Value: selfDelegation, Commission: commission, MinSelfDelegation: minSelfDelegation, - } + }, nil } // Route implements the sdk.Msg interface. @@ -105,7 +107,7 @@ func (msg MsgCreateValidator) ValidateBasic() error { return ErrBadValidatorAddr } - if msg.Pubkey == "" { + if msg.Pubkey == nil { return ErrEmptyValidatorPubKey } @@ -136,6 +138,12 @@ func (msg MsgCreateValidator) ValidateBasic() error { return nil } +// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces +func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { + var pubKey crypto.PubKey + return unpacker.UnpackAny(msg.Pubkey, &pubKey) +} + // NewMsgEditValidator creates a new MsgEditValidator instance //nolint:interfacer func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *sdk.Int) *MsgEditValidator { diff --git a/x/staking/types/msg_test.go b/x/staking/types/msg_test.go index 127e80549ba8..eb83b33162ce 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -6,6 +6,11 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -14,6 +19,38 @@ var ( coinZero = sdk.NewInt64Coin(sdk.DefaultBondDenom, 0) ) +func TestMsgDecode(t *testing.T) { + registry := codectypes.NewInterfaceRegistry() + cryptocodec.RegisterInterfaces(registry) + RegisterInterfaces(registry) + cdc := codec.NewProtoCodec(registry) + + // firstly we start testing the pubkey serialization + + pk1bz, err := codec.MarshalAny(cdc, pk1) + require.NoError(t, err) + var pkUnmarshaled cryptotypes.PubKey + err = codec.UnmarshalAny(cdc, &pkUnmarshaled, pk1bz) + require.NoError(t, err) + require.True(t, pk1.Equals(pkUnmarshaled.(*ed25519.PubKey))) + + // now let's try to serialize the whole message + + commission1 := NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) + msg, err := NewMsgCreateValidator(valAddr1, pk1, coinPos, Description{}, commission1, sdk.OneInt()) + require.NoError(t, err) + msgSerialized, err := codec.MarshalAny(cdc, msg) + require.NoError(t, err) + + var msgUnmarshaled sdk.Msg + err = codec.UnmarshalAny(cdc, &msgUnmarshaled, msgSerialized) + require.NoError(t, err) + msg2, ok := msgUnmarshaled.(*MsgCreateValidator) + require.True(t, ok) + require.True(t, msg.Value.IsEqual(msg2.Value)) + require.True(t, msg.Pubkey.Equal(msg2.Pubkey)) +} + // test ValidateBasic for MsgCreateValidator func TestMsgCreateValidator(t *testing.T) { commission1 := NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) @@ -41,8 +78,10 @@ func TestMsgCreateValidator(t *testing.T) { } for _, tc := range tests { + t.Logf("Test: %s, pk=%t", tc.name, tc.pubkey) description := NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) - msg := NewMsgCreateValidator(tc.validatorAddr, tc.pubkey, tc.bond, description, tc.CommissionRates, tc.minSelfDelegation) + msg, err := NewMsgCreateValidator(tc.validatorAddr, tc.pubkey, tc.bond, description, tc.CommissionRates, tc.minSelfDelegation) + require.NoError(t, err) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { diff --git a/x/staking/types/tx.pb.go b/x/staking/types/tx.pb.go index d2d26bd25116..f49c42ecdb13 100644 --- a/x/staking/types/tx.pb.go +++ b/x/staking/types/tx.pb.go @@ -6,10 +6,11 @@ package types import ( context "context" fmt "fmt" + types "github.com/cosmos/cosmos-sdk/codec/types" github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - grpc1 "github.com/gogo/protobuf/grpc" - types "github.com/cosmos/cosmos-sdk/types" + types1 "github.com/cosmos/cosmos-sdk/types" _ "github.com/gogo/protobuf/gogoproto" + grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" _ "github.com/golang/protobuf/ptypes/timestamp" @@ -41,8 +42,8 @@ type MsgCreateValidator struct { MinSelfDelegation github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=min_self_delegation,json=minSelfDelegation,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"min_self_delegation" yaml:"min_self_delegation"` DelegatorAddress string `protobuf:"bytes,4,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty" yaml:"delegator_address"` ValidatorAddress string `protobuf:"bytes,5,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty" yaml:"validator_address"` - Pubkey string `protobuf:"bytes,6,opt,name=pubkey,proto3" json:"pubkey,omitempty"` - Value types.Coin `protobuf:"bytes,7,opt,name=value,proto3" json:"value"` + Pubkey *types.Any `protobuf:"bytes,6,opt,name=pubkey,proto3" json:"pubkey,omitempty"` + Value types1.Coin `protobuf:"bytes,7,opt,name=value,proto3" json:"value"` } func (m *MsgCreateValidator) Reset() { *m = MsgCreateValidator{} } @@ -201,9 +202,9 @@ var xxx_messageInfo_MsgEditValidatorResponse proto.InternalMessageInfo // MsgDelegate defines a SDK message for performing a delegation of coins // from a delegator to a validator. type MsgDelegate struct { - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty" yaml:"delegator_address"` - ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty" yaml:"validator_address"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` + DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty" yaml:"delegator_address"` + ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty" yaml:"validator_address"` + Amount types1.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` } func (m *MsgDelegate) Reset() { *m = MsgDelegate{} } @@ -279,10 +280,10 @@ var xxx_messageInfo_MsgDelegateResponse proto.InternalMessageInfo // MsgBeginRedelegate defines a SDK message for performing a redelegation // of coins from a delegator and source validator to a destination validator. type MsgBeginRedelegate struct { - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty" yaml:"delegator_address"` - ValidatorSrcAddress string `protobuf:"bytes,2,opt,name=validator_src_address,json=validatorSrcAddress,proto3" json:"validator_src_address,omitempty" yaml:"validator_src_address"` - ValidatorDstAddress string `protobuf:"bytes,3,opt,name=validator_dst_address,json=validatorDstAddress,proto3" json:"validator_dst_address,omitempty" yaml:"validator_dst_address"` - Amount types.Coin `protobuf:"bytes,4,opt,name=amount,proto3" json:"amount"` + DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty" yaml:"delegator_address"` + ValidatorSrcAddress string `protobuf:"bytes,2,opt,name=validator_src_address,json=validatorSrcAddress,proto3" json:"validator_src_address,omitempty" yaml:"validator_src_address"` + ValidatorDstAddress string `protobuf:"bytes,3,opt,name=validator_dst_address,json=validatorDstAddress,proto3" json:"validator_dst_address,omitempty" yaml:"validator_dst_address"` + Amount types1.Coin `protobuf:"bytes,4,opt,name=amount,proto3" json:"amount"` } func (m *MsgBeginRedelegate) Reset() { *m = MsgBeginRedelegate{} } @@ -366,9 +367,9 @@ func (m *MsgBeginRedelegateResponse) GetCompletionTime() time.Time { // MsgUndelegate defines a SDK message for performing an undelegation from a // delegate and a validator. type MsgUndelegate struct { - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty" yaml:"delegator_address"` - ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty" yaml:"validator_address"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` + DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty" yaml:"delegator_address"` + ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty" yaml:"validator_address"` + Amount types1.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` } func (m *MsgUndelegate) Reset() { *m = MsgUndelegate{} } @@ -465,58 +466,59 @@ func init() { func init() { proto.RegisterFile("cosmos/staking/v1beta1/tx.proto", fileDescriptor_0926ef28816b35ab) } var fileDescriptor_0926ef28816b35ab = []byte{ - // 815 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x96, 0x4f, 0x6b, 0xdb, 0x48, - 0x18, 0xc6, 0x2d, 0xdb, 0xf1, 0x66, 0x27, 0xe4, 0x9f, 0xb2, 0x09, 0x5e, 0x11, 0xac, 0xa0, 0xec, - 0xb6, 0xa1, 0x6d, 0xa4, 0x26, 0xa5, 0x14, 0x72, 0x29, 0x75, 0xdc, 0xd2, 0xd0, 0xfa, 0xa2, 0xa4, - 0x3d, 0x94, 0x82, 0x91, 0xa5, 0xb1, 0x2a, 0x2c, 0x69, 0x1c, 0xcd, 0x38, 0x24, 0xd0, 0x0f, 0xd0, - 0x63, 0xa0, 0xb7, 0x42, 0x21, 0x1f, 0x27, 0xa7, 0x92, 0x63, 0xe9, 0xc1, 0x2d, 0x09, 0x94, 0x9c, - 0xfd, 0x09, 0x8a, 0x46, 0xd2, 0x58, 0x96, 0x6d, 0x61, 0x42, 0x7d, 0xe9, 0x29, 0xf1, 0xe8, 0x37, - 0xcf, 0x68, 0x9e, 0x79, 0xe6, 0x7d, 0x05, 0x44, 0x1d, 0x61, 0x07, 0x61, 0x05, 0x13, 0xad, 0x69, - 0xb9, 0xa6, 0x72, 0xb4, 0x55, 0x87, 0x44, 0xdb, 0x52, 0xc8, 0xb1, 0xdc, 0xf2, 0x10, 0x41, 0xfc, - 0x4a, 0x00, 0xc8, 0x21, 0x20, 0x87, 0x80, 0xf0, 0x8f, 0x89, 0x4c, 0x44, 0x11, 0xc5, 0xff, 0x2f, - 0xa0, 0x85, 0x52, 0x28, 0x57, 0xd7, 0x30, 0x64, 0x5a, 0x3a, 0xb2, 0xdc, 0xf0, 0xb9, 0x68, 0x22, - 0x64, 0xda, 0x50, 0xa1, 0xbf, 0xea, 0xed, 0x86, 0x42, 0x2c, 0x07, 0x62, 0xa2, 0x39, 0xad, 0x10, - 0xf8, 0x6f, 0xc4, 0xfb, 0x44, 0xcb, 0x53, 0x4a, 0xfa, 0x9c, 0x07, 0x7c, 0x15, 0x9b, 0xbb, 0x1e, - 0xd4, 0x08, 0x7c, 0xad, 0xd9, 0x96, 0xa1, 0x11, 0xe4, 0xf1, 0x2f, 0xc0, 0x8c, 0x01, 0xb1, 0xee, - 0x59, 0x2d, 0x62, 0x21, 0xb7, 0xc8, 0xad, 0x71, 0x1b, 0x33, 0xdb, 0xeb, 0xf2, 0xf0, 0x1d, 0xc8, - 0x95, 0x1e, 0x5a, 0xce, 0x9f, 0x77, 0xc4, 0x8c, 0x1a, 0x9f, 0xcd, 0x57, 0x01, 0xd0, 0x91, 0xe3, - 0x58, 0x18, 0xfb, 0x5a, 0x59, 0xaa, 0x75, 0x7b, 0x94, 0xd6, 0x2e, 0x23, 0x55, 0x8d, 0x40, 0x1c, - 0xea, 0xc5, 0x04, 0xf8, 0xf7, 0x60, 0xc9, 0xb1, 0xdc, 0x1a, 0x86, 0x76, 0xa3, 0x66, 0x40, 0x1b, - 0x9a, 0x1a, 0x7d, 0xc7, 0xdc, 0x1a, 0xb7, 0xf1, 0x77, 0xf9, 0xa5, 0x8f, 0x7f, 0xeb, 0x88, 0xb7, - 0x4c, 0x8b, 0xbc, 0x6b, 0xd7, 0x65, 0x1d, 0x39, 0x4a, 0x68, 0x44, 0xf0, 0x67, 0x13, 0x1b, 0x4d, - 0x85, 0x9c, 0xb4, 0x20, 0x96, 0xf7, 0x5c, 0xd2, 0xed, 0x88, 0xc2, 0x89, 0xe6, 0xd8, 0x3b, 0xd2, - 0x10, 0x49, 0x49, 0x5d, 0x74, 0x2c, 0x77, 0x1f, 0xda, 0x8d, 0x0a, 0x1b, 0xe3, 0xf7, 0xc0, 0x62, - 0x48, 0x20, 0xaf, 0xa6, 0x19, 0x86, 0x07, 0x31, 0x2e, 0xe6, 0xe9, 0xda, 0xab, 0xdd, 0x8e, 0x58, - 0x0c, 0xd4, 0x06, 0x10, 0x49, 0x5d, 0x60, 0x63, 0x4f, 0x82, 0x21, 0x5f, 0xea, 0x28, 0x72, 0x9c, - 0x49, 0x4d, 0x25, 0xa5, 0x06, 0x10, 0x49, 0x5d, 0x60, 0x63, 0x91, 0xd4, 0x0a, 0x28, 0xb4, 0xda, - 0xf5, 0x26, 0x3c, 0x29, 0x16, 0xfc, 0xf9, 0x6a, 0xf8, 0x8b, 0x7f, 0x08, 0xa6, 0x8e, 0x34, 0xbb, - 0x0d, 0x8b, 0x7f, 0x51, 0xd7, 0xff, 0x8d, 0x5c, 0xf7, 0x53, 0x15, 0xb3, 0xdc, 0x8a, 0xce, 0x2d, - 0xa0, 0x77, 0xa6, 0x3f, 0x9c, 0x89, 0x99, 0xeb, 0x33, 0x31, 0x23, 0xad, 0x02, 0x61, 0x30, 0x1e, - 0x2a, 0xc4, 0x2d, 0xe4, 0x62, 0x28, 0x7d, 0xcc, 0x81, 0x85, 0x2a, 0x36, 0x9f, 0x1a, 0x16, 0x99, - 0x50, 0x76, 0x1e, 0x0f, 0xf3, 0x28, 0x4b, 0x3d, 0xe2, 0xbb, 0x1d, 0x71, 0x2e, 0xf0, 0x28, 0xc5, - 0x19, 0x07, 0xcc, 0xf7, 0xb2, 0x53, 0xf3, 0x34, 0x02, 0xc3, 0xa4, 0x54, 0xc6, 0x4c, 0x49, 0x05, - 0xea, 0xdd, 0x8e, 0xb8, 0x12, 0x2c, 0x94, 0x90, 0x92, 0xd4, 0x39, 0xbd, 0x2f, 0xaf, 0xfc, 0xf1, - 0xf0, 0x70, 0x06, 0x01, 0x79, 0x3e, 0xc1, 0x60, 0xc6, 0xce, 0x4c, 0x00, 0xc5, 0xe4, 0xa1, 0xb0, - 0x13, 0xfb, 0xc9, 0x81, 0x99, 0x2a, 0x36, 0xc3, 0x79, 0x70, 0x78, 0x9c, 0xb9, 0xdf, 0x17, 0xe7, - 0xec, 0x8d, 0xe2, 0xfc, 0x08, 0x14, 0x34, 0x07, 0xb5, 0x5d, 0x42, 0xcf, 0x6a, 0x8c, 0xdc, 0x86, - 0x78, 0xcc, 0x84, 0x65, 0xb0, 0x14, 0xdb, 0x27, 0xdb, 0xff, 0x97, 0x2c, 0xad, 0x77, 0x65, 0x68, - 0x5a, 0xae, 0x0a, 0x8d, 0x09, 0xd8, 0x70, 0x00, 0x96, 0x7b, 0x7b, 0xc4, 0x9e, 0x9e, 0xb0, 0x62, - 0xad, 0xdb, 0x11, 0x57, 0x93, 0x56, 0xc4, 0x30, 0x49, 0x5d, 0x62, 0xe3, 0xfb, 0x9e, 0x3e, 0x54, - 0xd5, 0xc0, 0x84, 0xa9, 0xe6, 0x46, 0xab, 0xc6, 0xb0, 0xb8, 0x6a, 0x05, 0x93, 0x41, 0x9f, 0xf3, - 0x37, 0xf5, 0xb9, 0x49, 0x0b, 0x44, 0xc2, 0xcf, 0xc8, 0x6e, 0xbe, 0x4a, 0x6f, 0x5f, 0xcb, 0x86, - 0x7e, 0x44, 0x6b, 0x7e, 0x8b, 0x0a, 0xeb, 0x81, 0x20, 0x07, 0xfd, 0x4b, 0x8e, 0xfa, 0x97, 0x7c, - 0x10, 0xf5, 0xaf, 0xf2, 0xb4, 0xbf, 0xd4, 0xe9, 0x77, 0x91, 0xa3, 0xb7, 0x2b, 0x9c, 0xec, 0x3f, - 0x96, 0xae, 0x39, 0x30, 0x5b, 0xc5, 0xe6, 0x2b, 0xd7, 0xf8, 0xe3, 0xf3, 0xdb, 0x00, 0xcb, 0x7d, - 0x3b, 0x9d, 0x90, 0xa5, 0xdb, 0x9f, 0xf2, 0x20, 0x57, 0xc5, 0x26, 0x7f, 0x08, 0xe6, 0x93, 0x1f, - 0x01, 0x77, 0x46, 0xd5, 0xec, 0xc1, 0x8e, 0x20, 0x6c, 0x8f, 0xcf, 0xb2, 0x9d, 0x34, 0xc1, 0x6c, - 0x7f, 0xe7, 0xd8, 0x48, 0x11, 0xe9, 0x23, 0x85, 0xfb, 0xe3, 0x92, 0x6c, 0xb1, 0xb7, 0x60, 0x9a, - 0x15, 0xbd, 0xf5, 0x94, 0xd9, 0x11, 0x24, 0xdc, 0x1d, 0x03, 0x62, 0xea, 0x87, 0x60, 0x3e, 0x59, - 0x52, 0xd2, 0xdc, 0x4b, 0xb0, 0xa9, 0xee, 0x8d, 0xba, 0x5a, 0x75, 0x00, 0x62, 0xf7, 0xe0, 0xff, - 0x14, 0x85, 0x1e, 0x26, 0x6c, 0x8e, 0x85, 0x45, 0x6b, 0x94, 0x9f, 0x9d, 0x5f, 0x96, 0xb8, 0x8b, - 0xcb, 0x12, 0xf7, 0xe3, 0xb2, 0xc4, 0x9d, 0x5e, 0x95, 0x32, 0x17, 0x57, 0xa5, 0xcc, 0xd7, 0xab, - 0x52, 0xe6, 0xcd, 0xbd, 0xd4, 0x36, 0x76, 0xcc, 0xbe, 0x3a, 0x69, 0x43, 0xab, 0x17, 0x68, 0x24, - 0x1f, 0xfc, 0x0a, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x72, 0xf7, 0x1e, 0x24, 0x0b, 0x00, 0x00, + // 829 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x96, 0xcb, 0x4e, 0xdb, 0x4a, + 0x1c, 0xc6, 0xe3, 0x24, 0xe4, 0x70, 0x06, 0x71, 0x33, 0x17, 0x05, 0x0b, 0xc5, 0xc8, 0x9c, 0x0b, + 0x3a, 0x07, 0xec, 0x03, 0x47, 0x55, 0x25, 0x36, 0x15, 0x21, 0xad, 0x8a, 0xda, 0x6c, 0x0c, 0xed, + 0xa2, 0xaa, 0x14, 0x39, 0xf6, 0xc4, 0xb5, 0x62, 0x7b, 0x82, 0x67, 0x82, 0x88, 0xd4, 0x07, 0xe8, + 0x12, 0xa9, 0xbb, 0xae, 0x78, 0x87, 0xbe, 0x04, 0xab, 0x8a, 0x65, 0xd5, 0x45, 0x5a, 0x81, 0x54, + 0xb1, 0xce, 0x13, 0x54, 0x1e, 0xdb, 0x13, 0xc7, 0xb9, 0x28, 0x42, 0xcd, 0xa6, 0x2b, 0xc8, 0xf8, + 0x37, 0xdf, 0x78, 0xbe, 0xff, 0x37, 0xff, 0x31, 0x10, 0x75, 0x84, 0x1d, 0x84, 0x15, 0x4c, 0xb4, + 0xba, 0xe5, 0x9a, 0xca, 0xd9, 0x6e, 0x15, 0x12, 0x6d, 0x57, 0x21, 0xe7, 0x72, 0xc3, 0x43, 0x04, + 0xf1, 0xab, 0x01, 0x20, 0x87, 0x80, 0x1c, 0x02, 0xc2, 0xb2, 0x89, 0x4c, 0x44, 0x11, 0xc5, 0xff, + 0x2f, 0xa0, 0x85, 0x42, 0x28, 0x57, 0xd5, 0x30, 0x64, 0x5a, 0x3a, 0xb2, 0xdc, 0xf0, 0xb9, 0x68, + 0x22, 0x64, 0xda, 0x50, 0xa1, 0xbf, 0xaa, 0xcd, 0x9a, 0x42, 0x2c, 0x07, 0x62, 0xa2, 0x39, 0x8d, + 0x10, 0xf8, 0x63, 0xc8, 0xfb, 0x44, 0xcb, 0x07, 0xd4, 0x5a, 0x52, 0x46, 0x73, 0x5b, 0xc1, 0x23, + 0xe9, 0x63, 0x16, 0xf0, 0x65, 0x6c, 0x1e, 0x7a, 0x50, 0x23, 0xf0, 0xa5, 0x66, 0x5b, 0x86, 0x46, + 0x90, 0xc7, 0x3f, 0x03, 0x33, 0x06, 0xc4, 0xba, 0x67, 0x35, 0x88, 0x85, 0xdc, 0x3c, 0xb7, 0xc1, + 0x6d, 0xcd, 0xec, 0x6d, 0xca, 0x83, 0x37, 0x27, 0x97, 0xba, 0x68, 0x31, 0x7b, 0xd5, 0x16, 0x53, + 0x6a, 0x7c, 0x36, 0x5f, 0x06, 0x40, 0x47, 0x8e, 0x63, 0x61, 0xec, 0x6b, 0xa5, 0xa9, 0xd6, 0xdf, + 0xc3, 0xb4, 0x0e, 0x19, 0xa9, 0x6a, 0x04, 0xe2, 0x50, 0x2f, 0x26, 0xc0, 0xbf, 0x05, 0x4b, 0x8e, + 0xe5, 0x56, 0x30, 0xb4, 0x6b, 0x15, 0x03, 0xda, 0xd0, 0xd4, 0xe8, 0x3b, 0x66, 0x36, 0xb8, 0xad, + 0xdf, 0x8b, 0xcf, 0x7d, 0xfc, 0x4b, 0x5b, 0xfc, 0xcb, 0xb4, 0xc8, 0x9b, 0x66, 0x55, 0xd6, 0x91, + 0xa3, 0x84, 0x1e, 0x05, 0x7f, 0x76, 0xb0, 0x51, 0x57, 0x48, 0xab, 0x01, 0xb1, 0x7c, 0xe4, 0x92, + 0x4e, 0x5b, 0x14, 0x5a, 0x9a, 0x63, 0xef, 0x4b, 0x03, 0x24, 0x25, 0x75, 0xd1, 0xb1, 0xdc, 0x63, + 0x68, 0xd7, 0x4a, 0x6c, 0x8c, 0x3f, 0x02, 0x8b, 0x21, 0x81, 0xbc, 0x8a, 0x66, 0x18, 0x1e, 0xc4, + 0x38, 0x9f, 0xa5, 0x6b, 0xaf, 0x77, 0xda, 0x62, 0x3e, 0x50, 0xeb, 0x43, 0x24, 0x75, 0x81, 0x8d, + 0x1d, 0x04, 0x43, 0xbe, 0xd4, 0x59, 0xe4, 0x38, 0x93, 0x9a, 0x4a, 0x4a, 0xf5, 0x21, 0x92, 0xba, + 0xc0, 0xc6, 0x22, 0xa9, 0x6d, 0x90, 0x6b, 0x34, 0xab, 0x75, 0xd8, 0xca, 0xe7, 0xa8, 0xbd, 0xcb, + 0x72, 0x50, 0x72, 0x39, 0x2a, 0xb9, 0x7c, 0xe0, 0xb6, 0xd4, 0x90, 0xe1, 0x1f, 0x80, 0xa9, 0x33, + 0xcd, 0x6e, 0xc2, 0xfc, 0x6f, 0x14, 0x5e, 0x8b, 0x6a, 0xe1, 0xc7, 0x30, 0x56, 0x08, 0x2b, 0xaa, + 0x66, 0x40, 0xef, 0x4f, 0xbf, 0xbb, 0x14, 0x53, 0x77, 0x97, 0x62, 0x4a, 0x5a, 0x07, 0x42, 0x7f, + 0x68, 0x54, 0x88, 0x1b, 0xc8, 0xc5, 0x50, 0x7a, 0x9f, 0x01, 0x0b, 0x65, 0x6c, 0x3e, 0x36, 0x2c, + 0x32, 0xa1, 0x44, 0x3d, 0x1a, 0xe4, 0x5c, 0x9a, 0x3a, 0xc7, 0x77, 0xda, 0xe2, 0x5c, 0xe0, 0xdc, + 0x08, 0xbf, 0x1c, 0x30, 0xdf, 0x4d, 0x54, 0xc5, 0xd3, 0x08, 0x0c, 0xf3, 0x53, 0x1a, 0x33, 0x3b, + 0x25, 0xa8, 0x77, 0xda, 0xe2, 0x6a, 0xb0, 0x50, 0x42, 0x4a, 0x52, 0xe7, 0xf4, 0x9e, 0x14, 0xf3, + 0xe7, 0x83, 0x23, 0x1b, 0xc4, 0xe6, 0xe9, 0x04, 0xe3, 0x1a, 0xab, 0x99, 0x00, 0xf2, 0xc9, 0xa2, + 0xb0, 0x8a, 0x7d, 0xe7, 0xc0, 0x4c, 0x19, 0x9b, 0xe1, 0x3c, 0x38, 0x38, 0xe4, 0xdc, 0xcf, 0x0b, + 0x79, 0xfa, 0x5e, 0x21, 0x7f, 0x08, 0x72, 0x9a, 0x83, 0x9a, 0x2e, 0xa1, 0xb5, 0x1a, 0x23, 0xb7, + 0x21, 0x1e, 0x33, 0x61, 0x05, 0x2c, 0xc5, 0xf6, 0xc9, 0xf6, 0xff, 0x29, 0x4d, 0xbb, 0x60, 0x11, + 0x9a, 0x96, 0xab, 0x42, 0x63, 0x02, 0x36, 0x9c, 0x80, 0x95, 0xee, 0x1e, 0xb1, 0xa7, 0x27, 0xac, + 0xd8, 0xe8, 0xb4, 0xc5, 0xf5, 0xa4, 0x15, 0x31, 0x4c, 0x52, 0x97, 0xd8, 0xf8, 0xb1, 0xa7, 0x0f, + 0x54, 0x35, 0x30, 0x61, 0xaa, 0x99, 0xe1, 0xaa, 0x31, 0x2c, 0xae, 0x5a, 0xc2, 0xa4, 0xdf, 0xe7, + 0xec, 0x7d, 0x7d, 0xae, 0xd3, 0x06, 0x91, 0xf0, 0x33, 0xb2, 0x9b, 0x2f, 0xd3, 0xd3, 0xd7, 0xb0, + 0xa1, 0x1f, 0xd1, 0x8a, 0x7f, 0xa7, 0x85, 0xfd, 0x40, 0xe8, 0x6b, 0x5b, 0x27, 0xd1, 0x85, 0x57, + 0x9c, 0xf6, 0x97, 0xba, 0xf8, 0x2a, 0x72, 0xf4, 0x74, 0x85, 0x93, 0xfd, 0xc7, 0xd2, 0x1d, 0x07, + 0x66, 0xcb, 0xd8, 0x7c, 0xe1, 0x1a, 0xbf, 0x7c, 0x7e, 0x6b, 0x60, 0xa5, 0x67, 0xa7, 0x13, 0xb2, + 0x74, 0xef, 0x43, 0x16, 0x64, 0xca, 0xd8, 0xe4, 0x4f, 0xc1, 0x7c, 0xf2, 0xd3, 0xe0, 0x9f, 0x61, + 0x3d, 0xbb, 0xff, 0x46, 0x10, 0xf6, 0xc6, 0x67, 0xd9, 0x4e, 0xea, 0x60, 0xb6, 0xf7, 0xe6, 0xd8, + 0x1a, 0x21, 0xd2, 0x43, 0x0a, 0xff, 0x8d, 0x4b, 0xb2, 0xc5, 0x5e, 0x83, 0x69, 0xd6, 0xf4, 0x36, + 0x47, 0xcc, 0x8e, 0x20, 0xe1, 0xdf, 0x31, 0x20, 0xa6, 0x7e, 0x0a, 0xe6, 0x93, 0x2d, 0x65, 0x94, + 0x7b, 0x09, 0x76, 0xa4, 0x7b, 0xc3, 0x8e, 0x56, 0x15, 0x80, 0xd8, 0x39, 0xf8, 0x73, 0x84, 0x42, + 0x17, 0x13, 0x76, 0xc6, 0xc2, 0xa2, 0x35, 0x8a, 0x4f, 0xae, 0x6e, 0x0a, 0xdc, 0xf5, 0x4d, 0x81, + 0xfb, 0x76, 0x53, 0xe0, 0x2e, 0x6e, 0x0b, 0xa9, 0xeb, 0xdb, 0x42, 0xea, 0xf3, 0x6d, 0x21, 0xf5, + 0x6a, 0x7b, 0xe4, 0x35, 0x76, 0xce, 0x3e, 0x53, 0xe9, 0x85, 0x56, 0xcd, 0xd1, 0x48, 0xfe, 0xff, + 0x23, 0x00, 0x00, 0xff, 0xff, 0x9f, 0x9d, 0x50, 0xee, 0x55, 0x0b, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -789,10 +791,15 @@ func (m *MsgCreateValidator) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x3a - if len(m.Pubkey) > 0 { - i -= len(m.Pubkey) - copy(dAtA[i:], m.Pubkey) - i = encodeVarintTx(dAtA, i, uint64(len(m.Pubkey))) + if m.Pubkey != nil { + { + size, err := m.Pubkey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } i-- dAtA[i] = 0x32 } @@ -1097,12 +1104,12 @@ func (m *MsgBeginRedelegateResponse) MarshalToSizedBuffer(dAtA []byte) (int, err _ = i var l int _ = l - n7, err7 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.CompletionTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.CompletionTime):]) - if err7 != nil { - return 0, err7 + n8, err8 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.CompletionTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.CompletionTime):]) + if err8 != nil { + return 0, err8 } - i -= n7 - i = encodeVarintTx(dAtA, i, uint64(n7)) + i -= n8 + i = encodeVarintTx(dAtA, i, uint64(n8)) i-- dAtA[i] = 0xa return len(dAtA) - i, nil @@ -1175,12 +1182,12 @@ func (m *MsgUndelegateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - n9, err9 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.CompletionTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.CompletionTime):]) - if err9 != nil { - return 0, err9 + n10, err10 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.CompletionTime, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.CompletionTime):]) + if err10 != nil { + return 0, err10 } - i -= n9 - i = encodeVarintTx(dAtA, i, uint64(n9)) + i -= n10 + i = encodeVarintTx(dAtA, i, uint64(n10)) i-- dAtA[i] = 0xa return len(dAtA) - i, nil @@ -1217,8 +1224,8 @@ func (m *MsgCreateValidator) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - l = len(m.Pubkey) - if l > 0 { + if m.Pubkey != nil { + l = m.Pubkey.Size() n += 1 + l + sovTx(uint64(l)) } l = m.Value.Size() @@ -1562,7 +1569,7 @@ func (m *MsgCreateValidator) Unmarshal(dAtA []byte) error { if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pubkey", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -1572,23 +1579,27 @@ func (m *MsgCreateValidator) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Pubkey = string(dAtA[iNdEx:postIndex]) + if m.Pubkey == nil { + m.Pubkey = &types.Any{} + } + if err := m.Pubkey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 7: if wireType != 2 {