From c8a8d821bba6d29ccea46bb125a379e2c172488d Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Mon, 12 Feb 2024 23:41:09 +0100 Subject: [PATCH 01/20] migrate staking to use env --- x/staking/keeper/alias_functions.go | 6 +- x/staking/keeper/cons_pubkey.go | 16 ++--- x/staking/keeper/delegation.go | 27 ++++---- x/staking/keeper/genesis.go | 2 +- x/staking/keeper/grpc_query.go | 8 +-- x/staking/keeper/historical_info.go | 13 ++-- x/staking/keeper/keeper.go | 12 ++-- x/staking/keeper/migrations.go | 2 +- x/staking/keeper/msg_server.go | 97 ++++++++++++---------------- x/staking/keeper/slash.go | 17 +++-- x/staking/keeper/unbonding.go | 11 ++-- x/staking/keeper/val_state_change.go | 41 ++++++------ x/staking/keeper/validator.go | 23 ++++--- 13 files changed, 126 insertions(+), 149 deletions(-) diff --git a/x/staking/keeper/alias_functions.go b/x/staking/keeper/alias_functions.go index fde1c5254e1e..9aa826982a6c 100644 --- a/x/staking/keeper/alias_functions.go +++ b/x/staking/keeper/alias_functions.go @@ -15,7 +15,7 @@ import ( // IterateValidators iterates through the validator set and perform the provided function func (k Keeper) IterateValidators(ctx context.Context, fn func(index int64, validator sdk.ValidatorI) (stop bool)) error { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey)) if err != nil { return err @@ -42,7 +42,7 @@ func (k Keeper) IterateValidators(ctx context.Context, fn func(index int64, vali // IterateBondedValidatorsByPower iterates through the bonded validator set and perform the provided function func (k Keeper) IterateBondedValidatorsByPower(ctx context.Context, fn func(index int64, validator sdk.ValidatorI) (stop bool)) error { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) maxValidators, err := k.MaxValidators(ctx) if err != nil { return err @@ -115,7 +115,7 @@ func (k Keeper) IterateDelegations(ctx context.Context, delAddr sdk.AccAddress, // GetAllSDKDelegations returns all delegations used during genesis dump // TODO: remove this func, change all usage for iterate functionality func (k Keeper) GetAllSDKDelegations(ctx context.Context) (delegations []types.Delegation, err error) { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) iterator, err := store.Iterator(types.DelegationKey, storetypes.PrefixEndBytes(types.DelegationKey)) if err != nil { return delegations, err diff --git a/x/staking/keeper/cons_pubkey.go b/x/staking/keeper/cons_pubkey.go index 03e41f226186..f666ae21e542 100644 --- a/x/staking/keeper/cons_pubkey.go +++ b/x/staking/keeper/cons_pubkey.go @@ -25,8 +25,8 @@ func (k Keeper) setConsPubKeyRotationHistory( ctx context.Context, valAddr sdk.ValAddress, oldPubKey, newPubKey *codectypes.Any, fee sdk.Coin, ) error { - sdkCtx := sdk.UnwrapSDKContext(ctx) - height := uint64(sdkCtx.BlockHeight()) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + height := uint64(headerInfo.Height) history := types.ConsPubKeyRotationHistory{ OperatorAddress: valAddr.Bytes(), OldConsPubkey: oldPubKey, @@ -44,7 +44,7 @@ func (k Keeper) setConsPubKeyRotationHistory( return err } - queueTime := sdkCtx.HeaderInfo().Time.Add(ubdTime) + queueTime := headerInfo.Time.Add(ubdTime) if err := k.ValidatorConsensusKeyRotationRecordIndexKey.Set(ctx, collections.Join(valAddr.Bytes(), queueTime)); err != nil { return err } @@ -179,7 +179,7 @@ func bytesSliceExists(sliceList [][]byte, targetBytes []byte) bool { } // PurgeAllMaturedConsKeyRotatedKeys deletes all the matured key rotations. -func (k Keeper) PurgeAllMaturedConsKeyRotatedKeys(ctx sdk.Context, maturedTime time.Time) error { +func (k Keeper) PurgeAllMaturedConsKeyRotatedKeys(ctx context.Context, maturedTime time.Time) error { maturedRotatedValAddrs, err := k.getAndRemoveAllMaturedRotatedKeys(ctx, maturedTime) if err != nil { return err @@ -197,7 +197,7 @@ func (k Keeper) PurgeAllMaturedConsKeyRotatedKeys(ctx sdk.Context, maturedTime t // deleteConsKeyIndexKey deletes the keys which forms a with given validator address and time lesser than the given time. // eventually there should be only one occurrence since we allow only one rotation for bonding period. -func (k Keeper) deleteConsKeyIndexKey(ctx sdk.Context, valAddr sdk.ValAddress, ts time.Time) error { +func (k Keeper) deleteConsKeyIndexKey(ctx context.Context, valAddr sdk.ValAddress, ts time.Time) error { rng := new(collections.Range[collections.Pair[[]byte, time.Time]]). StartInclusive(collections.Join(valAddr.Bytes(), time.Time{})). EndInclusive(collections.Join(valAddr.Bytes(), ts)) @@ -208,7 +208,7 @@ func (k Keeper) deleteConsKeyIndexKey(ctx sdk.Context, valAddr sdk.ValAddress, t } // getAndRemoveAllMaturedRotatedKeys returns all matured valaddresses. -func (k Keeper) getAndRemoveAllMaturedRotatedKeys(ctx sdk.Context, matureTime time.Time) ([][]byte, error) { +func (k Keeper) getAndRemoveAllMaturedRotatedKeys(ctx context.Context, matureTime time.Time) ([][]byte, error) { valAddrs := [][]byte{} // get an iterator for all timeslices from time 0 until the current HeaderInfo time @@ -226,9 +226,9 @@ func (k Keeper) getAndRemoveAllMaturedRotatedKeys(ctx sdk.Context, matureTime ti // GetBlockConsPubKeyRotationHistory returns the rotation history for the current height. func (k Keeper) GetBlockConsPubKeyRotationHistory(ctx context.Context) ([]types.ConsPubKeyRotationHistory, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) - iterator, err := k.RotationHistory.Indexes.Block.MatchExact(ctx, uint64(sdkCtx.BlockHeight())) + iterator, err := k.RotationHistory.Indexes.Block.MatchExact(ctx, uint64(headerInfo.Height)) if err != nil { return nil, err } diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 87f405537c3c..4dbe93dd81c6 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -165,7 +165,7 @@ func (k Keeper) GetUnbondingDelegation(ctx context.Context, delAddr sdk.AccAddre // GetUnbondingDelegationsFromValidator returns all unbonding delegations from a // particular validator. func (k Keeper) GetUnbondingDelegationsFromValidator(ctx context.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation, err error) { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) rng := collections.NewPrefixedPairRange[[]byte, []byte](valAddr) err = k.UnbondingDelegationByValIndex.Walk( ctx, @@ -653,11 +653,10 @@ func (k Keeper) InsertRedelegationQueue(ctx context.Context, red types.Redelegat // the queue. func (k Keeper) DequeueAllMatureRedelegationQueue(ctx context.Context, currTime time.Time) (matureRedelegations []types.DVVTriplet, err error) { var keys []time.Time - - sdkCtx := sdk.UnwrapSDKContext(ctx) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) // gets an iterator for all timeslices from time 0 until the current Blockheader time - rng := (&collections.Range[time.Time]{}).EndInclusive(sdkCtx.HeaderInfo().Time) + rng := (&collections.Range[time.Time]{}).EndInclusive(headerInfo.Time) err = k.RedelegationQueue.Walk(ctx, rng, func(key time.Time, value types.DVVTriplets) (bool, error) { keys = append(keys, key) matureRedelegations = append(matureRedelegations, value.Triplets...) @@ -891,7 +890,7 @@ func (k Keeper) getBeginInfo( if err != nil && errors.Is(err, types.ErrNoValidatorFound) { return completionTime, height, false, nil } - sdkCtx := sdk.UnwrapSDKContext(ctx) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) unbondingTime, err := k.UnbondingTime(ctx) if err != nil { return completionTime, height, false, err @@ -901,8 +900,8 @@ func (k Keeper) getBeginInfo( switch { case errors.Is(err, types.ErrNoValidatorFound) || validator.IsBonded(): // the longest wait - just unbonding period from now - completionTime = sdkCtx.HeaderInfo().Time.Add(unbondingTime) - height = sdkCtx.BlockHeight() + completionTime = headerInfo.Time.Add(unbondingTime) + height = headerInfo.Height return completionTime, height, false, nil @@ -957,9 +956,9 @@ func (k Keeper) Undelegate( return time.Time{}, math.Int{}, err } - sdkCtx := sdk.UnwrapSDKContext(ctx) - completionTime := sdkCtx.HeaderInfo().Time.Add(unbondingTime) - ubd, err := k.SetUnbondingDelegationEntry(ctx, delAddr, valAddr, sdkCtx.BlockHeight(), completionTime, returnAmount) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + completionTime := headerInfo.Time.Add(unbondingTime) + ubd, err := k.SetUnbondingDelegationEntry(ctx, delAddr, valAddr, headerInfo.Height, completionTime, returnAmount) if err != nil { return time.Time{}, math.Int{}, err } @@ -987,8 +986,8 @@ func (k Keeper) CompleteUnbonding(ctx context.Context, delAddr sdk.AccAddress, v } balances := sdk.NewCoins() - sdkCtx := sdk.UnwrapSDKContext(ctx) - ctxTime := sdkCtx.HeaderInfo().Time + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + ctxTime := headerInfo.Time delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress) if err != nil { @@ -1132,8 +1131,8 @@ func (k Keeper) CompleteRedelegation( } balances := sdk.NewCoins() - sdkCtx := sdk.UnwrapSDKContext(ctx) - ctxTime := sdkCtx.HeaderInfo().Time + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + ctxTime := headerInfo.Time // loop through all the entries and complete mature redelegation entries for i := 0; i < len(red.Entries); i++ { diff --git a/x/staking/keeper/genesis.go b/x/staking/keeper/genesis.go index cfed8a488f76..e63721550bd1 100644 --- a/x/staking/keeper/genesis.go +++ b/x/staking/keeper/genesis.go @@ -28,7 +28,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res // first TM block is at height 1, so state updates applied from // genesis.json are in block 0. sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay) + sdkCtx = sdkCtx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay) // TODO: replace this ctx = sdkCtx if err := k.Params.Set(ctx, data.Params); err != nil { diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index 305f1b469565..942d29997358 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -40,7 +40,7 @@ func (k Querier) Validators(ctx context.Context, req *types.QueryValidatorsReque return nil, status.Errorf(codes.InvalidArgument, "invalid validator status %s", req.Status) } - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) valStore := prefix.NewStore(store, types.ValidatorsKey) validators, pageRes, err := query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, val *types.Validator) (*types.Validator, error) { @@ -144,7 +144,7 @@ func (k Querier) ValidatorDelegations(ctx context.Context, req *types.QueryValid } func (k Querier) getValidatorDelegationsLegacy(ctx context.Context, req *types.QueryValidatorDelegationsRequest) ([]*types.Delegation, *query.PageResponse, error) { - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) valStore := prefix.NewStore(store, types.DelegationKey) return query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, delegation *types.Delegation) (*types.Delegation, error) { @@ -178,7 +178,7 @@ func (k Querier) ValidatorUnbondingDelegations(ctx context.Context, req *types.Q return nil, err } - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) keys, pageRes, err := query.CollectionPaginate( ctx, k.UnbondingDelegationByValIndex, @@ -415,7 +415,7 @@ func (k Querier) Redelegations(ctx context.Context, req *types.QueryRedelegation var pageRes *query.PageResponse var err error - store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) switch { case req.DelegatorAddr != "" && req.SrcValidatorAddr != "" && req.DstValidatorAddr != "": redels, err = queryRedelegation(ctx, k, req) diff --git a/x/staking/keeper/historical_info.go b/x/staking/keeper/historical_info.go index 721b97f8fa44..89dbdfba36d0 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -4,7 +4,6 @@ import ( "context" "cosmossdk.io/x/staking/types" - sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -16,7 +15,7 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error { return err } - sdkCtx := sdk.UnwrapSDKContext(ctx) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) // Prune store to ensure we only have parameter-defined historical entries. // In most cases, this will involve removing a single historical entry. @@ -25,7 +24,7 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error { // Since the entries to be deleted are always in a continuous range, we can iterate // over the historical entries starting from the most recent version to be pruned // and then return at the first empty entry. - for i := sdkCtx.HeaderInfo().Height - int64(entryNum); i >= 0; i-- { + for i := headerInfo.Height - int64(entryNum); i >= 0; i-- { has, err := k.HistoricalInfo.Has(ctx, uint64(i)) if err != nil { return err @@ -43,14 +42,14 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error { return nil } - time := sdkCtx.HeaderInfo().Time + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: remove this historicalEntry := types.HistoricalRecord{ - Time: &time, + Time: &headerInfo.Time, ValidatorsHash: sdkCtx.CometInfo().ValidatorsHash, - Apphash: sdkCtx.HeaderInfo().AppHash, + Apphash: headerInfo.AppHash, } // Set latest HistoricalInfo at current height - return k.HistoricalInfo.Set(ctx, uint64(sdkCtx.HeaderInfo().Height), historicalEntry) + return k.HistoricalInfo.Set(ctx, uint64(headerInfo.Height), historicalEntry) } diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index 0bad3d7dc684..7d124c55ca87 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -11,7 +11,7 @@ import ( collcodec "cosmossdk.io/collections/codec" "cosmossdk.io/collections/indexes" addresscodec "cosmossdk.io/core/address" - storetypes "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" "cosmossdk.io/log" "cosmossdk.io/math" "cosmossdk.io/x/staking/types" @@ -69,7 +69,7 @@ func NewRotationHistoryIndexes(sb *collections.SchemaBuilder) rotationHistoryInd // Keeper of the x/staking store type Keeper struct { - storeService storetypes.KVStoreService + environment appmodule.Environment cdc codec.BinaryCodec authKeeper types.AccountKeeper bankKeeper types.BankKeeper @@ -135,14 +135,14 @@ type Keeper struct { // NewKeeper creates a new staking Keeper instance func NewKeeper( cdc codec.BinaryCodec, - storeService storetypes.KVStoreService, + env appmodule.Environment, ak types.AccountKeeper, bk types.BankKeeper, authority string, validatorAddressCodec addresscodec.Codec, consensusAddressCodec addresscodec.Codec, ) *Keeper { - sb := collections.NewSchemaBuilder(storeService) + sb := collections.NewSchemaBuilder(env.KVStoreService) // ensure bonded and not bonded module accounts are set if addr := ak.GetModuleAddress(types.BondedPoolName); addr == nil { panic(fmt.Sprintf("%s module account has not been set", types.BondedPoolName)) @@ -162,7 +162,7 @@ func NewKeeper( } k := &Keeper{ - storeService: storeService, + environment: env, cdc: cdc, authKeeper: ak, bankKeeper: bk, @@ -317,7 +317,7 @@ func NewKeeper( // Logger returns a module-specific logger. func (k Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO remove this return sdkCtx.Logger().With("module", "x/"+types.ModuleName) } diff --git a/x/staking/keeper/migrations.go b/x/staking/keeper/migrations.go index f04dc799976f..7d43584d6ade 100644 --- a/x/staking/keeper/migrations.go +++ b/x/staking/keeper/migrations.go @@ -37,6 +37,6 @@ func (m Migrator) Migrate3to4(ctx context.Context) error { // Migrate4to5 migrates x/staking state from consensus version 4 to 5. func (m Migrator) Migrate4to5(ctx context.Context) error { - store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(m.keeper.environment.KVStoreService.OpenKVStore(ctx)) return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger(ctx)) } diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index b45b81099a4d..6cee27f5ce89 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -12,6 +12,7 @@ import ( "google.golang.org/grpc/status" "cosmossdk.io/collections" + "cosmossdk.io/core/event" errorsmod "cosmossdk.io/errors" "cosmossdk.io/math" "cosmossdk.io/x/staking/types" @@ -65,7 +66,7 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidType, "Expecting cryptotypes.PubKey, got %T", msg.Pubkey.GetCachedValue()) } - sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: remove this cp := sdkCtx.ConsensusParams() if cp.Validator != nil { pkType := pk.Type() @@ -148,13 +149,11 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali return nil, err } - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeCreateValidator, - sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Value.String()), - ), - }) + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeCreateValidator, + event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), + event.NewAttribute(sdk.AttributeKeyAmount, msg.Value.String()), + ) return &types.MsgCreateValidatorResponse{}, nil } @@ -237,14 +236,11 @@ func (k msgServer) EditValidator(ctx context.Context, msg *types.MsgEditValidato return nil, err } - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeEditValidator, - sdk.NewAttribute(types.AttributeKeyCommissionRate, validator.Commission.String()), - sdk.NewAttribute(types.AttributeKeyMinSelfDelegation, validator.MinSelfDelegation.String()), - ), - }) + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeEditValidator, + event.NewAttribute(types.AttributeKeyCommissionRate, validator.Commission.String()), + event.NewAttribute(types.AttributeKeyMinSelfDelegation, validator.MinSelfDelegation.String()), + ) return &types.MsgEditValidatorResponse{}, nil } @@ -301,16 +297,13 @@ func (k msgServer) Delegate(ctx context.Context, msg *types.MsgDelegate) (*types }() } - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeDelegate, - sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), - sdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()), - ), - }) + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeDelegate, + event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), + event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), + event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), + event.NewAttribute(types.AttributeKeyNewShares, newShares.String()), + ) return &types.MsgDelegateResponse{}, nil } @@ -375,16 +368,13 @@ func (k msgServer) BeginRedelegate(ctx context.Context, msg *types.MsgBeginRedel }() } - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeRedelegate, - sdk.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress), - sdk.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ), - }) + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeRedelegate, + event.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress), + event.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress), + event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), + event.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), + ) return &types.MsgBeginRedelegateResponse{ CompletionTime: completionTime, @@ -446,16 +436,13 @@ func (k msgServer) Undelegate(ctx context.Context, msg *types.MsgUndelegate) (*t }() } - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeUnbond, - sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), - sdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), - sdk.NewAttribute(sdk.AttributeKeyAmount, undelegatedCoin.String()), - sdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ), - }) + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeUnbond, + event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), + event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), + event.NewAttribute(sdk.AttributeKeyAmount, undelegatedCoin.String()), + event.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), + ) return &types.MsgUndelegateResponse{ CompletionTime: completionTime, @@ -546,8 +533,8 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg return nil, sdkerrors.ErrInvalidRequest.Wrap("amount is greater than the unbonding delegation entry balance") } - sdkCtx := sdk.UnwrapSDKContext(ctx) - if unbondEntry.CompletionTime.Before(sdkCtx.HeaderInfo().Time) { + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + if unbondEntry.CompletionTime.Before(headerInfo.Time) { return nil, sdkerrors.ErrInvalidRequest.Wrap("unbonding delegation is already processed") } @@ -578,14 +565,12 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg return nil, err } - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCancelUnbondingDelegation, - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), - sdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), - sdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)), - ), + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeCancelUnbondingDelegation, + event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), + event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), + event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), + event.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)), ) return &types.MsgCancelUnbondingDelegationResponse{}, nil diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 9a5b5e406407..e862f6285041 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -36,7 +36,6 @@ import ( // but not at a height in the future func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec) (math.Int, error) { logger := k.Logger(ctx) - sdkCtx := sdk.UnwrapSDKContext(ctx) if slashFactor.IsNegative() { return math.NewInt(0), fmt.Errorf("attempted to slash with a negative slash factor: %v", slashFactor) @@ -89,14 +88,16 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH // redelegations, as that stake has since unbonded remainingSlashAmount := slashAmount + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + height := headerInfo.Height switch { - case infractionHeight > sdkCtx.BlockHeight(): + case infractionHeight > height: // Can't slash infractions in the future return math.NewInt(0), fmt.Errorf( "impossible attempt to slash future infraction at height %d but we are at height %d", - infractionHeight, sdkCtx.BlockHeight()) + infractionHeight, height) - case infractionHeight == sdkCtx.BlockHeight(): + case infractionHeight == height: // Special-case slash at current height for efficiency - we don't need to // look through unbonding delegations or redelegations. logger.Info( @@ -104,7 +105,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH "height", infractionHeight, ) - case infractionHeight < sdkCtx.BlockHeight(): + case infractionHeight < height: // Iterate through unbonding delegations from slashed validator unbondingDelegations, err := k.GetUnbondingDelegationsFromValidator(ctx, operatorAddress) if err != nil { @@ -245,8 +246,7 @@ func (k Keeper) Unjail(ctx context.Context, consAddr sdk.ConsAddress) error { func (k Keeper) SlashUnbondingDelegation(ctx context.Context, unbondingDelegation types.UnbondingDelegation, infractionHeight int64, slashFactor math.LegacyDec, ) (totalSlashAmount math.Int, err error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - now := sdkCtx.HeaderInfo().Time + now := k.environment.HeaderService.GetHeaderInfo(ctx).Time totalSlashAmount = math.ZeroInt() burnedAmount := math.ZeroInt() @@ -302,8 +302,7 @@ func (k Keeper) SlashUnbondingDelegation(ctx context.Context, unbondingDelegatio func (k Keeper) SlashRedelegation(ctx context.Context, srcValidator types.Validator, redelegation types.Redelegation, infractionHeight int64, slashFactor math.LegacyDec, ) (totalSlashAmount math.Int, err error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - now := sdkCtx.HeaderInfo().Time + now := k.environment.HeaderService.GetHeaderInfo(ctx).Time totalSlashAmount = math.ZeroInt() bondedBurnedAmount, notBondedBurnedAmount := math.ZeroInt(), math.ZeroInt() diff --git a/x/staking/keeper/unbonding.go b/x/staking/keeper/unbonding.go index afe89f4fda66..22ab6e0f4f6a 100644 --- a/x/staking/keeper/unbonding.go +++ b/x/staking/keeper/unbonding.go @@ -75,7 +75,7 @@ func (k Keeper) GetUnbondingDelegationByUnbondingID(ctx context.Context, id uint // GetRedelegationByUnbondingID returns a unbonding delegation that has an unbonding delegation entry with a certain ID func (k Keeper) GetRedelegationByUnbondingID(ctx context.Context, id uint64) (red types.Redelegation, err error) { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) redKey, err := k.UnbondingIndex.Get(ctx, id) if err != nil { @@ -109,7 +109,7 @@ func (k Keeper) GetRedelegationByUnbondingID(ctx context.Context, id uint64) (re // GetValidatorByUnbondingID returns the validator that is unbonding with a certain unbonding op ID func (k Keeper) GetValidatorByUnbondingID(ctx context.Context, id uint64) (val types.Validator, err error) { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) valKey, err := k.UnbondingIndex.Get(ctx, id) if err != nil { @@ -282,9 +282,8 @@ func (k Keeper) unbondingDelegationEntryCanComplete(ctx context.Context, id uint } ubd.Entries[i].UnbondingOnHoldRefCount-- - sdkCtx := sdk.UnwrapSDKContext(ctx) // Check if entry is matured. - if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(sdkCtx.HeaderInfo().Time) { + if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(k.environment.HeaderService.GetHeaderInfo(ctx).Time) { // If matured, complete it. delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress) if err != nil { @@ -345,8 +344,8 @@ func (k Keeper) redelegationEntryCanComplete(ctx context.Context, id uint64) err } red.Entries[i].UnbondingOnHoldRefCount-- - sdkCtx := sdk.UnwrapSDKContext(ctx) - if !red.Entries[i].OnHold() && red.Entries[i].IsMature(sdkCtx.HeaderInfo().Time) { + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + if !red.Entries[i].OnHold() && red.Entries[i].IsMature(headerInfo.Time) { // If matured, complete it. // Remove entry red.RemoveEntry(int64(i)) diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index cbebd10410c9..e2aa6a4e6f4d 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -10,6 +10,7 @@ import ( gogotypes "github.com/cosmos/gogoproto/types" "cosmossdk.io/core/address" + "cosmossdk.io/core/event" errorsmod "cosmossdk.io/errors" "cosmossdk.io/math" "cosmossdk.io/x/staking/types" @@ -43,9 +44,9 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda return nil, err } - sdkCtx := sdk.UnwrapSDKContext(ctx) + time := k.environment.HeaderService.GetHeaderInfo(ctx).Time // Remove all mature unbonding delegations from the ubd queue. - matureUnbonds, err := k.DequeueAllMatureUBDQueue(ctx, sdkCtx.HeaderInfo().Time) + matureUnbonds, err := k.DequeueAllMatureUBDQueue(ctx, time) if err != nil { return nil, err } @@ -65,18 +66,16 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda continue } - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCompleteUnbonding, - sdk.NewAttribute(sdk.AttributeKeyAmount, balances.String()), - sdk.NewAttribute(types.AttributeKeyValidator, dvPair.ValidatorAddress), - sdk.NewAttribute(types.AttributeKeyDelegator, dvPair.DelegatorAddress), - ), + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeCompleteUnbonding, + event.NewAttribute(sdk.AttributeKeyAmount, balances.String()), + event.NewAttribute(types.AttributeKeyValidator, dvPair.ValidatorAddress), + event.NewAttribute(types.AttributeKeyDelegator, dvPair.DelegatorAddress), ) } // Remove all mature redelegations from the red queue. - matureRedelegations, err := k.DequeueAllMatureRedelegationQueue(ctx, sdkCtx.HeaderInfo().Time) + matureRedelegations, err := k.DequeueAllMatureRedelegationQueue(ctx, time) if err != nil { return nil, err } @@ -105,18 +104,16 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda continue } - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCompleteRedelegation, - sdk.NewAttribute(sdk.AttributeKeyAmount, balances.String()), - sdk.NewAttribute(types.AttributeKeyDelegator, dvvTriplet.DelegatorAddress), - sdk.NewAttribute(types.AttributeKeySrcValidator, dvvTriplet.ValidatorSrcAddress), - sdk.NewAttribute(types.AttributeKeyDstValidator, dvvTriplet.ValidatorDstAddress), - ), + k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeCompleteRedelegation, + event.NewAttribute(sdk.AttributeKeyAmount, balances.String()), + event.NewAttribute(types.AttributeKeyDelegator, dvvTriplet.DelegatorAddress), + event.NewAttribute(types.AttributeKeySrcValidator, dvvTriplet.ValidatorSrcAddress), + event.NewAttribute(types.AttributeKeyDstValidator, dvvTriplet.ValidatorDstAddress), ) } - err = k.PurgeAllMaturedConsKeyRotatedKeys(sdkCtx, sdkCtx.HeaderInfo().Time) + err = k.PurgeAllMaturedConsKeyRotatedKeys(ctx, time) if err != nil { return nil, err } @@ -470,10 +467,10 @@ func (k Keeper) BeginUnbondingValidator(ctx context.Context, validator types.Val validator = validator.UpdateStatus(types.Unbonding) - sdkCtx := sdk.UnwrapSDKContext(ctx) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) // set the unbonding completion time and completion height appropriately - validator.UnbondingTime = sdkCtx.HeaderInfo().Time.Add(params.UnbondingTime) - validator.UnbondingHeight = sdkCtx.HeaderInfo().Height + validator.UnbondingTime = headerInfo.Time.Add(params.UnbondingTime) + validator.UnbondingHeight = headerInfo.Height validator.UnbondingIds = append(validator.UnbondingIds, id) diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 1a222b2cb4b4..b8c4472cccb4 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -100,7 +100,7 @@ func (k Keeper) SetValidatorByPowerIndex(ctx context.Context, validator types.Va return nil } - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) if err != nil { return err @@ -110,13 +110,13 @@ func (k Keeper) SetValidatorByPowerIndex(ctx context.Context, validator types.Va // DeleteValidatorByPowerIndex deletes a record by power index func (k Keeper) DeleteValidatorByPowerIndex(ctx context.Context, validator types.Validator) error { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) return store.Delete(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx), k.validatorAddressCodec)) } // SetNewValidatorByPowerIndex adds new entry by power index func (k Keeper) SetNewValidatorByPowerIndex(ctx context.Context, validator types.Validator) error { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) if err != nil { return err @@ -187,8 +187,7 @@ func (k Keeper) UpdateValidatorCommission(ctx context.Context, validator types.Validator, newRate math.LegacyDec, ) (types.Commission, error) { commission := validator.Commission - sdkCtx := sdk.UnwrapSDKContext(ctx) - blockTime := sdkCtx.HeaderInfo().Time + blockTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time if err := commission.ValidateNewRate(newRate, blockTime); err != nil { return commission, err @@ -232,7 +231,7 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err } // delete the old validator record - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) if err = k.Validators.Remove(ctx, address); err != nil { return err } @@ -261,7 +260,7 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err // GetAllValidators gets the set of all validators with no limits, used during genesis dump func (k Keeper) GetAllValidators(ctx context.Context) (validators []types.Validator, err error) { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey)) if err != nil { @@ -282,7 +281,7 @@ func (k Keeper) GetAllValidators(ctx context.Context) (validators []types.Valida // GetValidators returns a given amount of all the validators func (k Keeper) GetValidators(ctx context.Context, maxRetrieve uint32) (validators []types.Validator, err error) { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) validators = make([]types.Validator, maxRetrieve) iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey)) @@ -336,7 +335,7 @@ func (k Keeper) GetBondedValidatorsByPower(ctx context.Context) ([]types.Validat // ValidatorsPowerStoreIterator returns an iterator for the current validator power store func (k Keeper) ValidatorsPowerStoreIterator(ctx context.Context) (corestore.Iterator, error) { - store := k.storeService.OpenKVStore(ctx) + store := k.environment.KVStoreService.OpenKVStore(ctx) return store.ReverseIterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey)) } @@ -488,9 +487,9 @@ func (k Keeper) DeleteValidatorQueue(ctx context.Context, val types.Validator) e // UnbondAllMatureValidators unbonds all the mature unbonding validators that // have finished their unbonding period. func (k Keeper) UnbondAllMatureValidators(ctx context.Context) error { - sdkCtx := sdk.UnwrapSDKContext(ctx) - blockTime := sdkCtx.HeaderInfo().Time - blockHeight := uint64(sdkCtx.BlockHeight()) + headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + blockTime := headerInfo.Time + blockHeight := uint64(headerInfo.Height) rng := new(collections.Range[collections.Triple[uint64, time.Time, uint64]]). EndInclusive(collections.Join3(uint64(29), blockTime, blockHeight)) From 864e881b4ab28c119ba0139a0724676362934dc5 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Mon, 12 Feb 2024 23:48:09 +0100 Subject: [PATCH 02/20] add logger --- core/appmodule/environment.go | 2 ++ runtime/environment.go | 4 +++- runtime/module.go | 3 ++- simapp/app.go | 6 +++--- x/circuit/keeper/genesis_test.go | 3 ++- x/circuit/keeper/keeper_test.go | 3 ++- x/nft/keeper/keeper_test.go | 3 ++- x/staking/depinject.go | 5 ++--- x/staking/keeper/keeper.go | 3 +-- x/staking/keeper/test_common.go | 4 ++-- 10 files changed, 21 insertions(+), 15 deletions(-) diff --git a/core/appmodule/environment.go b/core/appmodule/environment.go index f7305db9fc3d..17ab778191c0 100644 --- a/core/appmodule/environment.go +++ b/core/appmodule/environment.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/core/gas" "cosmossdk.io/core/header" "cosmossdk.io/core/store" + "cosmossdk.io/log" ) // Environment is used to get all services to their respective module @@ -16,4 +17,5 @@ type Environment struct { HeaderService header.Service KVStoreService store.KVStoreService MemStoreService store.MemoryStoreService + Logger log.Logger } diff --git a/runtime/environment.go b/runtime/environment.go index 6f34e9f67dd7..2a592363eb6d 100644 --- a/runtime/environment.go +++ b/runtime/environment.go @@ -3,16 +3,18 @@ package runtime import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/store" + "cosmossdk.io/log" ) // NewEnvironment creates a new environment for the application // if memstoreservice is needed, it can be added to the environment: environment.MemStoreService = memstoreservice -func NewEnvironment(kvService store.KVStoreService) appmodule.Environment { +func NewEnvironment(kvService store.KVStoreService, logger log.Logger) appmodule.Environment { return appmodule.Environment{ EventService: EventService{}, HeaderService: HeaderService{}, BranchService: BranchService{}, GasService: GasService{}, KVStoreService: kvService, + Logger: logger, } } diff --git a/runtime/module.go b/runtime/module.go index dbfe511b92c4..81fe48cea89c 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -227,7 +227,8 @@ func ProvideGenesisTxHandler(appBuilder *AppBuilder) genesis.TxHandler { func ProvideEnvironment(config *runtimev1alpha1.Module, key depinject.ModuleKey, app *AppBuilder) (store.KVStoreService, appmodule.Environment) { storeKey := ProvideKVStoreKey(config, key, app) kvService := kvStoreService{key: storeKey} - return kvService, NewEnvironment(kvService) + + return kvService, NewEnvironment(kvService, app.app.logger) } func ProvideMemoryStoreService(key depinject.ModuleKey, app *AppBuilder) store.MemoryStoreService { diff --git a/simapp/app.go b/simapp/app.go index cf19ae6fc0b0..218d5fb7ffdf 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -333,7 +333,7 @@ func NewSimApp( app.txConfig = txConfig app.StakingKeeper = stakingkeeper.NewKeeper( - appCodec, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), app.AuthKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), + appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), logger), app.AuthKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), ) app.MintKeeper = mintkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[minttypes.StoreKey]), app.StakingKeeper, app.AuthKeeper, app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) @@ -353,7 +353,7 @@ func NewSimApp( stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), ) - app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[circuittypes.StoreKey])), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec()) + app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[circuittypes.StoreKey]), logger), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec()) app.BaseApp.SetCircuitBreaker(&app.CircuitKeeper) app.AuthzKeeper = authzkeeper.NewKeeper(runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), appCodec, app.MsgServiceRouter(), app.AuthKeeper) @@ -401,7 +401,7 @@ func NewSimApp( ), ) - app.NFTKeeper = nftkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[nftkeeper.StoreKey])), appCodec, app.AuthKeeper, app.BankKeeper) + app.NFTKeeper = nftkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[nftkeeper.StoreKey]), logger), appCodec, app.AuthKeeper, app.BankKeeper) // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( diff --git a/x/circuit/keeper/genesis_test.go b/x/circuit/keeper/genesis_test.go index e11e0da5b30c..9848d237997f 100644 --- a/x/circuit/keeper/genesis_test.go +++ b/x/circuit/keeper/genesis_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/suite" + "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/circuit" @@ -48,7 +49,7 @@ func (s *GenesisTestSuite) SetupTest() { s.Require().NoError(err) s.addrBytes = bz - s.keeper = keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key)), s.cdc, authority.String(), ac) + s.keeper = keeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()), s.cdc, authority.String(), ac) } func (s *GenesisTestSuite) TestInitExportGenesis() { diff --git a/x/circuit/keeper/keeper_test.go b/x/circuit/keeper/keeper_test.go index f3091989dd44..e77691c38d26 100644 --- a/x/circuit/keeper/keeper_test.go +++ b/x/circuit/keeper/keeper_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/address" + "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" "cosmossdk.io/x/circuit" @@ -43,7 +44,7 @@ func initFixture(t *testing.T) *fixture { ac := addresscodec.NewBech32Codec("cosmos") mockStoreKey := storetypes.NewKVStoreKey("test") - env := runtime.NewEnvironment(runtime.NewKVStoreService(mockStoreKey)) + env := runtime.NewEnvironment(runtime.NewKVStoreService(mockStoreKey), log.NewNopLogger()) k := keeper.NewKeeper(env, encCfg.Codec, authtypes.NewModuleAddress("gov").String(), ac) bz, err := ac.StringToBytes(authtypes.NewModuleAddress("gov").String()) diff --git a/x/nft/keeper/keeper_test.go b/x/nft/keeper/keeper_test.go index 863dba3c3a3e..b685cdbc73f7 100644 --- a/x/nft/keeper/keeper_test.go +++ b/x/nft/keeper/keeper_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/core/header" + "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/nft" "cosmossdk.io/x/nft/keeper" @@ -72,7 +73,7 @@ func (s *TestSuite) SetupTest() { s.accountKeeper = accountKeeper - env := runtime.NewEnvironment(runtime.NewKVStoreService(key)) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) nftKeeper := keeper.NewKeeper(env, s.encCfg.Codec, accountKeeper, bankKeeper) queryHelper := baseapp.NewQueryServerTestHelper(ctx, s.encCfg.InterfaceRegistry) nft.RegisterQueryServer(queryHelper, nftKeeper) diff --git a/x/staking/depinject.go b/x/staking/depinject.go index cce30c34783f..93a4567e9ee3 100644 --- a/x/staking/depinject.go +++ b/x/staking/depinject.go @@ -8,7 +8,6 @@ import ( modulev1 "cosmossdk.io/api/cosmos/staking/module/v1" "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/store" "cosmossdk.io/depinject" "cosmossdk.io/depinject/appconfig" authtypes "cosmossdk.io/x/auth/types" @@ -44,7 +43,7 @@ type ModuleInputs struct { AccountKeeper types.AccountKeeper BankKeeper types.BankKeeper Cdc codec.Codec - StoreService store.KVStoreService + Environment appmodule.Environment } // Dependency Injection Outputs @@ -69,7 +68,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { k := keeper.NewKeeper( in.Cdc, - in.StoreService, + in.Environment, in.AccountKeeper, in.BankKeeper, as, diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index 7d124c55ca87..c0c241ef12ac 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -317,8 +317,7 @@ func NewKeeper( // Logger returns a module-specific logger. func (k Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO remove this - return sdkCtx.Logger().With("module", "x/"+types.ModuleName) + return k.environment.Logger.With("module", "x/"+types.ModuleName) } // Hooks gets the hooks for staking *Keeper { diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index a13ba94a1a0f..829b71a40a16 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -12,7 +12,7 @@ import ( // ValidatorByPowerIndexExists does a certain by-power index record exist func ValidatorByPowerIndexExists(ctx context.Context, keeper *Keeper, power []byte) bool { - store := keeper.storeService.OpenKVStore(ctx) + store := keeper.environment.KVStoreService.OpenKVStore(ctx) has, err := store.Has(power) if err != nil { panic(err) @@ -28,7 +28,7 @@ func TestingUpdateValidator(keeper *Keeper, ctx sdk.Context, validator types.Val } // Remove any existing power key for validator. - store := keeper.storeService.OpenKVStore(ctx) + store := keeper.environment.KVStoreService.OpenKVStore(ctx) deleted := false iterator, err := store.Iterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey)) From c00c3bac6d0c66d96c3f3eba798e958aa4288abf Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 08:31:07 +0100 Subject: [PATCH 03/20] fix staking --- x/staking/keeper/keeper_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/x/staking/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go index b13404cabc69..16b87cbbeec1 100644 --- a/x/staking/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -10,6 +10,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/header" + "cosmossdk.io/log" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -53,6 +54,7 @@ func (s *KeeperTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(stakingtypes.StoreKey) s.key = key storeService := runtime.NewKVStoreService(key) + env := runtime.NewEnvironment(storeService, log.NewNopLogger()) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) s.key = key ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) @@ -69,7 +71,7 @@ func (s *KeeperTestSuite) SetupTest() { keeper := stakingkeeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, authtypes.NewModuleAddress(stakingtypes.GovModuleName).String(), From 96ba789a05138721624d06f95734ce3993d833eb Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 08:33:57 +0100 Subject: [PATCH 04/20] go mod tidy --- core/go.mod | 5 +++++ core/go.sum | 19 +++++++++++++++++++ x/circuit/go.mod | 2 +- x/nft/go.mod | 2 +- 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/core/go.mod b/core/go.mod index edeea757b6bf..fda367de2e2b 100644 --- a/core/go.mod +++ b/core/go.mod @@ -3,6 +3,7 @@ module cosmossdk.io/core go 1.20 require ( + cosmossdk.io/log v1.3.1 github.com/stretchr/testify v1.8.4 google.golang.org/grpc v1.61.0 google.golang.org/protobuf v1.32.0 @@ -12,8 +13,12 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/kr/pretty v0.3.1 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/rs/zerolog v1.32.0 // indirect golang.org/x/net v0.20.0 // indirect golang.org/x/sys v0.16.0 // indirect golang.org/x/text v0.14.0 // indirect diff --git a/core/go.sum b/core/go.sum index 6cb44a1b40d0..c1cf8458d9b6 100644 --- a/core/go.sum +++ b/core/go.sum @@ -1,6 +1,10 @@ +cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI= +cosmossdk.io/log v1.3.1/go.mod h1:2/dIomt8mKdk6vl3OWJcPk2be3pGOS8OQaLUM/3/tCM= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= @@ -13,16 +17,30 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0= +github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= @@ -41,3 +59,4 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= diff --git a/x/circuit/go.mod b/x/circuit/go.mod index b56215f00c26..4bb180442d69 100644 --- a/x/circuit/go.mod +++ b/x/circuit/go.mod @@ -8,6 +8,7 @@ require ( cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 cosmossdk.io/depinject v1.0.0-alpha.4 cosmossdk.io/errors v1.0.1 + cosmossdk.io/log v1.3.1 cosmossdk.io/store v1.0.2 cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 github.com/cockroachdb/errors v1.11.1 @@ -21,7 +22,6 @@ require ( ) require ( - cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/math v1.2.0 // indirect cosmossdk.io/x/bank v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/staking v0.0.0-00010101000000-000000000000 // indirect diff --git a/x/nft/go.mod b/x/nft/go.mod index 2314d07acc6d..99207ddf85fa 100644 --- a/x/nft/go.mod +++ b/x/nft/go.mod @@ -7,6 +7,7 @@ require ( cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7 cosmossdk.io/depinject v1.0.0-alpha.4 cosmossdk.io/errors v1.0.1 + cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.2.0 cosmossdk.io/store v1.0.2 github.com/cosmos/cosmos-proto v1.0.0-beta.3 @@ -22,7 +23,6 @@ require ( require ( cosmossdk.io/collections v0.4.0 // indirect - cosmossdk.io/log v1.3.1 // indirect cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/bank v0.0.0-00010101000000-000000000000 // indirect cosmossdk.io/x/staking v0.0.0-00010101000000-000000000000 // indirect From a5a2e92c668fa99c330a1a85bd4cb225f594a4e7 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 09:33:44 +0100 Subject: [PATCH 05/20] fix integration tests --- tests/integration/distribution/keeper/msg_server_test.go | 2 +- tests/integration/evidence/keeper/infraction_test.go | 2 +- tests/integration/gov/keeper/keeper_test.go | 2 +- tests/integration/slashing/keeper/keeper_test.go | 2 +- tests/integration/staking/keeper/common_test.go | 2 +- tests/integration/staking/keeper/deterministic_test.go | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index 56990187ab0c..aca5bca549bc 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -105,7 +105,7 @@ func initFixture(t *testing.T) *fixture { log.NewNopLogger(), ) - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) + stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) require.NoError(t, stakingKeeper.Params.Set(newCtx, stakingtypes.DefaultParams())) poolKeeper := poolkeeper.NewKeeper( diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index 176ae20b381f..575b611914f7 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -124,7 +124,7 @@ func initFixture(tb testing.TB) *fixture { log.NewNopLogger(), ) - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) + stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) slashingKeeper := slashingkeeper.NewKeeper(cdc, codec.NewLegacyAmino(), runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), stakingKeeper, authority.String()) diff --git a/tests/integration/gov/keeper/keeper_test.go b/tests/integration/gov/keeper/keeper_test.go index e4b2757b553c..eb0d442a53ef 100644 --- a/tests/integration/gov/keeper/keeper_test.go +++ b/tests/integration/gov/keeper/keeper_test.go @@ -91,7 +91,7 @@ func initFixture(tb testing.TB) *fixture { log.NewNopLogger(), ) - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) + stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) poolKeeper := poolkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[pooltypes.StoreKey]), accountKeeper, bankKeeper, stakingKeeper, authority.String()) diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index 651b9f22173a..d4e1c4c155d7 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -91,7 +91,7 @@ func initFixture(tb testing.TB) *fixture { log.NewNopLogger(), ) - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) + stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) slashingKeeper := slashingkeeper.NewKeeper(cdc, &codec.LegacyAmino{}, runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), stakingKeeper, authority.String()) diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go index da294ed4e6e5..5e80e6098855 100644 --- a/tests/integration/staking/keeper/common_test.go +++ b/tests/integration/staking/keeper/common_test.go @@ -137,7 +137,7 @@ func initFixture(tb testing.TB) *fixture { log.NewNopLogger(), ) - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[types.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) + stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[types.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) diff --git a/tests/integration/staking/keeper/deterministic_test.go b/tests/integration/staking/keeper/deterministic_test.go index fd999c5cf7bd..8e98ba474ffa 100644 --- a/tests/integration/staking/keeper/deterministic_test.go +++ b/tests/integration/staking/keeper/deterministic_test.go @@ -106,7 +106,7 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { log.NewNopLogger(), ) - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) + stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) From f1da81d79184ad75e014cd407fe408ad5a290dee Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 13:52:51 +0100 Subject: [PATCH 06/20] fix linting --- math/int_test.go | 4 ++-- x/staking/keeper/historical_info.go | 1 + x/staking/keeper/msg_server.go | 30 +++++++++++++++++++---------- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/math/int_test.go b/math/int_test.go index 197f75ab6104..714ef5e65e50 100644 --- a/math/int_test.go +++ b/math/int_test.go @@ -689,7 +689,7 @@ func BenchmarkIntSize(b *testing.B) { } func BenchmarkIntOverflowCheckTime(b *testing.B) { - var ints = []*big.Int{} + ints := []*big.Int{} for _, st := range sizeTests { ii, _ := math.NewIntFromString(st.s) @@ -699,7 +699,7 @@ func BenchmarkIntOverflowCheckTime(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - for j, _ := range sizeTests { + for j := range sizeTests { got := math.NewIntFromBigIntMut(ints[j]) sink = got } diff --git a/x/staking/keeper/historical_info.go b/x/staking/keeper/historical_info.go index 89dbdfba36d0..b2fcac03fa48 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -4,6 +4,7 @@ import ( "context" "cosmossdk.io/x/staking/types" + sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index 6cee27f5ce89..b033a811ec0e 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -149,11 +149,13 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali return nil, err } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeCreateValidator, event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), event.NewAttribute(sdk.AttributeKeyAmount, msg.Value.String()), - ) + ); err != nil { + return nil, err + } return &types.MsgCreateValidatorResponse{}, nil } @@ -236,11 +238,13 @@ func (k msgServer) EditValidator(ctx context.Context, msg *types.MsgEditValidato return nil, err } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeEditValidator, event.NewAttribute(types.AttributeKeyCommissionRate, validator.Commission.String()), event.NewAttribute(types.AttributeKeyMinSelfDelegation, validator.MinSelfDelegation.String()), - ) + ); err != nil { + return nil, err + } return &types.MsgEditValidatorResponse{}, nil } @@ -297,13 +301,15 @@ func (k msgServer) Delegate(ctx context.Context, msg *types.MsgDelegate) (*types }() } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeDelegate, event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), event.NewAttribute(types.AttributeKeyNewShares, newShares.String()), - ) + ); err != nil { + return nil, err + } return &types.MsgDelegateResponse{}, nil } @@ -368,13 +374,15 @@ func (k msgServer) BeginRedelegate(ctx context.Context, msg *types.MsgBeginRedel }() } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeRedelegate, event.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress), event.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress), event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), event.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ) + ); err != nil { + return nil, err + } return &types.MsgBeginRedelegateResponse{ CompletionTime: completionTime, @@ -436,13 +444,15 @@ func (k msgServer) Undelegate(ctx context.Context, msg *types.MsgUndelegate) (*t }() } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeUnbond, event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), event.NewAttribute(sdk.AttributeKeyAmount, undelegatedCoin.String()), event.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ) + ); err != nil { + return nil, err + } return &types.MsgUndelegateResponse{ CompletionTime: completionTime, From a3a8f4bf8f7a811b3a7f4b257f64a9553be6d139 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 14:54:44 +0100 Subject: [PATCH 07/20] fix linting --- x/staking/keeper/msg_server.go | 6 ++++-- x/staking/keeper/val_state_change.go | 12 ++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index b033a811ec0e..49ad4dcf6278 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -575,13 +575,15 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg return nil, err } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeCancelUnbondingDelegation, event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), event.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)), - ) + ); err != nil { + return nil, err + } return &types.MsgCancelUnbondingDelegationResponse{}, nil } diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index e2aa6a4e6f4d..a53868d00c16 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -66,12 +66,14 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda continue } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeCompleteUnbonding, event.NewAttribute(sdk.AttributeKeyAmount, balances.String()), event.NewAttribute(types.AttributeKeyValidator, dvPair.ValidatorAddress), event.NewAttribute(types.AttributeKeyDelegator, dvPair.DelegatorAddress), - ) + ); err != nil { + return nil, err + } } // Remove all mature redelegations from the red queue. @@ -104,13 +106,15 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda continue } - k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.environment.EventService.EventManager(ctx).EmitKV( types.EventTypeCompleteRedelegation, event.NewAttribute(sdk.AttributeKeyAmount, balances.String()), event.NewAttribute(types.AttributeKeyDelegator, dvvTriplet.DelegatorAddress), event.NewAttribute(types.AttributeKeySrcValidator, dvvTriplet.ValidatorSrcAddress), event.NewAttribute(types.AttributeKeyDstValidator, dvvTriplet.ValidatorDstAddress), - ) + ); err != nil { + return nil, err + } } err = k.PurgeAllMaturedConsKeyRotatedKeys(ctx, time) From 7a78ba25933ae48356ed4a3cdf0b1538895356b4 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 18:00:43 +0100 Subject: [PATCH 08/20] some cleanup --- x/staking/keeper/historical_info.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/x/staking/keeper/historical_info.go b/x/staking/keeper/historical_info.go index b2fcac03fa48..77cab7424407 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -43,11 +43,9 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error { return nil } - sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: remove this - historicalEntry := types.HistoricalRecord{ Time: &headerInfo.Time, - ValidatorsHash: sdkCtx.CometInfo().ValidatorsHash, + ValidatorsHash: sdk.UnwrapSDKContext(ctx).CometInfo().ValidatorsHash, Apphash: headerInfo.AppHash, } From 643c603543bf33fbd913dddecaa3786b458d7809 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 18:08:46 +0100 Subject: [PATCH 09/20] fix one test --- tests/integration/staking/keeper/msg_server_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/integration/staking/keeper/msg_server_test.go b/tests/integration/staking/keeper/msg_server_test.go index eadd352b8a7b..aa55c8e07669 100644 --- a/tests/integration/staking/keeper/msg_server_test.go +++ b/tests/integration/staking/keeper/msg_server_test.go @@ -326,8 +326,7 @@ func TestRotateConsPubKey(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - newCtx := ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(params.UnbondingTime)}) - newCtx = newCtx.WithBlockHeight(newCtx.BlockHeight() + 1) + newCtx := ctx.WithHeaderInfo(header.Info{Height: ctx.BlockHeight() + 1, Time: ctx.HeaderInfo().Time.Add(params.UnbondingTime)}).WithBlockHeight(ctx.BlockHeight() + 1) // this should remove keys from waiting queue since unbonding time is reached _, err = stakingKeeper.EndBlocker(newCtx) assert.NilError(t, err) From 89752e2e403c1ac698653251dd46f0e7098311bb Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 18:36:26 +0100 Subject: [PATCH 10/20] minor changes --- x/staking/keeper/keeper.go | 3 +-- x/staking/keeper/migrations.go | 2 +- x/staking/keeper/slash.go | 9 ++++----- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index c0c241ef12ac..6cb5dab27826 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -1,7 +1,6 @@ package keeper import ( - "context" "fmt" "time" @@ -316,7 +315,7 @@ func NewKeeper( } // Logger returns a module-specific logger. -func (k Keeper) Logger(ctx context.Context) log.Logger { +func (k Keeper) Logger() log.Logger { return k.environment.Logger.With("module", "x/"+types.ModuleName) } diff --git a/x/staking/keeper/migrations.go b/x/staking/keeper/migrations.go index 7d43584d6ade..63a674470595 100644 --- a/x/staking/keeper/migrations.go +++ b/x/staking/keeper/migrations.go @@ -38,5 +38,5 @@ func (m Migrator) Migrate3to4(ctx context.Context) error { // Migrate4to5 migrates x/staking state from consensus version 4 to 5. func (m Migrator) Migrate4to5(ctx context.Context) error { store := runtime.KVStoreAdapter(m.keeper.environment.KVStoreService.OpenKVStore(ctx)) - return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger(ctx)) + return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger()) } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index e862f6285041..176913eb16a6 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -35,7 +35,7 @@ import ( // Infraction was committed at the current height or at a past height, // but not at a height in the future func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec) (math.Int, error) { - logger := k.Logger(ctx) + logger := k.Logger() if slashFactor.IsNegative() { return math.NewInt(0), fmt.Errorf("attempted to slash with a negative slash factor: %v", slashFactor) @@ -219,8 +219,7 @@ func (k Keeper) Jail(ctx context.Context, consAddr sdk.ConsAddress) error { return err } - logger := k.Logger(ctx) - logger.Info("validator jailed", "validator", consAddr) + k.Logger().Info("validator jailed", "validator", consAddr) return nil } @@ -233,8 +232,8 @@ func (k Keeper) Unjail(ctx context.Context, consAddr sdk.ConsAddress) error { if err := k.unjailValidator(ctx, validator); err != nil { return err } - logger := k.Logger(ctx) - logger.Info("validator un-jailed", "validator", consAddr) + + k.Logger().Info("validator un-jailed", "validator", consAddr) return nil } From 1e57d2cc318228e4b0872d76cdd68eacef145994 Mon Sep 17 00:00:00 2001 From: Facundo Date: Tue, 13 Feb 2024 21:15:42 +0100 Subject: [PATCH 11/20] fix logger --- runtime/module.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/runtime/module.go b/runtime/module.go index 81fe48cea89c..1dcf06f78a83 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -224,11 +224,17 @@ func ProvideGenesisTxHandler(appBuilder *AppBuilder) genesis.TxHandler { return appBuilder.app } -func ProvideEnvironment(config *runtimev1alpha1.Module, key depinject.ModuleKey, app *AppBuilder) (store.KVStoreService, appmodule.Environment) { +func ProvideEnvironment(config *runtimev1alpha1.Module, key depinject.ModuleKey, app *AppBuilder, logger log.Logger) (store.KVStoreService, appmodule.Environment) { storeKey := ProvideKVStoreKey(config, key, app) kvService := kvStoreService{key: storeKey} + if app.app == nil { + panic("app is nil") + } - return kvService, NewEnvironment(kvService, app.app.logger) + if logger == nil { + panic("logger is nil") + } + return kvService, NewEnvironment(kvService, logger) } func ProvideMemoryStoreService(key depinject.ModuleKey, app *AppBuilder) store.MemoryStoreService { From 74708c91521f9b494dd90450644cfb315983bde4 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 23:11:08 +0100 Subject: [PATCH 12/20] fix some tests --- x/staking/keeper/delegation_test.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index f4915506e136..c2200e04867e 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -524,6 +524,10 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondingValidator() { require.True(blockTime2.Add(params.UnbondingTime).Equal(ubd.Entries[0].CompletionTime)) } +// TestUndelegateFromUnbondedValidator tests the undelegation process from an unbonded validator. +// It creates a validator with a self-delegation and a second delegation to the same validator. +// Then it unbonds the self-delegation to put the validator in the unbonding state. +// Finally, it unbonds the remaining shares of the second delegation and verifies that the validator is deleted from the state. func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { ctx, keeper := s.ctx, s.stakingKeeper require := s.Require() @@ -576,7 +580,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { require.True(ctx.HeaderInfo().Time.Add(params.UnbondingTime).Equal(validator.UnbondingTime)) // unbond the validator - ctx = ctx.WithHeaderInfo(coreheader.Info{Time: validator.UnbondingTime}) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: validator.UnbondingTime}) err = keeper.UnbondAllMatureValidators(ctx) require.NoError(err) @@ -602,6 +606,9 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { require.ErrorIs(err, stakingtypes.ErrNoValidatorFound) } +// TestUnbondingAllDelegationFromValidator tests the process of unbonding all delegations from a validator. +// It creates a validator with a self-delegation and a second delegation, then unbonds all the delegations +// to put the validator in an unbonding state. Finally, it verifies that the validator is deleted from the state. func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { ctx, keeper := s.ctx, s.stakingKeeper require := s.Require() @@ -636,7 +643,6 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) - ctx = ctx.WithBlockHeight(10) ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: time.Unix(333, 0)}) // unbond the all self-delegation to put validator in unbonding state @@ -660,7 +666,7 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { require.Equal(validator.Status, stakingtypes.Unbonding) // unbond the validator - ctx = ctx.WithHeaderInfo(coreheader.Info{Time: validator.UnbondingTime}) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: validator.UnbondingTime}) err = keeper.UnbondAllMatureValidators(ctx) require.NoError(err) From 3ada1abfc9f937798ec6d652714d565af881eca6 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 23:13:59 +0100 Subject: [PATCH 13/20] fix some more --- tests/integration/staking/keeper/slash_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/integration/staking/keeper/slash_test.go b/tests/integration/staking/keeper/slash_test.go index 6e8f12f4b223..39957b06925f 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/staking/keeper/slash_test.go @@ -254,7 +254,10 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 5).String(), diffTokens.String()) } -// tests Slash at a previous height with an unbonding delegation +// TestSlashWithUnbondingDelegation tests the slashing of a validator with an unbonding delegation. +// It sets up an environment with a validator and an unbonding delegation, and then performs slashing +// operations on the validator. The test verifies that the slashing correctly affects the unbonding +// delegation and the validator's power. func TestSlashWithUnbondingDelegation(t *testing.T) { f, addrDels, addrVals := bootstrapSlashTest(t, 10) @@ -271,7 +274,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd)) // slash validator for the first time - f.sdkCtx = f.sdkCtx.WithBlockHeight(12) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Height: 12}) bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) From bac20cfd5fe737a789a9f82062d2c18eabc2ebd7 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 23:18:03 +0100 Subject: [PATCH 14/20] add changelog --- x/staking/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/x/staking/CHANGELOG.md b/x/staking/CHANGELOG.md index 34f2a5ac3a18..236e06783a54 100644 --- a/x/staking/CHANGELOG.md +++ b/x/staking/CHANGELOG.md @@ -81,6 +81,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * remove `Keeper`: `SetLastTotalPower`, `GetLastTotalPower` * [#17335](https://github.com/cosmos/cosmos-sdk/pull/17335) Remove usage of `"cosmossdk.io/x/staking/types".Infraction_*` in favour of `"cosmossdk.io/api/cosmos/staking/v1beta1".Infraction_` in order to remove dependency between modules on staking * [#17655](https://github.com/cosmos/cosmos-sdk/pull/17655) `QueryHistoricalInfo` was adjusted to return `HistoricalRecord` and marked `Hist` as deprecated. +* [#19414](https://github.com/cosmos/cosmos-sdk/pull/19414) Staking module takes an environment variable in `NewStakingKeeper` instead of individual services. ### State Breaking changes From 173f1b4cd0a27b32ebc63273cd6577cecbeee7d8 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 23:32:13 +0100 Subject: [PATCH 15/20] update todo --- x/staking/keeper/genesis.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/staking/keeper/genesis.go b/x/staking/keeper/genesis.go index e63721550bd1..f41e214219bd 100644 --- a/x/staking/keeper/genesis.go +++ b/x/staking/keeper/genesis.go @@ -28,7 +28,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res // first TM block is at height 1, so state updates applied from // genesis.json are in block 0. sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay) // TODO: replace this + sdkCtx = sdkCtx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay) // TODO: remove this need for WithBlockHeight ctx = sdkCtx if err := k.Params.Set(ctx, data.Params); err != nil { From 66f2128e6a2b0c0e93fce4f889e45c0cd8e84447 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 23:35:35 +0100 Subject: [PATCH 16/20] remove nil check --- runtime/module.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/runtime/module.go b/runtime/module.go index 1dcf06f78a83..2633918092d3 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -227,13 +227,6 @@ func ProvideGenesisTxHandler(appBuilder *AppBuilder) genesis.TxHandler { func ProvideEnvironment(config *runtimev1alpha1.Module, key depinject.ModuleKey, app *AppBuilder, logger log.Logger) (store.KVStoreService, appmodule.Environment) { storeKey := ProvideKVStoreKey(config, key, app) kvService := kvStoreService{key: storeKey} - if app.app == nil { - panic("app is nil") - } - - if logger == nil { - panic("logger is nil") - } return kvService, NewEnvironment(kvService, logger) } From c1790e272dc4f99d32beff8bffaebfb2c7ae8601 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 23:51:45 +0100 Subject: [PATCH 17/20] more fixes --- tests/integration/slashing/abci_test.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/integration/slashing/abci_test.go b/tests/integration/slashing/abci_test.go index 8279fc57bc38..014391c18bea 100644 --- a/tests/integration/slashing/abci_test.go +++ b/tests/integration/slashing/abci_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/comet" + coreheader "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" bankkeeper "cosmossdk.io/x/bank/keeper" @@ -21,6 +22,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// TestBeginBlocker is a unit test function that tests the behavior of the BeginBlocker function. +// It sets up the necessary dependencies and context, creates a validator, and performs various operations +// to test the slashing logic. It checks if the validator is correctly jailed after a certain number of blocks. func TestBeginBlocker(t *testing.T) { var ( interfaceRegistry codectypes.InterfaceRegistry @@ -80,7 +84,7 @@ func TestBeginBlocker(t *testing.T) { info, err := slashingKeeper.ValidatorSigningInfo.Get(ctx, sdk.ConsAddress(pk.Address())) require.NoError(t, err) - require.Equal(t, ctx.BlockHeight(), info.StartHeight) + require.Equal(t, ctx.HeaderInfo().Height, info.StartHeight) require.Equal(t, int64(1), info.IndexOffset) require.Equal(t, time.Unix(0, 0).UTC(), info.JailedUntil) require.Equal(t, int64(0), info.MissedBlocksCounter) @@ -91,7 +95,7 @@ func TestBeginBlocker(t *testing.T) { require.NoError(t, err) // for 100 blocks, mark the validator as having signed for ; height < signedBlocksWindow; height++ { - ctx = ctx.WithBlockHeight(height) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: height}) err = slashing.BeginBlocker(ctx, slashingKeeper) require.NoError(t, err) @@ -101,7 +105,7 @@ func TestBeginBlocker(t *testing.T) { require.NoError(t, err) // for 50 blocks, mark the validator as having not signed for ; height < ((signedBlocksWindow * 2) - minSignedPerWindow + 1); height++ { - ctx = ctx.WithBlockHeight(height).WithCometInfo(comet.Info{ + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithCometInfo(comet.Info{ LastCommit: comet.CommitInfo{Votes: []comet.VoteInfo{{ Validator: abciVal, BlockIDFlag: comet.BlockIDFlagAbsent, From d3bebcda520a6d2d879d611e77a5df05c88a7f57 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 13 Feb 2024 23:57:31 +0100 Subject: [PATCH 18/20] more fixes --- x/staking/keeper/validator_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index 3745c3636ed1..5ac1a44865bb 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -423,6 +423,7 @@ func (s *KeeperTestSuite) TestValidatorToken() { require.True(validator.Tokens.IsZero()) } +// TestUnbondingValidator tests the functionality of unbonding a validator. func (s *KeeperTestSuite) TestUnbondingValidator() { ctx, keeper := s.ctx, s.stakingKeeper require := s.Require() @@ -434,7 +435,7 @@ func (s *KeeperTestSuite) TestUnbondingValidator() { // set unbonding validator endTime := time.Now() - endHeight := ctx.BlockHeight() + 10 + endHeight := ctx.HeaderInfo().Height + 10 require.NoError(keeper.SetUnbondingValidatorsQueue(ctx, endTime, endHeight, []string{valAddr.String()})) resVals, err := keeper.GetUnbondingValidators(ctx, endTime, endHeight) @@ -461,12 +462,12 @@ func (s *KeeperTestSuite) TestUnbondingValidator() { require.Equal(valAddr.String(), resVals[0]) // check unbonding mature validators - ctx = ctx.WithBlockHeight(endHeight).WithHeaderInfo(header.Info{Time: endTime}) + ctx = ctx.WithHeaderInfo(header.Info{Height: endHeight, Time: endTime}) err = keeper.UnbondAllMatureValidators(ctx) require.EqualError(err, "validator in the unbonding queue was not found: validator does not exist") require.NoError(keeper.SetValidator(ctx, validator)) - ctx = ctx.WithBlockHeight(endHeight).WithHeaderInfo(header.Info{Time: endTime}) + ctx = ctx.WithHeaderInfo(header.Info{Height: endHeight, Time: endTime}) err = keeper.UnbondAllMatureValidators(ctx) require.EqualError(err, "unexpected validator in unbonding queue; status was not unbonding") From dd203e97a305a06082e174291f5a61d1bcd66859 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Wed, 14 Feb 2024 23:39:06 +0100 Subject: [PATCH 19/20] fix tests --- tests/integration/slashing/abci_test.go | 2 +- .../slashing/keeper/keeper_test.go | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/tests/integration/slashing/abci_test.go b/tests/integration/slashing/abci_test.go index 014391c18bea..c56c97cad7da 100644 --- a/tests/integration/slashing/abci_test.go +++ b/tests/integration/slashing/abci_test.go @@ -105,7 +105,7 @@ func TestBeginBlocker(t *testing.T) { require.NoError(t, err) // for 50 blocks, mark the validator as having not signed for ; height < ((signedBlocksWindow * 2) - minSignedPerWindow + 1); height++ { - ctx = ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithCometInfo(comet.Info{ + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height).WithCometInfo(comet.Info{ LastCommit: comet.CommitInfo{Votes: []comet.VoteInfo{{ Validator: abciVal, BlockIDFlag: comet.BlockIDFlagAbsent, diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index d4e1c4c155d7..31b69b13f156 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/comet" + coreheader "cosmossdk.io/core/header" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/auth" @@ -300,7 +301,7 @@ func TestHandleAlreadyJailed(t *testing.T) { consaddr, err := f.stakingKeeper.ConsensusAddressCodec().BytesToString(val.Address()) assert.NilError(t, err) - info := slashingtypes.NewValidatorSigningInfo(consaddr, f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) + info := slashingtypes.NewValidatorSigningInfo(consaddr, f.ctx.HeaderInfo().Height, int64(0), time.Unix(0, 0), false, int64(0)) assert.NilError(t, f.slashingKeeper.ValidatorSigningInfo.Set(f.ctx, sdk.ConsAddress(val.Address()), info)) amt := tstaking.CreateValidatorWithValPower(addr, val, power, true) @@ -314,7 +315,7 @@ func TestHandleAlreadyJailed(t *testing.T) { // 1000 first blocks OK height := int64(0) for ; height < signedBlocksWindow; height++ { - f.ctx = f.ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height) err = f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagCommit) assert.NilError(t, err) } @@ -324,7 +325,7 @@ func TestHandleAlreadyJailed(t *testing.T) { // 501 blocks missed for ; height < signedBlocksWindow+(signedBlocksWindow-minSignedPerWindow)+1; height++ { - f.ctx = f.ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height) err = f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagAbsent) assert.NilError(t, err) } @@ -342,7 +343,7 @@ func TestHandleAlreadyJailed(t *testing.T) { assert.DeepEqual(t, resultingTokens, validator.GetTokens()) // another block missed - f.ctx = f.ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height) assert.NilError(t, f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagAbsent)) // validator should not have been slashed twice @@ -389,7 +390,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // 100 first blocks OK height := int64(0) for ; height < int64(100); height++ { - f.ctx = f.ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height}) assert.NilError(t, f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagCommit)) } @@ -403,7 +404,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // 600 more blocks happened height += 600 - f.ctx = f.ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height}) // validator added back in tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), valAddr, 50) @@ -429,7 +430,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // misses 500 blocks + within the signing windows i.e. 700-1700 // validators misses all 1000 blocks of a SignedBlockWindows for ; height < latest+1; height++ { - err = f.slashingKeeper.HandleValidatorSignature(f.ctx.WithBlockHeight(height), val.Address(), newPower, comet.BlockIDFlagAbsent) + err = f.slashingKeeper.HandleValidatorSignature(f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height}), val.Address(), newPower, comet.BlockIDFlagAbsent) assert.NilError(t, err) } @@ -451,7 +452,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // some blocks pass height = int64(5000) - f.ctx = f.ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height}) info = slashingtypes.NewValidatorSigningInfo(consaddrStr, f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) err = f.slashingKeeper.ValidatorSigningInfo.Set(f.ctx, consAddr, info) @@ -479,7 +480,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator misses 501 blocks after SignedBlockWindow period (1000 blocks) latest = signedBlocksWindow + height for ; height < latest+minSignedPerWindow; height++ { - f.ctx = f.ctx.WithBlockHeight(height) + f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height}) err = f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, comet.BlockIDFlagAbsent) assert.NilError(t, err) } From f5a7068b6e48f8ad5befdda14ae5d28803ff69e2 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Wed, 14 Feb 2024 23:58:20 +0100 Subject: [PATCH 20/20] fix tests --- tests/integration/staking/keeper/delegation_test.go | 2 +- tests/integration/staking/keeper/slash_test.go | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/integration/staking/keeper/delegation_test.go b/tests/integration/staking/keeper/delegation_test.go index 3519b89ea4c9..a7cde2f7aed1 100644 --- a/tests/integration/staking/keeper/delegation_test.go +++ b/tests/integration/staking/keeper/delegation_test.go @@ -66,7 +66,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { totalUnbonded := math.NewInt(0) for i := int64(0); i < int64(maxEntries); i++ { var err error - ctx = ctx.WithBlockHeight(i) + ctx = ctx.WithHeaderInfo(header.Info{Height: i}) var amount math.Int completionTime, amount, err = f.stakingKeeper.Undelegate(ctx, addrDel, addrVal, math.LegacyNewDec(1)) assert.NilError(t, err) diff --git a/tests/integration/staking/keeper/slash_test.go b/tests/integration/staking/keeper/slash_test.go index 39957b06925f..ff3ea047cd49 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/staking/keeper/slash_test.go @@ -420,7 +420,7 @@ func TestSlashWithRedelegation(t *testing.T) { oldNotBonded := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount // slash validator - f.sdkCtx = f.sdkCtx.WithBlockHeight(12) + f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) _, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) assert.Assert(t, found) @@ -488,7 +488,7 @@ func TestSlashWithRedelegation(t *testing.T) { assert.Equal(t, int64(4), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) // slash the validator again, by 100% - f.sdkCtx = f.sdkCtx.WithBlockHeight(12) + f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) _, found = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) assert.Assert(t, found) @@ -521,7 +521,7 @@ func TestSlashWithRedelegation(t *testing.T) { // slash the validator again, by 100% // no stake remains to be slashed - f.sdkCtx = f.sdkCtx.WithBlockHeight(12) + f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) // validator still in unbonding period validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) assert.Equal(t, validator.GetStatus(), sdk.Unbonding) @@ -588,7 +588,7 @@ func TestSlashBoth(t *testing.T) { oldBonded := f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount oldNotBonded := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount // slash validator - f.sdkCtx = f.sdkCtx.WithBlockHeight(12) + f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) _, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, sdk.GetConsAddress(PKs[0])) assert.Assert(t, found) consAddr0 := sdk.ConsAddress(PKs[0].Address())