From 48515243fdadb2c0596e757b9dc1fccb99fbfeed Mon Sep 17 00:00:00 2001 From: Marko Date: Mon, 26 Aug 2024 16:50:11 +0200 Subject: [PATCH] refactor: migrate from sdk.Context to Context.Context (1/n) (#7058) * migrate context part 1 * ++ * ++ * ++ * ++ * ++fafo * linting * linting * nit: rename arg from key -> storeService * chore: rm redundant import aliases (linter) * chore: consistent import aliasing of corestore, godoc nit, apease linter * chore: more corestore import aliasing consistency and var naming localhost client mod * ammend comments * remove todo * add back panic * chore: update ibc commitment prefix with exported.StoreKey const in favour of hardcoded string * refactor: make panics consistent on store ops * chore: update TODOs in code to link to issue * chore: keep conditionals as they were --------- Co-authored-by: Damian Nolan Co-authored-by: DimitrisJim --- .../controller/ibc_middleware.go | 9 +- .../controller/keeper/keeper.go | 3 +- .../controller/keeper/relay_test.go | 2 +- .../27-interchain-accounts/host/ibc_module.go | 3 +- .../host/ibc_module_test.go | 4 +- .../host/keeper/keeper.go | 3 +- .../types/expected_keepers.go | 12 +- modules/apps/29-fee/ibc_middleware.go | 9 +- modules/apps/29-fee/keeper/grpc_query.go | 16 +- modules/apps/29-fee/keeper/keeper.go | 220 +++++---- modules/apps/29-fee/keeper/migrations.go | 3 +- modules/apps/29-fee/keeper/relay.go | 9 +- modules/apps/29-fee/types/expected_keepers.go | 10 +- modules/apps/callbacks/ibc_middleware.go | 23 +- modules/apps/callbacks/testing/simapp/app.go | 4 +- modules/apps/transfer/ibc_module.go | 3 +- .../apps/transfer/types/expected_keepers.go | 10 +- .../transfer/types/transfer_authorization.go | 2 +- modules/core/02-client/keeper/grpc_query.go | 7 +- modules/core/02-client/keeper/keeper.go | 124 +++-- modules/core/02-client/keeper/migrations.go | 2 +- .../migrations/v7/expected_keepers.go | 10 +- .../02-client/migrations/v7/genesis_test.go | 3 +- modules/core/02-client/migrations/v7/store.go | 6 +- .../02-client/migrations/v7/store_test.go | 5 +- modules/core/02-client/types/height.go | 8 +- modules/core/02-client/types/router_test.go | 6 +- modules/core/02-client/types/store.go | 20 +- .../core/03-connection/keeper/grpc_query.go | 4 +- modules/core/03-connection/keeper/keeper.go | 123 +++-- modules/core/03-connection/keeper/verify.go | 19 +- .../migrations/v7/expected_keepers.go | 6 +- .../03-connection/types/expected_keepers.go | 14 +- modules/core/04-channel/keeper/grpc_query.go | 74 +-- modules/core/04-channel/keeper/keeper.go | 460 +++++++++++------- modules/core/04-channel/keeper/packet.go | 15 +- .../core/04-channel/types/expected_keepers.go | 30 +- modules/core/05-port/keeper/keeper.go | 27 +- modules/core/05-port/types/module.go | 10 +- .../core/23-commitment/types/merkle_test.go | 8 +- modules/core/exported/client.go | 28 +- modules/core/keeper/keeper.go | 10 +- modules/core/keeper/keeper_test.go | 6 +- modules/core/migrations/v7/genesis_test.go | 3 +- .../06-solomachine/light_client_module.go | 26 +- .../06-solomachine/misbehaviour_handle.go | 5 +- modules/light-clients/06-solomachine/proof.go | 2 +- .../06-solomachine/proposal_handle.go | 4 +- .../light-clients/06-solomachine/update.go | 7 +- .../07-tendermint/client_state.go | 17 +- .../07-tendermint/light_client_module.go | 28 +- .../migrations/expected_keepers.go | 12 +- .../07-tendermint/misbehaviour_handle.go | 10 +- .../07-tendermint/proposal_handle.go | 4 +- modules/light-clients/07-tendermint/store.go | 6 +- modules/light-clients/07-tendermint/update.go | 20 +- .../light-clients/07-tendermint/upgrade.go | 4 +- .../08-wasm/light_client_module.go | 58 ++- .../08-wasm/testing/simapp/app.go | 4 +- .../08-wasm/types/expected_keepers.go | 10 +- .../09-localhost/light_client_module.go | 55 ++- simapp/app.go | 4 +- testing/mock/ibc_module.go | 3 +- testing/mock/middleware.go | 7 +- testing/mock/mock.go | 5 +- testing/simapp/app.go | 4 +- 66 files changed, 970 insertions(+), 698 deletions(-) diff --git a/modules/apps/27-interchain-accounts/controller/ibc_middleware.go b/modules/apps/27-interchain-accounts/controller/ibc_middleware.go index db7db8bc4e8..05dd4cb3177 100644 --- a/modules/apps/27-interchain-accounts/controller/ibc_middleware.go +++ b/modules/apps/27-interchain-accounts/controller/ibc_middleware.go @@ -1,6 +1,7 @@ package controller import ( + "context" "errors" errorsmod "cosmossdk.io/errors" @@ -324,7 +325,7 @@ func (im IBCMiddleware) OnChanUpgradeOpen(ctx sdk.Context, portID, channelID str // SendPacket implements the ICS4 Wrapper interface func (IBCMiddleware) SendPacket( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, @@ -337,7 +338,7 @@ func (IBCMiddleware) SendPacket( // WriteAcknowledgement implements the ICS4 Wrapper interface func (IBCMiddleware) WriteAcknowledgement( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, ack ibcexported.Acknowledgement, @@ -346,14 +347,14 @@ func (IBCMiddleware) WriteAcknowledgement( } // GetAppVersion returns the interchain accounts metadata. -func (im IBCMiddleware) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (im IBCMiddleware) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { return im.keeper.GetAppVersion(ctx, portID, channelID) } // UnmarshalPacketData attempts to unmarshal the provided packet data bytes // into an InterchainAccountPacketData. This function implements the optional // PacketDataUnmarshaler interface required for ADR 008 support. -func (im IBCMiddleware) UnmarshalPacketData(ctx sdk.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { +func (im IBCMiddleware) UnmarshalPacketData(ctx context.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { var data icatypes.InterchainAccountPacketData err := data.UnmarshalJSON(bz) if err != nil { diff --git a/modules/apps/27-interchain-accounts/controller/keeper/keeper.go b/modules/apps/27-interchain-accounts/controller/keeper/keeper.go index 09d751b00bb..46b040c4568 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/keeper.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/keeper.go @@ -2,6 +2,7 @@ package keeper import ( "bytes" + "context" "errors" "fmt" "strings" @@ -130,7 +131,7 @@ func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability } // GetAppVersion calls the ICS4Wrapper GetAppVersion function. -func (k Keeper) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (k Keeper) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { return k.ics4Wrapper.GetAppVersion(ctx, portID, channelID) } diff --git a/modules/apps/27-interchain-accounts/controller/keeper/relay_test.go b/modules/apps/27-interchain-accounts/controller/keeper/relay_test.go index 08a762768b7..5279bbb27d2 100644 --- a/modules/apps/27-interchain-accounts/controller/keeper/relay_test.go +++ b/modules/apps/27-interchain-accounts/controller/keeper/relay_test.go @@ -156,7 +156,7 @@ func (suite *KeeperTestSuite) TestSendTx() { tc.malleate() // malleate mutates test data - //nolint: staticcheck // SA1019: ibctesting.FirstConnectionID is deprecated: use path.EndpointA.ConnectionID instead. (staticcheck) + // nolint: staticcheck // SA1019: ibctesting.FirstConnectionID is deprecated: use path.EndpointA.ConnectionID instead. (staticcheck) _, err = suite.chainA.GetSimApp().ICAControllerKeeper.SendTx(suite.chainA.GetContext(), nil, ibctesting.FirstConnectionID, path.EndpointA.ChannelConfig.PortID, packetData, timeoutTimestamp) if tc.expErr == nil { diff --git a/modules/apps/27-interchain-accounts/host/ibc_module.go b/modules/apps/27-interchain-accounts/host/ibc_module.go index 65af63a3a30..752b4b9d5c7 100644 --- a/modules/apps/27-interchain-accounts/host/ibc_module.go +++ b/modules/apps/27-interchain-accounts/host/ibc_module.go @@ -1,6 +1,7 @@ package host import ( + "context" "fmt" errorsmod "cosmossdk.io/errors" @@ -186,7 +187,7 @@ func (IBCModule) OnChanUpgradeOpen(_ sdk.Context, _, _ string, _ channeltypes.Or // UnmarshalPacketData attempts to unmarshal the provided packet data bytes // into an InterchainAccountPacketData. This function implements the optional // PacketDataUnmarshaler interface required for ADR 008 support. -func (im IBCModule) UnmarshalPacketData(ctx sdk.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { +func (im IBCModule) UnmarshalPacketData(ctx context.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { var data icatypes.InterchainAccountPacketData err := data.UnmarshalJSON(bz) if err != nil { diff --git a/modules/apps/27-interchain-accounts/host/ibc_module_test.go b/modules/apps/27-interchain-accounts/host/ibc_module_test.go index 54afc584a83..c29efb59816 100644 --- a/modules/apps/27-interchain-accounts/host/ibc_module_test.go +++ b/modules/apps/27-interchain-accounts/host/ibc_module_test.go @@ -853,7 +853,7 @@ func (suite *InterchainAccountsTestSuite) TestControlAccountAfterChannelClose() params := types.NewParams(true, []string{sdk.MsgTypeURL(msg)}) suite.chainB.GetSimApp().ICAHostKeeper.SetParams(suite.chainB.GetContext(), params) - //nolint: staticcheck // SA1019: ibctesting.FirstConnectionID is deprecated: use path.EndpointA.ConnectionID instead. (staticcheck) + // nolint: staticcheck // SA1019: ibctesting.FirstConnectionID is deprecated: use path.EndpointA.ConnectionID instead. (staticcheck) _, err = suite.chainA.GetSimApp().ICAControllerKeeper.SendTx(suite.chainA.GetContext(), nil, ibctesting.FirstConnectionID, path.EndpointA.ChannelConfig.PortID, icaPacketData, ^uint64(0)) suite.Require().NoError(err) err = path.EndpointB.UpdateClient() @@ -879,7 +879,7 @@ func (suite *InterchainAccountsTestSuite) TestControlAccountAfterChannelClose() path.EndpointB.ChannelID = "" path.CreateChannels() - //nolint: staticcheck // SA1019: ibctesting.FirstConnectionID is deprecated: use path.EndpointA.ConnectionID instead. (staticcheck) + // nolint: staticcheck // SA1019: ibctesting.FirstConnectionID is deprecated: use path.EndpointA.ConnectionID instead. (staticcheck) _, err = suite.chainA.GetSimApp().ICAControllerKeeper.SendTx(suite.chainA.GetContext(), nil, ibctesting.FirstConnectionID, path.EndpointA.ChannelConfig.PortID, icaPacketData, ^uint64(0)) suite.Require().NoError(err) err = path.EndpointB.UpdateClient() diff --git a/modules/apps/27-interchain-accounts/host/keeper/keeper.go b/modules/apps/27-interchain-accounts/host/keeper/keeper.go index 50e7414939b..86fb5f7accf 100644 --- a/modules/apps/27-interchain-accounts/host/keeper/keeper.go +++ b/modules/apps/27-interchain-accounts/host/keeper/keeper.go @@ -1,6 +1,7 @@ package keeper import ( + "context" "errors" "fmt" "strings" @@ -135,7 +136,7 @@ func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability } // GetAppVersion calls the ICS4Wrapper GetAppVersion function. -func (k Keeper) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (k Keeper) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { return k.ics4Wrapper.GetAppVersion(ctx, portID, channelID) } diff --git a/modules/apps/27-interchain-accounts/types/expected_keepers.go b/modules/apps/27-interchain-accounts/types/expected_keepers.go index 2a93fafaa92..3c65541acd3 100644 --- a/modules/apps/27-interchain-accounts/types/expected_keepers.go +++ b/modules/apps/27-interchain-accounts/types/expected_keepers.go @@ -22,16 +22,16 @@ type AccountKeeper interface { // ChannelKeeper defines the expected IBC channel keeper type ChannelKeeper interface { - GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) - GetConnection(ctx sdk.Context, connectionID string) (connectiontypes.ConnectionEnd, error) - GetAllChannelsWithPortPrefix(ctx sdk.Context, portPrefix string) []channeltypes.IdentifiedChannel + GetChannel(ctx context.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) + GetNextSequenceSend(ctx context.Context, portID, channelID string) (uint64, bool) + GetConnection(ctx context.Context, connectionID string) (connectiontypes.ConnectionEnd, error) + GetAllChannelsWithPortPrefix(ctx context.Context, portPrefix string) []channeltypes.IdentifiedChannel } // PortKeeper defines the expected IBC port keeper type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability - IsBound(ctx sdk.Context, portID string) bool + BindPort(ctx context.Context, portID string) *capabilitytypes.Capability + IsBound(ctx context.Context, portID string) bool } // ParamSubspace defines the expected Subspace interface for module parameters. diff --git a/modules/apps/29-fee/ibc_middleware.go b/modules/apps/29-fee/ibc_middleware.go index dce52a87cdc..850caec1e92 100644 --- a/modules/apps/29-fee/ibc_middleware.go +++ b/modules/apps/29-fee/ibc_middleware.go @@ -1,6 +1,7 @@ package fee import ( + "context" "encoding/json" "strings" @@ -457,7 +458,7 @@ func (im IBCMiddleware) OnChanUpgradeOpen(ctx sdk.Context, portID, channelID str // SendPacket implements the ICS4 Wrapper interface func (im IBCMiddleware) SendPacket( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, @@ -470,7 +471,7 @@ func (im IBCMiddleware) SendPacket( // WriteAcknowledgement implements the ICS4 Wrapper interface func (im IBCMiddleware) WriteAcknowledgement( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, packet exported.PacketI, ack exported.Acknowledgement, @@ -479,14 +480,14 @@ func (im IBCMiddleware) WriteAcknowledgement( } // GetAppVersion returns the application version of the underlying application -func (im IBCMiddleware) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (im IBCMiddleware) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { return im.keeper.GetAppVersion(ctx, portID, channelID) } // UnmarshalPacketData attempts to use the underlying app to unmarshal the packet data. // If the underlying app does not support the PacketDataUnmarshaler interface, an error is returned. // This function implements the optional PacketDataUnmarshaler interface required for ADR 008 support. -func (im IBCMiddleware) UnmarshalPacketData(ctx sdk.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { +func (im IBCMiddleware) UnmarshalPacketData(ctx context.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { unmarshaler, ok := im.app.(porttypes.PacketDataUnmarshaler) if !ok { return nil, "", errorsmod.Wrapf(types.ErrUnsupportedAction, "underlying app does not implement %T", (*porttypes.PacketDataUnmarshaler)(nil)) diff --git a/modules/apps/29-fee/keeper/grpc_query.go b/modules/apps/29-fee/keeper/grpc_query.go index 508c6f6fc89..cd6a0e05f33 100644 --- a/modules/apps/29-fee/keeper/grpc_query.go +++ b/modules/apps/29-fee/keeper/grpc_query.go @@ -9,6 +9,7 @@ import ( errorsmod "cosmossdk.io/errors" "cosmossdk.io/store/prefix" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" @@ -20,15 +21,14 @@ import ( var _ types.QueryServer = (*Keeper)(nil) // IncentivizedPackets implements the Query/IncentivizedPackets gRPC method -func (k Keeper) IncentivizedPackets(goCtx context.Context, req *types.QueryIncentivizedPacketsRequest) (*types.QueryIncentivizedPacketsResponse, error) { +func (k Keeper) IncentivizedPackets(ctx context.Context, req *types.QueryIncentivizedPacketsRequest) (*types.QueryIncentivizedPacketsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx).WithBlockHeight(int64(req.QueryHeight)) - var identifiedPackets []types.IdentifiedPacketFees - store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte(types.FeesInEscrowPrefix)) + + store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), []byte(types.FeesInEscrowPrefix)) pagination, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { packetID, err := types.ParseKeyFeesInEscrow(types.FeesInEscrowPrefix + string(key)) if err != nil { @@ -90,7 +90,7 @@ func (k Keeper) IncentivizedPacketsForChannel(goCtx context.Context, req *types. var packets []*types.IdentifiedPacketFees keyPrefix := types.KeyFeesInEscrowChannelPrefix(req.PortId, req.ChannelId) - store := prefix.NewStore(ctx.KVStore(k.storeKey), keyPrefix) + store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), keyPrefix) pagination, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { packetID, err := types.ParseKeyFeesInEscrow(string(keyPrefix) + string(key)) if err != nil { @@ -229,15 +229,13 @@ func (k Keeper) CounterpartyPayee(goCtx context.Context, req *types.QueryCounter } // FeeEnabledChannels implements the Query/FeeEnabledChannels gRPC method and returns a list of fee enabled channels -func (k Keeper) FeeEnabledChannels(goCtx context.Context, req *types.QueryFeeEnabledChannelsRequest) (*types.QueryFeeEnabledChannelsResponse, error) { +func (k Keeper) FeeEnabledChannels(ctx context.Context, req *types.QueryFeeEnabledChannelsRequest) (*types.QueryFeeEnabledChannelsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(goCtx).WithBlockHeight(int64(req.QueryHeight)) - var feeEnabledChannels []types.FeeEnabledChannel - store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte(types.FeeEnabledKeyPrefix)) + store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), []byte(types.FeeEnabledKeyPrefix)) pagination, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { portID, channelID, err := types.ParseKeyFeeEnabled(types.FeeEnabledKeyPrefix + string(key)) if err != nil { diff --git a/modules/apps/29-fee/keeper/keeper.go b/modules/apps/29-fee/keeper/keeper.go index 74228c9477b..5dbb766dbbb 100644 --- a/modules/apps/29-fee/keeper/keeper.go +++ b/modules/apps/29-fee/keeper/keeper.go @@ -1,10 +1,14 @@ package keeper import ( + "context" + + corestore "cosmossdk.io/core/store" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" @@ -23,8 +27,8 @@ var ( // Keeper defines the IBC fungible transfer keeper type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.BinaryCodec + storeService corestore.KVStoreService + cdc codec.BinaryCodec authKeeper types.AccountKeeper ics4Wrapper porttypes.ICS4Wrapper @@ -35,13 +39,13 @@ type Keeper struct { // NewKeeper creates a new 29-fee Keeper instance func NewKeeper( - cdc codec.BinaryCodec, key storetypes.StoreKey, + cdc codec.BinaryCodec, storeService corestore.KVStoreService, ics4Wrapper porttypes.ICS4Wrapper, channelKeeper types.ChannelKeeper, portKeeper types.PortKeeper, authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, ) Keeper { return Keeper{ cdc: cdc, - storeKey: key, + storeService: storeService, ics4Wrapper: ics4Wrapper, channelKeeper: channelKeeper, portKeeper: portKeeper, @@ -63,33 +67,34 @@ func (k Keeper) GetICS4Wrapper() porttypes.ICS4Wrapper { } // Logger returns a module-specific logger. -func (Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+ibcexported.ModuleName+"-"+types.ModuleName) +func (Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return sdkCtx.Logger().With("module", "x/"+ibcexported.ModuleName+"-"+types.ModuleName) } // BindPort defines a wrapper function for the port Keeper's function in // order to expose it to module's InitGenesis function -func (k Keeper) BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability { +func (k Keeper) BindPort(ctx context.Context, portID string) *capabilitytypes.Capability { return k.portKeeper.BindPort(ctx, portID) } // GetChannel wraps IBC ChannelKeeper's GetChannel function -func (k Keeper) GetChannel(ctx sdk.Context, portID, channelID string) (channeltypes.Channel, bool) { +func (k Keeper) GetChannel(ctx context.Context, portID, channelID string) (channeltypes.Channel, bool) { return k.channelKeeper.GetChannel(ctx, portID, channelID) } // HasChannel returns true if the channel with the given identifiers exists in state. -func (k Keeper) HasChannel(ctx sdk.Context, portID, channelID string) bool { +func (k Keeper) HasChannel(ctx context.Context, portID, channelID string) bool { return k.channelKeeper.HasChannel(ctx, portID, channelID) } // GetPacketCommitment wraps IBC ChannelKeeper's GetPacketCommitment function -func (k Keeper) GetPacketCommitment(ctx sdk.Context, portID, channelID string, sequence uint64) []byte { +func (k Keeper) GetPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) []byte { return k.channelKeeper.GetPacketCommitment(ctx, portID, channelID, sequence) } // GetNextSequenceSend wraps IBC ChannelKeeper's GetNextSequenceSend function -func (k Keeper) GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) { +func (k Keeper) GetNextSequenceSend(ctx context.Context, portID, channelID string) (uint64, bool) { return k.channelKeeper.GetNextSequenceSend(ctx, portID, channelID) } @@ -99,7 +104,7 @@ func (k Keeper) GetFeeModuleAddress() sdk.AccAddress { } // EscrowAccountHasBalance verifies if the escrow account has the provided fee. -func (k Keeper) EscrowAccountHasBalance(ctx sdk.Context, coins sdk.Coins) bool { +func (k Keeper) EscrowAccountHasBalance(ctx context.Context, coins sdk.Coins) bool { for _, coin := range coins { if !k.bankKeeper.HasBalance(ctx, k.GetFeeModuleAddress(), coin) { return false @@ -112,43 +117,57 @@ func (k Keeper) EscrowAccountHasBalance(ctx sdk.Context, coins sdk.Coins) bool { // lockFeeModule sets a flag to determine if fee handling logic should run for the given channel // identified by channel and port identifiers. // Please see ADR 004 for more information. -func (k Keeper) lockFeeModule(ctx sdk.Context) { - store := ctx.KVStore(k.storeKey) - store.Set(types.KeyLocked(), []byte{1}) +func (k Keeper) lockFeeModule(ctx context.Context) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(types.KeyLocked(), []byte{1}); err != nil { + panic(err) + } } // IsLocked indicates if the fee module is locked // Please see ADR 004 for more information. -func (k Keeper) IsLocked(ctx sdk.Context) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.KeyLocked()) +func (k Keeper) IsLocked(ctx context.Context) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(types.KeyLocked()) + if err != nil { + panic(err) + } + return has } // SetFeeEnabled sets a flag to determine if fee handling logic should run for the given channel // identified by channel and port identifiers. -func (k Keeper) SetFeeEnabled(ctx sdk.Context, portID, channelID string) { - store := ctx.KVStore(k.storeKey) - store.Set(types.KeyFeeEnabled(portID, channelID), []byte{1}) +func (k Keeper) SetFeeEnabled(ctx context.Context, portID, channelID string) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(types.KeyFeeEnabled(portID, channelID), []byte{1}); err != nil { + panic(err) + } } // DeleteFeeEnabled deletes the fee enabled flag for a given portID and channelID -func (k Keeper) DeleteFeeEnabled(ctx sdk.Context, portID, channelID string) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.KeyFeeEnabled(portID, channelID)) +func (k Keeper) DeleteFeeEnabled(ctx context.Context, portID, channelID string) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Delete(types.KeyFeeEnabled(portID, channelID)); err != nil { + panic(err) + } } // IsFeeEnabled returns whether fee handling logic should be run for the given port. It will check the // fee enabled flag for the given port and channel identifiers -func (k Keeper) IsFeeEnabled(ctx sdk.Context, portID, channelID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.KeyFeeEnabled(portID, channelID)) +func (k Keeper) IsFeeEnabled(ctx context.Context, portID, channelID string) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(types.KeyFeeEnabled(portID, channelID)) + if err != nil { + panic(err) + } + return has } // GetAllFeeEnabledChannels returns a list of all ics29 enabled channels containing portID & channelID that are stored in state -func (k Keeper) GetAllFeeEnabledChannels(ctx sdk.Context) []types.FeeEnabledChannel { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetAllFeeEnabledChannels(ctx context.Context) []types.FeeEnabledChannel { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.FeeEnabledKeyPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) var enabledChArr []types.FeeEnabledChannel for ; iterator.Valid(); iterator.Next() { @@ -168,28 +187,35 @@ func (k Keeper) GetAllFeeEnabledChannels(ctx sdk.Context) []types.FeeEnabledChan } // GetPayeeAddress retrieves the fee payee address stored in state given the provided channel identifier and relayer address -func (k Keeper) GetPayeeAddress(ctx sdk.Context, relayerAddr, channelID string) (string, bool) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetPayeeAddress(ctx context.Context, relayerAddr, channelID string) (string, bool) { + store := k.storeService.OpenKVStore(ctx) key := types.KeyPayee(relayerAddr, channelID) - if !store.Has(key) { + bz, err := store.Get(key) + if err != nil { + panic(err) + } + + if len(bz) == 0 { return "", false } - return string(store.Get(key)), true + return string(bz), true } // SetPayeeAddress stores the fee payee address in state keyed by the provided channel identifier and relayer address -func (k Keeper) SetPayeeAddress(ctx sdk.Context, relayerAddr, payeeAddr, channelID string) { - store := ctx.KVStore(k.storeKey) - store.Set(types.KeyPayee(relayerAddr, channelID), []byte(payeeAddr)) +func (k Keeper) SetPayeeAddress(ctx context.Context, relayerAddr, payeeAddr, channelID string) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(types.KeyPayee(relayerAddr, channelID), []byte(payeeAddr)); err != nil { + panic(err) + } } // GetAllPayees returns all registered payees addresses -func (k Keeper) GetAllPayees(ctx sdk.Context) []types.RegisteredPayee { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetAllPayees(ctx context.Context) []types.RegisteredPayee { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.PayeeKeyPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) var registeredPayees []types.RegisteredPayee for ; iterator.Valid(); iterator.Next() { @@ -212,29 +238,34 @@ func (k Keeper) GetAllPayees(ctx sdk.Context) []types.RegisteredPayee { // SetCounterpartyPayeeAddress maps the destination chain counterparty payee address to the source relayer address // The receiving chain must store the mapping from: address -> counterpartyPayeeAddress for the given channel -func (k Keeper) SetCounterpartyPayeeAddress(ctx sdk.Context, address, counterpartyAddress, channelID string) { - store := ctx.KVStore(k.storeKey) - store.Set(types.KeyCounterpartyPayee(address, channelID), []byte(counterpartyAddress)) +func (k Keeper) SetCounterpartyPayeeAddress(ctx context.Context, address, counterpartyAddress, channelID string) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(types.KeyCounterpartyPayee(address, channelID), []byte(counterpartyAddress)); err != nil { + panic(err) + } } // GetCounterpartyPayeeAddress gets the counterparty payee address given a destination relayer address -func (k Keeper) GetCounterpartyPayeeAddress(ctx sdk.Context, address, channelID string) (string, bool) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetCounterpartyPayeeAddress(ctx context.Context, address, channelID string) (string, bool) { + store := k.storeService.OpenKVStore(ctx) key := types.KeyCounterpartyPayee(address, channelID) - if !store.Has(key) { - return "", false + addr, err := store.Get(key) + if err != nil { + panic(err) } - addr := string(store.Get(key)) - return addr, true + if len(addr) == 0 { + return "", false + } + return string(addr), true } // GetAllCounterpartyPayees returns all registered counterparty payee addresses -func (k Keeper) GetAllCounterpartyPayees(ctx sdk.Context) []types.RegisteredCounterpartyPayee { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetAllCounterpartyPayees(ctx context.Context) []types.RegisteredCounterpartyPayee { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.CounterpartyPayeeKeyPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) var registeredCounterpartyPayees []types.RegisteredCounterpartyPayee for ; iterator.Valid(); iterator.Next() { @@ -256,28 +287,35 @@ func (k Keeper) GetAllCounterpartyPayees(ctx sdk.Context) []types.RegisteredCoun } // SetRelayerAddressForAsyncAck sets the forward relayer address during OnRecvPacket in case of async acknowledgement -func (k Keeper) SetRelayerAddressForAsyncAck(ctx sdk.Context, packetID channeltypes.PacketId, address string) { - store := ctx.KVStore(k.storeKey) - store.Set(types.KeyRelayerAddressForAsyncAck(packetID), []byte(address)) +func (k Keeper) SetRelayerAddressForAsyncAck(ctx context.Context, packetID channeltypes.PacketId, address string) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(types.KeyRelayerAddressForAsyncAck(packetID), []byte(address)); err != nil { + panic(err) + } } // GetRelayerAddressForAsyncAck gets forward relayer address for a particular packet -func (k Keeper) GetRelayerAddressForAsyncAck(ctx sdk.Context, packetID channeltypes.PacketId) (string, bool) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetRelayerAddressForAsyncAck(ctx context.Context, packetID channeltypes.PacketId) (string, bool) { + store := k.storeService.OpenKVStore(ctx) key := types.KeyRelayerAddressForAsyncAck(packetID) - if !store.Has(key) { + + addr, err := store.Get(key) + if err != nil { + panic(err) + } + + if len(addr) == 0 { return "", false } - addr := string(store.Get(key)) - return addr, true + return string(addr), true } // GetAllForwardRelayerAddresses returns all forward relayer addresses stored for async acknowledgements -func (k Keeper) GetAllForwardRelayerAddresses(ctx sdk.Context) []types.ForwardRelayerAddress { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetAllForwardRelayerAddresses(ctx context.Context) []types.ForwardRelayerAddress { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.ForwardRelayerPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) var forwardRelayerAddr []types.ForwardRelayerAddress for ; iterator.Valid(); iterator.Next() { @@ -298,17 +336,22 @@ func (k Keeper) GetAllForwardRelayerAddresses(ctx sdk.Context) []types.ForwardRe } // DeleteForwardRelayerAddress deletes the forwardRelayerAddr associated with the packetID -func (k Keeper) DeleteForwardRelayerAddress(ctx sdk.Context, packetID channeltypes.PacketId) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) DeleteForwardRelayerAddress(ctx context.Context, packetID channeltypes.PacketId) { + store := k.storeService.OpenKVStore(ctx) key := types.KeyRelayerAddressForAsyncAck(packetID) - store.Delete(key) + if err := store.Delete(key); err != nil { + panic(err) + } } // GetFeesInEscrow returns all escrowed packet fees for a given packetID -func (k Keeper) GetFeesInEscrow(ctx sdk.Context, packetID channeltypes.PacketId) (types.PacketFees, bool) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId) (types.PacketFees, bool) { + store := k.storeService.OpenKVStore(ctx) key := types.KeyFeesInEscrow(packetID) - bz := store.Get(key) + bz, err := store.Get(key) + if err != nil { + panic(err) + } if len(bz) == 0 { return types.PacketFees{}, false } @@ -317,35 +360,42 @@ func (k Keeper) GetFeesInEscrow(ctx sdk.Context, packetID channeltypes.PacketId) } // HasFeesInEscrow returns true if packet fees exist for the provided packetID -func (k Keeper) HasFeesInEscrow(ctx sdk.Context, packetID channeltypes.PacketId) bool { - store := ctx.KVStore(k.storeKey) +func (k Keeper) HasFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId) bool { + store := k.storeService.OpenKVStore(ctx) key := types.KeyFeesInEscrow(packetID) - - return store.Has(key) + has, err := store.Has(key) + if err != nil { + panic(err) + } + return has } // SetFeesInEscrow sets the given packet fees in escrow keyed by the packetID -func (k Keeper) SetFeesInEscrow(ctx sdk.Context, packetID channeltypes.PacketId, fees types.PacketFees) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) SetFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId, fees types.PacketFees) { + store := k.storeService.OpenKVStore(ctx) bz := k.MustMarshalFees(fees) - store.Set(types.KeyFeesInEscrow(packetID), bz) + if err := store.Set(types.KeyFeesInEscrow(packetID), bz); err != nil { + panic(err) + } } // DeleteFeesInEscrow deletes the fee associated with the given packetID -func (k Keeper) DeleteFeesInEscrow(ctx sdk.Context, packetID channeltypes.PacketId) { - store := ctx.KVStore(k.storeKey) +func (k Keeper) DeleteFeesInEscrow(ctx context.Context, packetID channeltypes.PacketId) { + store := k.storeService.OpenKVStore(ctx) key := types.KeyFeesInEscrow(packetID) - store.Delete(key) + if err := store.Delete(key); err != nil { + panic(err) + } } // GetIdentifiedPacketFeesForChannel returns all the currently escrowed fees on a given channel. -func (k Keeper) GetIdentifiedPacketFeesForChannel(ctx sdk.Context, portID, channelID string) []types.IdentifiedPacketFees { +func (k Keeper) GetIdentifiedPacketFeesForChannel(ctx context.Context, portID, channelID string) []types.IdentifiedPacketFees { var identifiedPacketFees []types.IdentifiedPacketFees - store := ctx.KVStore(k.storeKey) + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, types.KeyFeesInEscrowChannelPrefix(portID, channelID)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { packetID, err := types.ParseKeyFeesInEscrow(string(iterator.Key())) if err != nil { @@ -362,10 +412,10 @@ func (k Keeper) GetIdentifiedPacketFeesForChannel(ctx sdk.Context, portID, chann } // GetAllIdentifiedPacketFees returns a list of all IdentifiedPacketFees that are stored in state -func (k Keeper) GetAllIdentifiedPacketFees(ctx sdk.Context) []types.IdentifiedPacketFees { - store := ctx.KVStore(k.storeKey) +func (k Keeper) GetAllIdentifiedPacketFees(ctx context.Context) []types.IdentifiedPacketFees { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.FeesInEscrowPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) var identifiedFees []types.IdentifiedPacketFees for ; iterator.Valid(); iterator.Next() { diff --git a/modules/apps/29-fee/keeper/migrations.go b/modules/apps/29-fee/keeper/migrations.go index c4c093de5de..25408c95954 100644 --- a/modules/apps/29-fee/keeper/migrations.go +++ b/modules/apps/29-fee/keeper/migrations.go @@ -3,6 +3,7 @@ package keeper import ( storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/ibc-go/v9/modules/apps/29-fee/types" @@ -23,7 +24,7 @@ func NewMigrator(keeper Keeper) Migrator { // Migrate1to2 migrates ibc-fee module from ConsensusVersion 1 to 2 // by refunding leftover fees to the refund address. func (m Migrator) Migrate1to2(ctx sdk.Context) error { - store := ctx.KVStore(m.keeper.storeKey) + store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(types.FeesInEscrowPrefix)) defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) diff --git a/modules/apps/29-fee/keeper/relay.go b/modules/apps/29-fee/keeper/relay.go index a93ea0c88ce..b1a2a1306b6 100644 --- a/modules/apps/29-fee/keeper/relay.go +++ b/modules/apps/29-fee/keeper/relay.go @@ -1,12 +1,11 @@ package keeper import ( + "context" "fmt" errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" "github.com/cosmos/ibc-go/v9/modules/apps/29-fee/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -16,7 +15,7 @@ import ( // SendPacket wraps the ICS4Wrapper SendPacket function func (k Keeper) SendPacket( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, @@ -29,7 +28,7 @@ func (k Keeper) SendPacket( // WriteAcknowledgement wraps IBC ChannelKeeper's WriteAcknowledgement function // ICS29 WriteAcknowledgement is used for asynchronous acknowledgements -func (k Keeper) WriteAcknowledgement(ctx sdk.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, acknowledgement ibcexported.Acknowledgement) error { +func (k Keeper) WriteAcknowledgement(ctx context.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, acknowledgement ibcexported.Acknowledgement) error { if !k.IsFeeEnabled(ctx, packet.GetDestPort(), packet.GetDestChannel()) { // ics4Wrapper may be core IBC or higher-level middleware return k.ics4Wrapper.WriteAcknowledgement(ctx, chanCap, packet, acknowledgement) @@ -56,7 +55,7 @@ func (k Keeper) WriteAcknowledgement(ctx sdk.Context, chanCap *capabilitytypes.C } // GetAppVersion returns the underlying application version. -func (k Keeper) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (k Keeper) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { version, found := k.ics4Wrapper.GetAppVersion(ctx, portID, channelID) if !found { return "", false diff --git a/modules/apps/29-fee/types/expected_keepers.go b/modules/apps/29-fee/types/expected_keepers.go index acd20d9e7ec..f83198484b4 100644 --- a/modules/apps/29-fee/types/expected_keepers.go +++ b/modules/apps/29-fee/types/expected_keepers.go @@ -17,15 +17,15 @@ type AccountKeeper interface { // ChannelKeeper defines the expected IBC channel keeper type ChannelKeeper interface { - GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - GetPacketCommitment(ctx sdk.Context, portID, channelID string, sequence uint64) []byte - GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) - HasChannel(ctx sdk.Context, portID, channelID string) bool + GetChannel(ctx context.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) + GetPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) []byte + GetNextSequenceSend(ctx context.Context, portID, channelID string) (uint64, bool) + HasChannel(ctx context.Context, portID, channelID string) bool } // PortKeeper defines the expected IBC port keeper type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability + BindPort(ctx context.Context, portID string) *capabilitytypes.Capability } // BankKeeper defines the expected bank keeper diff --git a/modules/apps/callbacks/ibc_middleware.go b/modules/apps/callbacks/ibc_middleware.go index 2fb1065fb58..b7a19237797 100644 --- a/modules/apps/callbacks/ibc_middleware.go +++ b/modules/apps/callbacks/ibc_middleware.go @@ -1,6 +1,7 @@ package ibccallbacks import ( + "context" "errors" "fmt" @@ -86,7 +87,7 @@ func (im *IBCMiddleware) GetICS4Wrapper() porttypes.ICS4Wrapper { // If the contract callback returns an error, panics, or runs out of gas, then // the packet send is rejected. func (im IBCMiddleware) SendPacket( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, @@ -102,7 +103,8 @@ func (im IBCMiddleware) SendPacket( // packet is created without destination information present, GetSourceCallbackData does not use these. packet := channeltypes.NewPacket(data, seq, sourcePort, sourceChannel, "", "", timeoutHeight, timeoutTimestamp) - callbackData, err := types.GetSourceCallbackData(ctx, im.app, packet, im.maxCallbackGas) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + callbackData, err := types.GetSourceCallbackData(sdkCtx, im.app, packet, im.maxCallbackGas) // SendPacket is not blocked if the packet does not opt-in to callbacks if err != nil { return seq, nil @@ -114,13 +116,13 @@ func (im IBCMiddleware) SendPacket( ) } - err = im.processCallback(ctx, types.CallbackTypeSendPacket, callbackData, callbackExecutor) + err = im.processCallback(sdkCtx, types.CallbackTypeSendPacket, callbackData, callbackExecutor) // contract keeper is allowed to reject the packet send. if err != nil { return 0, err } - types.EmitCallbackEvent(ctx, sourcePort, sourceChannel, seq, types.CallbackTypeSendPacket, callbackData, nil) + types.EmitCallbackEvent(sdkCtx, sourcePort, sourceChannel, seq, types.CallbackTypeSendPacket, callbackData, nil) return seq, nil } @@ -239,7 +241,7 @@ func (im IBCMiddleware) OnRecvPacket(ctx sdk.Context, channelVersion string, pac // If the contract callback runs out of gas and may be retried with a higher gas limit then the state changes are // reverted via a panic. func (im IBCMiddleware) WriteAcknowledgement( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, packet ibcexported.PacketI, ack ibcexported.Acknowledgement, @@ -254,8 +256,9 @@ func (im IBCMiddleware) WriteAcknowledgement( panic(fmt.Errorf("expected type %T, got %T", &channeltypes.Packet{}, packet)) } + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 callbackData, err := types.GetDestCallbackData( - ctx, im.app, chanPacket, im.maxCallbackGas, + sdkCtx, im.app, chanPacket, im.maxCallbackGas, ) // WriteAcknowledgement is not blocked if the packet does not opt-in to callbacks if err != nil { @@ -267,9 +270,9 @@ func (im IBCMiddleware) WriteAcknowledgement( } // callback execution errors are not allowed to block the packet lifecycle, they are only used in event emissions - err = im.processCallback(ctx, types.CallbackTypeReceivePacket, callbackData, callbackExecutor) + err = im.processCallback(sdkCtx, types.CallbackTypeReceivePacket, callbackData, callbackExecutor) types.EmitCallbackEvent( - ctx, packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence(), + sdkCtx, packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence(), types.CallbackTypeReceivePacket, callbackData, err, ) @@ -420,12 +423,12 @@ func (im IBCMiddleware) OnChanUpgradeOpen(ctx sdk.Context, portID, channelID str // GetAppVersion implements the ICS4Wrapper interface. Callbacks has no version, // so the call is deferred to the underlying application. -func (im IBCMiddleware) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (im IBCMiddleware) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { return im.ics4Wrapper.GetAppVersion(ctx, portID, channelID) } // UnmarshalPacketData defers to the underlying app to unmarshal the packet data. // This function implements the optional PacketDataUnmarshaler interface. -func (im IBCMiddleware) UnmarshalPacketData(ctx sdk.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { +func (im IBCMiddleware) UnmarshalPacketData(ctx context.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { return im.app.UnmarshalPacketData(ctx, portID, channelID, bz) } diff --git a/modules/apps/callbacks/testing/simapp/app.go b/modules/apps/callbacks/testing/simapp/app.go index 931a51ce690..7aa3f1334a4 100644 --- a/modules/apps/callbacks/testing/simapp/app.go +++ b/modules/apps/callbacks/testing/simapp/app.go @@ -405,7 +405,7 @@ func NewSimApp( app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String()) app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, keys[ibcexported.StoreKey], app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, runtime.NewKVStoreService(keys[ibcexported.StoreKey]), app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) // NOTE: The mock ContractKeeper is only created for testing. @@ -430,7 +430,7 @@ func NewSimApp( // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], + appCodec, runtime.NewKVStoreService(keys[ibcfeetypes.StoreKey]), app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware app.IBCKeeper.ChannelKeeper, app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, diff --git a/modules/apps/transfer/ibc_module.go b/modules/apps/transfer/ibc_module.go index 39220cc75eb..f40d2a9b326 100644 --- a/modules/apps/transfer/ibc_module.go +++ b/modules/apps/transfer/ibc_module.go @@ -1,6 +1,7 @@ package transfer import ( + "context" "fmt" "math" "slices" @@ -312,7 +313,7 @@ func (IBCModule) OnChanUpgradeOpen(ctx sdk.Context, portID, channelID string, pr // UnmarshalPacketData attempts to unmarshal the provided packet data bytes // into a FungibleTokenPacketData. This function implements the optional // PacketDataUnmarshaler interface required for ADR 008 support. -func (im IBCModule) UnmarshalPacketData(ctx sdk.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { +func (im IBCModule) UnmarshalPacketData(ctx context.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { ics20Version, found := im.keeper.GetICS4Wrapper().GetAppVersion(ctx, portID, channelID) if !found { return types.FungibleTokenPacketDataV2{}, "", errorsmod.Wrapf(ibcerrors.ErrNotFound, "app version not found for port %s and channel %s", portID, channelID) diff --git a/modules/apps/transfer/types/expected_keepers.go b/modules/apps/transfer/types/expected_keepers.go index 5125eb43315..ee12699cd9a 100644 --- a/modules/apps/transfer/types/expected_keepers.go +++ b/modules/apps/transfer/types/expected_keepers.go @@ -36,10 +36,10 @@ type BankKeeper interface { // ChannelKeeper defines the expected IBC channel keeper type ChannelKeeper interface { - GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) - GetAllChannelsWithPortPrefix(ctx sdk.Context, portPrefix string) []channeltypes.IdentifiedChannel - HasChannel(ctx sdk.Context, portID, channelID string) bool + GetChannel(ctx context.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) + GetNextSequenceSend(ctx context.Context, portID, channelID string) (uint64, bool) + GetAllChannelsWithPortPrefix(ctx context.Context, portPrefix string) []channeltypes.IdentifiedChannel + HasChannel(ctx context.Context, portID, channelID string) bool } // ClientKeeper defines the expected IBC client keeper @@ -54,7 +54,7 @@ type ConnectionKeeper interface { // PortKeeper defines the expected IBC port keeper type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability + BindPort(ctx context.Context, portID string) *capabilitytypes.Capability } // ParamSubspace defines the expected Subspace interface for module parameters. diff --git a/modules/apps/transfer/types/transfer_authorization.go b/modules/apps/transfer/types/transfer_authorization.go index 6e166fe63b9..81a19b0b384 100644 --- a/modules/apps/transfer/types/transfer_authorization.go +++ b/modules/apps/transfer/types/transfer_authorization.go @@ -123,7 +123,7 @@ func (a TransferAuthorization) ValidateBasic() error { } if err := allocation.SpendLimit.Validate(); err != nil { - return errorsmod.Wrapf(ibcerrors.ErrInvalidCoins, err.Error()) + return errorsmod.Wrapf(ibcerrors.ErrInvalidCoins, "invalid spend limit: %s", err.Error()) } if err := host.PortIdentifierValidator(allocation.SourcePort); err != nil { diff --git a/modules/core/02-client/keeper/grpc_query.go b/modules/core/02-client/keeper/grpc_query.go index b8d742ba838..e0dafbd3294 100644 --- a/modules/core/02-client/keeper/grpc_query.go +++ b/modules/core/02-client/keeper/grpc_query.go @@ -14,6 +14,7 @@ import ( errorsmod "cosmossdk.io/errors" "cosmossdk.io/store/prefix" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" @@ -77,7 +78,7 @@ func (q *queryServer) ClientStates(c context.Context, req *types.QueryClientStat ctx := sdk.UnwrapSDKContext(c) var clientStates types.IdentifiedClientStates - store := prefix.NewStore(ctx.KVStore(q.storeKey), host.KeyClientStorePrefix) + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.KeyClientStorePrefix) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { // filter any metadata stored under client state key @@ -172,7 +173,7 @@ func (q *queryServer) ConsensusStates(c context.Context, req *types.QueryConsens ctx := sdk.UnwrapSDKContext(c) var consensusStates []types.ConsensusStateWithHeight - store := prefix.NewStore(ctx.KVStore(q.storeKey), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { // filter any metadata stored under consensus state key @@ -216,7 +217,7 @@ func (q *queryServer) ConsensusStateHeights(c context.Context, req *types.QueryC ctx := sdk.UnwrapSDKContext(c) var consensusStateHeights []types.Height - store := prefix.NewStore(ctx.KVStore(q.storeKey), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.FullClientKey(req.ClientId, []byte(fmt.Sprintf("%s/", host.KeyConsensusStatePrefix)))) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, _ []byte, accumulate bool) (bool, error) { // filter any metadata stored under consensus state key diff --git a/modules/core/02-client/keeper/keeper.go b/modules/core/02-client/keeper/keeper.go index 4f551220a7e..87bb1041ffc 100644 --- a/modules/core/02-client/keeper/keeper.go +++ b/modules/core/02-client/keeper/keeper.go @@ -1,10 +1,12 @@ package keeper import ( + "context" "errors" "fmt" "strings" + corestore "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" "cosmossdk.io/log" "cosmossdk.io/store/prefix" @@ -12,6 +14,7 @@ import ( upgradetypes "cosmossdk.io/x/upgrade/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -24,7 +27,7 @@ import ( // Keeper represents a type that grants read and write permissions to any client // state information type Keeper struct { - storeKey storetypes.StoreKey + storeService corestore.KVStoreService cdc codec.BinaryCodec router *types.Router legacySubspace types.ParamSubspace @@ -32,13 +35,13 @@ type Keeper struct { } // NewKeeper creates a new NewKeeper instance -func NewKeeper(cdc codec.BinaryCodec, key storetypes.StoreKey, legacySubspace types.ParamSubspace, uk types.UpgradeKeeper) *Keeper { +func NewKeeper(cdc codec.BinaryCodec, storeService corestore.KVStoreService, legacySubspace types.ParamSubspace, uk types.UpgradeKeeper) *Keeper { router := types.NewRouter() - localhostModule := localhost.NewLightClientModule(cdc, key) + localhostModule := localhost.NewLightClientModule(cdc, storeService) router.AddRoute(exported.Localhost, localhostModule) return &Keeper{ - storeKey: key, + storeService: storeService, cdc: cdc, router: router, legacySubspace: legacySubspace, @@ -52,8 +55,9 @@ func (k *Keeper) Codec() codec.BinaryCodec { } // Logger returns a module-specific logger. -func (Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) +func (Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) } // AddRoute adds a new route to the underlying router. @@ -63,11 +67,11 @@ func (k *Keeper) AddRoute(clientType string, module exported.LightClientModule) // GetStoreProvider returns the light client store provider. func (k *Keeper) GetStoreProvider() types.StoreProvider { - return types.NewStoreProvider(k.storeKey) + return types.NewStoreProvider(k.storeService) } // Route returns the light client module for the given client identifier. -func (k *Keeper) Route(ctx sdk.Context, clientID string) (exported.LightClientModule, error) { +func (k *Keeper) Route(ctx context.Context, clientID string) (exported.LightClientModule, error) { clientType, _, err := types.ParseClientIdentifier(clientID) if err != nil { return nil, errorsmod.Wrapf(err, "unable to parse client identifier %s", clientID) @@ -89,7 +93,7 @@ func (k *Keeper) Route(ctx sdk.Context, clientID string) (exported.LightClientMo } // GenerateClientIdentifier returns the next client identifier. -func (k *Keeper) GenerateClientIdentifier(ctx sdk.Context, clientType string) string { +func (k *Keeper) GenerateClientIdentifier(ctx context.Context, clientType string) string { nextClientSeq := k.GetNextClientSequence(ctx) clientID := types.FormatClientIdentifier(clientType, nextClientSeq) @@ -99,7 +103,7 @@ func (k *Keeper) GenerateClientIdentifier(ctx sdk.Context, clientType string) st } // GetClientState gets a particular client from the store -func (k *Keeper) GetClientState(ctx sdk.Context, clientID string) (exported.ClientState, bool) { +func (k *Keeper) GetClientState(ctx context.Context, clientID string) (exported.ClientState, bool) { store := k.ClientStore(ctx, clientID) bz := store.Get(host.ClientStateKey()) if len(bz) == 0 { @@ -111,13 +115,13 @@ func (k *Keeper) GetClientState(ctx sdk.Context, clientID string) (exported.Clie } // SetClientState sets a particular Client to the store -func (k *Keeper) SetClientState(ctx sdk.Context, clientID string, clientState exported.ClientState) { +func (k *Keeper) SetClientState(ctx context.Context, clientID string, clientState exported.ClientState) { store := k.ClientStore(ctx, clientID) store.Set(host.ClientStateKey(), types.MustMarshalClientState(k.cdc, clientState)) } // GetClientConsensusState gets the stored consensus state from a client at a given height. -func (k *Keeper) GetClientConsensusState(ctx sdk.Context, clientID string, height exported.Height) (exported.ConsensusState, bool) { +func (k *Keeper) GetClientConsensusState(ctx context.Context, clientID string, height exported.Height) (exported.ConsensusState, bool) { store := k.ClientStore(ctx, clientID) bz := store.Get(host.ConsensusStateKey(height)) if len(bz) == 0 { @@ -130,15 +134,18 @@ func (k *Keeper) GetClientConsensusState(ctx sdk.Context, clientID string, heigh // SetClientConsensusState sets a ConsensusState to a particular client at the given // height -func (k *Keeper) SetClientConsensusState(ctx sdk.Context, clientID string, height exported.Height, consensusState exported.ConsensusState) { +func (k *Keeper) SetClientConsensusState(ctx context.Context, clientID string, height exported.Height, consensusState exported.ConsensusState) { store := k.ClientStore(ctx, clientID) store.Set(host.ConsensusStateKey(height), types.MustMarshalConsensusState(k.cdc, consensusState)) } // GetNextClientSequence gets the next client sequence from the store. -func (k *Keeper) GetNextClientSequence(ctx sdk.Context) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.KeyNextClientSequence)) +func (k *Keeper) GetNextClientSequence(ctx context.Context) uint64 { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get([]byte(types.KeyNextClientSequence)) + if err != nil { + panic(err) + } if len(bz) == 0 { panic(errors.New("next client sequence is nil")) } @@ -147,20 +154,22 @@ func (k *Keeper) GetNextClientSequence(ctx sdk.Context) uint64 { } // SetNextClientSequence sets the next client sequence to the store. -func (k *Keeper) SetNextClientSequence(ctx sdk.Context, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetNextClientSequence(ctx context.Context, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set([]byte(types.KeyNextClientSequence), bz) + if err := store.Set([]byte(types.KeyNextClientSequence), bz); err != nil { + panic(err) + } } // IterateConsensusStates provides an iterator over all stored consensus states. // objects. For each State object, cb will be called. If the cb returns true, // the iterator will close and stop. -func (k *Keeper) IterateConsensusStates(ctx sdk.Context, cb func(clientID string, cs types.ConsensusStateWithHeight) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IterateConsensusStates(ctx context.Context, cb func(clientID string, cs types.ConsensusStateWithHeight) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.KeyClientStorePrefix) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { keySplit := strings.Split(string(iterator.Key()), "/") // consensus key is in the format "clients//consensusStates/" @@ -181,11 +190,11 @@ func (k *Keeper) IterateConsensusStates(ctx sdk.Context, cb func(clientID string // iterateMetadata provides an iterator over all stored metadata keys in the client store. // For each metadata object, it will perform a callback. -func (k *Keeper) iterateMetadata(ctx sdk.Context, cb func(clientID string, key, value []byte) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) iterateMetadata(ctx context.Context, cb func(clientID string, key, value []byte) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.KeyClientStorePrefix) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { split := strings.Split(string(iterator.Key()), "/") if len(split) == 3 && split[2] == string(host.KeyClientState) { @@ -216,7 +225,7 @@ func (k *Keeper) iterateMetadata(ctx sdk.Context, cb func(clientID string, key, } // GetAllGenesisClients returns all the clients in state with their client ids returned as IdentifiedClientState -func (k *Keeper) GetAllGenesisClients(ctx sdk.Context) types.IdentifiedClientStates { +func (k *Keeper) GetAllGenesisClients(ctx context.Context) types.IdentifiedClientStates { var genClients types.IdentifiedClientStates k.IterateClientStates(ctx, nil, func(clientID string, cs exported.ClientState) bool { genClients = append(genClients, types.NewIdentifiedClientState(clientID, cs)) @@ -229,7 +238,7 @@ func (k *Keeper) GetAllGenesisClients(ctx sdk.Context) types.IdentifiedClientSta // GetAllClientMetadata will take a list of IdentifiedClientState and return a list // of IdentifiedGenesisMetadata necessary for exporting and importing client metadata // into the client store. -func (k *Keeper) GetAllClientMetadata(ctx sdk.Context, genClients []types.IdentifiedClientState) ([]types.IdentifiedGenesisMetadata, error) { +func (k *Keeper) GetAllClientMetadata(ctx context.Context, genClients []types.IdentifiedClientState) ([]types.IdentifiedGenesisMetadata, error) { metadataMap := make(map[string][]types.GenesisMetadata) k.iterateMetadata(ctx, func(clientID string, key, value []byte) bool { metadataMap[clientID] = append(metadataMap[clientID], types.NewGenesisMetadata(key, value)) @@ -251,7 +260,7 @@ func (k *Keeper) GetAllClientMetadata(ctx sdk.Context, genClients []types.Identi } // SetAllClientMetadata takes a list of IdentifiedGenesisMetadata and stores all of the metadata in the client store at the appropriate paths. -func (k *Keeper) SetAllClientMetadata(ctx sdk.Context, genMetadata []types.IdentifiedGenesisMetadata) { +func (k *Keeper) SetAllClientMetadata(ctx context.Context, genMetadata []types.IdentifiedGenesisMetadata) { for _, igm := range genMetadata { // create client store store := k.ClientStore(ctx, igm.ClientId) @@ -263,7 +272,7 @@ func (k *Keeper) SetAllClientMetadata(ctx sdk.Context, genMetadata []types.Ident } // GetAllConsensusStates returns all stored client consensus states. -func (k *Keeper) GetAllConsensusStates(ctx sdk.Context) types.ClientsConsensusStates { +func (k *Keeper) GetAllConsensusStates(ctx context.Context) types.ClientsConsensusStates { clientConsStates := make(types.ClientsConsensusStates, 0) mapClientIDToConsStateIdx := make(map[string]int) @@ -289,13 +298,13 @@ func (k *Keeper) GetAllConsensusStates(ctx sdk.Context) types.ClientsConsensusSt // HasClientConsensusState returns if keeper has a ConsensusState for a particular // client at the given height -func (k *Keeper) HasClientConsensusState(ctx sdk.Context, clientID string, height exported.Height) bool { +func (k *Keeper) HasClientConsensusState(ctx context.Context, clientID string, height exported.Height) bool { store := k.ClientStore(ctx, clientID) return store.Has(host.ConsensusStateKey(height)) } // GetLatestClientConsensusState gets the latest ConsensusState stored for a given client -func (k *Keeper) GetLatestClientConsensusState(ctx sdk.Context, clientID string) (exported.ConsensusState, bool) { +func (k *Keeper) GetLatestClientConsensusState(ctx context.Context, clientID string) (exported.ConsensusState, bool) { clientModule, err := k.Route(ctx, clientID) if err != nil { return nil, false @@ -305,7 +314,7 @@ func (k *Keeper) GetLatestClientConsensusState(ctx sdk.Context, clientID string) } // VerifyMembership retrieves the light client module for the clientID and verifies the proof of the existence of a key-value pair at a specified height. -func (k *Keeper) VerifyMembership(ctx sdk.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path, value []byte) error { +func (k *Keeper) VerifyMembership(ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path, value []byte) error { clientModule, err := k.Route(ctx, clientID) if err != nil { return err @@ -315,7 +324,7 @@ func (k *Keeper) VerifyMembership(ctx sdk.Context, clientID string, height expor } // VerifyNonMembership retrieves the light client module for the clientID and verifies the absence of a given key at a specified height. -func (k *Keeper) VerifyNonMembership(ctx sdk.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path) error { +func (k *Keeper) VerifyNonMembership(ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path) error { clientModule, err := k.Route(ctx, clientID) if err != nil { return err @@ -325,33 +334,33 @@ func (k *Keeper) VerifyNonMembership(ctx sdk.Context, clientID string, height ex } // GetUpgradePlan executes the upgrade keeper GetUpgradePlan function. -func (k *Keeper) GetUpgradePlan(ctx sdk.Context) (upgradetypes.Plan, error) { +func (k *Keeper) GetUpgradePlan(ctx context.Context) (upgradetypes.Plan, error) { return k.upgradeKeeper.GetUpgradePlan(ctx) } // GetUpgradedClient executes the upgrade keeper GetUpgradeClient function. -func (k *Keeper) GetUpgradedClient(ctx sdk.Context, planHeight int64) ([]byte, error) { +func (k *Keeper) GetUpgradedClient(ctx context.Context, planHeight int64) ([]byte, error) { return k.upgradeKeeper.GetUpgradedClient(ctx, planHeight) } // GetUpgradedConsensusState returns the upgraded consensus state -func (k *Keeper) GetUpgradedConsensusState(ctx sdk.Context, planHeight int64) ([]byte, error) { +func (k *Keeper) GetUpgradedConsensusState(ctx context.Context, planHeight int64) ([]byte, error) { return k.upgradeKeeper.GetUpgradedConsensusState(ctx, planHeight) } // SetUpgradedConsensusState executes the upgrade keeper SetUpgradedConsensusState function. -func (k *Keeper) SetUpgradedConsensusState(ctx sdk.Context, planHeight int64, bz []byte) error { +func (k *Keeper) SetUpgradedConsensusState(ctx context.Context, planHeight int64, bz []byte) error { return k.upgradeKeeper.SetUpgradedConsensusState(ctx, planHeight, bz) } // IterateClientStates provides an iterator over all stored ibc ClientState // objects using the provided store prefix. For each ClientState object, cb will be called. If the cb returns true, // the iterator will close and stop. -func (k *Keeper) IterateClientStates(ctx sdk.Context, storePrefix []byte, cb func(clientID string, cs exported.ClientState) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IterateClientStates(ctx context.Context, storePrefix []byte, cb func(clientID string, cs exported.ClientState) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.PrefixedClientStoreKey(storePrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { path := string(iterator.Key()) if !strings.Contains(path, host.KeyClientState) { @@ -369,7 +378,7 @@ func (k *Keeper) IterateClientStates(ctx sdk.Context, storePrefix []byte, cb fun } // GetAllClients returns all stored light client State objects. -func (k *Keeper) GetAllClients(ctx sdk.Context) []exported.ClientState { +func (k *Keeper) GetAllClients(ctx context.Context) []exported.ClientState { var states []exported.ClientState k.IterateClientStates(ctx, nil, func(_ string, state exported.ClientState) bool { states = append(states, state) @@ -381,14 +390,15 @@ func (k *Keeper) GetAllClients(ctx sdk.Context) []exported.ClientState { // ClientStore returns isolated prefix store for each client so they can read/write in separate // namespace without being able to read/write other client's data -func (k *Keeper) ClientStore(ctx sdk.Context, clientID string) storetypes.KVStore { +func (k *Keeper) ClientStore(ctx context.Context, clientID string) storetypes.KVStore { clientPrefix := []byte(fmt.Sprintf("%s/%s/", host.KeyClientStorePrefix, clientID)) - return prefix.NewStore(ctx.KVStore(k.storeKey), clientPrefix) + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + return prefix.NewStore(store, clientPrefix) } // GetClientStatus returns the status for a client state given a client identifier. If the client type is not in the allowed // clients param field, Unauthorized is returned, otherwise the client state status is returned. -func (k *Keeper) GetClientStatus(ctx sdk.Context, clientID string) exported.Status { +func (k *Keeper) GetClientStatus(ctx context.Context, clientID string) exported.Status { clientModule, err := k.Route(ctx, clientID) if err != nil { return exported.Unauthorized @@ -399,7 +409,7 @@ func (k *Keeper) GetClientStatus(ctx sdk.Context, clientID string) exported.Stat // GetClientLatestHeight returns the latest height of a client state for a given client identifier. If the client type is not in the allowed // clients param field, a zero value height is returned, otherwise the client state latest height is returned. -func (k *Keeper) GetClientLatestHeight(ctx sdk.Context, clientID string) types.Height { +func (k *Keeper) GetClientLatestHeight(ctx context.Context, clientID string) types.Height { clientModule, err := k.Route(ctx, clientID) if err != nil { return types.ZeroHeight() @@ -414,7 +424,7 @@ func (k *Keeper) GetClientLatestHeight(ctx sdk.Context, clientID string) types.H } // GetClientTimestampAtHeight returns the timestamp in nanoseconds of the consensus state at the given height. -func (k *Keeper) GetClientTimestampAtHeight(ctx sdk.Context, clientID string, height exported.Height) (uint64, error) { +func (k *Keeper) GetClientTimestampAtHeight(ctx context.Context, clientID string, height exported.Height) (uint64, error) { clientModule, err := k.Route(ctx, clientID) if err != nil { return 0, err @@ -424,9 +434,12 @@ func (k *Keeper) GetClientTimestampAtHeight(ctx sdk.Context, clientID string, he } // GetParams returns the total set of ibc-client parameters. -func (k *Keeper) GetParams(ctx sdk.Context) types.Params { - store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.ParamsKey)) +func (k *Keeper) GetParams(ctx context.Context) types.Params { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get([]byte(types.ParamsKey)) + if err != nil { + panic(err) + } if bz == nil { // only panic on unset params and not on empty params panic(errors.New("client params are not set in store")) } @@ -437,14 +450,16 @@ func (k *Keeper) GetParams(ctx sdk.Context) types.Params { } // SetParams sets the total set of ibc-client parameters. -func (k *Keeper) SetParams(ctx sdk.Context, params types.Params) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetParams(ctx context.Context, params types.Params) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) - store.Set([]byte(types.ParamsKey), bz) + if err := store.Set([]byte(types.ParamsKey), bz); err != nil { + panic(err) + } } // ScheduleIBCSoftwareUpgrade schedules an upgrade for the IBC client. -func (k *Keeper) ScheduleIBCSoftwareUpgrade(ctx sdk.Context, plan upgradetypes.Plan, upgradedClientState exported.ClientState) error { +func (k *Keeper) ScheduleIBCSoftwareUpgrade(ctx context.Context, plan upgradetypes.Plan, upgradedClientState exported.ClientState) error { // zero out any custom fields before setting cs, ok := upgradedClientState.(*ibctm.ClientState) if !ok { @@ -468,7 +483,8 @@ func (k *Keeper) ScheduleIBCSoftwareUpgrade(ctx sdk.Context, plan upgradetypes.P } // emitting an event for scheduling an upgrade plan - emitScheduleIBCSoftwareUpgradeEvent(ctx, plan.Name, plan.Height) + sdkContext := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + emitScheduleIBCSoftwareUpgradeEvent(sdkContext, plan.Name, plan.Height) return nil } diff --git a/modules/core/02-client/keeper/migrations.go b/modules/core/02-client/keeper/migrations.go index ba45e543622..d39a756ed93 100644 --- a/modules/core/02-client/keeper/migrations.go +++ b/modules/core/02-client/keeper/migrations.go @@ -26,7 +26,7 @@ func NewMigrator(keeper *Keeper) Migrator { // - removes the localhost client // - asserts that existing tendermint clients are properly registered on the chain codec func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v7.MigrateStore(ctx, m.keeper.storeKey, m.keeper.cdc, m.keeper) + return v7.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc, m.keeper) } // MigrateParams migrates from consensus version 4 to 5. diff --git a/modules/core/02-client/migrations/v7/expected_keepers.go b/modules/core/02-client/migrations/v7/expected_keepers.go index d25f9f880f6..feb486b73f2 100644 --- a/modules/core/02-client/migrations/v7/expected_keepers.go +++ b/modules/core/02-client/migrations/v7/expected_keepers.go @@ -1,16 +1,16 @@ package v7 import ( - storetypes "cosmossdk.io/store/types" + "context" - sdk "github.com/cosmos/cosmos-sdk/types" + storetypes "cosmossdk.io/store/types" "github.com/cosmos/ibc-go/v9/modules/core/exported" ) // ClientKeeper expected IBC client keeper type ClientKeeper interface { - GetClientState(ctx sdk.Context, clientID string) (exported.ClientState, bool) - SetClientState(ctx sdk.Context, clientID string, clientState exported.ClientState) - ClientStore(ctx sdk.Context, clientID string) storetypes.KVStore + GetClientState(ctx context.Context, clientID string) (exported.ClientState, bool) + SetClientState(ctx context.Context, clientID string, clientState exported.ClientState) + ClientStore(ctx context.Context, clientID string) storetypes.KVStore } diff --git a/modules/core/02-client/migrations/v7/genesis_test.go b/modules/core/02-client/migrations/v7/genesis_test.go index f97f5aa4ed7..2478f2a00f4 100644 --- a/modules/core/02-client/migrations/v7/genesis_test.go +++ b/modules/core/02-client/migrations/v7/genesis_test.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" ibcclient "github.com/cosmos/ibc-go/v9/modules/core/02-client" "github.com/cosmos/ibc-go/v9/modules/core/02-client/migrations/v7" @@ -107,7 +108,7 @@ func (suite *MigrationsV7TestSuite) TestMigrateGenesisSolomachine() { // migrate store get expected genesis // store migration and genesis migration should produce identical results // NOTE: tendermint clients are not pruned in genesis so the test should not have expired tendermint clients - err := v7.MigrateStore(suite.chainA.GetContext(), suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) + err := v7.MigrateStore(suite.chainA.GetContext(), runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey)), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) suite.Require().NoError(err) expectedClientGenState := ibcclient.ExportGenesis(suite.chainA.GetContext(), suite.chainA.App.GetIBCKeeper().ClientKeeper) diff --git a/modules/core/02-client/migrations/v7/store.go b/modules/core/02-client/migrations/v7/store.go index a75de44cbed..2bfff6099de 100644 --- a/modules/core/02-client/migrations/v7/store.go +++ b/modules/core/02-client/migrations/v7/store.go @@ -3,11 +3,13 @@ package v7 import ( "strings" + corestore "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -29,8 +31,8 @@ const Localhost string = "09-localhost" // - Pruning all solo machine consensus states // - Removing the localhost client // - Asserting existing tendermint clients are properly registered on the chain codec -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, cdc codec.BinaryCodec, clientKeeper ClientKeeper) error { - store := ctx.KVStore(storeKey) +func MigrateStore(ctx sdk.Context, storeService corestore.KVStoreService, cdc codec.BinaryCodec, clientKeeper ClientKeeper) error { + store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) if err := handleSolomachineMigration(ctx, store, cdc, clientKeeper); err != nil { return err diff --git a/modules/core/02-client/migrations/v7/store_test.go b/modules/core/02-client/migrations/v7/store_test.go index 620da77107c..f9e104e823f 100644 --- a/modules/core/02-client/migrations/v7/store_test.go +++ b/modules/core/02-client/migrations/v7/store_test.go @@ -7,6 +7,7 @@ import ( testifysuite "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/ibc-go/v9/modules/core/02-client/migrations/v7" "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -61,7 +62,7 @@ func (suite *MigrationsV7TestSuite) TestMigrateStore() { suite.createSolomachineClients(solomachines) suite.createLocalhostClients() - err := v7.MigrateStore(suite.chainA.GetContext(), suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) + err := v7.MigrateStore(suite.chainA.GetContext(), runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey)), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) suite.Require().NoError(err) suite.assertSolomachineClients(solomachines) @@ -77,7 +78,7 @@ func (suite *MigrationsV7TestSuite) TestMigrateStoreNoTendermintClients() { suite.createSolomachineClients(solomachines) suite.createLocalhostClients() - err := v7.MigrateStore(suite.chainA.GetContext(), suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) + err := v7.MigrateStore(suite.chainA.GetContext(), runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey)), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) suite.Require().NoError(err) suite.assertSolomachineClients(solomachines) diff --git a/modules/core/02-client/types/height.go b/modules/core/02-client/types/height.go index a326142a685..c5d6839588a 100644 --- a/modules/core/02-client/types/height.go +++ b/modules/core/02-client/types/height.go @@ -1,6 +1,7 @@ package types import ( + "context" "fmt" "math/big" "regexp" @@ -185,7 +186,8 @@ func ParseChainID(chainID string) uint64 { // GetSelfHeight is a utility function that returns self height given context // Revision number is retrieved from ctx.ChainID() -func GetSelfHeight(ctx sdk.Context) Height { - revision := ParseChainID(ctx.ChainID()) - return NewHeight(revision, uint64(ctx.BlockHeight())) +func GetSelfHeight(ctx context.Context) Height { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + revision := ParseChainID(sdkCtx.ChainID()) + return NewHeight(revision, uint64(sdkCtx.BlockHeight())) } diff --git a/modules/core/02-client/types/router_test.go b/modules/core/02-client/types/router_test.go index 7b18319601c..095c7fb141e 100644 --- a/modules/core/02-client/types/router_test.go +++ b/modules/core/02-client/types/router_test.go @@ -6,6 +6,8 @@ import ( "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" "github.com/cosmos/ibc-go/v9/modules/core/exported" ibctm "github.com/cosmos/ibc-go/v9/modules/light-clients/07-tendermint" @@ -53,7 +55,7 @@ func (suite *TypesTestSuite) TestAddRoute() { suite.SetupTest() cdc := suite.chainA.App.AppCodec() - storeProvider := types.NewStoreProvider(suite.chainA.GetSimApp().GetKey(exported.StoreKey)) + storeProvider := types.NewStoreProvider(runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(exported.StoreKey))) tmLightClientModule := ibctm.NewLightClientModule(cdc, storeProvider) router = types.NewRouter() @@ -110,7 +112,7 @@ func (suite *TypesTestSuite) TestHasGetRoute() { suite.SetupTest() cdc := suite.chainA.App.AppCodec() - storeProvider := types.NewStoreProvider(suite.chainA.GetSimApp().GetKey(exported.StoreKey)) + storeProvider := types.NewStoreProvider(runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(exported.StoreKey))) tmLightClientModule := ibctm.NewLightClientModule(cdc, storeProvider) router := types.NewRouter() router.AddRoute(exported.Tendermint, &tmLightClientModule) diff --git a/modules/core/02-client/types/store.go b/modules/core/02-client/types/store.go index 446e6933d8a..416a75e3ec5 100644 --- a/modules/core/02-client/types/store.go +++ b/modules/core/02-client/types/store.go @@ -1,35 +1,37 @@ package types import ( + "context" "fmt" + corestore "cosmossdk.io/core/store" "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/runtime" host "github.com/cosmos/ibc-go/v9/modules/core/24-host" ) -// StoreProvider encapsulates the IBC core store key and offers convenience methods for LightClientModules. +// StoreProvider encapsulates the IBC core store service and offers convenience methods for LightClientModules. type StoreProvider struct { - storeKey storetypes.StoreKey + storeService corestore.KVStoreService } // NewStoreProvider creates and returns a new client StoreProvider. -func NewStoreProvider(storeKey storetypes.StoreKey) StoreProvider { +func NewStoreProvider(storeService corestore.KVStoreService) StoreProvider { return StoreProvider{ - storeKey: storeKey, + storeService: storeService, } } // ClientStore returns isolated prefix store for each client so they can read/write in separate namespaces. -func (s StoreProvider) ClientStore(ctx sdk.Context, clientID string) storetypes.KVStore { +func (s StoreProvider) ClientStore(ctx context.Context, clientID string) storetypes.KVStore { clientPrefix := []byte(fmt.Sprintf("%s/%s/", host.KeyClientStorePrefix, clientID)) - return prefix.NewStore(ctx.KVStore(s.storeKey), clientPrefix) + return prefix.NewStore(runtime.KVStoreAdapter(s.storeService.OpenKVStore(ctx)), clientPrefix) } // ClientModuleStore returns the module store for a provided client type. -func (s StoreProvider) ClientModuleStore(ctx sdk.Context, clientType string) storetypes.KVStore { - return prefix.NewStore(ctx.KVStore(s.storeKey), host.PrefixedClientStoreKey([]byte(clientType))) +func (s StoreProvider) ClientModuleStore(ctx context.Context, clientType string) storetypes.KVStore { + return prefix.NewStore(runtime.KVStoreAdapter(s.storeService.OpenKVStore(ctx)), host.PrefixedClientStoreKey([]byte(clientType))) } diff --git a/modules/core/03-connection/keeper/grpc_query.go b/modules/core/03-connection/keeper/grpc_query.go index 960c1ea025c..859b6125332 100644 --- a/modules/core/03-connection/keeper/grpc_query.go +++ b/modules/core/03-connection/keeper/grpc_query.go @@ -9,6 +9,7 @@ import ( errorsmod "cosmossdk.io/errors" "cosmossdk.io/store/prefix" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" @@ -66,7 +67,8 @@ func (q *queryServer) Connections(c context.Context, req *types.QueryConnections ctx := sdk.UnwrapSDKContext(c) var connections []*types.IdentifiedConnection - store := prefix.NewStore(ctx.KVStore(q.storeKey), []byte(host.KeyConnectionPrefix)) + + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), []byte(host.KeyConnectionPrefix)) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { var result types.ConnectionEnd diff --git a/modules/core/03-connection/keeper/keeper.go b/modules/core/03-connection/keeper/keeper.go index 2ce0c82aa69..08d465f6716 100644 --- a/modules/core/03-connection/keeper/keeper.go +++ b/modules/core/03-connection/keeper/keeper.go @@ -1,13 +1,16 @@ package keeper import ( + "context" "errors" + corestore "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -22,16 +25,16 @@ type Keeper struct { // implements gRPC QueryServer interface types.QueryServer - storeKey storetypes.StoreKey + storeService corestore.KVStoreService legacySubspace types.ParamSubspace cdc codec.BinaryCodec clientKeeper types.ClientKeeper } // NewKeeper creates a new IBC connection Keeper instance -func NewKeeper(cdc codec.BinaryCodec, key storetypes.StoreKey, legacySubspace types.ParamSubspace, ck types.ClientKeeper) *Keeper { +func NewKeeper(cdc codec.BinaryCodec, storeService corestore.KVStoreService, legacySubspace types.ParamSubspace, ck types.ClientKeeper) *Keeper { return &Keeper{ - storeKey: key, + storeService: storeService, cdc: cdc, legacySubspace: legacySubspace, clientKeeper: ck, @@ -39,18 +42,19 @@ func NewKeeper(cdc codec.BinaryCodec, key storetypes.StoreKey, legacySubspace ty } // Logger returns a module-specific logger. -func (Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) +func (Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) } // GetCommitmentPrefix returns the IBC connection store prefix as a commitment // Prefix -func (k *Keeper) GetCommitmentPrefix() exported.Prefix { - return commitmenttypes.NewMerklePrefix([]byte(k.storeKey.Name())) +func (*Keeper) GetCommitmentPrefix() exported.Prefix { + return commitmenttypes.NewMerklePrefix([]byte(exported.StoreKey)) } // GenerateConnectionIdentifier returns the next connection identifier. -func (k *Keeper) GenerateConnectionIdentifier(ctx sdk.Context) string { +func (k *Keeper) GenerateConnectionIdentifier(ctx context.Context) string { nextConnSeq := k.GetNextConnectionSequence(ctx) connectionID := types.FormatConnectionIdentifier(nextConnSeq) @@ -60,9 +64,13 @@ func (k *Keeper) GenerateConnectionIdentifier(ctx sdk.Context) string { } // GetConnection returns a connection with a particular identifier -func (k *Keeper) GetConnection(ctx sdk.Context, connectionID string) (types.ConnectionEnd, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.ConnectionKey(connectionID)) +func (k *Keeper) GetConnection(ctx context.Context, connectionID string) (types.ConnectionEnd, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.ConnectionKey(connectionID)) + if err != nil { + panic(err) + } + if len(bz) == 0 { return types.ConnectionEnd{}, false } @@ -75,23 +83,33 @@ func (k *Keeper) GetConnection(ctx sdk.Context, connectionID string) (types.Conn // HasConnection returns a true if the connection with the given identifier // exists in the store. -func (k *Keeper) HasConnection(ctx sdk.Context, connectionID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(host.ConnectionKey(connectionID)) +func (k *Keeper) HasConnection(ctx context.Context, connectionID string) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(host.ConnectionKey(connectionID)) + if err != nil { + return false + } + return has } // SetConnection sets a connection to the store -func (k *Keeper) SetConnection(ctx sdk.Context, connectionID string, connection types.ConnectionEnd) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetConnection(ctx context.Context, connectionID string, connection types.ConnectionEnd) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&connection) - store.Set(host.ConnectionKey(connectionID), bz) + if err := store.Set(host.ConnectionKey(connectionID), bz); err != nil { + panic(err) + } } // GetClientConnectionPaths returns all the connection paths stored under a // particular client -func (k *Keeper) GetClientConnectionPaths(ctx sdk.Context, clientID string) ([]string, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.ClientConnectionsKey(clientID)) +func (k *Keeper) GetClientConnectionPaths(ctx context.Context, clientID string) ([]string, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.ClientConnectionsKey(clientID)) + if err != nil { + panic(err) + } + if len(bz) == 0 { return nil, false } @@ -102,17 +120,23 @@ func (k *Keeper) GetClientConnectionPaths(ctx sdk.Context, clientID string) ([]s } // SetClientConnectionPaths sets the connections paths for client -func (k *Keeper) SetClientConnectionPaths(ctx sdk.Context, clientID string, paths []string) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetClientConnectionPaths(ctx context.Context, clientID string, paths []string) { + store := k.storeService.OpenKVStore(ctx) clientPaths := types.ClientPaths{Paths: paths} bz := k.cdc.MustMarshal(&clientPaths) - store.Set(host.ClientConnectionsKey(clientID), bz) + if err := store.Set(host.ClientConnectionsKey(clientID), bz); err != nil { + panic(err) + } } // GetNextConnectionSequence gets the next connection sequence from the store. -func (k *Keeper) GetNextConnectionSequence(ctx sdk.Context) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.KeyNextConnectionSequence)) +func (k *Keeper) GetNextConnectionSequence(ctx context.Context) uint64 { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get([]byte(types.KeyNextConnectionSequence)) + if err != nil { + panic(err) + } + if len(bz) == 0 { panic(errors.New("next connection sequence is nil")) } @@ -121,18 +145,21 @@ func (k *Keeper) GetNextConnectionSequence(ctx sdk.Context) uint64 { } // SetNextConnectionSequence sets the next connection sequence to the store. -func (k *Keeper) SetNextConnectionSequence(ctx sdk.Context, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetNextConnectionSequence(ctx context.Context, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set([]byte(types.KeyNextConnectionSequence), bz) + if err := store.Set([]byte(types.KeyNextConnectionSequence), bz); err != nil { + panic(err) + } } // GetAllClientConnectionPaths returns all stored clients connection id paths. It // will ignore the clients that haven't initialized a connection handshake since // no paths are stored. -func (k *Keeper) GetAllClientConnectionPaths(ctx sdk.Context) []types.ConnectionPaths { +func (k *Keeper) GetAllClientConnectionPaths(ctx context.Context) []types.ConnectionPaths { var allConnectionPaths []types.ConnectionPaths - k.clientKeeper.IterateClientStates(ctx, nil, func(clientID string, cs exported.ClientState) bool { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + k.clientKeeper.IterateClientStates(sdkCtx, nil, func(clientID string, cs exported.ClientState) bool { paths, found := k.GetClientConnectionPaths(ctx, clientID) if !found { // continue when connection handshake is not initialized @@ -149,11 +176,12 @@ func (k *Keeper) GetAllClientConnectionPaths(ctx sdk.Context) []types.Connection // IterateConnections provides an iterator over all ConnectionEnd objects. // For each ConnectionEnd, cb will be called. If the cb returns true, the // iterator will close and stop. -func (k *Keeper) IterateConnections(ctx sdk.Context, cb func(types.IdentifiedConnection) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IterateConnections(ctx context.Context, cb func(types.IdentifiedConnection) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyConnectionPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { var connection types.ConnectionEnd k.cdc.MustUnmarshal(iterator.Value(), &connection) @@ -167,7 +195,7 @@ func (k *Keeper) IterateConnections(ctx sdk.Context, cb func(types.IdentifiedCon } // GetAllConnections returns all stored ConnectionEnd objects. -func (k *Keeper) GetAllConnections(ctx sdk.Context) (connections []types.IdentifiedConnection) { +func (k *Keeper) GetAllConnections(ctx context.Context) (connections []types.IdentifiedConnection) { k.IterateConnections(ctx, func(connection types.IdentifiedConnection) bool { connections = append(connections, connection) return false @@ -176,7 +204,7 @@ func (k *Keeper) GetAllConnections(ctx sdk.Context) (connections []types.Identif } // CreateSentinelLocalhostConnection creates and sets the sentinel localhost connection end in the IBC store. -func (k *Keeper) CreateSentinelLocalhostConnection(ctx sdk.Context) { +func (k *Keeper) CreateSentinelLocalhostConnection(ctx context.Context) { counterparty := types.NewCounterparty(exported.LocalhostClientID, exported.LocalhostConnectionID, commitmenttypes.NewMerklePrefix(k.GetCommitmentPrefix().Bytes())) connectionEnd := types.NewConnectionEnd(types.OPEN, exported.LocalhostClientID, counterparty, types.GetCompatibleVersions(), 0) @@ -185,8 +213,9 @@ func (k *Keeper) CreateSentinelLocalhostConnection(ctx sdk.Context) { // addConnectionToClient is used to add a connection identifier to the set of // connections associated with a client. -func (k *Keeper) addConnectionToClient(ctx sdk.Context, clientID, connectionID string) error { - _, found := k.clientKeeper.GetClientState(ctx, clientID) +func (k *Keeper) addConnectionToClient(ctx context.Context, clientID, connectionID string) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, found := k.clientKeeper.GetClientState(sdkCtx, clientID) if !found { return errorsmod.Wrap(clienttypes.ErrClientNotFound, clientID) } @@ -202,9 +231,13 @@ func (k *Keeper) addConnectionToClient(ctx sdk.Context, clientID, connectionID s } // GetParams returns the total set of ibc-connection parameters. -func (k *Keeper) GetParams(ctx sdk.Context) types.Params { - store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.ParamsKey)) +func (k *Keeper) GetParams(ctx context.Context) types.Params { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get([]byte(types.ParamsKey)) + if err != nil { + panic(err) + } + if bz == nil { // only panic on unset params and not on empty params panic(errors.New("connection params are not set in store")) } @@ -215,8 +248,10 @@ func (k *Keeper) GetParams(ctx sdk.Context) types.Params { } // SetParams sets the total set of ibc-connection parameters. -func (k *Keeper) SetParams(ctx sdk.Context, params types.Params) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetParams(ctx context.Context, params types.Params) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) - store.Set([]byte(types.ParamsKey), bz) + if err := store.Set([]byte(types.ParamsKey), bz); err != nil { + panic(err) + } } diff --git a/modules/core/03-connection/keeper/verify.go b/modules/core/03-connection/keeper/verify.go index a46f4cf0a99..5dd4969edd2 100644 --- a/modules/core/03-connection/keeper/verify.go +++ b/modules/core/03-connection/keeper/verify.go @@ -1,6 +1,7 @@ package keeper import ( + "context" "math" errorsmod "cosmossdk.io/errors" @@ -18,7 +19,7 @@ import ( // VerifyConnectionState verifies a proof of the connection state of the // specified connection end stored on the target machine. func (k *Keeper) VerifyConnectionState( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, height exported.Height, proof []byte, @@ -55,7 +56,7 @@ func (k *Keeper) VerifyConnectionState( // VerifyChannelState verifies a proof of the channel state of the specified // channel end, under the specified port, stored on the target machine. func (k *Keeper) VerifyChannelState( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, height exported.Height, proof []byte, @@ -93,7 +94,7 @@ func (k *Keeper) VerifyChannelState( // VerifyPacketCommitment verifies a proof of an outgoing packet commitment at // the specified port, specified channel, and specified sequence. func (k *Keeper) VerifyPacketCommitment( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, height exported.Height, proof []byte, @@ -129,7 +130,7 @@ func (k *Keeper) VerifyPacketCommitment( // VerifyPacketAcknowledgement verifies a proof of an incoming packet // acknowledgement at the specified port, specified channel, and specified sequence. func (k *Keeper) VerifyPacketAcknowledgement( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, height exported.Height, proof []byte, @@ -167,7 +168,7 @@ func (k *Keeper) VerifyPacketAcknowledgement( // incoming packet receipt at the specified port, specified channel, and // specified sequence. func (k *Keeper) VerifyPacketReceiptAbsence( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, height exported.Height, proof []byte, @@ -202,7 +203,7 @@ func (k *Keeper) VerifyPacketReceiptAbsence( // VerifyNextSequenceRecv verifies a proof of the next sequence number to be // received of the specified channel at the specified port. func (k *Keeper) VerifyNextSequenceRecv( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, height exported.Height, proof []byte, @@ -238,7 +239,7 @@ func (k *Keeper) VerifyNextSequenceRecv( // VerifyChannelUpgradeError verifies a proof of the provided upgrade error receipt. func (k *Keeper) VerifyChannelUpgradeError( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, height exported.Height, proof []byte, @@ -275,7 +276,7 @@ func (k *Keeper) VerifyChannelUpgradeError( // VerifyChannelUpgrade verifies the proof that a particular proposed upgrade has been stored in the upgrade path. func (k *Keeper) VerifyChannelUpgrade( - ctx sdk.Context, + ctx context.Context, connection types.ConnectionEnd, proofHeight exported.Height, upgradeProof []byte, @@ -312,7 +313,7 @@ func (k *Keeper) VerifyChannelUpgrade( // getBlockDelay calculates the block delay period from the time delay of the connection // and the maximum expected time per block. -func (k *Keeper) getBlockDelay(ctx sdk.Context, connection types.ConnectionEnd) uint64 { +func (k *Keeper) getBlockDelay(ctx context.Context, connection types.ConnectionEnd) uint64 { // expectedTimePerBlock should never be zero, however if it is then return a 0 block delay for safety // as the expectedTimePerBlock parameter was not set. expectedTimePerBlock := k.GetParams(ctx).MaxExpectedTimePerBlock diff --git a/modules/core/03-connection/migrations/v7/expected_keepers.go b/modules/core/03-connection/migrations/v7/expected_keepers.go index 8427e2cc2bf..c36d1fbae93 100644 --- a/modules/core/03-connection/migrations/v7/expected_keepers.go +++ b/modules/core/03-connection/migrations/v7/expected_keepers.go @@ -1,10 +1,8 @@ package v7 -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) +import "context" // ConnectionKeeper expected IBC connection keeper type ConnectionKeeper interface { - CreateSentinelLocalhostConnection(ctx sdk.Context) + CreateSentinelLocalhostConnection(ctx context.Context) } diff --git a/modules/core/03-connection/types/expected_keepers.go b/modules/core/03-connection/types/expected_keepers.go index ff13cf0d742..81430da3242 100644 --- a/modules/core/03-connection/types/expected_keepers.go +++ b/modules/core/03-connection/types/expected_keepers.go @@ -1,6 +1,8 @@ package types import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" @@ -9,12 +11,12 @@ import ( // ClientKeeper expected account IBC client keeper type ClientKeeper interface { - GetClientStatus(ctx sdk.Context, clientID string) exported.Status - GetClientState(ctx sdk.Context, clientID string) (exported.ClientState, bool) - GetClientConsensusState(ctx sdk.Context, clientID string, height exported.Height) (exported.ConsensusState, bool) - VerifyMembership(ctx sdk.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path, value []byte) error - VerifyNonMembership(ctx sdk.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path) error - IterateClientStates(ctx sdk.Context, prefix []byte, cb func(string, exported.ClientState) bool) + GetClientStatus(ctx context.Context, clientID string) exported.Status + GetClientState(ctx context.Context, clientID string) (exported.ClientState, bool) + GetClientConsensusState(ctx context.Context, clientID string, height exported.Height) (exported.ConsensusState, bool) + VerifyMembership(ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path, value []byte) error + VerifyNonMembership(ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path) error + IterateClientStates(ctx context.Context, prefix []byte, cb func(string, exported.ClientState) bool) } // ParamSubspace defines the expected Subspace interface for module parameters. diff --git a/modules/core/04-channel/keeper/grpc_query.go b/modules/core/04-channel/keeper/grpc_query.go index 3d03f8f9088..648a8028534 100644 --- a/modules/core/04-channel/keeper/grpc_query.go +++ b/modules/core/04-channel/keeper/grpc_query.go @@ -11,7 +11,7 @@ import ( errorsmod "cosmossdk.io/errors" "cosmossdk.io/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/ibc-go/v9/internal/validate" @@ -37,7 +37,7 @@ func NewQueryServer(k *Keeper) types.QueryServer { } // Channel implements the Query/Channel gRPC method -func (q *queryServer) Channel(c context.Context, req *types.QueryChannelRequest) (*types.QueryChannelResponse, error) { +func (q *queryServer) Channel(ctx context.Context, req *types.QueryChannelRequest) (*types.QueryChannelResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -46,7 +46,6 @@ func (q *queryServer) Channel(c context.Context, req *types.QueryChannelRequest) return nil, err } - ctx := sdk.UnwrapSDKContext(c) channel, found := q.GetChannel(ctx, req.PortId, req.ChannelId) if !found { return nil, status.Error( @@ -60,15 +59,13 @@ func (q *queryServer) Channel(c context.Context, req *types.QueryChannelRequest) } // Channels implements the Query/Channels gRPC method -func (q *queryServer) Channels(c context.Context, req *types.QueryChannelsRequest) (*types.QueryChannelsResponse, error) { +func (q *queryServer) Channels(ctx context.Context, req *types.QueryChannelsRequest) (*types.QueryChannelsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - ctx := sdk.UnwrapSDKContext(c) - var channels []*types.IdentifiedChannel - store := prefix.NewStore(ctx.KVStore(q.storeKey), []byte(host.KeyChannelEndPrefix)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), []byte(host.KeyChannelEndPrefix)) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { var result types.Channel @@ -98,7 +95,7 @@ func (q *queryServer) Channels(c context.Context, req *types.QueryChannelsReques } // ConnectionChannels implements the Query/ConnectionChannels gRPC method -func (q *queryServer) ConnectionChannels(c context.Context, req *types.QueryConnectionChannelsRequest) (*types.QueryConnectionChannelsResponse, error) { +func (q *queryServer) ConnectionChannels(ctx context.Context, req *types.QueryConnectionChannelsRequest) (*types.QueryConnectionChannelsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -107,10 +104,9 @@ func (q *queryServer) ConnectionChannels(c context.Context, req *types.QueryConn return nil, status.Error(codes.InvalidArgument, err.Error()) } - ctx := sdk.UnwrapSDKContext(c) - var channels []*types.IdentifiedChannel - store := prefix.NewStore(ctx.KVStore(q.storeKey), []byte(host.KeyChannelEndPrefix)) + + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), []byte(host.KeyChannelEndPrefix)) pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { // filter any metadata stored under channel key @@ -147,7 +143,7 @@ func (q *queryServer) ConnectionChannels(c context.Context, req *types.QueryConn } // ChannelClientState implements the Query/ChannelClientState gRPC method -func (q *queryServer) ChannelClientState(c context.Context, req *types.QueryChannelClientStateRequest) (*types.QueryChannelClientStateResponse, error) { +func (q *queryServer) ChannelClientState(ctx context.Context, req *types.QueryChannelClientStateRequest) (*types.QueryChannelClientStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -156,8 +152,6 @@ func (q *queryServer) ChannelClientState(c context.Context, req *types.QueryChan return nil, err } - ctx := sdk.UnwrapSDKContext(c) - clientID, clientState, err := q.GetChannelClientState(ctx, req.PortId, req.ChannelId) if err != nil { return nil, status.Error(codes.NotFound, err.Error()) @@ -170,7 +164,7 @@ func (q *queryServer) ChannelClientState(c context.Context, req *types.QueryChan } // ChannelConsensusState implements the Query/ChannelConsensusState gRPC method -func (q *queryServer) ChannelConsensusState(c context.Context, req *types.QueryChannelConsensusStateRequest) (*types.QueryChannelConsensusStateResponse, error) { +func (q *queryServer) ChannelConsensusState(ctx context.Context, req *types.QueryChannelConsensusStateRequest) (*types.QueryChannelConsensusStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -179,8 +173,6 @@ func (q *queryServer) ChannelConsensusState(c context.Context, req *types.QueryC return nil, err } - ctx := sdk.UnwrapSDKContext(c) - channel, found := q.GetChannel(ctx, req.PortId, req.ChannelId) if !found { return nil, status.Error( @@ -216,7 +208,7 @@ func (q *queryServer) ChannelConsensusState(c context.Context, req *types.QueryC } // PacketCommitment implements the Query/PacketCommitment gRPC method -func (q *queryServer) PacketCommitment(c context.Context, req *types.QueryPacketCommitmentRequest) (*types.QueryPacketCommitmentResponse, error) { +func (q *queryServer) PacketCommitment(ctx context.Context, req *types.QueryPacketCommitmentRequest) (*types.QueryPacketCommitmentResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -229,8 +221,6 @@ func (q *queryServer) PacketCommitment(c context.Context, req *types.QueryPacket return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0") } - ctx := sdk.UnwrapSDKContext(c) - if !q.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, @@ -248,7 +238,7 @@ func (q *queryServer) PacketCommitment(c context.Context, req *types.QueryPacket } // PacketCommitments implements the Query/PacketCommitments gRPC method -func (q *queryServer) PacketCommitments(c context.Context, req *types.QueryPacketCommitmentsRequest) (*types.QueryPacketCommitmentsResponse, error) { +func (q *queryServer) PacketCommitments(ctx context.Context, req *types.QueryPacketCommitmentsRequest) (*types.QueryPacketCommitmentsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -257,8 +247,6 @@ func (q *queryServer) PacketCommitments(c context.Context, req *types.QueryPacke return nil, err } - ctx := sdk.UnwrapSDKContext(c) - if !q.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, @@ -266,7 +254,7 @@ func (q *queryServer) PacketCommitments(c context.Context, req *types.QueryPacke ) } var commitments []*types.PacketState - store := prefix.NewStore(ctx.KVStore(q.storeKey), host.PacketCommitmentPrefixKey(req.PortId, req.ChannelId)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.PacketCommitmentPrefixKey(req.PortId, req.ChannelId)) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { keySplit := strings.Split(string(key), "/") @@ -293,7 +281,7 @@ func (q *queryServer) PacketCommitments(c context.Context, req *types.QueryPacke } // PacketReceipt implements the Query/PacketReceipt gRPC method -func (q *queryServer) PacketReceipt(c context.Context, req *types.QueryPacketReceiptRequest) (*types.QueryPacketReceiptResponse, error) { +func (q *queryServer) PacketReceipt(ctx context.Context, req *types.QueryPacketReceiptRequest) (*types.QueryPacketReceiptResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -306,8 +294,6 @@ func (q *queryServer) PacketReceipt(c context.Context, req *types.QueryPacketRec return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0") } - ctx := sdk.UnwrapSDKContext(c) - if !q.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, @@ -321,7 +307,7 @@ func (q *queryServer) PacketReceipt(c context.Context, req *types.QueryPacketRec } // PacketAcknowledgement implements the Query/PacketAcknowledgement gRPC method -func (q *queryServer) PacketAcknowledgement(c context.Context, req *types.QueryPacketAcknowledgementRequest) (*types.QueryPacketAcknowledgementResponse, error) { +func (q *queryServer) PacketAcknowledgement(ctx context.Context, req *types.QueryPacketAcknowledgementRequest) (*types.QueryPacketAcknowledgementResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -334,8 +320,6 @@ func (q *queryServer) PacketAcknowledgement(c context.Context, req *types.QueryP return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0") } - ctx := sdk.UnwrapSDKContext(c) - if !q.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, @@ -352,7 +336,7 @@ func (q *queryServer) PacketAcknowledgement(c context.Context, req *types.QueryP } // PacketAcknowledgements implements the Query/PacketAcknowledgements gRPC method -func (q *queryServer) PacketAcknowledgements(c context.Context, req *types.QueryPacketAcknowledgementsRequest) (*types.QueryPacketAcknowledgementsResponse, error) { +func (q *queryServer) PacketAcknowledgements(ctx context.Context, req *types.QueryPacketAcknowledgementsRequest) (*types.QueryPacketAcknowledgementsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -361,8 +345,6 @@ func (q *queryServer) PacketAcknowledgements(c context.Context, req *types.Query return nil, err } - ctx := sdk.UnwrapSDKContext(c) - if !q.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, @@ -370,7 +352,7 @@ func (q *queryServer) PacketAcknowledgements(c context.Context, req *types.Query ) } var acks []*types.PacketState - store := prefix.NewStore(ctx.KVStore(q.storeKey), host.PacketAcknowledgementPrefixKey(req.PortId, req.ChannelId)) + store := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), host.PacketAcknowledgementPrefixKey(req.PortId, req.ChannelId)) // if a list of packet sequences is provided then query for each specific ack and return a list <= len(req.PacketCommitmentSequences) // otherwise, maintain previous behaviour and perform paginated query @@ -434,7 +416,7 @@ func (q *queryServer) PacketAcknowledgements(c context.Context, req *types.Query // commitments is correct and will not function properly if the list // is not up to date. Ideally the query height should equal the latest height // on the counterparty's client which represents this chain. -func (q *queryServer) UnreceivedPackets(c context.Context, req *types.QueryUnreceivedPacketsRequest) (*types.QueryUnreceivedPacketsResponse, error) { +func (q *queryServer) UnreceivedPackets(ctx context.Context, req *types.QueryUnreceivedPacketsRequest) (*types.QueryUnreceivedPacketsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -443,8 +425,6 @@ func (q *queryServer) UnreceivedPackets(c context.Context, req *types.QueryUnrec return nil, err } - ctx := sdk.UnwrapSDKContext(c) - channel, found := q.GetChannel(ctx, req.PortId, req.ChannelId) if !found { return nil, status.Error( @@ -520,7 +500,7 @@ func (q *queryServer) UnreceivedPackets(c context.Context, req *types.QueryUnrec // acknowledgements is correct and will not function properly if the list // is not up to date. Ideally the query height should equal the latest height // on the counterparty's client which represents this chain. -func (q *queryServer) UnreceivedAcks(c context.Context, req *types.QueryUnreceivedAcksRequest) (*types.QueryUnreceivedAcksResponse, error) { +func (q *queryServer) UnreceivedAcks(ctx context.Context, req *types.QueryUnreceivedAcksRequest) (*types.QueryUnreceivedAcksResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -529,8 +509,6 @@ func (q *queryServer) UnreceivedAcks(c context.Context, req *types.QueryUnreceiv return nil, err } - ctx := sdk.UnwrapSDKContext(c) - if !q.HasChannel(ctx, req.PortId, req.ChannelId) { return nil, status.Error( codes.NotFound, @@ -560,7 +538,7 @@ func (q *queryServer) UnreceivedAcks(c context.Context, req *types.QueryUnreceiv } // NextSequenceReceive implements the Query/NextSequenceReceive gRPC method -func (q *queryServer) NextSequenceReceive(c context.Context, req *types.QueryNextSequenceReceiveRequest) (*types.QueryNextSequenceReceiveResponse, error) { +func (q *queryServer) NextSequenceReceive(ctx context.Context, req *types.QueryNextSequenceReceiveRequest) (*types.QueryNextSequenceReceiveResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -569,7 +547,6 @@ func (q *queryServer) NextSequenceReceive(c context.Context, req *types.QueryNex return nil, err } - ctx := sdk.UnwrapSDKContext(c) channel, found := q.GetChannel(ctx, req.PortId, req.ChannelId) if !found { return nil, status.Error( @@ -595,7 +572,7 @@ func (q *queryServer) NextSequenceReceive(c context.Context, req *types.QueryNex } // NextSequenceSend implements the Query/NextSequenceSend gRPC method -func (q *queryServer) NextSequenceSend(c context.Context, req *types.QueryNextSequenceSendRequest) (*types.QueryNextSequenceSendResponse, error) { +func (q *queryServer) NextSequenceSend(ctx context.Context, req *types.QueryNextSequenceSendRequest) (*types.QueryNextSequenceSendResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -604,8 +581,6 @@ func (q *queryServer) NextSequenceSend(c context.Context, req *types.QueryNextSe return nil, err } - ctx := sdk.UnwrapSDKContext(c) - sequence, found := q.GetNextSequenceSend(ctx, req.PortId, req.ChannelId) if !found { return nil, status.Error( @@ -618,7 +593,7 @@ func (q *queryServer) NextSequenceSend(c context.Context, req *types.QueryNextSe } // UpgradeErrorReceipt implements the Query/UpgradeErrorReceipt gRPC method -func (q *queryServer) UpgradeError(c context.Context, req *types.QueryUpgradeErrorRequest) (*types.QueryUpgradeErrorResponse, error) { +func (q *queryServer) UpgradeError(ctx context.Context, req *types.QueryUpgradeErrorRequest) (*types.QueryUpgradeErrorResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -627,7 +602,6 @@ func (q *queryServer) UpgradeError(c context.Context, req *types.QueryUpgradeErr return nil, err } - ctx := sdk.UnwrapSDKContext(c) found := q.HasChannel(ctx, req.PortId, req.ChannelId) if !found { return nil, status.Error( @@ -649,7 +623,7 @@ func (q *queryServer) UpgradeError(c context.Context, req *types.QueryUpgradeErr } // Upgrade implements the Query/UpgradeSequence gRPC method -func (q *queryServer) Upgrade(c context.Context, req *types.QueryUpgradeRequest) (*types.QueryUpgradeResponse, error) { +func (q *queryServer) Upgrade(ctx context.Context, req *types.QueryUpgradeRequest) (*types.QueryUpgradeResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -658,7 +632,6 @@ func (q *queryServer) Upgrade(c context.Context, req *types.QueryUpgradeRequest) return nil, err } - ctx := sdk.UnwrapSDKContext(c) found := q.HasChannel(ctx, req.PortId, req.ChannelId) if !found { return nil, status.Error( @@ -680,8 +653,7 @@ func (q *queryServer) Upgrade(c context.Context, req *types.QueryUpgradeRequest) } // ChannelParams implements the Query/ChannelParams gRPC method. -func (q *queryServer) ChannelParams(c context.Context, req *types.QueryChannelParamsRequest) (*types.QueryChannelParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) +func (q *queryServer) ChannelParams(ctx context.Context, req *types.QueryChannelParamsRequest) (*types.QueryChannelParamsResponse, error) { params := q.GetParams(ctx) return &types.QueryChannelParamsResponse{ diff --git a/modules/core/04-channel/keeper/keeper.go b/modules/core/04-channel/keeper/keeper.go index 33f9e6d2856..ddf461e9a6d 100644 --- a/modules/core/04-channel/keeper/keeper.go +++ b/modules/core/04-channel/keeper/keeper.go @@ -1,17 +1,20 @@ package keeper import ( + "context" "errors" "strconv" "strings" db "github.com/cosmos/cosmos-db" + corestore "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" @@ -30,7 +33,7 @@ type Keeper struct { // implements gRPC QueryServer interface types.QueryServer - storeKey storetypes.StoreKey + storeService corestore.KVStoreService cdc codec.BinaryCodec clientKeeper types.ClientKeeper connectionKeeper types.ConnectionKeeper @@ -40,12 +43,15 @@ type Keeper struct { // NewKeeper creates a new IBC channel Keeper instance func NewKeeper( - cdc codec.BinaryCodec, key storetypes.StoreKey, - clientKeeper types.ClientKeeper, connectionKeeper types.ConnectionKeeper, - portKeeper types.PortKeeper, scopedKeeper exported.ScopedKeeper, + cdc codec.BinaryCodec, + storeService corestore.KVStoreService, + clientKeeper types.ClientKeeper, + connectionKeeper types.ConnectionKeeper, + portKeeper types.PortKeeper, + scopedKeeper exported.ScopedKeeper, ) *Keeper { return &Keeper{ - storeKey: key, + storeService: storeService, cdc: cdc, clientKeeper: clientKeeper, connectionKeeper: connectionKeeper, @@ -55,12 +61,13 @@ func NewKeeper( } // Logger returns a module-specific logger. -func (Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) +func (Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) } // GenerateChannelIdentifier returns the next channel identifier. -func (k *Keeper) GenerateChannelIdentifier(ctx sdk.Context) string { +func (k *Keeper) GenerateChannelIdentifier(ctx context.Context) string { nextChannelSeq := k.GetNextChannelSequence(ctx) channelID := types.FormatChannelIdentifier(nextChannelSeq) @@ -70,15 +77,22 @@ func (k *Keeper) GenerateChannelIdentifier(ctx sdk.Context) string { } // HasChannel true if the channel with the given identifiers exists in state. -func (k *Keeper) HasChannel(ctx sdk.Context, portID, channelID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(host.ChannelKey(portID, channelID)) +func (k *Keeper) HasChannel(ctx context.Context, portID, channelID string) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(host.ChannelKey(portID, channelID)) + if err != nil { + panic(err) + } + return has } // GetChannel returns a channel with a particular identifier binded to a specific port -func (k *Keeper) GetChannel(ctx sdk.Context, portID, channelID string) (types.Channel, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.ChannelKey(portID, channelID)) +func (k *Keeper) GetChannel(ctx context.Context, portID, channelID string) (types.Channel, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.ChannelKey(portID, channelID)) + if err != nil { + panic(err) + } if len(bz) == 0 { return types.Channel{}, false } @@ -89,14 +103,16 @@ func (k *Keeper) GetChannel(ctx sdk.Context, portID, channelID string) (types.Ch } // SetChannel sets a channel to the store -func (k *Keeper) SetChannel(ctx sdk.Context, portID, channelID string, channel types.Channel) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetChannel(ctx context.Context, portID, channelID string, channel types.Channel) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&channel) - store.Set(host.ChannelKey(portID, channelID), bz) + if err := store.Set(host.ChannelKey(portID, channelID), bz); err != nil { + panic(err) + } } // GetAppVersion gets the version for the specified channel. -func (k *Keeper) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (k *Keeper) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { channel, found := k.GetChannel(ctx, portID, channelID) if !found { return "", false @@ -106,9 +122,12 @@ func (k *Keeper) GetAppVersion(ctx sdk.Context, portID, channelID string) (strin } // GetNextChannelSequence gets the next channel sequence from the store. -func (k *Keeper) GetNextChannelSequence(ctx sdk.Context) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.KeyNextChannelSequence)) +func (k *Keeper) GetNextChannelSequence(ctx context.Context) uint64 { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get([]byte(types.KeyNextChannelSequence)) + if err != nil { + panic(err) + } if len(bz) == 0 { panic(errors.New("next channel sequence is nil")) } @@ -117,16 +136,21 @@ func (k *Keeper) GetNextChannelSequence(ctx sdk.Context) uint64 { } // SetNextChannelSequence sets the next channel sequence to the store. -func (k *Keeper) SetNextChannelSequence(ctx sdk.Context, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetNextChannelSequence(ctx context.Context, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set([]byte(types.KeyNextChannelSequence), bz) + if err := store.Set([]byte(types.KeyNextChannelSequence), bz); err != nil { + panic(err) + } } // GetNextSequenceSend gets a channel's next send sequence from the store -func (k *Keeper) GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.NextSequenceSendKey(portID, channelID)) +func (k *Keeper) GetNextSequenceSend(ctx context.Context, portID, channelID string) (uint64, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.NextSequenceSendKey(portID, channelID)) + if err != nil { + panic(err) + } if len(bz) == 0 { return 0, false } @@ -135,16 +159,21 @@ func (k *Keeper) GetNextSequenceSend(ctx sdk.Context, portID, channelID string) } // SetNextSequenceSend sets a channel's next send sequence to the store -func (k *Keeper) SetNextSequenceSend(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetNextSequenceSend(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set(host.NextSequenceSendKey(portID, channelID), bz) + if err := store.Set(host.NextSequenceSendKey(portID, channelID), bz); err != nil { + panic(err) + } } // GetNextSequenceRecv gets a channel's next receive sequence from the store -func (k *Keeper) GetNextSequenceRecv(ctx sdk.Context, portID, channelID string) (uint64, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.NextSequenceRecvKey(portID, channelID)) +func (k *Keeper) GetNextSequenceRecv(ctx context.Context, portID, channelID string) (uint64, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.NextSequenceRecvKey(portID, channelID)) + if err != nil { + panic(err) + } if len(bz) == 0 { return 0, false } @@ -153,16 +182,22 @@ func (k *Keeper) GetNextSequenceRecv(ctx sdk.Context, portID, channelID string) } // SetNextSequenceRecv sets a channel's next receive sequence to the store -func (k *Keeper) SetNextSequenceRecv(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetNextSequenceRecv(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set(host.NextSequenceRecvKey(portID, channelID), bz) + if err := store.Set(host.NextSequenceRecvKey(portID, channelID), bz); err != nil { + panic(err) + } } // GetNextSequenceAck gets a channel's next ack sequence from the store -func (k *Keeper) GetNextSequenceAck(ctx sdk.Context, portID, channelID string) (uint64, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.NextSequenceAckKey(portID, channelID)) +func (k *Keeper) GetNextSequenceAck(ctx context.Context, portID, channelID string) (uint64, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.NextSequenceAckKey(portID, channelID)) + if err != nil { + panic(err) + } + if len(bz) == 0 { return 0, false } @@ -171,16 +206,22 @@ func (k *Keeper) GetNextSequenceAck(ctx sdk.Context, portID, channelID string) ( } // SetNextSequenceAck sets a channel's next ack sequence to the store -func (k *Keeper) SetNextSequenceAck(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetNextSequenceAck(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set(host.NextSequenceAckKey(portID, channelID), bz) + if err := store.Set(host.NextSequenceAckKey(portID, channelID), bz); err != nil { + panic(err) + } } // GetPacketReceipt gets a packet receipt from the store -func (k *Keeper) GetPacketReceipt(ctx sdk.Context, portID, channelID string, sequence uint64) (string, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.PacketReceiptKey(portID, channelID, sequence)) +func (k *Keeper) GetPacketReceipt(ctx context.Context, portID, channelID string, sequence uint64) (string, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.PacketReceiptKey(portID, channelID, sequence)) + if err != nil { + panic(err) + } + if len(bz) == 0 { return "", false } @@ -189,74 +230,103 @@ func (k *Keeper) GetPacketReceipt(ctx sdk.Context, portID, channelID string, seq } // SetPacketReceipt sets an empty packet receipt to the store -func (k *Keeper) SetPacketReceipt(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) - store.Set(host.PacketReceiptKey(portID, channelID, sequence), []byte{byte(1)}) +func (k *Keeper) SetPacketReceipt(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(host.PacketReceiptKey(portID, channelID, sequence), []byte{byte(1)}); err != nil { + panic(err) + } } // deletePacketReceipt deletes a packet receipt from the store -func (k *Keeper) deletePacketReceipt(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) - store.Delete(host.PacketReceiptKey(portID, channelID, sequence)) +func (k *Keeper) deletePacketReceipt(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Delete(host.PacketReceiptKey(portID, channelID, sequence)); err != nil { + panic(err) + } } // GetPacketCommitment gets the packet commitment hash from the store -func (k *Keeper) GetPacketCommitment(ctx sdk.Context, portID, channelID string, sequence uint64) []byte { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.PacketCommitmentKey(portID, channelID, sequence)) +func (k *Keeper) GetPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) []byte { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.PacketCommitmentKey(portID, channelID, sequence)) + if err != nil { + panic(err) + } + return bz } // HasPacketCommitment returns true if the packet commitment exists -func (k *Keeper) HasPacketCommitment(ctx sdk.Context, portID, channelID string, sequence uint64) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(host.PacketCommitmentKey(portID, channelID, sequence)) +func (k *Keeper) HasPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(host.PacketCommitmentKey(portID, channelID, sequence)) + if err != nil { + panic(err) + } + return has } // SetPacketCommitment sets the packet commitment hash to the store -func (k *Keeper) SetPacketCommitment(ctx sdk.Context, portID, channelID string, sequence uint64, commitmentHash []byte) { - store := ctx.KVStore(k.storeKey) - store.Set(host.PacketCommitmentKey(portID, channelID, sequence), commitmentHash) +func (k *Keeper) SetPacketCommitment(ctx context.Context, portID, channelID string, sequence uint64, commitmentHash []byte) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(host.PacketCommitmentKey(portID, channelID, sequence), commitmentHash); err != nil { + panic(err) + } } -func (k *Keeper) deletePacketCommitment(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) - store.Delete(host.PacketCommitmentKey(portID, channelID, sequence)) +func (k *Keeper) deletePacketCommitment(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Delete(host.PacketCommitmentKey(portID, channelID, sequence)); err != nil { + panic(err) + } } // SetPacketAcknowledgement sets the packet ack hash to the store -func (k *Keeper) SetPacketAcknowledgement(ctx sdk.Context, portID, channelID string, sequence uint64, ackHash []byte) { - store := ctx.KVStore(k.storeKey) - store.Set(host.PacketAcknowledgementKey(portID, channelID, sequence), ackHash) +func (k *Keeper) SetPacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64, ackHash []byte) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Set(host.PacketAcknowledgementKey(portID, channelID, sequence), ackHash); err != nil { + panic(err) + } } // GetPacketAcknowledgement gets the packet ack hash from the store -func (k *Keeper) GetPacketAcknowledgement(ctx sdk.Context, portID, channelID string, sequence uint64) ([]byte, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.PacketAcknowledgementKey(portID, channelID, sequence)) +func (k *Keeper) GetPacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64) ([]byte, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.PacketAcknowledgementKey(portID, channelID, sequence)) + if err != nil { + panic(err) + } + if len(bz) == 0 { return nil, false } + return bz, true } // HasPacketAcknowledgement check if the packet ack hash is already on the store -func (k *Keeper) HasPacketAcknowledgement(ctx sdk.Context, portID, channelID string, sequence uint64) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(host.PacketAcknowledgementKey(portID, channelID, sequence)) +func (k *Keeper) HasPacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(host.PacketAcknowledgementKey(portID, channelID, sequence)) + if err != nil { + panic(err) + } + return has } // deletePacketAcknowledgement deletes the packet ack hash from the store -func (k *Keeper) deletePacketAcknowledgement(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) - store.Delete(host.PacketAcknowledgementKey(portID, channelID, sequence)) +func (k *Keeper) deletePacketAcknowledgement(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Delete(host.PacketAcknowledgementKey(portID, channelID, sequence)); err != nil { + panic(err) + } } // IteratePacketSequence provides an iterator over all send, receive or ack sequences. // For each sequence, cb will be called. If the cb returns true, the iterator // will close and stop. -func (Keeper) IteratePacketSequence(ctx sdk.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64) bool) { - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) +func (k *Keeper) IteratePacketSequence(ctx context.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64) bool) { + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { portID, channelID, err := host.ParseChannelPath(string(iterator.Key())) if err != nil { @@ -273,8 +343,8 @@ func (Keeper) IteratePacketSequence(ctx sdk.Context, iterator db.Iterator, cb fu } // GetAllPacketSendSeqs returns all stored next send sequences. -func (k *Keeper) GetAllPacketSendSeqs(ctx sdk.Context) (seqs []types.PacketSequence) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) GetAllPacketSendSeqs(ctx context.Context) (seqs []types.PacketSequence) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyNextSeqSendPrefix)) k.IteratePacketSequence(ctx, iterator, func(portID, channelID string, nextSendSeq uint64) bool { ps := types.NewPacketSequence(portID, channelID, nextSendSeq) @@ -285,8 +355,8 @@ func (k *Keeper) GetAllPacketSendSeqs(ctx sdk.Context) (seqs []types.PacketSeque } // GetAllPacketRecvSeqs returns all stored next recv sequences. -func (k *Keeper) GetAllPacketRecvSeqs(ctx sdk.Context) (seqs []types.PacketSequence) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) GetAllPacketRecvSeqs(ctx context.Context) (seqs []types.PacketSequence) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyNextSeqRecvPrefix)) k.IteratePacketSequence(ctx, iterator, func(portID, channelID string, nextRecvSeq uint64) bool { ps := types.NewPacketSequence(portID, channelID, nextRecvSeq) @@ -297,8 +367,8 @@ func (k *Keeper) GetAllPacketRecvSeqs(ctx sdk.Context) (seqs []types.PacketSeque } // GetAllPacketAckSeqs returns all stored next acknowledgements sequences. -func (k *Keeper) GetAllPacketAckSeqs(ctx sdk.Context) (seqs []types.PacketSequence) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) GetAllPacketAckSeqs(ctx context.Context) (seqs []types.PacketSequence) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyNextSeqAckPrefix)) k.IteratePacketSequence(ctx, iterator, func(portID, channelID string, nextAckSeq uint64) bool { ps := types.NewPacketSequence(portID, channelID, nextAckSeq) @@ -311,14 +381,14 @@ func (k *Keeper) GetAllPacketAckSeqs(ctx sdk.Context) (seqs []types.PacketSequen // IteratePacketCommitment provides an iterator over all PacketCommitment objects. For each // packet commitment, cb will be called. If the cb returns true, the iterator will close // and stop. -func (k *Keeper) IteratePacketCommitment(ctx sdk.Context, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IteratePacketCommitment(ctx context.Context, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyPacketCommitmentPrefix)) k.iterateHashes(ctx, iterator, cb) } // GetAllPacketCommitments returns all stored PacketCommitments objects. -func (k *Keeper) GetAllPacketCommitments(ctx sdk.Context) (commitments []types.PacketState) { +func (k *Keeper) GetAllPacketCommitments(ctx context.Context) (commitments []types.PacketState) { k.IteratePacketCommitment(ctx, func(portID, channelID string, sequence uint64, hash []byte) bool { pc := types.NewPacketState(portID, channelID, sequence, hash) commitments = append(commitments, pc) @@ -330,15 +400,15 @@ func (k *Keeper) GetAllPacketCommitments(ctx sdk.Context) (commitments []types.P // IteratePacketCommitmentAtChannel provides an iterator over all PacketCommmitment objects // at a specified channel. For each packet commitment, cb will be called. If the cb returns // true, the iterator will close and stop. -func (k *Keeper) IteratePacketCommitmentAtChannel(ctx sdk.Context, portID, channelID string, cb func(_, _ string, sequence uint64, hash []byte) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IteratePacketCommitmentAtChannel(ctx context.Context, portID, channelID string, cb func(_, _ string, sequence uint64, hash []byte) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, host.PacketCommitmentPrefixKey(portID, channelID)) k.iterateHashes(ctx, iterator, cb) } // GetAllPacketCommitmentsAtChannel returns all stored PacketCommitments objects for a specified // port ID and channel ID. -func (k *Keeper) GetAllPacketCommitmentsAtChannel(ctx sdk.Context, portID, channelID string) (commitments []types.PacketState) { +func (k *Keeper) GetAllPacketCommitmentsAtChannel(ctx context.Context, portID, channelID string) (commitments []types.PacketState) { k.IteratePacketCommitmentAtChannel(ctx, portID, channelID, func(_, _ string, sequence uint64, hash []byte) bool { pc := types.NewPacketState(portID, channelID, sequence, hash) commitments = append(commitments, pc) @@ -350,14 +420,14 @@ func (k *Keeper) GetAllPacketCommitmentsAtChannel(ctx sdk.Context, portID, chann // IteratePacketReceipt provides an iterator over all PacketReceipt objects. For each // receipt, cb will be called. If the cb returns true, the iterator will close // and stop. -func (k *Keeper) IteratePacketReceipt(ctx sdk.Context, cb func(portID, channelID string, sequence uint64, receipt []byte) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IteratePacketReceipt(ctx context.Context, cb func(portID, channelID string, sequence uint64, receipt []byte) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyPacketReceiptPrefix)) k.iterateHashes(ctx, iterator, cb) } // GetAllPacketReceipts returns all stored PacketReceipt objects. -func (k *Keeper) GetAllPacketReceipts(ctx sdk.Context) (receipts []types.PacketState) { +func (k *Keeper) GetAllPacketReceipts(ctx context.Context) (receipts []types.PacketState) { k.IteratePacketReceipt(ctx, func(portID, channelID string, sequence uint64, receipt []byte) bool { packetReceipt := types.NewPacketState(portID, channelID, sequence, receipt) receipts = append(receipts, packetReceipt) @@ -369,14 +439,14 @@ func (k *Keeper) GetAllPacketReceipts(ctx sdk.Context) (receipts []types.PacketS // IteratePacketAcknowledgement provides an iterator over all PacketAcknowledgement objects. For each // acknowledgement, cb will be called. If the cb returns true, the iterator will close // and stop. -func (k *Keeper) IteratePacketAcknowledgement(ctx sdk.Context, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IteratePacketAcknowledgement(ctx context.Context, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyPacketAckPrefix)) k.iterateHashes(ctx, iterator, cb) } // GetAllPacketAcks returns all stored PacketAcknowledgements objects. -func (k *Keeper) GetAllPacketAcks(ctx sdk.Context) (acks []types.PacketState) { +func (k *Keeper) GetAllPacketAcks(ctx context.Context) (acks []types.PacketState) { k.IteratePacketAcknowledgement(ctx, func(portID, channelID string, sequence uint64, ack []byte) bool { packetAck := types.NewPacketState(portID, channelID, sequence, ack) acks = append(acks, packetAck) @@ -388,11 +458,11 @@ func (k *Keeper) GetAllPacketAcks(ctx sdk.Context) (acks []types.PacketState) { // IterateChannels provides an iterator over all Channel objects. For each // Channel, cb will be called. If the cb returns true, the iterator will close // and stop. -func (k *Keeper) IterateChannels(ctx sdk.Context, cb func(types.IdentifiedChannel) bool) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) IterateChannels(ctx context.Context, cb func(types.IdentifiedChannel) bool) { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, []byte(host.KeyChannelEndPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { var channel types.Channel k.cdc.MustUnmarshal(iterator.Value(), &channel) @@ -407,13 +477,13 @@ func (k *Keeper) IterateChannels(ctx sdk.Context, cb func(types.IdentifiedChanne // GetAllChannelsWithPortPrefix returns all channels with the specified port prefix. If an empty prefix is provided // all channels will be returned. -func (k *Keeper) GetAllChannelsWithPortPrefix(ctx sdk.Context, portPrefix string) []types.IdentifiedChannel { +func (k *Keeper) GetAllChannelsWithPortPrefix(ctx context.Context, portPrefix string) []types.IdentifiedChannel { if strings.TrimSpace(portPrefix) == "" { return k.GetAllChannels(ctx) } - store := ctx.KVStore(k.storeKey) + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) iterator := storetypes.KVStorePrefixIterator(store, types.FilteredPortPrefix(portPrefix)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) var filteredChannels []types.IdentifiedChannel for ; iterator.Valid(); iterator.Next() { @@ -428,7 +498,7 @@ func (k *Keeper) GetAllChannelsWithPortPrefix(ctx sdk.Context, portPrefix string } // GetAllChannels returns all stored Channel objects. -func (k *Keeper) GetAllChannels(ctx sdk.Context) (channels []types.IdentifiedChannel) { +func (k *Keeper) GetAllChannels(ctx context.Context) (channels []types.IdentifiedChannel) { k.IterateChannels(ctx, func(channel types.IdentifiedChannel) bool { channels = append(channels, channel) return false @@ -437,7 +507,7 @@ func (k *Keeper) GetAllChannels(ctx sdk.Context) (channels []types.IdentifiedCha } // GetChannelClientState returns the associated client state with its ID, from a port and channel identifier. -func (k *Keeper) GetChannelClientState(ctx sdk.Context, portID, channelID string) (string, exported.ClientState, error) { +func (k *Keeper) GetChannelClientState(ctx context.Context, portID, channelID string) (string, exported.ClientState, error) { channel, found := k.GetChannel(ctx, portID, channelID) if !found { return "", nil, errorsmod.Wrapf(types.ErrChannelNotFound, "port-id: %s, channel-id: %s", portID, channelID) @@ -457,7 +527,7 @@ func (k *Keeper) GetChannelClientState(ctx sdk.Context, portID, channelID string } // GetConnection wraps the connection keeper's GetConnection function. -func (k *Keeper) GetConnection(ctx sdk.Context, connectionID string) (connectiontypes.ConnectionEnd, error) { +func (k *Keeper) GetConnection(ctx context.Context, connectionID string) (connectiontypes.ConnectionEnd, error) { connection, found := k.connectionKeeper.GetConnection(ctx, connectionID) if !found { return connectiontypes.ConnectionEnd{}, errorsmod.Wrapf(connectiontypes.ErrConnectionNotFound, "connection-id: %s", connectionID) @@ -467,7 +537,7 @@ func (k *Keeper) GetConnection(ctx sdk.Context, connectionID string) (connection } // GetChannelConnection returns the connection ID and state associated with the given port and channel identifier. -func (k *Keeper) GetChannelConnection(ctx sdk.Context, portID, channelID string) (string, connectiontypes.ConnectionEnd, error) { +func (k *Keeper) GetChannelConnection(ctx context.Context, portID, channelID string) (string, connectiontypes.ConnectionEnd, error) { channel, found := k.GetChannel(ctx, portID, channelID) if !found { return "", connectiontypes.ConnectionEnd{}, errorsmod.Wrapf(types.ErrChannelNotFound, "port-id: %s, channel-id: %s", portID, channelID) @@ -484,8 +554,9 @@ func (k *Keeper) GetChannelConnection(ctx sdk.Context, portID, channelID string) } // LookupModuleByChannel will return the IBCModule along with the capability associated with a given channel defined by its portID and channelID -func (k *Keeper) LookupModuleByChannel(ctx sdk.Context, portID, channelID string) (string, *capabilitytypes.Capability, error) { - modules, capability, err := k.scopedKeeper.LookupModules(ctx, host.ChannelCapabilityPath(portID, channelID)) +func (k *Keeper) LookupModuleByChannel(ctx context.Context, portID, channelID string) (string, *capabilitytypes.Capability, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + modules, capability, err := k.scopedKeeper.LookupModules(sdkCtx, host.ChannelCapabilityPath(portID, channelID)) if err != nil { return "", nil, err } @@ -494,10 +565,14 @@ func (k *Keeper) LookupModuleByChannel(ctx sdk.Context, portID, channelID string } // GetUpgradeErrorReceipt returns the upgrade error receipt for the provided port and channel identifiers. -func (k *Keeper) GetUpgradeErrorReceipt(ctx sdk.Context, portID, channelID string) (types.ErrorReceipt, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.ChannelUpgradeErrorKey(portID, channelID)) - if bz == nil { +func (k *Keeper) GetUpgradeErrorReceipt(ctx context.Context, portID, channelID string) (types.ErrorReceipt, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.ChannelUpgradeErrorKey(portID, channelID)) + if err != nil { + panic(err) + } + + if len(bz) == 0 { return types.ErrorReceipt{}, false } @@ -508,23 +583,33 @@ func (k *Keeper) GetUpgradeErrorReceipt(ctx sdk.Context, portID, channelID strin } // setUpgradeErrorReceipt sets the provided error receipt in store using the port and channel identifiers. -func (k *Keeper) setUpgradeErrorReceipt(ctx sdk.Context, portID, channelID string, errorReceipt types.ErrorReceipt) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) setUpgradeErrorReceipt(ctx context.Context, portID, channelID string, errorReceipt types.ErrorReceipt) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&errorReceipt) - store.Set(host.ChannelUpgradeErrorKey(portID, channelID), bz) + if err := store.Set(host.ChannelUpgradeErrorKey(portID, channelID), bz); err != nil { + panic(err) + } } // hasUpgrade returns true if a proposed upgrade exists in store -func (k *Keeper) hasUpgrade(ctx sdk.Context, portID, channelID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(host.ChannelUpgradeKey(portID, channelID)) +func (k *Keeper) hasUpgrade(ctx context.Context, portID, channelID string) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(host.ChannelUpgradeKey(portID, channelID)) + if err != nil { + panic(err) + } + return has } // GetUpgrade returns the proposed upgrade for the provided port and channel identifiers. -func (k *Keeper) GetUpgrade(ctx sdk.Context, portID, channelID string) (types.Upgrade, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.ChannelUpgradeKey(portID, channelID)) - if bz == nil { +func (k *Keeper) GetUpgrade(ctx context.Context, portID, channelID string) (types.Upgrade, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.ChannelUpgradeKey(portID, channelID)) + if err != nil { + panic(err) + } + + if len(bz) == 0 { return types.Upgrade{}, false } @@ -535,29 +620,41 @@ func (k *Keeper) GetUpgrade(ctx sdk.Context, portID, channelID string) (types.Up } // SetUpgrade sets the proposed upgrade using the provided port and channel identifiers. -func (k *Keeper) SetUpgrade(ctx sdk.Context, portID, channelID string, upgrade types.Upgrade) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetUpgrade(ctx context.Context, portID, channelID string, upgrade types.Upgrade) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&upgrade) - store.Set(host.ChannelUpgradeKey(portID, channelID), bz) + if err := store.Set(host.ChannelUpgradeKey(portID, channelID), bz); err != nil { + panic(err) + } } // deleteUpgrade deletes the upgrade for the provided port and channel identifiers. -func (k *Keeper) deleteUpgrade(ctx sdk.Context, portID, channelID string) { - store := ctx.KVStore(k.storeKey) - store.Delete(host.ChannelUpgradeKey(portID, channelID)) +func (k *Keeper) deleteUpgrade(ctx context.Context, portID, channelID string) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Delete(host.ChannelUpgradeKey(portID, channelID)); err != nil { + panic(err) + } } // hasCounterpartyUpgrade returns true if a counterparty upgrade exists in store -func (k *Keeper) hasCounterpartyUpgrade(ctx sdk.Context, portID, channelID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(host.ChannelCounterpartyUpgradeKey(portID, channelID)) +func (k *Keeper) hasCounterpartyUpgrade(ctx context.Context, portID, channelID string) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(host.ChannelCounterpartyUpgradeKey(portID, channelID)) + if err != nil { + panic(err) + } + return has } // GetCounterpartyUpgrade gets the counterparty upgrade from the store. -func (k *Keeper) GetCounterpartyUpgrade(ctx sdk.Context, portID, channelID string) (types.Upgrade, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.ChannelCounterpartyUpgradeKey(portID, channelID)) - if bz == nil { +func (k *Keeper) GetCounterpartyUpgrade(ctx context.Context, portID, channelID string) (types.Upgrade, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.ChannelCounterpartyUpgradeKey(portID, channelID)) + if err != nil { + panic(err) + } + + if len(bz) == 0 { return types.Upgrade{}, false } @@ -568,35 +665,45 @@ func (k *Keeper) GetCounterpartyUpgrade(ctx sdk.Context, portID, channelID strin } // SetCounterpartyUpgrade sets the counterparty upgrade in the store. -func (k *Keeper) SetCounterpartyUpgrade(ctx sdk.Context, portID, channelID string, upgrade types.Upgrade) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetCounterpartyUpgrade(ctx context.Context, portID, channelID string, upgrade types.Upgrade) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(&upgrade) - store.Set(host.ChannelCounterpartyUpgradeKey(portID, channelID), bz) + if err := store.Set(host.ChannelCounterpartyUpgradeKey(portID, channelID), bz); err != nil { + panic(err) + } } // deleteCounterpartyUpgrade deletes the counterparty upgrade in the store. -func (k *Keeper) deleteCounterpartyUpgrade(ctx sdk.Context, portID, channelID string) { - store := ctx.KVStore(k.storeKey) - store.Delete(host.ChannelCounterpartyUpgradeKey(portID, channelID)) +func (k *Keeper) deleteCounterpartyUpgrade(ctx context.Context, portID, channelID string) { + store := k.storeService.OpenKVStore(ctx) + if err := store.Delete(host.ChannelCounterpartyUpgradeKey(portID, channelID)); err != nil { + panic(err) + } } // deleteUpgradeInfo deletes all auxiliary upgrade information. -func (k *Keeper) deleteUpgradeInfo(ctx sdk.Context, portID, channelID string) { +func (k *Keeper) deleteUpgradeInfo(ctx context.Context, portID, channelID string) { k.deleteUpgrade(ctx, portID, channelID) k.deleteCounterpartyUpgrade(ctx, portID, channelID) } // SetParams sets the channel parameters. -func (k *Keeper) SetParams(ctx sdk.Context, params types.Params) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetParams(ctx context.Context, params types.Params) { + store := k.storeService.OpenKVStore(ctx) bz := k.cdc.MustMarshal(¶ms) - store.Set([]byte(types.ParamsKey), bz) + if err := store.Set([]byte(types.ParamsKey), bz); err != nil { + panic(err) + } } // GetParams returns the total set of the channel parameters. -func (k *Keeper) GetParams(ctx sdk.Context) types.Params { - store := ctx.KVStore(k.storeKey) - bz := store.Get([]byte(types.ParamsKey)) +func (k *Keeper) GetParams(ctx context.Context) types.Params { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get([]byte(types.ParamsKey)) + if err != nil { + panic(err) + } + if bz == nil { // only panic on unset params and not on empty params panic(errors.New("channel params are not set in store")) } @@ -607,8 +714,8 @@ func (k *Keeper) GetParams(ctx sdk.Context) types.Params { } // common functionality for IteratePacketCommitment and IteratePacketAcknowledgement -func (Keeper) iterateHashes(ctx sdk.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) +func (k *Keeper) iterateHashes(ctx context.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) for ; iterator.Valid(); iterator.Next() { keySplit := strings.Split(string(iterator.Key()), "/") @@ -628,27 +735,34 @@ func (Keeper) iterateHashes(ctx sdk.Context, iterator db.Iterator, cb func(portI // HasInflightPackets returns true if there are packet commitments stored at the specified // port and channel, and false otherwise. -func (k *Keeper) HasInflightPackets(ctx sdk.Context, portID, channelID string) bool { - iterator := storetypes.KVStorePrefixIterator(ctx.KVStore(k.storeKey), host.PacketCommitmentPrefixKey(portID, channelID)) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) +func (k *Keeper) HasInflightPackets(ctx context.Context, portID, channelID string) bool { + store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)) + iterator := storetypes.KVStorePrefixIterator(store, host.PacketCommitmentPrefixKey(portID, channelID)) + defer sdk.LogDeferred(k.Logger(ctx), func() error { return iterator.Close() }) return iterator.Valid() } // setRecvStartSequence sets the channel's recv start sequence to the store. -func (k *Keeper) setRecvStartSequence(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) setRecvStartSequence(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set(host.RecvStartSequenceKey(portID, channelID), bz) + if err := store.Set(host.RecvStartSequenceKey(portID, channelID), bz); err != nil { + panic(err) + } } // GetRecvStartSequence gets a channel's recv start sequence from the store. // The recv start sequence will be set to the counterparty's next sequence send // upon a successful channel upgrade. It will be used for replay protection of // historical packets and as the upper bound for pruning stale packet receives. -func (k *Keeper) GetRecvStartSequence(ctx sdk.Context, portID, channelID string) (uint64, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.RecvStartSequenceKey(portID, channelID)) +func (k *Keeper) GetRecvStartSequence(ctx context.Context, portID, channelID string) (uint64, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.RecvStartSequenceKey(portID, channelID)) + if err != nil { + panic(err) + } + if len(bz) == 0 { return 0, false } @@ -657,16 +771,22 @@ func (k *Keeper) GetRecvStartSequence(ctx sdk.Context, portID, channelID string) } // SetPruningSequenceStart sets a channel's pruning sequence start to the store. -func (k *Keeper) SetPruningSequenceStart(ctx sdk.Context, portID, channelID string, sequence uint64) { - store := ctx.KVStore(k.storeKey) +func (k *Keeper) SetPruningSequenceStart(ctx context.Context, portID, channelID string, sequence uint64) { + store := k.storeService.OpenKVStore(ctx) bz := sdk.Uint64ToBigEndian(sequence) - store.Set(host.PruningSequenceStartKey(portID, channelID), bz) + if err := store.Set(host.PruningSequenceStartKey(portID, channelID), bz); err != nil { + panic(err) + } } // GetPruningSequenceStart gets a channel's pruning sequence start from the store. -func (k *Keeper) GetPruningSequenceStart(ctx sdk.Context, portID, channelID string) (uint64, bool) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(host.PruningSequenceStartKey(portID, channelID)) +func (k *Keeper) GetPruningSequenceStart(ctx context.Context, portID, channelID string) (uint64, bool) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(host.PruningSequenceStartKey(portID, channelID)) + if err != nil { + panic(err) + } + if len(bz) == 0 { return 0, false } @@ -675,9 +795,13 @@ func (k *Keeper) GetPruningSequenceStart(ctx sdk.Context, portID, channelID stri } // HasPruningSequenceStart returns true if the pruning sequence start is set for the specified channel. -func (k *Keeper) HasPruningSequenceStart(ctx sdk.Context, portID, channelID string) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(host.PruningSequenceStartKey(portID, channelID)) +func (k *Keeper) HasPruningSequenceStart(ctx context.Context, portID, channelID string) bool { + store := k.storeService.OpenKVStore(ctx) + has, err := store.Has(host.PruningSequenceStartKey(portID, channelID)) + if err != nil { + panic(err) + } + return has } // PruneAcknowledgements prunes packet acknowledgements and receipts that have a sequence number less than pruning sequence end. @@ -685,7 +809,7 @@ func (k *Keeper) HasPruningSequenceStart(ctx sdk.Context, portID, channelID stri // // Pruning sequence start keeps track of the packet ack/receipt that can be pruned next. When it reaches pruningSequenceEnd, // pruning is complete. -func (k *Keeper) PruneAcknowledgements(ctx sdk.Context, portID, channelID string, limit uint64) (uint64, uint64, error) { +func (k *Keeper) PruneAcknowledgements(ctx context.Context, portID, channelID string, limit uint64) (uint64, uint64, error) { pruningSequenceStart, found := k.GetPruningSequenceStart(ctx, portID, channelID) if !found { return 0, 0, errorsmod.Wrapf(types.ErrPruningSequenceStartNotFound, "port ID (%s) channel ID (%s)", portID, channelID) diff --git a/modules/core/04-channel/keeper/packet.go b/modules/core/04-channel/keeper/packet.go index c73ff4ce073..64320cfc005 100644 --- a/modules/core/04-channel/keeper/packet.go +++ b/modules/core/04-channel/keeper/packet.go @@ -2,6 +2,7 @@ package keeper import ( "bytes" + "context" "slices" "strconv" @@ -21,7 +22,7 @@ import ( // The packet sequence generated for the packet to be sent is returned. An error // is returned if one occurs. func (k *Keeper) SendPacket( - ctx sdk.Context, + ctx context.Context, channelCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, @@ -38,7 +39,8 @@ func (k *Keeper) SendPacket( return 0, errorsmod.Wrapf(types.ErrInvalidChannelState, "channel is not OPEN (got %s)", channel.State) } - if !k.scopedKeeper.AuthenticateCapability(ctx, channelCap, host.ChannelCapabilityPath(sourcePort, sourceChannel)) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + if !k.scopedKeeper.AuthenticateCapability(sdkCtx, channelCap, host.ChannelCapabilityPath(sourcePort, sourceChannel)) { return 0, errorsmod.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", sourcePort, sourceChannel) } @@ -89,7 +91,7 @@ func (k *Keeper) SendPacket( k.SetNextSequenceSend(ctx, sourcePort, sourceChannel, sequence+1) k.SetPacketCommitment(ctx, sourcePort, sourceChannel, packet.GetSequence(), commitment) - emitSendPacketEvent(ctx, packet, channel, timeoutHeight) + emitSendPacketEvent(sdkCtx, packet, channel, timeoutHeight) k.Logger(ctx).Info( "packet sent", @@ -291,7 +293,7 @@ func (k *Keeper) applyReplayProtection(ctx sdk.Context, packet types.Packet, cha // 2) Assumes that packet receipt has been written (unordered), or nextSeqRecv was incremented (ordered) // previously by RecvPacket. func (k *Keeper) WriteAcknowledgement( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, packet exported.PacketI, acknowledgement exported.Acknowledgement, @@ -307,7 +309,8 @@ func (k *Keeper) WriteAcknowledgement( // Authenticate capability to ensure caller has authority to receive packet on this channel capName := host.ChannelCapabilityPath(packet.GetDestPort(), packet.GetDestChannel()) - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + if !k.scopedKeeper.AuthenticateCapability(sdkCtx, chanCap, capName) { return errorsmod.Wrapf( types.ErrInvalidChannelCapability, "channel capability failed authentication for capability name %s", capName, @@ -356,7 +359,7 @@ func (k *Keeper) WriteAcknowledgement( "dst_channel", packet.GetDestChannel(), ) - emitWriteAcknowledgementEvent(ctx, packet.(types.Packet), channel, bz) + emitWriteAcknowledgementEvent(sdkCtx, packet.(types.Packet), channel, bz) return nil } diff --git a/modules/core/04-channel/types/expected_keepers.go b/modules/core/04-channel/types/expected_keepers.go index 47ff95e4685..79595818798 100644 --- a/modules/core/04-channel/types/expected_keepers.go +++ b/modules/core/04-channel/types/expected_keepers.go @@ -1,7 +1,7 @@ package types import ( - sdk "github.com/cosmos/cosmos-sdk/types" + "context" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" @@ -11,18 +11,18 @@ import ( // ClientKeeper expected account IBC client keeper type ClientKeeper interface { - GetClientStatus(ctx sdk.Context, clientID string) exported.Status - GetClientState(ctx sdk.Context, clientID string) (exported.ClientState, bool) - GetClientConsensusState(ctx sdk.Context, clientID string, height exported.Height) (exported.ConsensusState, bool) - GetClientLatestHeight(ctx sdk.Context, clientID string) clienttypes.Height - GetClientTimestampAtHeight(ctx sdk.Context, clientID string, height exported.Height) (uint64, error) + GetClientStatus(ctx context.Context, clientID string) exported.Status + GetClientState(ctx context.Context, clientID string) (exported.ClientState, bool) + GetClientConsensusState(ctx context.Context, clientID string, height exported.Height) (exported.ConsensusState, bool) + GetClientLatestHeight(ctx context.Context, clientID string) clienttypes.Height + GetClientTimestampAtHeight(ctx context.Context, clientID string, height exported.Height) (uint64, error) } // ConnectionKeeper expected account IBC connection keeper type ConnectionKeeper interface { - GetConnection(ctx sdk.Context, connectionID string) (connectiontypes.ConnectionEnd, bool) + GetConnection(ctx context.Context, connectionID string) (connectiontypes.ConnectionEnd, bool) VerifyChannelState( - ctx sdk.Context, + ctx context.Context, connection connectiontypes.ConnectionEnd, height exported.Height, proof []byte, @@ -31,7 +31,7 @@ type ConnectionKeeper interface { channel Channel, ) error VerifyPacketCommitment( - ctx sdk.Context, + ctx context.Context, connection connectiontypes.ConnectionEnd, height exported.Height, proof []byte, @@ -41,7 +41,7 @@ type ConnectionKeeper interface { commitmentBytes []byte, ) error VerifyPacketAcknowledgement( - ctx sdk.Context, + ctx context.Context, connection connectiontypes.ConnectionEnd, height exported.Height, proof []byte, @@ -51,7 +51,7 @@ type ConnectionKeeper interface { acknowledgement []byte, ) error VerifyPacketReceiptAbsence( - ctx sdk.Context, + ctx context.Context, connection connectiontypes.ConnectionEnd, height exported.Height, proof []byte, @@ -60,7 +60,7 @@ type ConnectionKeeper interface { sequence uint64, ) error VerifyNextSequenceRecv( - ctx sdk.Context, + ctx context.Context, connection connectiontypes.ConnectionEnd, height exported.Height, proof []byte, @@ -69,7 +69,7 @@ type ConnectionKeeper interface { nextSequenceRecv uint64, ) error VerifyChannelUpgrade( - ctx sdk.Context, + ctx context.Context, connection connectiontypes.ConnectionEnd, height exported.Height, proof []byte, @@ -78,7 +78,7 @@ type ConnectionKeeper interface { upgrade Upgrade, ) error VerifyChannelUpgradeError( - ctx sdk.Context, + ctx context.Context, connection connectiontypes.ConnectionEnd, height exported.Height, proof []byte, @@ -90,5 +90,5 @@ type ConnectionKeeper interface { // PortKeeper expected account IBC port keeper type PortKeeper interface { - Authenticate(ctx sdk.Context, key *capabilitytypes.Capability, portID string) bool + Authenticate(ctx context.Context, key *capabilitytypes.Capability, portID string) bool } diff --git a/modules/core/05-port/keeper/keeper.go b/modules/core/05-port/keeper/keeper.go index c6310ed3d4c..ea0188099be 100644 --- a/modules/core/05-port/keeper/keeper.go +++ b/modules/core/05-port/keeper/keeper.go @@ -1,6 +1,7 @@ package keeper import ( + "context" "fmt" "cosmossdk.io/log" @@ -28,13 +29,15 @@ func NewKeeper(sck exported.ScopedKeeper) *Keeper { } // Logger returns a module-specific logger. -func (Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) +func (Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return sdkCtx.Logger().With("module", "x/"+exported.ModuleName+"/"+types.SubModuleName) } // IsBound checks a given port ID is already bounded. -func (k *Keeper) IsBound(ctx sdk.Context, portID string) bool { - _, ok := k.scopedKeeper.GetCapability(ctx, host.PortPath(portID)) +func (k *Keeper) IsBound(ctx context.Context, portID string) bool { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, ok := k.scopedKeeper.GetCapability(sdkCtx, host.PortPath(portID)) return ok } @@ -42,7 +45,7 @@ func (k *Keeper) IsBound(ctx sdk.Context, portID string) bool { // Ports must be bound statically when the chain starts in `app.go`. // The capability must then be passed to a module which will need to pass // it as an extra parameter when calling functions on the IBC module. -func (k *Keeper) BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability { +func (k *Keeper) BindPort(ctx context.Context, portID string) *capabilitytypes.Capability { if err := host.PortIdentifierValidator(portID); err != nil { panic(err.Error()) } @@ -51,7 +54,9 @@ func (k *Keeper) BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capab panic(fmt.Errorf("port %s is already bound", portID)) } - key, err := k.scopedKeeper.NewCapability(ctx, host.PortPath(portID)) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + + key, err := k.scopedKeeper.NewCapability(sdkCtx, host.PortPath(portID)) if err != nil { panic(err.Error()) } @@ -64,17 +69,19 @@ func (k *Keeper) BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capab // by checking if the memory address of the capability was previously // generated and bound to the port (provided as a parameter) which the capability // is being authenticated against. -func (k *Keeper) Authenticate(ctx sdk.Context, key *capabilitytypes.Capability, portID string) bool { +func (k *Keeper) Authenticate(ctx context.Context, key *capabilitytypes.Capability, portID string) bool { if err := host.PortIdentifierValidator(portID); err != nil { panic(err.Error()) } - return k.scopedKeeper.AuthenticateCapability(ctx, key, host.PortPath(portID)) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return k.scopedKeeper.AuthenticateCapability(sdkCtx, key, host.PortPath(portID)) } // LookupModuleByPort will return the IBCModule along with the capability associated with a given portID -func (k *Keeper) LookupModuleByPort(ctx sdk.Context, portID string) (string, *capabilitytypes.Capability, error) { - modules, capability, err := k.scopedKeeper.LookupModules(ctx, host.PortPath(portID)) +func (k *Keeper) LookupModuleByPort(ctx context.Context, portID string) (string, *capabilitytypes.Capability, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + modules, capability, err := k.scopedKeeper.LookupModules(sdkCtx, host.PortPath(portID)) if err != nil { return "", nil, err } diff --git a/modules/core/05-port/types/module.go b/modules/core/05-port/types/module.go index d1afbf5820e..f20d83e64aa 100644 --- a/modules/core/05-port/types/module.go +++ b/modules/core/05-port/types/module.go @@ -1,6 +1,8 @@ package types import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" @@ -163,7 +165,7 @@ type UpgradableModule interface { // ICS4Wrapper implements the ICS4 interfaces that IBC applications use to send packets and acknowledgements. type ICS4Wrapper interface { SendPacket( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, @@ -173,14 +175,14 @@ type ICS4Wrapper interface { ) (sequence uint64, err error) WriteAcknowledgement( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, packet exported.PacketI, ack exported.Acknowledgement, ) error GetAppVersion( - ctx sdk.Context, + ctx context.Context, portID, channelID string, ) (string, bool) @@ -199,5 +201,5 @@ type PacketDataUnmarshaler interface { // UnmarshalPacketData unmarshals the packet data into a concrete type // ctx, portID, channelID are provided as arguments, so that (if needed) // the packet data can be unmarshaled based on the channel version. - UnmarshalPacketData(ctx sdk.Context, portID string, channelID string, bz []byte) (interface{}, string, error) + UnmarshalPacketData(ctx context.Context, portID string, channelID string, bz []byte) (interface{}, string, error) } diff --git a/modules/core/23-commitment/types/merkle_test.go b/modules/core/23-commitment/types/merkle_test.go index 89bfd272013..dd1ec4e6172 100644 --- a/modules/core/23-commitment/types/merkle_test.go +++ b/modules/core/23-commitment/types/merkle_test.go @@ -67,10 +67,10 @@ func (suite *MerkleTestSuite) TestVerifyMembership() { err := proof.VerifyMembership(types.GetSDKSpecs(), &root, path, tc.value) if tc.shouldPass { - //nolint: scopelint + // nolint: scopelint suite.Require().NoError(err, "test case %d should have passed", i) } else { - //nolint: scopelint + // nolint: scopelint suite.Require().Error(err, "test case %d should have failed", i) } }) @@ -131,10 +131,10 @@ func (suite *MerkleTestSuite) TestVerifyNonMembership() { err := proof.VerifyNonMembership(types.GetSDKSpecs(), &root, path) if tc.shouldPass { - //nolint: scopelint + // nolint: scopelint suite.Require().NoError(err, "test case %d should have passed", i) } else { - //nolint: scopelint + // nolint: scopelint suite.Require().Error(err, "test case %d should have failed", i) } }) diff --git a/modules/core/exported/client.go b/modules/core/exported/client.go index 98f18b83a04..5a0e2084af6 100644 --- a/modules/core/exported/client.go +++ b/modules/core/exported/client.go @@ -1,9 +1,9 @@ package exported import ( - "github.com/cosmos/gogoproto/proto" + "context" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" ) // Status represents the status of a client @@ -44,29 +44,29 @@ type LightClientModule interface { // Initialize is called upon client creation, it allows the client to perform validation on the client state and initial consensus state. // The light client module is responsible for setting any client-specific data in the store. This includes the client state, // initial consensus state and any associated metadata. - Initialize(ctx sdk.Context, clientID string, clientState, consensusState []byte) error + Initialize(ctx context.Context, clientID string, clientState, consensusState []byte) error // VerifyClientMessage must verify a ClientMessage. A ClientMessage could be a Header, Misbehaviour, or batch update. // It must handle each type of ClientMessage appropriately. Calls to CheckForMisbehaviour, UpdateState, and UpdateStateOnMisbehaviour // will assume that the content of the ClientMessage has been verified and can be trusted. An error should be returned // if the ClientMessage fails to verify. - VerifyClientMessage(ctx sdk.Context, clientID string, clientMsg ClientMessage) error + VerifyClientMessage(ctx context.Context, clientID string, clientMsg ClientMessage) error // Checks for evidence of a misbehaviour in Header or Misbehaviour type. It assumes the ClientMessage // has already been verified. - CheckForMisbehaviour(ctx sdk.Context, clientID string, clientMsg ClientMessage) bool + CheckForMisbehaviour(ctx context.Context, clientID string, clientMsg ClientMessage) bool // UpdateStateOnMisbehaviour should perform appropriate state changes on a client state given that misbehaviour has been detected and verified - UpdateStateOnMisbehaviour(ctx sdk.Context, clientID string, clientMsg ClientMessage) + UpdateStateOnMisbehaviour(ctx context.Context, clientID string, clientMsg ClientMessage) // UpdateState updates and stores as necessary any associated information for an IBC client, such as the ClientState and corresponding ConsensusState. // Upon successful update, a list of consensus heights is returned. It assumes the ClientMessage has already been verified. - UpdateState(ctx sdk.Context, clientID string, clientMsg ClientMessage) []Height + UpdateState(ctx context.Context, clientID string, clientMsg ClientMessage) []Height // VerifyMembership is a generic proof verification method which verifies a proof of the existence of a value at a given CommitmentPath at the specified height. // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). VerifyMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height Height, delayTimePeriod uint64, @@ -79,7 +79,7 @@ type LightClientModule interface { // VerifyNonMembership is a generic proof verification method which verifies the absence of a given CommitmentPath at a specified height. // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). VerifyNonMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height Height, delayTimePeriod uint64, @@ -89,21 +89,21 @@ type LightClientModule interface { ) error // Status must return the status of the client. Only Active clients are allowed to process packets. - Status(ctx sdk.Context, clientID string) Status + Status(ctx context.Context, clientID string) Status // LatestHeight returns the latest height of the client. If no client is present for the provided client identifier a zero value height may be returned. - LatestHeight(ctx sdk.Context, clientID string) Height + LatestHeight(ctx context.Context, clientID string) Height // TimestampAtHeight must return the timestamp for the consensus state associated with the provided height. TimestampAtHeight( - ctx sdk.Context, + ctx context.Context, clientID string, height Height, ) (uint64, error) // RecoverClient must verify that the provided substitute may be used to update the subject client. // The light client module must set the updated client and consensus states within the clientStore for the subject client. - RecoverClient(ctx sdk.Context, clientID, substituteClientID string) error + RecoverClient(ctx context.Context, clientID, substituteClientID string) error // Upgrade functions // NOTE: proof heights are not included as upgrade to a new revision is expected to pass only on the last @@ -113,7 +113,7 @@ type LightClientModule interface { // may be cancelled or modified before the last planned height. // If the upgrade is verified, the upgraded client and consensus states must be set in the client store. VerifyUpgradeAndUpdateState( - ctx sdk.Context, + ctx context.Context, clientID string, newClient []byte, newConsState []byte, diff --git a/modules/core/keeper/keeper.go b/modules/core/keeper/keeper.go index fed78a94888..0ed9e438cad 100644 --- a/modules/core/keeper/keeper.go +++ b/modules/core/keeper/keeper.go @@ -5,7 +5,7 @@ import ( "reflect" "strings" - storetypes "cosmossdk.io/store/types" + corestore "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" @@ -33,7 +33,7 @@ type Keeper struct { // NewKeeper creates a new ibc Keeper func NewKeeper( - cdc codec.BinaryCodec, key storetypes.StoreKey, paramSpace types.ParamSubspace, + cdc codec.BinaryCodec, storeService corestore.KVStoreService, paramSpace types.ParamSubspace, upgradeKeeper clienttypes.UpgradeKeeper, scopedKeeper capabilitykeeper.ScopedKeeper, authority string, ) *Keeper { @@ -50,10 +50,10 @@ func NewKeeper( panic(errors.New("authority must be non-empty")) } - clientKeeper := clientkeeper.NewKeeper(cdc, key, paramSpace, upgradeKeeper) - connectionKeeper := connectionkeeper.NewKeeper(cdc, key, paramSpace, clientKeeper) + clientKeeper := clientkeeper.NewKeeper(cdc, storeService, paramSpace, upgradeKeeper) + connectionKeeper := connectionkeeper.NewKeeper(cdc, storeService, paramSpace, clientKeeper) portKeeper := portkeeper.NewKeeper(scopedKeeper) - channelKeeper := channelkeeper.NewKeeper(cdc, key, clientKeeper, connectionKeeper, portKeeper, scopedKeeper) + channelKeeper := channelkeeper.NewKeeper(cdc, storeService, clientKeeper, connectionKeeper, portKeeper, scopedKeeper) return &Keeper{ cdc: cdc, diff --git a/modules/core/keeper/keeper_test.go b/modules/core/keeper/keeper_test.go index ff7fb8b8f11..eb35bd015c3 100644 --- a/modules/core/keeper/keeper_test.go +++ b/modules/core/keeper/keeper_test.go @@ -7,6 +7,8 @@ import ( upgradekeeper "cosmossdk.io/x/upgrade/keeper" + "github.com/cosmos/cosmos-sdk/runtime" + capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" ibcexported "github.com/cosmos/ibc-go/v9/modules/core/exported" @@ -72,7 +74,7 @@ func (suite *KeeperTestSuite) TestNewKeeper() { newIBCKeeperFn = func() { ibckeeper.NewKeeper( suite.chainA.GetSimApp().AppCodec(), - suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey), + runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey)), suite.chainA.GetSimApp().GetSubspace(ibcexported.ModuleName), upgradeKeeper, scopedKeeper, @@ -91,7 +93,7 @@ func (suite *KeeperTestSuite) TestNewKeeper() { newIBCKeeperFn = func() { ibckeeper.NewKeeper( suite.chainA.GetSimApp().AppCodec(), - suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey), + runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey)), suite.chainA.GetSimApp().GetSubspace(ibcexported.ModuleName), upgradeKeeper, scopedKeeper, diff --git a/modules/core/migrations/v7/genesis_test.go b/modules/core/migrations/v7/genesis_test.go index 5bd598d1fee..57ceb04973f 100644 --- a/modules/core/migrations/v7/genesis_test.go +++ b/modules/core/migrations/v7/genesis_test.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ibcclient "github.com/cosmos/ibc-go/v9/modules/core/02-client" @@ -134,7 +135,7 @@ func (suite *MigrationsV7TestSuite) TestMigrateGenesisSolomachine() { // migrate store get expected genesis // store migration and genesis migration should produce identical results // NOTE: tendermint clients are not pruned in genesis so the test should not have expired tendermint clients - err := clientv7.MigrateStore(suite.chainA.GetContext(), suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) + err := clientv7.MigrateStore(suite.chainA.GetContext(), runtime.NewKVStoreService(suite.chainA.GetSimApp().GetKey(ibcexported.StoreKey)), suite.chainA.App.AppCodec(), suite.chainA.GetSimApp().IBCKeeper.ClientKeeper) suite.Require().NoError(err) expectedClientGenState := ibcclient.ExportGenesis(suite.chainA.GetContext(), suite.chainA.App.GetIBCKeeper().ClientKeeper) diff --git a/modules/light-clients/06-solomachine/light_client_module.go b/modules/light-clients/06-solomachine/light_client_module.go index 8c4885c776a..2ac9d66cf22 100644 --- a/modules/light-clients/06-solomachine/light_client_module.go +++ b/modules/light-clients/06-solomachine/light_client_module.go @@ -1,12 +1,12 @@ package solomachine import ( + "context" "reflect" errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" "github.com/cosmos/ibc-go/v9/modules/core/exported" @@ -30,7 +30,7 @@ func NewLightClientModule(cdc codec.BinaryCodec, storeProvider clienttypes.Store // Initialize unmarshals the provided client and consensus states and performs basic validation. It calls into the // clientState.Initialize method. -func (l LightClientModule) Initialize(ctx sdk.Context, clientID string, clientStateBz, consensusStateBz []byte) error { +func (l LightClientModule) Initialize(ctx context.Context, clientID string, clientStateBz, consensusStateBz []byte) error { var clientState ClientState if err := l.cdc.Unmarshal(clientStateBz, &clientState); err != nil { return err @@ -62,7 +62,7 @@ func (l LightClientModule) Initialize(ctx sdk.Context, clientID string, clientSt } // VerifyClientMessage obtains the client state associated with the client identifier and calls into the clientState.VerifyClientMessage method. -func (l LightClientModule) VerifyClientMessage(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) error { +func (l LightClientModule) VerifyClientMessage(ctx context.Context, clientID string, clientMsg exported.ClientMessage) error { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -73,7 +73,7 @@ func (l LightClientModule) VerifyClientMessage(ctx sdk.Context, clientID string, } // CheckForMisbehaviour obtains the client state associated with the client identifier and calls into the clientState.CheckForMisbehaviour method. -func (l LightClientModule) CheckForMisbehaviour(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) bool { +func (l LightClientModule) CheckForMisbehaviour(ctx context.Context, clientID string, clientMsg exported.ClientMessage) bool { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -86,7 +86,7 @@ func (l LightClientModule) CheckForMisbehaviour(ctx sdk.Context, clientID string // UpdateStateOnMisbehaviour updates state upon misbehaviour, freezing the ClientState. // This method should only be called when misbehaviour is detected as it does not perform // any misbehaviour checks. -func (l LightClientModule) UpdateStateOnMisbehaviour(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) { +func (l LightClientModule) UpdateStateOnMisbehaviour(ctx context.Context, clientID string, clientMsg exported.ClientMessage) { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -98,7 +98,7 @@ func (l LightClientModule) UpdateStateOnMisbehaviour(ctx sdk.Context, clientID s } // UpdateState obtains the client state associated with the client identifier and calls into the clientState.UpdateState method. -func (l LightClientModule) UpdateState(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) []exported.Height { +func (l LightClientModule) UpdateState(ctx context.Context, clientID string, clientMsg exported.ClientMessage) []exported.Height { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -110,7 +110,7 @@ func (l LightClientModule) UpdateState(ctx sdk.Context, clientID string, clientM // VerifyMembership obtains the client state associated with the client identifier and calls into the clientState.verifyMembership method. func (l LightClientModule) VerifyMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -130,7 +130,7 @@ func (l LightClientModule) VerifyMembership( // VerifyNonMembership obtains the client state associated with the client identifier and calls into the clientState.verifyNonMembership method. func (l LightClientModule) VerifyNonMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -152,7 +152,7 @@ func (l LightClientModule) VerifyNonMembership( // - Active: if `IsFrozen` is false. // - Frozen: if `IsFrozen` is true. // - Unknown: if the client state associated with the provided client identifier is not found. -func (l LightClientModule) Status(ctx sdk.Context, clientID string) exported.Status { +func (l LightClientModule) Status(ctx context.Context, clientID string) exported.Status { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -169,7 +169,7 @@ func (l LightClientModule) Status(ctx sdk.Context, clientID string) exported.Sta // LatestHeight returns the latest height for the client state for the given client identifier. // If no client is present for the provided client identifier a zero value height is returned. // NOTE: RevisionNumber is always 0 for solomachine client heights. -func (l LightClientModule) LatestHeight(ctx sdk.Context, clientID string) exported.Height { +func (l LightClientModule) LatestHeight(ctx context.Context, clientID string) exported.Height { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) @@ -181,7 +181,7 @@ func (l LightClientModule) LatestHeight(ctx sdk.Context, clientID string) export } // TimestampAtHeight obtains the client state associated with the client identifier and returns the timestamp in nanoseconds of the consensus state at the given height. -func (l LightClientModule) TimestampAtHeight(ctx sdk.Context, clientID string, height exported.Height) (uint64, error) { +func (l LightClientModule) TimestampAtHeight(ctx context.Context, clientID string, height exported.Height) (uint64, error) { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -193,7 +193,7 @@ func (l LightClientModule) TimestampAtHeight(ctx sdk.Context, clientID string, h // RecoverClient asserts that the substitute client is a solo machine client. It obtains the client state associated with the // subject client and calls into the subjectClientState.CheckSubstituteAndUpdateState method. -func (l LightClientModule) RecoverClient(ctx sdk.Context, clientID, substituteClientID string) error { +func (l LightClientModule) RecoverClient(ctx context.Context, clientID, substituteClientID string) error { substituteClientType, _, err := clienttypes.ParseClientIdentifier(substituteClientID) if err != nil { return err @@ -219,6 +219,6 @@ func (l LightClientModule) RecoverClient(ctx sdk.Context, clientID, substituteCl } // VerifyUpgradeAndUpdateState returns an error since solomachine client does not support upgrades -func (LightClientModule) VerifyUpgradeAndUpdateState(ctx sdk.Context, clientID string, newClient, newConsState, upgradeClientProof, upgradeConsensusStateProof []byte) error { +func (LightClientModule) VerifyUpgradeAndUpdateState(ctx context.Context, clientID string, newClient, newConsState, upgradeClientProof, upgradeConsensusStateProof []byte) error { return errorsmod.Wrap(clienttypes.ErrInvalidUpgradeClient, "cannot upgrade solomachine client") } diff --git a/modules/light-clients/06-solomachine/misbehaviour_handle.go b/modules/light-clients/06-solomachine/misbehaviour_handle.go index 0b38a4cbc88..3987a4823b0 100644 --- a/modules/light-clients/06-solomachine/misbehaviour_handle.go +++ b/modules/light-clients/06-solomachine/misbehaviour_handle.go @@ -1,18 +1,19 @@ package solomachine import ( + "context" + errorsmod "cosmossdk.io/errors" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" commitmenttypesv2 "github.com/cosmos/ibc-go/v9/modules/core/23-commitment/types/v2" "github.com/cosmos/ibc-go/v9/modules/core/exported" ) // CheckForMisbehaviour returns true for type Misbehaviour (passed VerifyClientMessage check), otherwise returns false -func (ClientState) CheckForMisbehaviour(_ sdk.Context, _ codec.BinaryCodec, _ storetypes.KVStore, clientMsg exported.ClientMessage) bool { +func (ClientState) CheckForMisbehaviour(_ context.Context, _ codec.BinaryCodec, _ storetypes.KVStore, clientMsg exported.ClientMessage) bool { if _, ok := clientMsg.(*Misbehaviour); ok { return true } diff --git a/modules/light-clients/06-solomachine/proof.go b/modules/light-clients/06-solomachine/proof.go index 516b8421d0d..3a3a3cc3d2f 100644 --- a/modules/light-clients/06-solomachine/proof.go +++ b/modules/light-clients/06-solomachine/proof.go @@ -26,7 +26,7 @@ func VerifySignature(pubKey cryptotypes.PubKey, signBytes []byte, sigData signin if err := pubKey.VerifyMultisignature(func(signing.SignMode) ([]byte, error) { return signBytes, nil }, data); err != nil { - return errorsmod.Wrapf(ErrSignatureVerificationFailed, err.Error()) + return errorsmod.Wrapf(ErrSignatureVerificationFailed, "failed to verify multisignature: %s", err.Error()) } default: diff --git a/modules/light-clients/06-solomachine/proposal_handle.go b/modules/light-clients/06-solomachine/proposal_handle.go index aae18d037c1..a1a89a84279 100644 --- a/modules/light-clients/06-solomachine/proposal_handle.go +++ b/modules/light-clients/06-solomachine/proposal_handle.go @@ -1,13 +1,13 @@ package solomachine import ( + "context" "reflect" errorsmod "cosmossdk.io/errors" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" "github.com/cosmos/ibc-go/v9/modules/core/exported" @@ -21,7 +21,7 @@ import ( // the substitute is not a solo machine, or the current public key equals // the new public key. func (cs ClientState) CheckSubstituteAndUpdateState( - ctx sdk.Context, cdc codec.BinaryCodec, subjectClientStore, + ctx context.Context, cdc codec.BinaryCodec, subjectClientStore, _ storetypes.KVStore, substituteClient exported.ClientState, ) error { substituteClientState, ok := substituteClient.(*ClientState) diff --git a/modules/light-clients/06-solomachine/update.go b/modules/light-clients/06-solomachine/update.go index ddc53dbb2d2..b3c1463028d 100644 --- a/modules/light-clients/06-solomachine/update.go +++ b/modules/light-clients/06-solomachine/update.go @@ -1,11 +1,12 @@ package solomachine import ( + "context" + errorsmod "cosmossdk.io/errors" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" "github.com/cosmos/ibc-go/v9/modules/core/exported" @@ -14,7 +15,7 @@ import ( // VerifyClientMessage introspects the provided ClientMessage and checks its validity // A Solomachine Header is considered valid if the currently registered public key has signed over the new public key with the correct sequence // A Solomachine Misbehaviour is considered valid if duplicate signatures of the current public key are found on two different messages at a given sequence -func (cs ClientState) VerifyClientMessage(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) error { +func (cs ClientState) VerifyClientMessage(ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) error { switch msg := clientMsg.(type) { case *Header: return cs.verifyHeader(cdc, msg) @@ -78,7 +79,7 @@ func (cs ClientState) verifyHeader(cdc codec.BinaryCodec, header *Header) error // UpdateState updates the consensus state to the new public key and an incremented sequence. // A list containing the updated consensus height is returned. // If the provided clientMsg is not of type Header, the handler will no-op and return an empty slice. -func (cs ClientState) UpdateState(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) []exported.Height { +func (cs ClientState) UpdateState(ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) []exported.Height { smHeader, ok := clientMsg.(*Header) if !ok { // clientMsg is invalid Misbehaviour, no update necessary diff --git a/modules/light-clients/07-tendermint/client_state.go b/modules/light-clients/07-tendermint/client_state.go index 2e5becea74f..89ab21128d7 100644 --- a/modules/light-clients/07-tendermint/client_state.go +++ b/modules/light-clients/07-tendermint/client_state.go @@ -1,6 +1,7 @@ package tendermint import ( + "context" "strings" "time" @@ -77,7 +78,7 @@ func (ClientState) getTimestampAtHeight( // A frozen client will become expired, so the Frozen status // has higher precedence. func (cs ClientState) status( - ctx sdk.Context, + ctx context.Context, clientStore storetypes.KVStore, cdc codec.BinaryCodec, ) exported.Status { @@ -93,7 +94,8 @@ func (cs ClientState) status( return exported.Expired } - if cs.IsExpired(consState.Timestamp, ctx.BlockTime()) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + if cs.IsExpired(consState.Timestamp, sdkCtx.BlockTime()) { return exported.Expired } @@ -186,7 +188,7 @@ func (cs ClientState) ZeroCustomFields() *ClientState { // initialize checks that the initial consensus state is an 07-tendermint consensus state and // sets the client state, consensus state and associated metadata in the provided client store. -func (cs ClientState) initialize(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, consState exported.ConsensusState) error { +func (cs ClientState) initialize(ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, consState exported.ConsensusState) error { consensusState, ok := consState.(*ConsensusState) if !ok { return errorsmod.Wrapf(clienttypes.ErrInvalidConsensus, "invalid initial consensus state. expected type: %T, got: %T", @@ -204,7 +206,7 @@ func (cs ClientState) initialize(ctx sdk.Context, cdc codec.BinaryCodec, clientS // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). // If a zero proof height is passed in, it will fail to retrieve the associated consensus state. func (cs ClientState) verifyMembership( - ctx sdk.Context, + ctx context.Context, clientStore storetypes.KVStore, cdc codec.BinaryCodec, height exported.Height, @@ -247,7 +249,7 @@ func (cs ClientState) verifyMembership( // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). // If a zero proof height is passed in, it will fail to retrieve the associated consensus state. func (cs ClientState) verifyNonMembership( - ctx sdk.Context, + ctx context.Context, clientStore storetypes.KVStore, cdc codec.BinaryCodec, height exported.Height, @@ -287,7 +289,7 @@ func (cs ClientState) verifyNonMembership( // verifyDelayPeriodPassed will ensure that at least delayTimePeriod amount of time and delayBlockPeriod number of blocks have passed // since consensus state was submitted before allowing verification to continue. -func verifyDelayPeriodPassed(ctx sdk.Context, store storetypes.KVStore, proofHeight exported.Height, delayTimePeriod, delayBlockPeriod uint64) error { +func verifyDelayPeriodPassed(ctx context.Context, store storetypes.KVStore, proofHeight exported.Height, delayTimePeriod, delayBlockPeriod uint64) error { if delayTimePeriod != 0 { // check that executing chain's timestamp has passed consensusState's processed time + delay time period processedTime, ok := GetProcessedTime(store, proofHeight) @@ -295,7 +297,8 @@ func verifyDelayPeriodPassed(ctx sdk.Context, store storetypes.KVStore, proofHei return errorsmod.Wrapf(ErrProcessedTimeNotFound, "processed time not found for height: %s", proofHeight) } - currentTimestamp := uint64(ctx.BlockTime().UnixNano()) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + currentTimestamp := uint64(sdkCtx.BlockTime().UnixNano()) validTime := processedTime + delayTimePeriod // NOTE: delay time period is inclusive, so if currentTimestamp is validTime, then we return no error diff --git a/modules/light-clients/07-tendermint/light_client_module.go b/modules/light-clients/07-tendermint/light_client_module.go index e0acee6d75e..821ccbeecfa 100644 --- a/modules/light-clients/07-tendermint/light_client_module.go +++ b/modules/light-clients/07-tendermint/light_client_module.go @@ -1,6 +1,7 @@ package tendermint import ( + "context" "fmt" errorsmod "cosmossdk.io/errors" @@ -31,7 +32,7 @@ func NewLightClientModule(cdc codec.BinaryCodec, storeProvider clienttypes.Store // Initialize unmarshals the provided client and consensus states and performs basic validation. It calls into the // clientState.initialize method. -func (l LightClientModule) Initialize(ctx sdk.Context, clientID string, clientStateBz, consensusStateBz []byte) error { +func (l LightClientModule) Initialize(ctx context.Context, clientID string, clientStateBz, consensusStateBz []byte) error { var clientState ClientState if err := l.cdc.Unmarshal(clientStateBz, &clientState); err != nil { return fmt.Errorf("failed to unmarshal client state bytes into client state: %w", err) @@ -56,18 +57,19 @@ func (l LightClientModule) Initialize(ctx sdk.Context, clientID string, clientSt } // VerifyClientMessage obtains the client state associated with the client identifier and calls into the clientState.VerifyClientMessage method. -func (l LightClientModule) VerifyClientMessage(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) error { +func (l LightClientModule) VerifyClientMessage(ctx context.Context, clientID string, clientMsg exported.ClientMessage) error { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { return errorsmod.Wrap(clienttypes.ErrClientNotFound, clientID) } - return clientState.VerifyClientMessage(ctx, l.cdc, clientStore, clientMsg) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return clientState.VerifyClientMessage(sdkCtx, l.cdc, clientStore, clientMsg) } // CheckForMisbehaviour obtains the client state associated with the client identifier and calls into the clientState.CheckForMisbehaviour method. -func (l LightClientModule) CheckForMisbehaviour(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) bool { +func (l LightClientModule) CheckForMisbehaviour(ctx context.Context, clientID string, clientMsg exported.ClientMessage) bool { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -78,7 +80,7 @@ func (l LightClientModule) CheckForMisbehaviour(ctx sdk.Context, clientID string } // UpdateStateOnMisbehaviour obtains the client state associated with the client identifier and calls into the clientState.UpdateStateOnMisbehaviour method. -func (l LightClientModule) UpdateStateOnMisbehaviour(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) { +func (l LightClientModule) UpdateStateOnMisbehaviour(ctx context.Context, clientID string, clientMsg exported.ClientMessage) { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -89,7 +91,7 @@ func (l LightClientModule) UpdateStateOnMisbehaviour(ctx sdk.Context, clientID s } // UpdateState obtains the client state associated with the client identifier and calls into the clientState.UpdateState method. -func (l LightClientModule) UpdateState(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) []exported.Height { +func (l LightClientModule) UpdateState(ctx context.Context, clientID string, clientMsg exported.ClientMessage) []exported.Height { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -101,7 +103,7 @@ func (l LightClientModule) UpdateState(ctx sdk.Context, clientID string, clientM // VerifyMembership obtains the client state associated with the client identifier and calls into the clientState.verifyMembership method. func (l LightClientModule) VerifyMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -121,7 +123,7 @@ func (l LightClientModule) VerifyMembership( // VerifyNonMembership obtains the client state associated with the client identifier and calls into the clientState.verifyNonMembership method. func (l LightClientModule) VerifyNonMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -139,7 +141,7 @@ func (l LightClientModule) VerifyNonMembership( } // Status obtains the client state associated with the client identifier and calls into the clientState.status method. -func (l LightClientModule) Status(ctx sdk.Context, clientID string) exported.Status { +func (l LightClientModule) Status(ctx context.Context, clientID string) exported.Status { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -151,7 +153,7 @@ func (l LightClientModule) Status(ctx sdk.Context, clientID string) exported.Sta // LatestHeight returns the latest height for the client state for the given client identifier. // If no client is present for the provided client identifier a zero value height is returned. -func (l LightClientModule) LatestHeight(ctx sdk.Context, clientID string) exported.Height { +func (l LightClientModule) LatestHeight(ctx context.Context, clientID string) exported.Height { clientStore := l.storeProvider.ClientStore(ctx, clientID) clientState, found := getClientState(clientStore, l.cdc) if !found { @@ -163,7 +165,7 @@ func (l LightClientModule) LatestHeight(ctx sdk.Context, clientID string) export // TimestampAtHeight obtains the client state associated with the client identifier and calls into the clientState.getTimestampAtHeight method. func (l LightClientModule) TimestampAtHeight( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, ) (uint64, error) { @@ -178,7 +180,7 @@ func (l LightClientModule) TimestampAtHeight( // RecoverClient asserts that the substitute client is a tendermint client. It obtains the client state associated with the // subject client and calls into the subjectClientState.CheckSubstituteAndUpdateState method. -func (l LightClientModule) RecoverClient(ctx sdk.Context, clientID, substituteClientID string) error { +func (l LightClientModule) RecoverClient(ctx context.Context, clientID, substituteClientID string) error { substituteClientType, _, err := clienttypes.ParseClientIdentifier(substituteClientID) if err != nil { return err @@ -207,7 +209,7 @@ func (l LightClientModule) RecoverClient(ctx sdk.Context, clientID, substituteCl // The new client and consensus states will be unmarshaled and an error is returned if the new client state is not at a height greater // than the existing client. func (l LightClientModule) VerifyUpgradeAndUpdateState( - ctx sdk.Context, + ctx context.Context, clientID string, newClient []byte, newConsState []byte, diff --git a/modules/light-clients/07-tendermint/migrations/expected_keepers.go b/modules/light-clients/07-tendermint/migrations/expected_keepers.go index b6b681d6402..48ff97e416d 100644 --- a/modules/light-clients/07-tendermint/migrations/expected_keepers.go +++ b/modules/light-clients/07-tendermint/migrations/expected_keepers.go @@ -1,18 +1,18 @@ package migrations import ( + "context" + "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/ibc-go/v9/modules/core/exported" ) // ClientKeeper expected account IBC client keeper type ClientKeeper interface { - GetClientState(ctx sdk.Context, clientID string) (exported.ClientState, bool) - IterateClientStates(ctx sdk.Context, prefix []byte, cb func(string, exported.ClientState) bool) - ClientStore(ctx sdk.Context, clientID string) storetypes.KVStore - Logger(ctx sdk.Context) log.Logger + GetClientState(ctx context.Context, clientID string) (exported.ClientState, bool) + IterateClientStates(ctx context.Context, prefix []byte, cb func(string, exported.ClientState) bool) + ClientStore(ctx context.Context, clientID string) storetypes.KVStore + Logger(ctx context.Context) log.Logger } diff --git a/modules/light-clients/07-tendermint/misbehaviour_handle.go b/modules/light-clients/07-tendermint/misbehaviour_handle.go index 11f5762b47e..a91cf67c29b 100644 --- a/modules/light-clients/07-tendermint/misbehaviour_handle.go +++ b/modules/light-clients/07-tendermint/misbehaviour_handle.go @@ -2,6 +2,7 @@ package tendermint import ( "bytes" + "context" "reflect" "time" @@ -19,7 +20,7 @@ import ( // CheckForMisbehaviour detects duplicate height misbehaviour and BFT time violation misbehaviour // in a submitted Header message and verifies the correctness of a submitted Misbehaviour ClientMessage -func (ClientState) CheckForMisbehaviour(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, msg exported.ClientMessage) bool { +func (ClientState) CheckForMisbehaviour(ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, msg exported.ClientMessage) bool { switch msg := msg.(type) { case *Header: tmHeader := msg @@ -90,7 +91,7 @@ func (ClientState) CheckForMisbehaviour(ctx sdk.Context, cdc codec.BinaryCodec, // Similarly, consensusState2 is the trusted consensus state that corresponds // to misbehaviour.Header2 // Misbehaviour sets frozen height to {0, 1} since it is only used as a boolean value (zero or non-zero). -func (cs *ClientState) verifyMisbehaviour(ctx sdk.Context, clientStore storetypes.KVStore, cdc codec.BinaryCodec, misbehaviour *Misbehaviour) error { +func (cs *ClientState) verifyMisbehaviour(ctx context.Context, clientStore storetypes.KVStore, cdc codec.BinaryCodec, misbehaviour *Misbehaviour) error { // Regardless of the type of misbehaviour, ensure that both headers are valid and would have been accepted by light-client // Retrieve trusted consensus states for each Header in misbehaviour @@ -109,13 +110,14 @@ func (cs *ClientState) verifyMisbehaviour(ctx sdk.Context, clientStore storetype // NOTE: header height and commitment root assertions are checked in // misbehaviour.ValidateBasic by the client keeper and msg.ValidateBasic // by the base application. + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 if err := checkMisbehaviourHeader( - cs, tmConsensusState1, misbehaviour.Header1, ctx.BlockTime(), + cs, tmConsensusState1, misbehaviour.Header1, sdkCtx.BlockTime(), ); err != nil { return errorsmod.Wrap(err, "verifying Header1 in Misbehaviour failed") } if err := checkMisbehaviourHeader( - cs, tmConsensusState2, misbehaviour.Header2, ctx.BlockTime(), + cs, tmConsensusState2, misbehaviour.Header2, sdkCtx.BlockTime(), ); err != nil { return errorsmod.Wrap(err, "verifying Header2 in Misbehaviour failed") } diff --git a/modules/light-clients/07-tendermint/proposal_handle.go b/modules/light-clients/07-tendermint/proposal_handle.go index 60f8ea4ac8b..ae83014cfec 100644 --- a/modules/light-clients/07-tendermint/proposal_handle.go +++ b/modules/light-clients/07-tendermint/proposal_handle.go @@ -1,6 +1,7 @@ package tendermint import ( + "context" "reflect" "time" @@ -8,7 +9,6 @@ import ( storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" "github.com/cosmos/ibc-go/v9/modules/core/exported" @@ -27,7 +27,7 @@ import ( // In case 1) before updating the client, the client will be unfrozen by resetting // the FrozenHeight to the zero Height. func (cs ClientState) CheckSubstituteAndUpdateState( - ctx sdk.Context, cdc codec.BinaryCodec, subjectClientStore, + ctx context.Context, cdc codec.BinaryCodec, subjectClientStore, substituteClientStore storetypes.KVStore, substituteClient exported.ClientState, ) error { substituteClientState, ok := substituteClient.(*ClientState) diff --git a/modules/light-clients/07-tendermint/store.go b/modules/light-clients/07-tendermint/store.go index 823ad4c55d8..db6dcc64bb0 100644 --- a/modules/light-clients/07-tendermint/store.go +++ b/modules/light-clients/07-tendermint/store.go @@ -2,6 +2,7 @@ package tendermint import ( "bytes" + "context" "encoding/binary" "fmt" @@ -322,8 +323,9 @@ func bigEndianHeightBytes(height exported.Height) []byte { // as this is internal tendermint light client logic. // client state and consensus state will be set by client keeper // set iteration key to provide ability for efficient ordered iteration of consensus states. -func setConsensusMetadata(ctx sdk.Context, clientStore storetypes.KVStore, height exported.Height) { - setConsensusMetadataWithValues(clientStore, height, clienttypes.GetSelfHeight(ctx), uint64(ctx.BlockTime().UnixNano())) +func setConsensusMetadata(ctx context.Context, clientStore storetypes.KVStore, height exported.Height) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + setConsensusMetadataWithValues(clientStore, height, clienttypes.GetSelfHeight(ctx), uint64(sdkCtx.BlockTime().UnixNano())) } // setConsensusMetadataWithValues sets the consensus metadata with the provided values diff --git a/modules/light-clients/07-tendermint/update.go b/modules/light-clients/07-tendermint/update.go index aa9d03cead6..07b3dc1ec42 100644 --- a/modules/light-clients/07-tendermint/update.go +++ b/modules/light-clients/07-tendermint/update.go @@ -2,6 +2,7 @@ package tendermint import ( "bytes" + "context" "fmt" errorsmod "cosmossdk.io/errors" @@ -21,7 +22,7 @@ import ( // VerifyClientMessage checks if the clientMessage is of type Header or Misbehaviour and verifies the message func (cs *ClientState) VerifyClientMessage( - ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, + ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage, ) error { switch msg := clientMsg.(type) { @@ -43,10 +44,11 @@ func (cs *ClientState) VerifyClientMessage( // - header timestamp is past the trusting period in relation to the consensus state // - header timestamp is less than or equal to the consensus state timestamp func (cs *ClientState) verifyHeader( - ctx sdk.Context, clientStore storetypes.KVStore, cdc codec.BinaryCodec, + ctx context.Context, clientStore storetypes.KVStore, cdc codec.BinaryCodec, header *Header, ) error { - currentTimestamp := ctx.BlockTime() + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + currentTimestamp := sdkCtx.BlockTime() // Retrieve trusted consensus states for each Header in misbehaviour consState, found := GetConsensusState(clientStore, cdc, header.TrustedHeight) @@ -132,7 +134,7 @@ func (cs *ClientState) verifyHeader( // number must be the same. To update to a new revision, use a separate upgrade path // UpdateState will prune the oldest consensus state if it is expired. // If the provided clientMsg is not of type of Header then the handler will noop and empty slice is returned. -func (cs ClientState) UpdateState(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) []exported.Height { +func (cs ClientState) UpdateState(ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) []exported.Height { header, ok := clientMsg.(*Header) if !ok { // clientMsg is invalid Misbehaviour, no update necessary @@ -141,7 +143,8 @@ func (cs ClientState) UpdateState(ctx sdk.Context, cdc codec.BinaryCodec, client // performance: do not prune in checkTx // simulation must prune for accurate gas estimation - if (!ctx.IsCheckTx() && !ctx.IsReCheckTx()) || ctx.ExecMode() == sdk.ExecModeSimulate { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + if (!sdkCtx.IsCheckTx() && !sdkCtx.IsReCheckTx()) || sdkCtx.ExecMode() == sdk.ExecModeSimulate { cs.pruneOldestConsensusState(ctx, cdc, clientStore) } @@ -176,7 +179,7 @@ func (cs ClientState) UpdateState(ctx sdk.Context, cdc codec.BinaryCodec, client // pruneOldestConsensusState will retrieve the earliest consensus state for this clientID and check if it is expired. If it is, // that consensus state will be pruned from store along with all associated metadata. This will prevent the client store from // becoming bloated with expired consensus states that can no longer be used for updates and packet verification. -func (cs ClientState) pruneOldestConsensusState(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore) { +func (cs ClientState) pruneOldestConsensusState(ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore) { // Check the earliest consensus state to see if it is expired, if so then set the prune height // so that we can delete consensus state and all associated metadata. var ( @@ -190,7 +193,8 @@ func (cs ClientState) pruneOldestConsensusState(ctx sdk.Context, cdc codec.Binar panic(errorsmod.Wrapf(clienttypes.ErrConsensusStateNotFound, "failed to retrieve consensus state at height: %s", height)) } - if cs.IsExpired(consState.Timestamp, ctx.BlockTime()) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + if cs.IsExpired(consState.Timestamp, sdkCtx.BlockTime()) { pruneHeight = height } @@ -208,7 +212,7 @@ func (cs ClientState) pruneOldestConsensusState(ctx sdk.Context, cdc codec.Binar // UpdateStateOnMisbehaviour updates state upon misbehaviour, freezing the ClientState. This method should only be called when misbehaviour is detected // as it does not perform any misbehaviour checks. -func (cs ClientState) UpdateStateOnMisbehaviour(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, _ exported.ClientMessage) { +func (cs ClientState) UpdateStateOnMisbehaviour(ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, _ exported.ClientMessage) { cs.FrozenHeight = FrozenHeight clientStore.Set(host.ClientStateKey(), clienttypes.MustMarshalClientState(cdc, &cs)) diff --git a/modules/light-clients/07-tendermint/upgrade.go b/modules/light-clients/07-tendermint/upgrade.go index 398b6652a75..9148b4f7c77 100644 --- a/modules/light-clients/07-tendermint/upgrade.go +++ b/modules/light-clients/07-tendermint/upgrade.go @@ -1,6 +1,7 @@ package tendermint import ( + "context" "fmt" errorsmod "cosmossdk.io/errors" @@ -8,7 +9,6 @@ import ( upgradetypes "cosmossdk.io/x/upgrade/types" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types" commitmenttypes "github.com/cosmos/ibc-go/v9/modules/core/23-commitment/types" @@ -28,7 +28,7 @@ import ( // - any Tendermint chain specified parameter in upgraded client such as ChainID, UnbondingPeriod, // and ProofSpecs do not match parameters set by committed client func (cs ClientState) VerifyUpgradeAndUpdateState( - ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, + ctx context.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, upgradedClient exported.ClientState, upgradedConsState exported.ConsensusState, upgradeClientProof, upgradeConsStateProof []byte, ) error { diff --git a/modules/light-clients/08-wasm/light_client_module.go b/modules/light-clients/08-wasm/light_client_module.go index d9660cec654..cd88887418e 100644 --- a/modules/light-clients/08-wasm/light_client_module.go +++ b/modules/light-clients/08-wasm/light_client_module.go @@ -2,6 +2,7 @@ package wasm import ( "bytes" + "context" "encoding/hex" "encoding/json" "fmt" @@ -38,7 +39,7 @@ func NewLightClientModule(keeper wasmkeeper.Keeper, storeProvider clienttypes.St // Initialize unmarshals the provided client and consensus states and performs basic validation. It sets the client // state and consensus state in the client store. // It also initializes the wasm contract for the client. -func (l LightClientModule) Initialize(ctx sdk.Context, clientID string, clientStateBz, consensusStateBz []byte) error { +func (l LightClientModule) Initialize(ctx context.Context, clientID string, clientStateBz, consensusStateBz []byte) error { var clientState types.ClientState if err := l.keeper.Codec().Unmarshal(clientStateBz, &clientState); err != nil { return err @@ -70,7 +71,8 @@ func (l LightClientModule) Initialize(ctx sdk.Context, clientID string, clientSt Checksum: clientState.Checksum, } - return l.keeper.WasmInstantiate(ctx, clientID, clientStore, &clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return l.keeper.WasmInstantiate(sdkCtx, clientID, clientStore, &clientState, payload) } // VerifyClientMessage obtains the client state associated with the client identifier, it then must verify the ClientMessage. @@ -78,7 +80,7 @@ func (l LightClientModule) Initialize(ctx sdk.Context, clientID string, clientSt // It must handle each type of ClientMessage appropriately. Calls to CheckForMisbehaviour, UpdateState, and UpdateStateOnMisbehaviour // will assume that the content of the ClientMessage has been verified and can be trusted. An error should be returned // if the ClientMessage fails to verify. -func (l LightClientModule) VerifyClientMessage(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) error { +func (l LightClientModule) VerifyClientMessage(ctx context.Context, clientID string, clientMsg exported.ClientMessage) error { clientStore := l.storeProvider.ClientStore(ctx, clientID) cdc := l.keeper.Codec() @@ -95,13 +97,14 @@ func (l LightClientModule) VerifyClientMessage(ctx sdk.Context, clientID string, payload := types.QueryMsg{ VerifyClientMessage: &types.VerifyClientMessageMsg{ClientMessage: clientMessage.Data}, } - _, err := l.keeper.WasmQuery(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, err := l.keeper.WasmQuery(sdkCtx, clientID, clientStore, clientState, payload) return err } // CheckForMisbehaviour obtains the client state associated with the client identifier, it detects misbehaviour in a submitted Header // message and verifies the correctness of a submitted Misbehaviour ClientMessage. -func (l LightClientModule) CheckForMisbehaviour(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) bool { +func (l LightClientModule) CheckForMisbehaviour(ctx context.Context, clientID string, clientMsg exported.ClientMessage) bool { clientStore := l.storeProvider.ClientStore(ctx, clientID) cdc := l.keeper.Codec() @@ -119,7 +122,8 @@ func (l LightClientModule) CheckForMisbehaviour(ctx sdk.Context, clientID string CheckForMisbehaviour: &types.CheckForMisbehaviourMsg{ClientMessage: clientMessage.Data}, } - res, err := l.keeper.WasmQuery(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + res, err := l.keeper.WasmQuery(sdkCtx, clientID, clientStore, clientState, payload) if err != nil { return false } @@ -135,7 +139,7 @@ func (l LightClientModule) CheckForMisbehaviour(ctx sdk.Context, clientID string // UpdateStateOnMisbehaviour obtains the client state associated with the client identifier performs appropriate state changes on // a client state given that misbehaviour has been detected and verified. // Client state is updated in the store by the contract. -func (l LightClientModule) UpdateStateOnMisbehaviour(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) { +func (l LightClientModule) UpdateStateOnMisbehaviour(ctx context.Context, clientID string, clientMsg exported.ClientMessage) { clientStore := l.storeProvider.ClientStore(ctx, clientID) cdc := l.keeper.Codec() @@ -153,7 +157,8 @@ func (l LightClientModule) UpdateStateOnMisbehaviour(ctx sdk.Context, clientID s UpdateStateOnMisbehaviour: &types.UpdateStateOnMisbehaviourMsg{ClientMessage: clientMessage.Data}, } - _, err := l.keeper.WasmSudo(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, err := l.keeper.WasmSudo(sdkCtx, clientID, clientStore, clientState, payload) if err != nil { panic(err) } @@ -161,7 +166,7 @@ func (l LightClientModule) UpdateStateOnMisbehaviour(ctx sdk.Context, clientID s // UpdateState obtains the client state associated with the client identifier and calls into the appropriate // contract endpoint. Client state and new consensus states are updated in the store by the contract. -func (l LightClientModule) UpdateState(ctx sdk.Context, clientID string, clientMsg exported.ClientMessage) []exported.Height { +func (l LightClientModule) UpdateState(ctx context.Context, clientID string, clientMsg exported.ClientMessage) []exported.Height { clientStore := l.storeProvider.ClientStore(ctx, clientID) cdc := l.keeper.Codec() @@ -179,7 +184,8 @@ func (l LightClientModule) UpdateState(ctx sdk.Context, clientID string, clientM UpdateState: &types.UpdateStateMsg{ClientMessage: clientMessage.Data}, } - res, err := l.keeper.WasmSudo(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + res, err := l.keeper.WasmSudo(sdkCtx, clientID, clientStore, clientState, payload) if err != nil { panic(err) } @@ -202,7 +208,7 @@ func (l LightClientModule) UpdateState(ctx sdk.Context, clientID string, clientM // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). // If a zero proof height is passed in, it will fail to retrieve the associated consensus state. func (l LightClientModule) VerifyMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -247,7 +253,8 @@ func (l LightClientModule) VerifyMembership( }, } - _, err := l.keeper.WasmSudo(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, err := l.keeper.WasmSudo(sdkCtx, clientID, clientStore, clientState, payload) return err } @@ -256,7 +263,7 @@ func (l LightClientModule) VerifyMembership( // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). // If a zero proof height is passed in, it will fail to retrieve the associated consensus state. func (l LightClientModule) VerifyNonMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -299,7 +306,8 @@ func (l LightClientModule) VerifyNonMembership( }, } - _, err := l.keeper.WasmSudo(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, err := l.keeper.WasmSudo(sdkCtx, clientID, clientStore, clientState, payload) return err } @@ -313,7 +321,7 @@ func (l LightClientModule) VerifyNonMembership( // // A frozen client will become expired, so the Frozen status // has higher precedence. -func (l LightClientModule) Status(ctx sdk.Context, clientID string) exported.Status { +func (l LightClientModule) Status(ctx context.Context, clientID string) exported.Status { clientStore := l.storeProvider.ClientStore(ctx, clientID) cdc := l.keeper.Codec() @@ -328,7 +336,8 @@ func (l LightClientModule) Status(ctx sdk.Context, clientID string) exported.Sta } payload := types.QueryMsg{Status: &types.StatusMsg{}} - res, err := l.keeper.WasmQuery(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + res, err := l.keeper.WasmQuery(sdkCtx, clientID, clientStore, clientState, payload) if err != nil { return exported.Unknown } @@ -343,7 +352,7 @@ func (l LightClientModule) Status(ctx sdk.Context, clientID string) exported.Sta // LatestHeight returns the latest height for the client state for the given client identifier. // If no client is present for the provided client identifier a zero value height is returned. -func (l LightClientModule) LatestHeight(ctx sdk.Context, clientID string) exported.Height { +func (l LightClientModule) LatestHeight(ctx context.Context, clientID string) exported.Height { clientStore := l.storeProvider.ClientStore(ctx, clientID) cdc := l.keeper.Codec() @@ -357,7 +366,7 @@ func (l LightClientModule) LatestHeight(ctx sdk.Context, clientID string) export // TimestampAtHeight obtains the client state associated with the client identifier and calls into the appropriate contract endpoint. // It returns the timestamp in nanoseconds of the consensus state at the given height. -func (l LightClientModule) TimestampAtHeight(ctx sdk.Context, clientID string, height exported.Height) (uint64, error) { +func (l LightClientModule) TimestampAtHeight(ctx context.Context, clientID string, height exported.Height) (uint64, error) { clientStore := l.storeProvider.ClientStore(ctx, clientID) cdc := l.keeper.Codec() @@ -377,7 +386,8 @@ func (l LightClientModule) TimestampAtHeight(ctx sdk.Context, clientID string, h }, } - res, err := l.keeper.WasmQuery(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + res, err := l.keeper.WasmQuery(sdkCtx, clientID, clientStore, clientState, payload) if err != nil { return 0, errorsmod.Wrapf(err, "height (%s)", height) } @@ -394,7 +404,7 @@ func (l LightClientModule) TimestampAtHeight(ctx sdk.Context, clientID string, h // subject client and calls into the appropriate contract endpoint. // It will verify that a substitute client state is valid and update the subject client state. // Note that this method is used only for recovery and will not allow changes to the checksum. -func (l LightClientModule) RecoverClient(ctx sdk.Context, clientID, substituteClientID string) error { +func (l LightClientModule) RecoverClient(ctx context.Context, clientID, substituteClientID string) error { substituteClientType, _, err := clienttypes.ParseClientIdentifier(substituteClientID) if err != nil { return err @@ -430,7 +440,8 @@ func (l LightClientModule) RecoverClient(ctx sdk.Context, clientID, substituteCl MigrateClientStore: &types.MigrateClientStoreMsg{}, } - _, err = l.keeper.WasmSudo(ctx, clientID, store, subjectClientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, err = l.keeper.WasmSudo(sdkCtx, clientID, store, subjectClientState, payload) return err } @@ -438,7 +449,7 @@ func (l LightClientModule) RecoverClient(ctx sdk.Context, clientID, substituteCl // The new client and consensus states will be unmarshaled and an error is returned if the new client state is not at a height greater // than the existing client. On a successful verification, it expects the contract to update the new client state, consensus state, and any other client metadata. func (l LightClientModule) VerifyUpgradeAndUpdateState( - ctx sdk.Context, + ctx context.Context, clientID string, newClient []byte, newConsState []byte, @@ -478,6 +489,7 @@ func (l LightClientModule) VerifyUpgradeAndUpdateState( }, } - _, err := l.keeper.WasmSudo(ctx, clientID, clientStore, clientState, payload) + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + _, err := l.keeper.WasmSudo(sdkCtx, clientID, clientStore, clientState, payload) return err } diff --git a/modules/light-clients/08-wasm/testing/simapp/app.go b/modules/light-clients/08-wasm/testing/simapp/app.go index 1ebf3d9fd35..f4538807337 100644 --- a/modules/light-clients/08-wasm/testing/simapp/app.go +++ b/modules/light-clients/08-wasm/testing/simapp/app.go @@ -412,7 +412,7 @@ func NewSimApp( app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String()) app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, keys[ibcexported.StoreKey], app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, runtime.NewKVStoreService(keys[ibcexported.StoreKey]), app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) govConfig := govtypes.DefaultConfig() @@ -475,7 +475,7 @@ func NewSimApp( // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], + appCodec, runtime.NewKVStoreService(keys[ibcfeetypes.StoreKey]), app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware app.IBCKeeper.ChannelKeeper, app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, diff --git a/modules/light-clients/08-wasm/types/expected_keepers.go b/modules/light-clients/08-wasm/types/expected_keepers.go index a9f8d40872e..a0a469b4c40 100644 --- a/modules/light-clients/08-wasm/types/expected_keepers.go +++ b/modules/light-clients/08-wasm/types/expected_keepers.go @@ -1,16 +1,16 @@ package types import ( - storetypes "cosmossdk.io/store/types" + "context" - sdk "github.com/cosmos/cosmos-sdk/types" + storetypes "cosmossdk.io/store/types" "github.com/cosmos/ibc-go/v9/modules/core/exported" ) // ClientKeeper defines the expected client keeper type ClientKeeper interface { - ClientStore(ctx sdk.Context, clientID string) storetypes.KVStore - GetClientState(ctx sdk.Context, clientID string) (exported.ClientState, bool) - SetClientState(ctx sdk.Context, clientID string, clientState exported.ClientState) + ClientStore(ctx context.Context, clientID string) storetypes.KVStore + GetClientState(ctx context.Context, clientID string) (exported.ClientState, bool) + SetClientState(ctx context.Context, clientID string, clientState exported.ClientState) } diff --git a/modules/light-clients/09-localhost/light_client_module.go b/modules/light-clients/09-localhost/light_client_module.go index 3095503d985..d18cbce8eef 100644 --- a/modules/light-clients/09-localhost/light_client_module.go +++ b/modules/light-clients/09-localhost/light_client_module.go @@ -2,9 +2,10 @@ package localhost import ( "bytes" + "context" + corestore "cosmossdk.io/core/store" errorsmod "cosmossdk.io/errors" - storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -32,40 +33,40 @@ var _ exported.LightClientModule = (*LightClientModule)(nil) // LightClientModule implements the core IBC api.LightClientModule interface. type LightClientModule struct { - cdc codec.BinaryCodec - key storetypes.StoreKey + cdc codec.BinaryCodec + storeService corestore.KVStoreService } // NewLightClientModule creates and returns a new 09-localhost LightClientModule. -func NewLightClientModule(cdc codec.BinaryCodec, key storetypes.StoreKey) *LightClientModule { +func NewLightClientModule(cdc codec.BinaryCodec, storeService corestore.KVStoreService) *LightClientModule { return &LightClientModule{ - cdc: cdc, - key: key, + cdc: cdc, + storeService: storeService, } } // Initialize returns an error because it is stateless. -func (LightClientModule) Initialize(_ sdk.Context, _ string, _, _ []byte) error { +func (LightClientModule) Initialize(_ context.Context, _ string, _, _ []byte) error { return errorsmod.Wrap(clienttypes.ErrClientExists, "localhost is stateless and cannot be initialized") } // VerifyClientMessage is unsupported by the 09-localhost client type and returns an error. -func (LightClientModule) VerifyClientMessage(_ sdk.Context, _ string, _ exported.ClientMessage) error { +func (LightClientModule) VerifyClientMessage(_ context.Context, _ string, _ exported.ClientMessage) error { return errorsmod.Wrap(clienttypes.ErrUpdateClientFailed, "client message verification is unsupported by the localhost client") } // CheckForMisbehaviour is unsupported by the 09-localhost client type and performs a no-op, returning false. -func (LightClientModule) CheckForMisbehaviour(_ sdk.Context, _ string, _ exported.ClientMessage) bool { +func (LightClientModule) CheckForMisbehaviour(_ context.Context, _ string, _ exported.ClientMessage) bool { return false } // UpdateStateOnMisbehaviour is unsupported by the 09-localhost client type and performs a no-op. -func (LightClientModule) UpdateStateOnMisbehaviour(_ sdk.Context, _ string, _ exported.ClientMessage) { +func (LightClientModule) UpdateStateOnMisbehaviour(_ context.Context, _ string, _ exported.ClientMessage) { // no-op } // UpdateState performs a no-op and returns the context height in the updated heights return value. -func (LightClientModule) UpdateState(ctx sdk.Context, _ string, _ exported.ClientMessage) []exported.Height { +func (LightClientModule) UpdateState(ctx context.Context, _ string, _ exported.ClientMessage) []exported.Height { return []exported.Height{clienttypes.GetSelfHeight(ctx)} } @@ -73,7 +74,7 @@ func (LightClientModule) UpdateState(ctx sdk.Context, _ string, _ exported.Clien // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). // The caller must provide the full IBC store. func (l LightClientModule) VerifyMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -82,7 +83,7 @@ func (l LightClientModule) VerifyMembership( path exported.Path, value []byte, ) error { - ibcStore := ctx.KVStore(l.key) + ibcStore := l.storeService.OpenKVStore(ctx) // ensure the proof provided is the expected sentinel localhost client proof if !bytes.Equal(proof, SentinelProof) { @@ -99,7 +100,10 @@ func (l LightClientModule) VerifyMembership( } // The commitment prefix (eg: "ibc") is omitted when operating on the core IBC store - bz := ibcStore.Get(merklePath.KeyPath[1]) + bz, err := ibcStore.Get(merklePath.KeyPath[1]) + if err != nil { + panic(err) + } if bz == nil { return errorsmod.Wrapf(clienttypes.ErrFailedMembershipVerification, "value not found for path %s", path) } @@ -115,7 +119,7 @@ func (l LightClientModule) VerifyMembership( // The caller is expected to construct the full CommitmentPath from a CommitmentPrefix and a standardized path (as defined in ICS 24). // The caller must provide the full IBC store. func (l LightClientModule) VerifyNonMembership( - ctx sdk.Context, + ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, @@ -123,7 +127,7 @@ func (l LightClientModule) VerifyNonMembership( proof []byte, path exported.Path, ) error { - ibcStore := ctx.KVStore(l.key) + ibcStore := l.storeService.OpenKVStore(ctx) // ensure the proof provided is the expected sentinel localhost client proof if !bytes.Equal(proof, SentinelProof) { @@ -140,7 +144,11 @@ func (l LightClientModule) VerifyNonMembership( } // The commitment prefix (eg: "ibc") is omitted when operating on the core IBC store - if ibcStore.Has(merklePath.KeyPath[1]) { + has, err := ibcStore.Has(merklePath.KeyPath[1]) + if err != nil { + return errorsmod.Wrapf(err, "error checking for value for path %s", path) + } + if has { return errorsmod.Wrapf(clienttypes.ErrFailedNonMembershipVerification, "value found for path %s", path) } @@ -148,27 +156,28 @@ func (l LightClientModule) VerifyNonMembership( } // Status always returns Active. The 09-localhost status cannot be changed. -func (LightClientModule) Status(_ sdk.Context, _ string) exported.Status { +func (LightClientModule) Status(_ context.Context, _ string) exported.Status { return exported.Active } // LatestHeight returns the context height. -func (LightClientModule) LatestHeight(ctx sdk.Context, _ string) exported.Height { +func (LightClientModule) LatestHeight(ctx context.Context, _ string) exported.Height { return clienttypes.GetSelfHeight(ctx) } // TimestampAtHeight returns the current block time retrieved from the application context. The localhost client does not store consensus states and thus // cannot provide a timestamp for the provided height. -func (LightClientModule) TimestampAtHeight(ctx sdk.Context, _ string, _ exported.Height) (uint64, error) { - return uint64(ctx.BlockTime().UnixNano()), nil +func (LightClientModule) TimestampAtHeight(ctx context.Context, _ string, _ exported.Height) (uint64, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: https://github.com/cosmos/ibc-go/issues/5917 + return uint64(sdkCtx.BlockTime().UnixNano()), nil } // RecoverClient returns an error. The localhost cannot be modified by proposals. -func (LightClientModule) RecoverClient(_ sdk.Context, _, _ string) error { +func (LightClientModule) RecoverClient(_ context.Context, _, _ string) error { return errorsmod.Wrap(clienttypes.ErrUpdateClientFailed, "cannot update localhost client with a proposal") } // VerifyUpgradeAndUpdateState returns an error since localhost cannot be upgraded. -func (LightClientModule) VerifyUpgradeAndUpdateState(_ sdk.Context, _ string, _, _, _, _ []byte) error { +func (LightClientModule) VerifyUpgradeAndUpdateState(_ context.Context, _ string, _, _, _, _ []byte) error { return errorsmod.Wrap(clienttypes.ErrInvalidUpgradeClient, "cannot upgrade localhost client") } diff --git a/simapp/app.go b/simapp/app.go index c40fc75e681..9d8e4fd7d63 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -404,7 +404,7 @@ func NewSimApp( app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String()) app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, keys[ibcexported.StoreKey], app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, runtime.NewKVStoreService(keys[ibcexported.StoreKey]), app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) govConfig := govtypes.DefaultConfig() @@ -425,7 +425,7 @@ func NewSimApp( // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], + appCodec, runtime.NewKVStoreService(keys[ibcfeetypes.StoreKey]), app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware app.IBCKeeper.ChannelKeeper, app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, diff --git a/testing/mock/ibc_module.go b/testing/mock/ibc_module.go index 03c21ffce4a..d96abb5bf1c 100644 --- a/testing/mock/ibc_module.go +++ b/testing/mock/ibc_module.go @@ -2,6 +2,7 @@ package mock import ( "bytes" + "context" "fmt" "reflect" "strconv" @@ -219,7 +220,7 @@ func (im IBCModule) OnChanUpgradeOpen(ctx sdk.Context, portID, channelID string, // UnmarshalPacketData returns the MockPacketData. This function implements the optional // PacketDataUnmarshaler interface required for ADR 008 support. -func (IBCModule) UnmarshalPacketData(ctx sdk.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { +func (IBCModule) UnmarshalPacketData(ctx context.Context, portID string, channelID string, bz []byte) (interface{}, string, error) { if reflect.DeepEqual(bz, MockPacketData) { return MockPacketData, Version, nil } diff --git a/testing/mock/middleware.go b/testing/mock/middleware.go index 6d6a33a1a1f..c0949fa5f67 100644 --- a/testing/mock/middleware.go +++ b/testing/mock/middleware.go @@ -2,6 +2,7 @@ package mock import ( "bytes" + "context" "strings" sdk "github.com/cosmos/cosmos-sdk/types" @@ -170,7 +171,7 @@ func (im BlockUpgradeMiddleware) OnTimeoutPacket(ctx sdk.Context, channelVersion // SendPacket implements the ICS4 Wrapper interface func (BlockUpgradeMiddleware) SendPacket( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, @@ -183,7 +184,7 @@ func (BlockUpgradeMiddleware) SendPacket( // WriteAcknowledgement implements the ICS4 Wrapper interface func (BlockUpgradeMiddleware) WriteAcknowledgement( - ctx sdk.Context, + ctx context.Context, chanCap *capabilitytypes.Capability, packet exported.PacketI, ack exported.Acknowledgement, @@ -192,6 +193,6 @@ func (BlockUpgradeMiddleware) WriteAcknowledgement( } // GetAppVersion returns the application version of the underlying application -func (BlockUpgradeMiddleware) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { +func (BlockUpgradeMiddleware) GetAppVersion(ctx context.Context, portID, channelID string) (string, bool) { return Version, true } diff --git a/testing/mock/mock.go b/testing/mock/mock.go index 150900664b2..17055eda29e 100644 --- a/testing/mock/mock.go +++ b/testing/mock/mock.go @@ -1,6 +1,7 @@ package mock import ( + "context" "encoding/json" "errors" "fmt" @@ -67,8 +68,8 @@ var ( // Expected Interface // PortKeeper defines the expected IBC port keeper type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability - IsBound(ctx sdk.Context, portID string) bool + BindPort(ctx context.Context, portID string) *capabilitytypes.Capability + IsBound(ctx context.Context, portID string) bool } // AppModuleBasic is the mock AppModuleBasic. diff --git a/testing/simapp/app.go b/testing/simapp/app.go index 6ebf791d319..ad986106660 100644 --- a/testing/simapp/app.go +++ b/testing/simapp/app.go @@ -367,7 +367,7 @@ func NewSimApp( app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String()) app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, keys[ibcexported.StoreKey], app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appCodec, runtime.NewKVStoreService(keys[ibcexported.StoreKey]), app.GetSubspace(ibcexported.ModuleName), app.UpgradeKeeper, scopedIBCKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) govConfig := govtypes.DefaultConfig() @@ -388,7 +388,7 @@ func NewSimApp( // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], + appCodec, runtime.NewKVStoreService(keys[ibcfeetypes.StoreKey]), app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware app.IBCKeeper.ChannelKeeper, app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper,