From 3936030e16c8483101c5ff0263b44077aecb81c3 Mon Sep 17 00:00:00 2001 From: Likhita Polavarapu <78951027+likhita-809@users.noreply.github.com> Date: Fri, 28 Apr 2023 13:28:35 +0530 Subject: [PATCH] test(x/slashing): write integration tests (#15928) --- tests/e2e/slashing/cli_test.go | 19 -- tests/e2e/slashing/grpc.go | 102 ---------- tests/e2e/slashing/suite.go | 184 ----------------- .../slashing/keeper/keeper_test.go | 190 +++++++++++++----- x/slashing/abci_test.go | 2 +- x/slashing/keeper/grpc_query.go | 10 +- x/slashing/keeper/grpc_query_test.go | 1 + .../val_init_helpers.go} | 4 +- 8 files changed, 152 insertions(+), 360 deletions(-) delete mode 100644 tests/e2e/slashing/cli_test.go delete mode 100644 tests/e2e/slashing/grpc.go delete mode 100644 tests/e2e/slashing/suite.go rename x/slashing/{init_test.go => testutil/val_init_helpers.go} (57%) diff --git a/tests/e2e/slashing/cli_test.go b/tests/e2e/slashing/cli_test.go deleted file mode 100644 index 0ea946ce45..0000000000 --- a/tests/e2e/slashing/cli_test.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build e2e -// +build e2e - -package testutil - -import ( - "testing" - - "cosmossdk.io/simapp" - "github.com/cosmos/cosmos-sdk/testutil/network" - - "github.com/stretchr/testify/suite" -) - -func TestE2ETestSuite(t *testing.T) { - cfg := network.DefaultConfig(simapp.NewTestNetworkFixture) - cfg.NumValidators = 1 - suite.Run(t, NewE2ETestSuite(cfg)) -} diff --git a/tests/e2e/slashing/grpc.go b/tests/e2e/slashing/grpc.go deleted file mode 100644 index efea63187d..0000000000 --- a/tests/e2e/slashing/grpc.go +++ /dev/null @@ -1,102 +0,0 @@ -package testutil - -import ( - "fmt" - "time" - - "github.com/cosmos/gogoproto/proto" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -func (s *E2ETestSuite) TestGRPCQueries() { - val := s.network.Validators[0] - baseURL := val.APIAddress - - consAddr := sdk.ConsAddress(val.PubKey.Address()).String() - - testCases := []struct { - name string - url string - headers map[string]string - expErr bool - respType proto.Message - expected proto.Message - }{ - { - "get signing infos (height specific)", - fmt.Sprintf("%s/cosmos/slashing/v1beta1/signing_infos", baseURL), - map[string]string{ - grpctypes.GRPCBlockHeightHeader: "1", - }, - false, - &types.QuerySigningInfosResponse{}, - &types.QuerySigningInfosResponse{ - Info: []types.ValidatorSigningInfo{ - { - Address: sdk.ConsAddress(val.PubKey.Address()).String(), - JailedUntil: time.Unix(0, 0), - }, - }, - Pagination: &query.PageResponse{ - Total: uint64(1), - }, - }, - }, - { - "get signing info (height specific)", - fmt.Sprintf("%s/cosmos/slashing/v1beta1/signing_infos/%s", baseURL, consAddr), - map[string]string{ - grpctypes.GRPCBlockHeightHeader: "1", - }, - false, - &types.QuerySigningInfoResponse{}, - &types.QuerySigningInfoResponse{ - ValSigningInfo: types.ValidatorSigningInfo{ - Address: sdk.ConsAddress(val.PubKey.Address()).String(), - JailedUntil: time.Unix(0, 0), - }, - }, - }, - { - "get signing info wrong address", - fmt.Sprintf("%s/cosmos/slashing/v1beta1/signing_infos/%s", baseURL, "wrongAddress"), - map[string]string{}, - true, - &types.QuerySigningInfoResponse{}, - nil, - }, - { - "params", - fmt.Sprintf("%s/cosmos/slashing/v1beta1/params", baseURL), - map[string]string{}, - false, - &types.QueryParamsResponse{}, - &types.QueryParamsResponse{ - Params: types.DefaultParams(), - }, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) - s.Require().NoError(err) - - err = val.ClientCtx.Codec.UnmarshalJSON(resp, tc.respType) - - if tc.expErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().Equal(tc.expected.String(), tc.respType.String()) - } - }) - } -} diff --git a/tests/e2e/slashing/suite.go b/tests/e2e/slashing/suite.go deleted file mode 100644 index a3d9835aa2..0000000000 --- a/tests/e2e/slashing/suite.go +++ /dev/null @@ -1,184 +0,0 @@ -package testutil - -import ( - "fmt" - "strings" - - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/suite" - - "github.com/cosmos/cosmos-sdk/client/flags" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/cosmos/cosmos-sdk/testutil/network" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" -) - -type E2ETestSuite struct { - suite.Suite - - cfg network.Config - network *network.Network -} - -func NewE2ETestSuite(cfg network.Config) *E2ETestSuite { - return &E2ETestSuite{cfg: cfg} -} - -// SetupSuite executes bootstrapping logic before all the tests, i.e. once before -// the entire suite, start executing. -func (s *E2ETestSuite) SetupSuite() { - s.T().Log("setting up e2e test suite") - - var err error - s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg) - s.Require().NoError(err) - - s.Require().NoError(s.network.WaitForNextBlock()) -} - -// TearDownSuite performs cleanup logic after all the tests, i.e. once after the -// entire suite, has finished executing. -func (s *E2ETestSuite) TearDownSuite() { - s.T().Log("tearing down e2e test suite") - s.network.Cleanup() -} - -func (s *E2ETestSuite) TestGetCmdQuerySigningInfo() { - val := s.network.Validators[0] - pubKeyBz, err := s.cfg.Codec.MarshalInterfaceJSON(val.PubKey) - s.Require().NoError(err) - pubKeyStr := string(pubKeyBz) - - testCases := []struct { - name string - args []string - expectErr bool - expectedOutput string - }{ - {"invalid address", []string{"foo"}, true, ``}, - { - "valid address (json output)", - []string{ - pubKeyStr, - fmt.Sprintf("--%s=json", flags.FlagOutput), - fmt.Sprintf("--%s=1", flags.FlagHeight), - }, - false, - fmt.Sprintf("{\"address\":\"%s\",\"start_height\":\"0\",\"index_offset\":\"0\",\"jailed_until\":\"1970-01-01T00:00:00Z\",\"tombstoned\":false,\"missed_blocks_counter\":\"0\"}", sdk.ConsAddress(val.PubKey.Address())), - }, - { - "valid address (text output)", - []string{ - pubKeyStr, - fmt.Sprintf("--%s=text", flags.FlagOutput), - fmt.Sprintf("--%s=1", flags.FlagHeight), - }, - false, - fmt.Sprintf(`address: %s -index_offset: "0" -jailed_until: "1970-01-01T00:00:00Z" -missed_blocks_counter: "0" -start_height: "0" -tombstoned: false`, sdk.ConsAddress(val.PubKey.Address())), - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := cli.GetCmdQuerySigningInfo() - clientCtx := val.ClientCtx - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().Equal(tc.expectedOutput, strings.TrimSpace(out.String())) - } - }) - } -} - -func (s *E2ETestSuite) TestGetCmdQueryParams() { - val := s.network.Validators[0] - - testCases := []struct { - name string - args []string - expectedOutput string - }{ - { - "json output", - []string{fmt.Sprintf("--%s=json", flags.FlagOutput)}, - `{"signed_blocks_window":"100","min_signed_per_window":"0.500000000000000000","downtime_jail_duration":"600s","slash_fraction_double_sign":"0.050000000000000000","slash_fraction_downtime":"0.010000000000000000"}`, - }, - { - "text output", - []string{fmt.Sprintf("--%s=text", flags.FlagOutput)}, - `downtime_jail_duration: 600s -min_signed_per_window: "0.500000000000000000" -signed_blocks_window: "100" -slash_fraction_double_sign: "0.050000000000000000" -slash_fraction_downtime: "0.010000000000000000"`, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := cli.GetCmdQueryParams() - clientCtx := val.ClientCtx - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - s.Require().NoError(err) - s.Require().Equal(tc.expectedOutput, strings.TrimSpace(out.String())) - }) - } -} - -func (s *E2ETestSuite) TestNewUnjailTxCmd() { - val := s.network.Validators[0] - testCases := []struct { - name string - args []string - expectErr bool - expectedCode uint32 - respType proto.Message - }{ - { - "valid transaction", - []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), // sync mode as there are no funds yet - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), - }, - false, slashingtypes.ErrValidatorNotJailed.ABCICode(), &sdk.TxResponse{}, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := cli.NewUnjailTxCmd() - clientCtx := val.ClientCtx - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) - - txResp := tc.respType.(*sdk.TxResponse) - s.Require().NoError(clitestutil.CheckTxCode(s.network, clientCtx, txResp.TxHash, tc.expectedCode)) - } - }) - } -} diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index 844850486a..8d56aaf904 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -4,65 +4,128 @@ import ( "testing" "time" + "cosmossdk.io/log" + storetypes "cosmossdk.io/store/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" "gotest.tools/v3/assert" - "cosmossdk.io/depinject" - "cosmossdk.io/log" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/testutil/integration" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing/testutil" - + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/bank" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/slashing" slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing/testutil" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil" - - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// The default power validators are initialized to have within tests -var InitTokens = sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction) - type fixture struct { - ctx sdk.Context + app *integration.App + + ctx sdk.Context + + bankKeeper bankkeeper.Keeper slashingKeeper slashingkeeper.Keeper stakingKeeper *stakingkeeper.Keeper - bankKeeper bankkeeper.Keeper - addrDels []sdk.AccAddress + + addrDels []sdk.AccAddress + valAddrs []sdk.ValAddress } -func initFixture(t assert.TestingT) *fixture { - f := &fixture{} - app, err := simtestutil.Setup( - depinject.Configs( - testutil.AppConfig, - depinject.Supply(log.NewNopLogger()), - ), - &f.bankKeeper, - &f.slashingKeeper, - &f.stakingKeeper, +func initFixture(t testing.TB) *fixture { + keys := storetypes.NewKVStoreKeys( + authtypes.StoreKey, banktypes.StoreKey, slashingtypes.StoreKey, stakingtypes.StoreKey, ) - assert.NilError(t, err) + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}).Codec - ctx := app.BaseApp.NewContext(false, cmtproto.Header{}) + logger := log.NewTestLogger(t) + cms := integration.CreateMultiStore(keys, logger) + + newCtx := sdk.NewContext(cms, cmtproto.Header{}, true, logger) + + authority := authtypes.NewModuleAddress("gov") + + maccPerms := map[string][]string{ + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + } + + accountKeeper := authkeeper.NewAccountKeeper( + cdc, + runtime.NewKVStoreService(keys[authtypes.StoreKey]), + authtypes.ProtoBaseAccount, + maccPerms, + sdk.Bech32MainPrefix, + authority.String(), + ) + + blockedAddresses := map[string]bool{ + accountKeeper.GetAuthority(): false, + } + bankKeeper := bankkeeper.NewBaseKeeper( + cdc, + runtime.NewKVStoreService(keys[banktypes.StoreKey]), + accountKeeper, + blockedAddresses, + authority.String(), + log.NewNopLogger(), + ) + + stakingKeeper := stakingkeeper.NewKeeper(cdc, keys[stakingtypes.StoreKey], accountKeeper, bankKeeper, authority.String()) + + slashingKeeper := slashingkeeper.NewKeeper(cdc, &codec.LegacyAmino{}, keys[slashingtypes.StoreKey], stakingKeeper, authority.String()) + + bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) + stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil) + slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, nil, cdc.InterfaceRegistry()) + + integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, bankModule, stakingModule, slashingModule) + + sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()) + + // Register MsgServer and QueryServer + slashingtypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), slashingkeeper.NewMsgServerImpl(slashingKeeper)) + slashingtypes.RegisterQueryServer(integrationApp.QueryHelper(), slashingkeeper.NewQuerier(slashingKeeper)) + + // set default staking params + stakingKeeper.SetParams(sdkCtx, stakingtypes.DefaultParams()) // TestParams set the SignedBlocksWindow to 1000 and MaxMissedBlocksPerWindow to 500 - f.slashingKeeper.SetParams(ctx, testutil.TestParams()) - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 5, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200)) + slashingKeeper.SetParams(sdkCtx, testutil.TestParams()) + addrDels := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, sdkCtx, 6, stakingKeeper.TokensFromConsensusPower(sdkCtx, 200)) + valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) info1 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), int64(4), int64(3), time.Unix(2, 0), false, int64(10)) info2 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), int64(5), int64(4), time.Unix(2, 0), false, int64(10)) - f.slashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), info1) - f.slashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1]), info2) + slashingKeeper.SetValidatorSigningInfo(sdkCtx, sdk.ConsAddress(addrDels[0]), info1) + slashingKeeper.SetValidatorSigningInfo(sdkCtx, sdk.ConsAddress(addrDels[1]), info2) - f.addrDels = addrDels - f.ctx = ctx - - return f + return &fixture{ + app: integrationApp, + ctx: sdkCtx, + bankKeeper: bankKeeper, + slashingKeeper: slashingKeeper, + stakingKeeper: stakingKeeper, + addrDels: addrDels, + valAddrs: valAddrs, + } } func TestUnJailNotBonded(t *testing.T) { @@ -73,14 +136,12 @@ func TestUnJailNotBonded(t *testing.T) { p.MaxValidators = 5 f.stakingKeeper.SetParams(f.ctx, p) - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 6, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) pks := simtestutil.CreateTestPubKeys(6) tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) // create max (5) validators all with the same power for i := uint32(0); i < p.MaxValidators; i++ { - addr, val := valAddrs[i], pks[i] + addr, val := f.valAddrs[i], pks[i] tstaking.CreateValidatorWithValPower(addr, val, 100, true) } @@ -88,7 +149,7 @@ func TestUnJailNotBonded(t *testing.T) { f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // create a 6th validator with less power than the cliff validator (won't be bonded) - addr, val := valAddrs[5], pks[5] + addr, val := f.valAddrs[5], pks[5] amt := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 50) msg := tstaking.CreateValidatorMsg(addr, val, amt) msg.MinSelfDelegation = amt @@ -113,7 +174,15 @@ func TestUnJailNotBonded(t *testing.T) { tstaking.CheckValidator(addr, -1, true) // verify we cannot unjail (yet) - assert.ErrorContains(t, f.slashingKeeper.Unjail(f.ctx, addr), "cannot be unjailed") + msgUnjail := slashingtypes.MsgUnjail{ + ValidatorAddr: addr.String(), + } + _, err = f.app.RunMsg( + &msgUnjail, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) + assert.ErrorContains(t, err, "cannot be unjailed") f.stakingKeeper.EndBlocker(f.ctx) f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) @@ -124,7 +193,12 @@ func TestUnJailNotBonded(t *testing.T) { f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // verify we can immediately unjail - assert.NilError(t, f.slashingKeeper.Unjail(f.ctx, addr)) + _, err = f.app.RunMsg( + &msgUnjail, + integration.WithAutomaticBeginEndBlock(), + integration.WithAutomaticCommit(), + ) + assert.NilError(t, err) tstaking.CheckValidator(addr, -1, false) } @@ -136,20 +210,23 @@ func TestHandleNewValidator(t *testing.T) { t.Parallel() f := initFixture(t) - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 1, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 0)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) pks := simtestutil.CreateTestPubKeys(1) - addr, val := valAddrs[0], pks[0] + addr, val := f.valAddrs[0], pks[0] tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) f.ctx = f.ctx.WithBlockHeight(f.slashingKeeper.SignedBlocksWindow(f.ctx) + 1) + f.slashingKeeper.AddPubkey(f.ctx, pks[0]) + + info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(val.Address()), f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) + f.slashingKeeper.SetValidatorSigningInfo(f.ctx, sdk.ConsAddress(val.Address()), info) + // Validator created amt := tstaking.CreateValidatorWithValPower(addr, val, 100, true) f.stakingKeeper.EndBlocker(f.ctx) assert.DeepEqual( t, f.bankKeeper.GetAllBalances(f.ctx, sdk.AccAddress(addr)), - sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.GetParams(f.ctx).BondDenom, InitTokens.Sub(amt))), + sdk.NewCoins(sdk.NewCoin(f.stakingKeeper.GetParams(f.ctx).BondDenom, testutil.InitTokens.Sub(amt))), ) assert.DeepEqual(t, amt, f.stakingKeeper.Validator(f.ctx, addr).GetBondedTokens()) @@ -170,8 +247,6 @@ func TestHandleNewValidator(t *testing.T) { assert.Equal(t, stakingtypes.Bonded, validator.GetStatus()) bondPool := f.stakingKeeper.GetBondedPool(f.ctx) expTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 100) - // adding genesis validator tokens - expTokens = expTokens.Add(f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1)) assert.Assert(t, expTokens.Equal(f.bankKeeper.GetBalance(f.ctx, bondPool.GetAddress(), f.stakingKeeper.BondDenom(f.ctx)).Amount)) } @@ -181,13 +256,16 @@ func TestHandleAlreadyJailed(t *testing.T) { t.Parallel() f := initFixture(t) - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 1, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) pks := simtestutil.CreateTestPubKeys(1) - addr, val := valAddrs[0], pks[0] + addr, val := f.valAddrs[0], pks[0] power := int64(100) tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) + f.slashingKeeper.AddPubkey(f.ctx, pks[0]) + + info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(val.Address()), f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) + f.slashingKeeper.SetValidatorSigningInfo(f.ctx, sdk.ConsAddress(val.Address()), info) + amt := tstaking.CreateValidatorWithValPower(addr, val, power, true) f.stakingKeeper.EndBlocker(f.ctx) @@ -245,10 +323,15 @@ func TestValidatorDippingInAndOut(t *testing.T) { tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) valAddr := sdk.ValAddress(addr) + f.slashingKeeper.AddPubkey(f.ctx, pks[0]) + + info := slashingtypes.NewValidatorSigningInfo(consAddr, f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) + f.slashingKeeper.SetValidatorSigningInfo(f.ctx, consAddr, info) + tstaking.CreateValidatorWithValPower(valAddr, val, power, true) validatorUpdates, err := f.stakingKeeper.EndBlocker(f.ctx) require.NoError(t, err) - assert.Equal(t, 2, len(validatorUpdates)) + assert.Equal(t, 1, len(validatorUpdates)) tstaking.CheckValidator(valAddr, stakingtypes.Bonded, false) // 100 first blocks OK @@ -289,16 +372,18 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator misses an additional 500 more blocks within the SignedBlockWindow (here 1000 blocks). latest := f.slashingKeeper.SignedBlocksWindow(f.ctx) + height // misses 500 blocks + within the signing windows i.e. 700-1700 - // validators misses all 1000 block of a SignedBlockWindows + // validators misses all 1000 blocks of a SignedBlockWindows for ; height < latest+1; height++ { - f.ctx = f.ctx.WithBlockHeight(height) - f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, false) + f.slashingKeeper.HandleValidatorSignature(f.ctx.WithBlockHeight(height), val.Address(), newPower, false) } // should now be jailed & kicked f.stakingKeeper.EndBlocker(f.ctx) tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, true) + info = slashingtypes.NewValidatorSigningInfo(consAddr, f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) + f.slashingKeeper.SetValidatorSigningInfo(f.ctx, consAddr, info) + // check all the signing information signInfo, found := f.slashingKeeper.GetValidatorSigningInfo(f.ctx, consAddr) assert.Assert(t, found) @@ -310,6 +395,9 @@ func TestValidatorDippingInAndOut(t *testing.T) { height = int64(5000) f.ctx = f.ctx.WithBlockHeight(height) + info = slashingtypes.NewValidatorSigningInfo(consAddr, f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) + f.slashingKeeper.SetValidatorSigningInfo(f.ctx, consAddr, info) + // validator rejoins and starts signing again f.stakingKeeper.Unjail(f.ctx, consAddr) diff --git a/x/slashing/abci_test.go b/x/slashing/abci_test.go index 8547825939..d3169a8043 100644 --- a/x/slashing/abci_test.go +++ b/x/slashing/abci_test.go @@ -53,7 +53,7 @@ func TestBeginBlocker(t *testing.T) { stakingKeeper.EndBlocker(ctx) require.Equal( t, bankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), - sdk.NewCoins(sdk.NewCoin(stakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), + sdk.NewCoins(sdk.NewCoin(stakingKeeper.GetParams(ctx).BondDenom, testutil.InitTokens.Sub(amt))), ) require.Equal(t, amt, stakingKeeper.Validator(ctx, addr).GetBondedTokens()) diff --git a/x/slashing/keeper/grpc_query.go b/x/slashing/keeper/grpc_query.go index f39fd9f71f..74b59bb525 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -13,7 +13,15 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing/types" ) -var _ types.QueryServer = Keeper{} +var _ types.QueryServer = Querier{} + +type Querier struct { + Keeper +} + +func NewQuerier(keeper Keeper) Querier { + return Querier{Keeper: keeper} +} // Params returns parameters of x/slashing module func (k Keeper) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { diff --git a/x/slashing/keeper/grpc_query_test.go b/x/slashing/keeper/grpc_query_test.go index 20f111439d..630b9cc719 100644 --- a/x/slashing/keeper/grpc_query_test.go +++ b/x/slashing/keeper/grpc_query_test.go @@ -26,6 +26,7 @@ func (s *KeeperTestSuite) TestGRPCSigningInfo() { infoResp, err := queryClient.SigningInfo(gocontext.Background(), &slashingtypes.QuerySigningInfoRequest{ConsAddress: ""}) require.Error(err) + require.ErrorContains(err, "invalid request") require.Nil(infoResp) signingInfo := slashingtypes.NewValidatorSigningInfo( diff --git a/x/slashing/init_test.go b/x/slashing/testutil/val_init_helpers.go similarity index 57% rename from x/slashing/init_test.go rename to x/slashing/testutil/val_init_helpers.go index b9bbfe694e..8ee2d8c79c 100644 --- a/x/slashing/init_test.go +++ b/x/slashing/testutil/val_init_helpers.go @@ -1,8 +1,8 @@ -package slashing_test +package testutil import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// The default power validators are initialized to have within tests +// InitTokens is the default power validators are initialized to have within tests var InitTokens = sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction)