diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d2142e26abf..2d68c1cee013 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -111,6 +111,7 @@ if the provided arguments are invalid. the `client/keys` add command. * `SupportedAlgos` and `SupportedAlgosLedger` functions return a slice of `SigningAlgo`s that are supported by the keybase and the ledger integration respectively. + * The option introduced in this PR is `WithKeygenFunc` which allows a custom bytes to key implementation to be defined when keys are created. * (simapp) [\#5419](https://github.com/cosmos/cosmos-sdk/pull/5419) simapp/helpers.GenTx() now accepts a gas argument. * (baseapp) [\#5455](https://github.com/cosmos/cosmos-sdk/issues/5455) An `sdk.Context` is passed into the `router.Route()` function. @@ -261,8 +262,11 @@ to detail this new feature and how state transitions occur. * (docs/interfaces/) Add documentation on building interfaces for the Cosmos SDK. * Redesigned user interface that features new dynamically generated sidebar, build-time code embedding from GitHub, new homepage as well as many other improvements. * (types) [\#5428](https://github.com/cosmos/cosmos-sdk/pull/5428) Add `Mod` (modulo) method and `RelativePow` (exponentation) function for `Uint`. +<<<<<<< HEAD * (modules) [\#5506](https://github.com/cosmos/cosmos-sdk/pull/5506) Remove redundancy in `x/distribution`s use of parameters. There now exists a single `Params` type with a getter and setter along with a getter for each individual parameter. +======= +>>>>>>> Update x/ibc error handling (#5462) ### Bug Fixes @@ -2866,3 +2870,5 @@ BUG FIXES: [v0.37.1]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.37.1 [v0.37.0]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.37.0 [v0.36.0]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.36.0 + + diff --git a/simapp/app.go b/simapp/app.go index 4a46d34e07dd..eac5db297345 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -232,7 +232,7 @@ func NewSimApp( staking.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), ) - app.IBCKeeper = ibc.NewKeeper(app.cdc, keys[ibc.StoreKey], ibc.DefaultCodespace, app.BankKeeper, app.SupplyKeeper) + app.IBCKeeper = ibc.NewKeeper(app.cdc, keys[ibc.StoreKey], app.BankKeeper, app.SupplyKeeper) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. diff --git a/types/result.go b/types/result.go index 7ef9a1775e3a..9530be01d25c 100644 --- a/types/result.go +++ b/types/result.go @@ -85,15 +85,6 @@ type TxResponse struct { Timestamp string `json:"timestamp,omitempty"` } -func (res TxResponse) IsOK() bool { - for _, lg := range res.Logs { - if !lg.Success { - return false - } - } - return true -} - // NewResponseResultTx returns a TxResponse given a ResultTx from tendermint func NewResponseResultTx(res *ctypes.ResultTx, tx Tx, timestamp string) TxResponse { if res == nil { diff --git a/x/ibc/02-client/alias.go b/x/ibc/02-client/alias.go index 02f3aa623668..d818bbb99572 100644 --- a/x/ibc/02-client/alias.go +++ b/x/ibc/02-client/alias.go @@ -13,26 +13,15 @@ import ( ) const ( - DefaultCodespace = errors.DefaultCodespace - CodeClientExists = errors.CodeClientExists - CodeClientNotFound = errors.CodeClientNotFound - CodeClientFrozen = errors.CodeClientFrozen - CodeConsensusStateNotFound = errors.CodeConsensusStateNotFound - CodeInvalidConsensusState = errors.CodeInvalidConsensusState - CodeClientTypeNotFound = errors.CodeClientTypeNotFound - CodeInvalidClientType = errors.CodeInvalidClientType - CodeRootNotFound = errors.CodeRootNotFound - CodeInvalidHeader = errors.CodeInvalidHeader - CodeInvalidEvidence = errors.CodeInvalidEvidence - AttributeKeyClientID = types.AttributeKeyClientID - SubModuleName = types.SubModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute - QueryAllClients = types.QueryAllClients - QueryClientState = types.QueryClientState - QueryConsensusState = types.QueryConsensusState - QueryVerifiedRoot = types.QueryVerifiedRoot + AttributeKeyClientID = types.AttributeKeyClientID + SubModuleName = types.SubModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + QueryAllClients = types.QueryAllClients + QueryClientState = types.QueryClientState + QueryConsensusState = types.QueryConsensusState + QueryVerifiedRoot = types.QueryVerifiedRoot ) var ( diff --git a/x/ibc/02-client/client/cli/cli.go b/x/ibc/02-client/client/cli/cli.go index d2db4d2be958..4a36894faf35 100644 --- a/x/ibc/02-client/client/cli/cli.go +++ b/x/ibc/02-client/client/cli/cli.go @@ -3,7 +3,7 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" ) @@ -16,7 +16,7 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { SuggestionsMinimumDistance: 2, } - ics02ClientQueryCmd.AddCommand(client.GetCommands( + ics02ClientQueryCmd.AddCommand(flags.GetCommands( GetCmdQueryClientStates(queryRoute, cdc), GetCmdQueryClientState(queryRoute, cdc), GetCmdQueryConsensusState(queryRoute, cdc), @@ -37,7 +37,7 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { SuggestionsMinimumDistance: 2, } - ics02ClientTxCmd.AddCommand(client.PostCommands( + ics02ClientTxCmd.AddCommand(flags.PostCommands( GetCmdCreateClient(cdc), GetCmdUpdateClient(cdc), )...) diff --git a/x/ibc/02-client/client/utils/utils.go b/x/ibc/02-client/client/utils/utils.go index 848d489b2308..02f1163b3d32 100644 --- a/x/ibc/02-client/client/utils/utils.go +++ b/x/ibc/02-client/client/utils/utils.go @@ -6,7 +6,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types/tendermint" @@ -62,10 +61,10 @@ func QueryClientState( return clientStateRes, nil } -// QueryConsensusStateProof queries the store to get the consensus state and a -// merkle proof. +// QueryConsensusState queries the store to get the consensus state and a merkle +// proof. func QueryConsensusState( - cliCtx client.CLIContext, clientID string, prove bool) (types.ConsensusStateResponse, error) { + cliCtx context.CLIContext, clientID string, prove bool) (types.ConsensusStateResponse, error) { var conStateRes types.ConsensusStateResponse req := abci.RequestQuery{ diff --git a/x/ibc/02-client/handler.go b/x/ibc/02-client/handler.go index 7363053f2319..0525e115a014 100644 --- a/x/ibc/02-client/handler.go +++ b/x/ibc/02-client/handler.go @@ -1,9 +1,8 @@ package client import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/evidence" evidenceexported "github.com/cosmos/cosmos-sdk/x/evidence/exported" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" @@ -11,17 +10,15 @@ import ( ) // HandleMsgCreateClient defines the sdk.Handler for MsgCreateClient -func HandleMsgCreateClient(ctx sdk.Context, k Keeper, msg MsgCreateClient) sdk.Result { +func HandleMsgCreateClient(ctx sdk.Context, k Keeper, msg MsgCreateClient) (*sdk.Result, error) { clientType := exported.ClientTypeFromString(msg.ClientType) if clientType == 0 { - return sdk.ResultFromError( - ErrInvalidClientType(DefaultCodespace, fmt.Sprintf("invalid client type '%s'", msg.ClientType)), - ) + return nil, sdkerrors.Wrap(ErrInvalidClientType, msg.ClientType) } _, err := k.CreateClient(ctx, msg.ClientID, clientType, msg.ConsensusState) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -36,14 +33,16 @@ func HandleMsgCreateClient(ctx sdk.Context, k Keeper, msg MsgCreateClient) sdk.R ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgUpdateClient defines the sdk.Handler for MsgUpdateClient -func HandleMsgUpdateClient(ctx sdk.Context, k Keeper, msg MsgUpdateClient) sdk.Result { +func HandleMsgUpdateClient(ctx sdk.Context, k Keeper, msg MsgUpdateClient) (*sdk.Result, error) { err := k.UpdateClient(ctx, msg.ClientID, msg.Header) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -58,7 +57,9 @@ func HandleMsgUpdateClient(ctx sdk.Context, k Keeper, msg MsgUpdateClient) sdk.R ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandlerClientMisbehaviour defines the Evidence module handler for submitting a @@ -70,8 +71,7 @@ func HandlerClientMisbehaviour(k Keeper) evidence.Handler { return k.CheckMisbehaviourAndUpdateState(ctx, evidence) default: - errMsg := fmt.Sprintf("unrecognized IBC client evidence type: %T", e) - return sdk.ErrUnknownRequest(errMsg) + return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized IBC client evidence type: %T", e) } } } diff --git a/x/ibc/02-client/keeper/client.go b/x/ibc/02-client/keeper/client.go index 9b72ef4a2c2c..91cadfe4a016 100644 --- a/x/ibc/02-client/keeper/client.go +++ b/x/ibc/02-client/keeper/client.go @@ -20,7 +20,7 @@ func (k Keeper) CreateClient( ) (types.State, error) { _, found := k.GetClientState(ctx, clientID) if found { - return types.State{}, errors.ErrClientExists(k.codespace, clientID) + return types.State{}, sdkerrors.Wrapf(errors.ErrClientExists, "cannot create client with ID %s", clientID) } _, found = k.GetClientType(ctx, clientID) @@ -41,31 +41,31 @@ func (k Keeper) CreateClient( func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.Header) error { clientType, found := k.GetClientType(ctx, clientID) if !found { - return sdkerrors.Wrap(errors.ErrClientTypeNotFound(k.codespace), "cannot update client") + return sdkerrors.Wrapf(errors.ErrClientTypeNotFound, "cannot update client with ID %s", clientID) } // check that the header consensus matches the client one if header.ClientType() != clientType { - return sdkerrors.Wrap(errors.ErrInvalidConsensus(k.codespace), "cannot update client") + return sdkerrors.Wrapf(errors.ErrInvalidConsensus, "cannot update client with ID %s", clientID) } clientState, found := k.GetClientState(ctx, clientID) if !found { - return sdkerrors.Wrap(errors.ErrClientNotFound(k.codespace, clientID), "cannot update client") + return sdkerrors.Wrapf(errors.ErrClientNotFound, "cannot update client with ID %s", clientID) } if clientState.Frozen { - return sdkerrors.Wrap(errors.ErrClientFrozen(k.codespace, clientID), "cannot update client") + return sdkerrors.Wrapf(errors.ErrClientFrozen, "cannot update client with ID %s", clientID) } consensusState, found := k.GetConsensusState(ctx, clientID) if !found { - return sdkerrors.Wrap(errors.ErrConsensusStateNotFound(k.codespace), "cannot update client") + return sdkerrors.Wrapf(errors.ErrConsensusStateNotFound, "cannot update client with ID %s", clientID) } consensusState, err := consensusState.CheckValidityAndUpdateState(header) if err != nil { - return sdkerrors.Wrap(err, "cannot update client") + return sdkerrors.Wrapf(err, "cannot update client with ID %s", clientID) } k.SetConsensusState(ctx, clientID, consensusState) @@ -83,25 +83,25 @@ func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.H func (k Keeper) CheckMisbehaviourAndUpdateState(ctx sdk.Context, evidence evidenceexported.Evidence) error { misbehaviour, ok := evidence.(tendermint.Misbehaviour) if !ok { - return errors.ErrInvalidClientType(k.codespace, "consensus type is not Tendermint") + return sdkerrors.Wrap(errors.ErrInvalidClientType, "consensus type is not Tendermint") } clientState, found := k.GetClientState(ctx, misbehaviour.ClientID) if !found { - return errors.ErrClientNotFound(k.codespace, misbehaviour.ClientID) + return sdkerrors.Wrap(errors.ErrClientNotFound, misbehaviour.ClientID) } committer, found := k.GetCommitter(ctx, misbehaviour.ClientID, uint64(misbehaviour.GetHeight())) if !found { - return errors.ErrCommitterNotFound(k.codespace, fmt.Sprintf("committer not found for height %d", misbehaviour.GetHeight())) + return errors.ErrCommitterNotFound } tmCommitter, ok := committer.(tendermint.Committer) if !ok { - return errors.ErrInvalidCommitter(k.codespace, "committer type is not Tendermint") + return sdkerrors.Wrap(errors.ErrInvalidCommitter, "committer type is not Tendermint") } if err := tendermint.CheckMisbehaviour(tmCommitter, misbehaviour); err != nil { - return errors.ErrInvalidEvidence(k.codespace, err.Error()) + return sdkerrors.Wrap(errors.ErrInvalidEvidence, err.Error()) } clientState, err := k.freeze(ctx, clientState) diff --git a/x/ibc/02-client/keeper/keeper.go b/x/ibc/02-client/keeper/keeper.go index a8b1876d1e41..5732913247b3 100644 --- a/x/ibc/02-client/keeper/keeper.go +++ b/x/ibc/02-client/keeper/keeper.go @@ -18,17 +18,15 @@ import ( // Keeper represents a type that grants read and write permissions to any client // state information type Keeper struct { - storeKey sdk.StoreKey - cdc *codec.Codec - codespace sdk.CodespaceType + storeKey sdk.StoreKey + cdc *codec.Codec } // NewKeeper creates a new NewKeeper instance -func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Keeper { +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { return Keeper{ - storeKey: key, - cdc: cdc, - codespace: sdk.CodespaceType(fmt.Sprintf("%s/%s", codespace, errors.DefaultCodespace)), // "ibc/client", + storeKey: key, + cdc: cdc, } } @@ -181,7 +179,7 @@ func (k Keeper) initialize(ctx sdk.Context, clientID string, consensusState expo // freeze updates the state of the client in the event of a misbehaviour func (k Keeper) freeze(ctx sdk.Context, clientState types.State) (types.State, error) { if clientState.Frozen { - return types.State{}, sdkerrors.Wrap(errors.ErrClientFrozen(k.codespace, clientState.ID), "already frozen") + return types.State{}, sdkerrors.Wrap(errors.ErrClientFrozen, clientState.ID) } clientState.Frozen = true diff --git a/x/ibc/02-client/keeper/querier.go b/x/ibc/02-client/keeper/querier.go index 104ad554c700..87da8c1eea5f 100644 --- a/x/ibc/02-client/keeper/querier.go +++ b/x/ibc/02-client/keeper/querier.go @@ -1,8 +1,6 @@ package keeper import ( - "fmt" - abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client" @@ -48,7 +46,7 @@ func QuerierClientState(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byt clientState, found := k.GetClientState(ctx, params.ClientID) if !found { - return nil, errors.ErrClientTypeNotFound(k.codespace) + return nil, sdkerrors.Wrap(errors.ErrClientTypeNotFound, params.ClientID) } bz, err := codec.MarshalJSONIndent(k.cdc, clientState) @@ -69,7 +67,7 @@ func QuerierConsensusState(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([] consensusState, found := k.GetConsensusState(ctx, params.ClientID) if !found { - return nil, errors.ErrConsensusStateNotFound(k.codespace) + return nil, errors.ErrConsensusStateNotFound } bz, err := codec.MarshalJSONIndent(k.cdc, consensusState) @@ -90,7 +88,7 @@ func QuerierVerifiedRoot(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]by root, found := k.GetVerifiedRoot(ctx, params.ClientID, params.Height) if !found { - return nil, errors.ErrRootNotFound(k.codespace) + return nil, errors.ErrRootNotFound } bz, err := codec.MarshalJSONIndent(k.cdc, root) @@ -111,10 +109,7 @@ func QuerierCommitter(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, committer, found := k.GetCommitter(ctx, params.ClientID, params.Height) if !found { - return nil, errors.ErrCommitterNotFound( - k.codespace, - fmt.Sprintf("committer not found on height: %d", params.Height), - ) + return nil, errors.ErrCommitterNotFound } bz, err := codec.MarshalJSONIndent(k.cdc, committer) diff --git a/x/ibc/02-client/types/errors/errors.go b/x/ibc/02-client/types/errors/errors.go index 1a7272ca1fcb..b6786a6113f6 100644 --- a/x/ibc/02-client/types/errors/errors.go +++ b/x/ibc/02-client/types/errors/errors.go @@ -1,134 +1,24 @@ package errors import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// client error codes -const ( - DefaultCodespace sdk.CodespaceType = "client" - - CodeClientExists sdk.CodeType = 200 - CodeClientNotFound sdk.CodeType = 201 - CodeClientFrozen sdk.CodeType = 202 - CodeConsensusStateNotFound sdk.CodeType = 203 - CodeInvalidConsensusState sdk.CodeType = 204 - CodeClientTypeNotFound sdk.CodeType = 205 - CodeInvalidClientType sdk.CodeType = 206 - CodeRootNotFound sdk.CodeType = 207 - CodeInvalidHeader sdk.CodeType = 208 - CodeInvalidEvidence sdk.CodeType = 209 - CodeCommitterNotFound sdk.CodeType = 210 - CodeInvalidCommitter sdk.CodeType = 211 +// SubModuleName is the error codespace +const SubModuleName string = "ibc/client" + +// IBC client sentinel errors +var ( + ErrClientExists = sdkerrors.Register(SubModuleName, 1, "light client already exists") + ErrClientNotFound = sdkerrors.Register(SubModuleName, 2, "light client not found") + ErrClientFrozen = sdkerrors.Register(SubModuleName, 3, "light client is frozen due to misbehaviour") + ErrConsensusStateNotFound = sdkerrors.Register(SubModuleName, 4, "consensus state not found") + ErrInvalidConsensus = sdkerrors.Register(SubModuleName, 5, "invalid consensus state") + ErrClientTypeNotFound = sdkerrors.Register(SubModuleName, 6, "client type not found") + ErrInvalidClientType = sdkerrors.Register(SubModuleName, 7, "invalid client type") + ErrRootNotFound = sdkerrors.Register(SubModuleName, 8, "commitment root not found") + ErrInvalidHeader = sdkerrors.Register(SubModuleName, 9, "invalid block header") + ErrInvalidEvidence = sdkerrors.Register(SubModuleName, 10, "invalid light client misbehaviour evidence") + ErrCommitterNotFound = sdkerrors.Register(SubModuleName, 11, "commiter not found") + ErrInvalidCommitter = sdkerrors.Register(SubModuleName, 12, "invalid commiter") ) - -// ErrClientExists implements sdk.Error -func ErrClientExists(codespace sdk.CodespaceType, clientID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeClientExists), - fmt.Sprintf("client with ID %s already exists", clientID), - ) -} - -// ErrClientNotFound implements sdk.Error -func ErrClientNotFound(codespace sdk.CodespaceType, clientID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeClientNotFound), - fmt.Sprintf("client with ID %s not found", clientID), - ) -} - -// ErrClientFrozen implements sdk.Error -func ErrClientFrozen(codespace sdk.CodespaceType, clientID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeClientFrozen), - fmt.Sprintf("client with ID %s is frozen due to misbehaviour", clientID), - ) -} - -// ErrConsensusStateNotFound implements sdk.Error -func ErrConsensusStateNotFound(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeConsensusStateNotFound), - "consensus state not found", - ) -} - -// ErrInvalidConsensus implements sdk.Error -func ErrInvalidConsensus(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidConsensusState), - "invalid consensus state", - ) -} - -// ErrClientTypeNotFound implements sdk.Error -func ErrClientTypeNotFound(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeClientTypeNotFound), - "client type not found", - ) -} - -// ErrInvalidClientType implements sdk.Error -func ErrInvalidClientType(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidClientType), - msg, - ) -} - -// ErrRootNotFound implements sdk.Error -func ErrRootNotFound(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeRootNotFound), - "commitment root not found", - ) -} - -// ErrInvalidHeader implements sdk.Error -func ErrInvalidHeader(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidHeader), - "invalid header", - ) -} - -// ErrInvalidEvidence implements sdk.Error -func ErrInvalidEvidence(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidEvidence), - fmt.Sprintf("invalid evidence: %s", msg), - ) -} - -// ErrCommitterNotFound implements sdk.Error -func ErrCommitterNotFound(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeCommitterNotFound), - fmt.Sprintf("invalid evidence: %s", msg), - ) -} - -// ErrInvalidEvidence implements sdk.Error -func ErrInvalidCommitter(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidCommitter), - fmt.Sprintf("invalid evidence: %s", msg), - ) -} diff --git a/x/ibc/02-client/types/msgs.go b/x/ibc/02-client/types/msgs.go index d52c0a614a44..128c76e4144b 100644 --- a/x/ibc/02-client/types/msgs.go +++ b/x/ibc/02-client/types/msgs.go @@ -1,9 +1,8 @@ package types import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" evidenceexported "github.com/cosmos/cosmos-sdk/x/evidence/exported" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types/errors" @@ -49,22 +48,17 @@ func (msg MsgCreateClient) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgCreateClient) ValidateBasic() sdk.Error { - if err := host.DefaultClientIdentifierValidator(msg.ClientID); err != nil { - return sdk.ConvertError(err) - } +func (msg MsgCreateClient) ValidateBasic() error { if clientType := exported.ClientTypeFromString(msg.ClientType); clientType == 0 { - return sdk.ConvertError( - errors.ErrInvalidClientType(errors.DefaultCodespace, fmt.Sprintf("invalid client type '%s'", msg.ClientType)), - ) + return sdkerrors.Wrap(errors.ErrInvalidClientType, msg.ClientType) } if msg.ConsensusState == nil { - return sdk.ConvertError(errors.ErrInvalidConsensus(errors.DefaultCodespace)) + return errors.ErrInvalidConsensus } if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("empty address") + return sdkerrors.ErrInvalidAddress } - return nil + return host.DefaultClientIdentifierValidator(msg.ClientID) } // GetSignBytes implements sdk.Msg @@ -106,17 +100,14 @@ func (msg MsgUpdateClient) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgUpdateClient) ValidateBasic() sdk.Error { - if err := host.DefaultClientIdentifierValidator(msg.ClientID); err != nil { - return sdk.ConvertError(err) - } +func (msg MsgUpdateClient) ValidateBasic() error { if msg.Header == nil { - return sdk.ConvertError(errors.ErrInvalidHeader(errors.DefaultCodespace)) + return errors.ErrInvalidHeader } if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("empty address") + return sdkerrors.ErrInvalidAddress } - return nil + return host.DefaultClientIdentifierValidator(msg.ClientID) } // GetSignBytes implements sdk.Msg @@ -156,20 +147,17 @@ func (msg MsgSubmitMisbehaviour) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgSubmitMisbehaviour) ValidateBasic() sdk.Error { - if err := host.DefaultClientIdentifierValidator(msg.ClientID); err != nil { - return sdk.ConvertError(err) - } +func (msg MsgSubmitMisbehaviour) ValidateBasic() error { if msg.Evidence == nil { - return sdk.ConvertError(errors.ErrInvalidEvidence(errors.DefaultCodespace, "evidence is nil")) + return sdkerrors.Wrap(errors.ErrInvalidEvidence, "evidence cannot be nil") } if err := msg.Evidence.ValidateBasic(); err != nil { - return sdk.ConvertError(errors.ErrInvalidEvidence(errors.DefaultCodespace, err.Error())) + return sdkerrors.Wrap(errors.ErrInvalidEvidence, err.Error()) } if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("empty address") + return sdkerrors.ErrInvalidAddress } - return nil + return host.DefaultClientIdentifierValidator(msg.ClientID) } // GetSignBytes implements sdk.Msg diff --git a/x/ibc/02-client/types/msgs_test.go b/x/ibc/02-client/types/msgs_test.go index b29633420ed4..844276b3ae6b 100644 --- a/x/ibc/02-client/types/msgs_test.go +++ b/x/ibc/02-client/types/msgs_test.go @@ -38,7 +38,7 @@ type mockBadEvidence struct { // Override ValidateBasic func (mbe mockBadEvidence) ValidateBasic() error { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, "invalid evidence") + return errors.ErrInvalidEvidence } func TestMsgCreateClientValidateBasic(t *testing.T) { diff --git a/x/ibc/02-client/types/tendermint/consensus_state.go b/x/ibc/02-client/types/tendermint/consensus_state.go index 25c2f8d990f8..cb7e2e42e849 100644 --- a/x/ibc/02-client/types/tendermint/consensus_state.go +++ b/x/ibc/02-client/types/tendermint/consensus_state.go @@ -53,7 +53,9 @@ func (cs ConsensusState) GetCommitter() exported.Committer { func (cs ConsensusState) CheckValidityAndUpdateState(header exported.Header) (exported.ConsensusState, error) { tmHeader, ok := header.(Header) if !ok { - return nil, clienterrors.ErrInvalidHeader(clienterrors.DefaultCodespace) + return nil, sdkerrors.Wrap( + clienterrors.ErrInvalidHeader, "header is not from Tendermint", + ) } if err := cs.checkValidity(tmHeader); err != nil { @@ -69,7 +71,7 @@ func (cs ConsensusState) CheckValidityAndUpdateState(header exported.Header) (ex func (cs ConsensusState) checkValidity(header Header) error { if header.GetHeight() < cs.Height { return sdkerrors.Wrap( - clienterrors.ErrInvalidHeader(clienterrors.DefaultCodespace), + clienterrors.ErrInvalidHeader, fmt.Sprintf("header height < consensus height (%d < %d)", header.GetHeight(), cs.Height), ) } diff --git a/x/ibc/02-client/types/tendermint/evidence.go b/x/ibc/02-client/types/tendermint/evidence.go index a8d1154a27ae..bc60b413b4e6 100644 --- a/x/ibc/02-client/types/tendermint/evidence.go +++ b/x/ibc/02-client/types/tendermint/evidence.go @@ -1,14 +1,13 @@ package tendermint import ( - "fmt" - yaml "gopkg.in/yaml.v2" "github.com/tendermint/tendermint/crypto/tmhash" cmn "github.com/tendermint/tendermint/libs/common" tmtypes "github.com/tendermint/tendermint/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" evidenceexported "github.com/cosmos/cosmos-sdk/x/evidence/exported" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types/errors" ) @@ -56,27 +55,31 @@ func (ev Evidence) GetHeight() int64 { func (ev Evidence) ValidateBasic() error { // ValidateBasic on both validators if err := ev.Header1.ValidateBasic(ev.ChainID); err != nil { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, fmt.Sprintf("Header1 failed ValidateBasic: %v", err)) + return sdkerrors.Wrap( + errors.ErrInvalidEvidence, + sdkerrors.Wrap(err, "header 1 failed validation").Error(), + ) } if err := ev.Header2.ValidateBasic(ev.ChainID); err != nil { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, fmt.Sprintf("Header2 failed ValidateBasic: %v", err)) + return sdkerrors.Wrap( + errors.ErrInvalidEvidence, + sdkerrors.Wrap(err, "header 2 failed validation").Error(), + ) } // Ensure that Heights are the same if ev.Header1.Height != ev.Header2.Height { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, "headers in evidence are on different heights") + return sdkerrors.Wrapf(errors.ErrInvalidEvidence, "headers in evidence are on different heights (%d ≠ %d)", ev.Header1.Height, ev.Header2.Height) } // Ensure that Commit Hashes are different if ev.Header1.Commit.BlockID.Equals(ev.Header2.Commit.BlockID) { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, "Headers commit to same blockID") + return sdkerrors.Wrap(errors.ErrInvalidEvidence, "headers commit to same blockID") } - - if err1 := ValidCommit(ev.ChainID, ev.Header1.Commit, ev.Header1.ValidatorSet); err1 != nil { - return err1 + if err := ValidCommit(ev.ChainID, ev.Header1.Commit, ev.Header1.ValidatorSet); err != nil { + return err } - if err2 := ValidCommit(ev.ChainID, ev.Header2.Commit, ev.Header2.ValidatorSet); err2 != nil { - return err2 + if err := ValidCommit(ev.ChainID, ev.Header2.Commit, ev.Header2.ValidatorSet); err != nil { + return err } - return nil } @@ -88,7 +91,7 @@ func (ev Evidence) ValidateBasic() error { func ValidCommit(chainID string, commit *tmtypes.Commit, valSet *tmtypes.ValidatorSet) (err error) { defer func() { if r := recover(); r != nil { - err = errors.ErrInvalidEvidence(errors.DefaultCodespace, fmt.Sprintf("invalid commit: %v", r)) + err = sdkerrors.Wrapf(errors.ErrInvalidEvidence, "invalid commit: %v", r) } }() @@ -99,7 +102,7 @@ func ValidCommit(chainID string, commit *tmtypes.Commit, valSet *tmtypes.Validat // Check that ValidatorSet did indeed commit to blockID in Commit if !ok || !blockID.Equals(commit.BlockID) { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, "ValidatorSet did not commit to Header1") + return sdkerrors.Wrap(errors.ErrInvalidEvidence, "validator set did not commit to header 1") } return nil diff --git a/x/ibc/02-client/types/tendermint/header.go b/x/ibc/02-client/types/tendermint/header.go index 133c1741e56e..9509d6370019 100644 --- a/x/ibc/02-client/types/tendermint/header.go +++ b/x/ibc/02-client/types/tendermint/header.go @@ -42,13 +42,13 @@ func (h Header) GetHeight() uint64 { // and checks that validatorsets are not nil func (h Header) ValidateBasic(chainID string) error { if err := h.SignedHeader.ValidateBasic(chainID); err != nil { - return err + return sdkerrors.Wrap(clienterrors.ErrInvalidHeader, err.Error()) } if h.ValidatorSet == nil { - return sdkerrors.Wrap(clienterrors.ErrInvalidHeader(clienterrors.DefaultCodespace), "ValidatorSet is nil") + return sdkerrors.Wrap(clienterrors.ErrInvalidHeader, "validator set is nil") } if h.NextValidatorSet == nil { - return sdkerrors.Wrap(clienterrors.ErrInvalidHeader(clienterrors.DefaultCodespace), "NextValidatorSet is nil") + return sdkerrors.Wrap(clienterrors.ErrInvalidHeader, "next validator set is nil") } return nil } diff --git a/x/ibc/02-client/types/tendermint/misbehaviour.go b/x/ibc/02-client/types/tendermint/misbehaviour.go index 5b04b6e3ec0c..36c8e14ce8ab 100644 --- a/x/ibc/02-client/types/tendermint/misbehaviour.go +++ b/x/ibc/02-client/types/tendermint/misbehaviour.go @@ -1,8 +1,7 @@ package tendermint import ( - "fmt" - + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" evidenceexported "github.com/cosmos/cosmos-sdk/x/evidence/exported" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types/errors" @@ -33,14 +32,15 @@ func (m Misbehaviour) GetEvidence() evidenceexported.Evidence { // client ID. func (m Misbehaviour) ValidateBasic() error { if m.Evidence == nil { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, "empty evidence") + return sdkerrors.Wrap(errors.ErrInvalidEvidence, "evidence is empty") } - if err := m.Evidence.ValidateBasic(); err != nil { - return err + return sdkerrors.Wrap(errors.ErrInvalidEvidence, err.Error()) } - - return host.DefaultClientIdentifierValidator(m.ClientID) + if err := host.DefaultClientIdentifierValidator(m.ClientID); err != nil { + return sdkerrors.Wrap(errors.ErrInvalidEvidence, err.Error()) + } + return nil } // CheckMisbehaviour checks if the evidence provided is a valid light client misbehaviour @@ -54,13 +54,17 @@ func CheckMisbehaviour(trustedCommitter Committer, m Misbehaviour) error { // Evidence is within trusting period. ValidatorSet must have 2/3 similarity with trustedCommitter ValidatorSet // check that the validator sets on both headers are valid given the last trusted validatorset // less than or equal to evidence height - if err := trustedValSet.VerifyFutureCommit(m.Evidence.Header1.ValidatorSet, m.Evidence.ChainID, - m.Evidence.Header1.Commit.BlockID, m.Evidence.Header1.Height, m.Evidence.Header1.Commit); err != nil { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, fmt.Sprintf("validator set in Header1 has too much change from last known committer: %v", err)) + if err := trustedValSet.VerifyFutureCommit( + m.Evidence.Header1.ValidatorSet, m.Evidence.ChainID, + m.Evidence.Header1.Commit.BlockID, m.Evidence.Header1.Height, m.Evidence.Header1.Commit, + ); err != nil { + return sdkerrors.Wrapf(errors.ErrInvalidEvidence, "validator set in header 1 has too much change from last known committer: %v", err) } - if err := trustedValSet.VerifyFutureCommit(m.Evidence.Header2.ValidatorSet, m.Evidence.ChainID, - m.Evidence.Header2.Commit.BlockID, m.Evidence.Header2.Height, m.Evidence.Header2.Commit); err != nil { - return errors.ErrInvalidEvidence(errors.DefaultCodespace, fmt.Sprintf("validator set in Header2 has too much change from last known committer: %v", err)) + if err := trustedValSet.VerifyFutureCommit( + m.Evidence.Header2.ValidatorSet, m.Evidence.ChainID, + m.Evidence.Header2.Commit.BlockID, m.Evidence.Header2.Height, m.Evidence.Header2.Commit, + ); err != nil { + return sdkerrors.Wrapf(errors.ErrInvalidEvidence, "validator set in header 2 has too much change from last known committer: %v", err) } return nil diff --git a/x/ibc/03-connection/alias.go b/x/ibc/03-connection/alias.go index 4d44e18048e8..2cb4faf887ff 100644 --- a/x/ibc/03-connection/alias.go +++ b/x/ibc/03-connection/alias.go @@ -12,33 +12,23 @@ import ( ) const ( - UNINITIALIZED = types.UNINITIALIZED - INIT = types.INIT - TRYOPEN = types.TRYOPEN - OPEN = types.OPEN - StateUninitialized = types.StateUninitialized - StateInit = types.StateInit - StateTryOpen = types.StateTryOpen - StateOpen = types.StateOpen - DefaultCodespace = types.DefaultCodespace - CodeConnectionExists = types.CodeConnectionExists - CodeConnectionNotFound = types.CodeConnectionNotFound - CodeClientConnectionPathsNotFound = types.CodeClientConnectionPathsNotFound - CodeConnectionPath = types.CodeConnectionPath - CodeInvalidCounterpartyConnection = types.CodeInvalidCounterpartyConnection - CodeInvalidVersion = types.CodeInvalidVersion - CodeInvalidHeight = types.CodeInvalidHeight - CodeInvalidConnectionState = types.CodeInvalidConnectionState - CodeInvalidCounterparty = types.CodeInvalidCounterparty - AttributeKeyConnectionID = types.AttributeKeyConnectionID - AttributeKeyCounterpartyClientID = types.AttributeKeyCounterpartyClientID - SubModuleName = types.SubModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute - QueryAllConnections = types.QueryAllConnections - QueryConnection = types.QueryConnection - QueryClientConnections = types.QueryClientConnections + UNINITIALIZED = types.UNINITIALIZED + INIT = types.INIT + TRYOPEN = types.TRYOPEN + OPEN = types.OPEN + StateUninitialized = types.StateUninitialized + StateInit = types.StateInit + StateTryOpen = types.StateTryOpen + StateOpen = types.StateOpen + AttributeKeyConnectionID = types.AttributeKeyConnectionID + AttributeKeyCounterpartyClientID = types.AttributeKeyCounterpartyClientID + SubModuleName = types.SubModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + QueryAllConnections = types.QueryAllConnections + QueryConnection = types.QueryConnection + QueryClientConnections = types.QueryClientConnections ) var ( @@ -55,8 +45,6 @@ var ( ErrConnectionNotFound = types.ErrConnectionNotFound ErrClientConnectionPathsNotFound = types.ErrClientConnectionPathsNotFound ErrConnectionPath = types.ErrConnectionPath - ErrInvalidCounterpartyConnection = types.ErrInvalidCounterpartyConnection - ErrInvalidHeight = types.ErrInvalidHeight ErrInvalidConnectionState = types.ErrInvalidConnectionState ErrInvalidCounterparty = types.ErrInvalidCounterparty ConnectionPath = types.ConnectionPath diff --git a/x/ibc/03-connection/client/cli/cli.go b/x/ibc/03-connection/client/cli/cli.go index e0ea7c89880f..92c3fa8cc901 100644 --- a/x/ibc/03-connection/client/cli/cli.go +++ b/x/ibc/03-connection/client/cli/cli.go @@ -3,7 +3,7 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" ) @@ -16,7 +16,7 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { SuggestionsMinimumDistance: 2, } - ics03ConnectionQueryCmd.AddCommand(client.GetCommands( + ics03ConnectionQueryCmd.AddCommand(flags.GetCommands( GetCmdQueryConnections(queryRoute, cdc), GetCmdQueryConnection(queryRoute, cdc), )...) @@ -30,7 +30,7 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { Short: "IBC connection transaction subcommands", } - ics03ConnectionTxCmd.AddCommand(client.PostCommands( + ics03ConnectionTxCmd.AddCommand(flags.PostCommands( GetCmdConnectionOpenInit(storeKey, cdc), GetCmdConnectionOpenTry(storeKey, cdc), GetCmdConnectionOpenAck(storeKey, cdc), diff --git a/x/ibc/03-connection/handler.go b/x/ibc/03-connection/handler.go index 854436eadd6a..b7c9eae08d3f 100644 --- a/x/ibc/03-connection/handler.go +++ b/x/ibc/03-connection/handler.go @@ -7,10 +7,10 @@ import ( ) // HandleMsgConnectionOpenInit defines the sdk.Handler for MsgConnectionOpenInit -func HandleMsgConnectionOpenInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenInit) sdk.Result { +func HandleMsgConnectionOpenInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenInit) (*sdk.Result, error) { err := k.ConnOpenInit(ctx, msg.ConnectionID, msg.ClientID, msg.Counterparty) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -26,16 +26,18 @@ func HandleMsgConnectionOpenInit(ctx sdk.Context, k keeper.Keeper, msg types.Msg ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgConnectionOpenTry defines the sdk.Handler for MsgConnectionOpenTry -func HandleMsgConnectionOpenTry(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenTry) sdk.Result { +func HandleMsgConnectionOpenTry(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenTry) (*sdk.Result, error) { err := k.ConnOpenTry( ctx, msg.ConnectionID, msg.Counterparty, msg.ClientID, msg.CounterpartyVersions, msg.ProofInit, msg.ProofConsensus, msg.ProofHeight, msg.ConsensusHeight) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -51,17 +53,19 @@ func HandleMsgConnectionOpenTry(ctx sdk.Context, k keeper.Keeper, msg types.MsgC ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgConnectionOpenAck defines the sdk.Handler for MsgConnectionOpenAck -func HandleMsgConnectionOpenAck(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenAck) sdk.Result { +func HandleMsgConnectionOpenAck(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenAck) (*sdk.Result, error) { err := k.ConnOpenAck( ctx, msg.ConnectionID, msg.Version, msg.ProofTry, msg.ProofConsensus, msg.ProofHeight, msg.ConsensusHeight, ) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -76,14 +80,16 @@ func HandleMsgConnectionOpenAck(ctx sdk.Context, k keeper.Keeper, msg types.MsgC ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgConnectionOpenConfirm defines the sdk.Handler for MsgConnectionOpenConfirm -func HandleMsgConnectionOpenConfirm(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenConfirm) sdk.Result { +func HandleMsgConnectionOpenConfirm(ctx sdk.Context, k keeper.Keeper, msg types.MsgConnectionOpenConfirm) (*sdk.Result, error) { err := k.ConnOpenConfirm(ctx, msg.ConnectionID, msg.ProofAck, msg.ProofHeight) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -98,5 +104,7 @@ func HandleMsgConnectionOpenConfirm(ctx sdk.Context, k keeper.Keeper, msg types. ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } diff --git a/x/ibc/03-connection/keeper/handshake.go b/x/ibc/03-connection/keeper/handshake.go index e5a011a84b3a..8a40c427de52 100644 --- a/x/ibc/03-connection/keeper/handshake.go +++ b/x/ibc/03-connection/keeper/handshake.go @@ -22,7 +22,7 @@ func (k Keeper) ConnOpenInit( ) error { _, found := k.GetConnection(ctx, connectionID) if found { - return sdkerrors.Wrap(types.ErrConnectionExists(k.codespace, connectionID), "cannot initialize connection") + return sdkerrors.Wrap(types.ErrConnectionExists, "cannot initialize connection") } // connection defines chain A's ConnectionEnd @@ -58,7 +58,7 @@ func (k Keeper) ConnOpenTry( // XXX: blocked by #5078 /* if consensusHeight > uint64(ctx.BlockHeight()) { - return errors.New("invalid consensus height") // TODO: sdk.Error + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "invalid consensus height") } expectedConsensusState, found := k.clientKeeper.GetConsensusState(ctx, clientID) @@ -112,7 +112,7 @@ func (k Keeper) ConnOpenTry( _, found := k.GetConnection(ctx, connectionID) if found { - return sdkerrors.Wrap(types.ErrConnectionExists(k.codespace, connectionID), "cannot relay connection attempt") + return sdkerrors.Wrap(types.ErrConnectionExists, "cannot relay connection attempt") } connection.State = types.TRYOPEN @@ -142,25 +142,25 @@ func (k Keeper) ConnOpenAck( // XXX: blocked by #5078 /* if consensusHeight > uint64(ctx.BlockHeight()) { - return errors.New("invalid consensus height") // TODO: sdk.Error + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "invalid consensus height") } */ connection, found := k.GetConnection(ctx, connectionID) if !found { - return sdkerrors.Wrap(types.ErrConnectionNotFound(k.codespace, connectionID), "cannot relay ACK of open attempt") + return sdkerrors.Wrap(types.ErrConnectionNotFound, "cannot relay ACK of open attempt") } if connection.State != types.INIT { - return types.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not INIT (got %s)", connection.State.String()), + return sdkerrors.Wrapf( + types.ErrInvalidConnectionState, + "connection state is not INIT (got %s)", connection.State.String(), ) } if types.LatestVersion(connection.Versions) != version { - return ibctypes.ErrInvalidVersion( - k.codespace, - fmt.Sprintf("connection version does't match provided one (%s ≠ %s)", types.LatestVersion(connection.Versions), version), + return sdkerrors.Wrapf( + ibctypes.ErrInvalidVersion, + "connection version does't match provided one (%s ≠ %s)", types.LatestVersion(connection.Versions), version, ) } @@ -223,13 +223,13 @@ func (k Keeper) ConnOpenConfirm( ) error { connection, found := k.GetConnection(ctx, connectionID) if !found { - return sdkerrors.Wrap(types.ErrConnectionNotFound(k.codespace, connectionID), "cannot relay ACK of open attempt") + return sdkerrors.Wrap(types.ErrConnectionNotFound, "cannot relay ACK of open attempt") } if connection.State != types.TRYOPEN { - return types.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not TRYOPEN (got %s)", connection.State.String()), + return sdkerrors.Wrapf( + types.ErrInvalidConnectionState, + "connection state is not TRYOPEN (got %s)", connection.State.String(), ) } @@ -247,7 +247,7 @@ func (k Keeper) ConnOpenConfirm( types.ConnectionPath(connection.Counterparty.ConnectionID), expConnBz, ) if !ok { - return types.ErrInvalidCounterpartyConnection(k.codespace) + return errors.New("couldn't verify connection membership on counterparty's client") } connection.State = types.OPEN diff --git a/x/ibc/03-connection/keeper/keeper.go b/x/ibc/03-connection/keeper/keeper.go index c20720c17788..5edec4cdf32b 100644 --- a/x/ibc/03-connection/keeper/keeper.go +++ b/x/ibc/03-connection/keeper/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" commitment "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" @@ -17,16 +18,14 @@ import ( type Keeper struct { storeKey sdk.StoreKey cdc *codec.Codec - codespace sdk.CodespaceType clientKeeper types.ClientKeeper } // NewKeeper creates a new IBC connection Keeper instance -func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType, ck types.ClientKeeper) Keeper { +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, ck types.ClientKeeper) Keeper { return Keeper{ storeKey: key, cdc: cdc, - codespace: sdk.CodespaceType(fmt.Sprintf("%s/%s", codespace, types.DefaultCodespace)), // "ibc/connection", clientKeeper: ck, } } @@ -133,12 +132,12 @@ func (k Keeper) addConnectionToClient(ctx sdk.Context, clientID, connectionID st func (k Keeper) removeConnectionFromClient(ctx sdk.Context, clientID, connectionID string) error { conns, found := k.GetClientConnectionPaths(ctx, clientID) if !found { - return types.ErrClientConnectionPathsNotFound(k.codespace, clientID) + return sdkerrors.Wrap(types.ErrClientConnectionPathsNotFound, clientID) } conns, ok := host.RemovePath(conns, connectionID) if !ok { - return types.ErrConnectionPath(k.codespace) + return sdkerrors.Wrap(types.ErrConnectionPath, clientID) } k.SetClientConnectionPaths(ctx, clientID, conns) diff --git a/x/ibc/03-connection/keeper/querier.go b/x/ibc/03-connection/keeper/querier.go index f5c56834161f..c888e84e32b2 100644 --- a/x/ibc/03-connection/keeper/querier.go +++ b/x/ibc/03-connection/keeper/querier.go @@ -20,12 +20,12 @@ func QuerierConnection(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte connection, found := k.GetConnection(ctx, params.ConnectionID) if !found { - return nil, types.ErrConnectionNotFound(k.codespace, params.ConnectionID) + return nil, sdkerrors.Wrap(types.ErrConnectionNotFound, params.ConnectionID) } - bz, err := codec.MarshalJSONIndent(k.cdc, connection) + bz, err := types.SubModuleCdc.MarshalJSON(connection) if err != nil { - return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) } return bz, nil @@ -66,7 +66,7 @@ func QuerierClientConnections(ctx sdk.Context, req abci.RequestQuery, k Keeper) clientConnectionPaths, found := k.GetClientConnectionPaths(ctx, params.ClientID) if !found { - return nil, types.ErrClientConnectionPathsNotFound(k.codespace, params.ClientID) + return nil, sdkerrors.Wrap(types.ErrClientConnectionPathsNotFound, params.ClientID) } bz, err := types.SubModuleCdc.MarshalJSON(clientConnectionPaths) diff --git a/x/ibc/03-connection/types/connection.go b/x/ibc/03-connection/types/connection.go index 65806e9f5a9a..5a441c22eb26 100644 --- a/x/ibc/03-connection/types/connection.go +++ b/x/ibc/03-connection/types/connection.go @@ -54,13 +54,23 @@ func NewCounterparty(clientID, connectionID string, prefix commitment.PrefixI) C // ValidateBasic performs a basic validation check of the identifiers and prefix func (c Counterparty) ValidateBasic() error { if err := host.DefaultConnectionIdentifierValidator(c.ConnectionID); err != nil { - return sdkerrors.Wrap(err, "invalid counterparty connection ID") + return sdkerrors.Wrap(err, + sdkerrors.Wrapf( + ErrInvalidCounterparty, + "invalid counterparty connection ID %s", c.ConnectionID, + ).Error(), + ) } if err := host.DefaultClientIdentifierValidator(c.ClientID); err != nil { - return sdkerrors.Wrap(err, "invalid counterparty client ID") + return sdkerrors.Wrap(err, + sdkerrors.Wrapf( + ErrInvalidCounterparty, + "invalid counterparty client ID %s", c.ClientID, + ).Error(), + ) } if c.Prefix == nil || len(c.Prefix.Bytes()) == 0 { - return ErrInvalidCounterparty(DefaultCodespace, "invalid counterparty prefix") + return sdkerrors.Wrap(ErrInvalidCounterparty, "invalid counterparty prefix") } return nil } diff --git a/x/ibc/03-connection/types/errors.go b/x/ibc/03-connection/types/errors.go index d62e14a49218..41199efc4103 100644 --- a/x/ibc/03-connection/types/errors.go +++ b/x/ibc/03-connection/types/errors.go @@ -1,95 +1,15 @@ package types import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// connection error codes -const ( - DefaultCodespace sdk.CodespaceType = SubModuleName - - CodeConnectionExists sdk.CodeType = 210 - CodeConnectionNotFound sdk.CodeType = 211 - CodeClientConnectionPathsNotFound sdk.CodeType = 212 - CodeConnectionPath sdk.CodeType = 213 - CodeInvalidCounterpartyConnection sdk.CodeType = 214 - CodeInvalidVersion sdk.CodeType = 215 - CodeInvalidHeight sdk.CodeType = 216 - CodeInvalidConnectionState sdk.CodeType = 217 - CodeInvalidCounterparty sdk.CodeType = 218 +// IBC connection sentinel errors +var ( + ErrConnectionExists = sdkerrors.Register(SubModuleName, 1, "connection already exists") + ErrConnectionNotFound = sdkerrors.Register(SubModuleName, 2, "connection not found") + ErrClientConnectionPathsNotFound = sdkerrors.Register(SubModuleName, 3, "light client connection paths not found") + ErrConnectionPath = sdkerrors.Register(SubModuleName, 4, "connection path is not associated to the given light client") + ErrInvalidConnectionState = sdkerrors.Register(SubModuleName, 5, "invalid connection state") + ErrInvalidCounterparty = sdkerrors.Register(SubModuleName, 6, "invalid counterparty connection") ) - -// ErrConnectionExists implements sdk.Error -func ErrConnectionExists(codespace sdk.CodespaceType, connectionID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeConnectionExists), - fmt.Sprintf("connection with ID %s already exists", connectionID), - ) -} - -// ErrConnectionNotFound implements sdk.Error -func ErrConnectionNotFound(codespace sdk.CodespaceType, connectionID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeConnectionNotFound), - fmt.Sprintf("connection with ID %s not found", connectionID), - ) -} - -// ErrClientConnectionPathsNotFound implements sdk.Error -func ErrClientConnectionPathsNotFound(codespace sdk.CodespaceType, clientID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeClientConnectionPathsNotFound), - fmt.Sprintf("client connection paths not found for ID %s", clientID), - ) -} - -// ErrConnectionPath implements sdk.Error -func ErrConnectionPath(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeConnectionPath), - "connection path is not associated to the client", - ) -} - -// ErrInvalidCounterpartyConnection implements sdk.Error -func ErrInvalidCounterpartyConnection(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidCounterpartyConnection), - "couldn't verify connection membership on counterparty's client", - ) -} - -// ErrInvalidHeight implements sdk.Error -func ErrInvalidHeight(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidHeight), - msg, - ) -} - -// ErrInvalidConnectionState implements sdk.Error -func ErrInvalidConnectionState(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidConnectionState), - msg, - ) -} - -// ErrInvalidCounterparty implements sdk.Error -func ErrInvalidCounterparty(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidCounterparty), - msg, - ) -} diff --git a/x/ibc/03-connection/types/msgs.go b/x/ibc/03-connection/types/msgs.go index e302badac9c4..bf0731c3bb66 100644 --- a/x/ibc/03-connection/types/msgs.go +++ b/x/ibc/03-connection/types/msgs.go @@ -47,17 +47,17 @@ func (msg MsgConnectionOpenInit) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgConnectionOpenInit) ValidateBasic() sdk.Error { +func (msg MsgConnectionOpenInit) ValidateBasic() error { if err := host.DefaultConnectionIdentifierValidator(msg.ConnectionID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid connection ID")) + return sdkerrors.Wrapf(err, "invalid connection ID: %s", msg.ConnectionID) } if err := host.DefaultClientIdentifierValidator(msg.ClientID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid client ID")) + return sdkerrors.Wrapf(err, "invalid client ID: %s", msg.ClientID) } if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("missing signer address") + return sdkerrors.ErrInvalidAddress } - return sdk.ConvertError(msg.Counterparty.ValidateBasic()) + return msg.Counterparty.ValidateBasic() } // GetSignBytes implements sdk.Msg @@ -118,37 +118,40 @@ func (msg MsgConnectionOpenTry) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgConnectionOpenTry) ValidateBasic() sdk.Error { +func (msg MsgConnectionOpenTry) ValidateBasic() error { if err := host.DefaultConnectionIdentifierValidator(msg.ConnectionID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid connection ID")) + return sdkerrors.Wrapf(err, "invalid connection ID: %s", msg.ConnectionID) } if err := host.DefaultClientIdentifierValidator(msg.ClientID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid client ID")) + return sdkerrors.Wrapf(err, "invalid client ID: %s", msg.ClientID) } if len(msg.CounterpartyVersions) == 0 { - return sdk.ConvertError(ibctypes.ErrInvalidVersion(DefaultCodespace, "missing counterparty versions")) + return sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "missing counterparty versions") } for _, version := range msg.CounterpartyVersions { if strings.TrimSpace(version) == "" { - return sdk.ConvertError(ibctypes.ErrInvalidVersion(DefaultCodespace, "version can't be blank")) + return sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "version can't be blank") } } - if msg.ProofInit == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof init cannot be nil")) + if msg.ProofInit == nil || msg.ProofConsensus == nil { + return sdkerrors.Wrap(commitment.ErrInvalidProof, "cannot submit an empty proof") } - if msg.ProofConsensus == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof consensus cannot be nil")) + if err := msg.ProofInit.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof init cannot be nil") + } + if err := msg.ProofConsensus.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof consensus cannot be nil") } if msg.ProofHeight == 0 { - return sdk.ConvertError(ErrInvalidHeight(DefaultCodespace, "proof height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "proof height must be > 0") } if msg.ConsensusHeight == 0 { - return sdk.ConvertError(ErrInvalidHeight(DefaultCodespace, "consensus height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "consensus height must be > 0") } if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("missing signer address") + return sdkerrors.ErrInvalidAddress } - return sdk.ConvertError(msg.Counterparty.ValidateBasic()) + return msg.Counterparty.ValidateBasic() } // GetSignBytes implements sdk.Msg @@ -203,27 +206,30 @@ func (msg MsgConnectionOpenAck) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgConnectionOpenAck) ValidateBasic() sdk.Error { +func (msg MsgConnectionOpenAck) ValidateBasic() error { if err := host.DefaultConnectionIdentifierValidator(msg.ConnectionID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid connection ID")) + return sdkerrors.Wrap(err, "invalid connection ID") } if strings.TrimSpace(msg.Version) == "" { - return sdk.ConvertError(ibctypes.ErrInvalidVersion(DefaultCodespace, "version can't be blank")) + return sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "version can't be blank") + } + if msg.ProofTry == nil || msg.ProofConsensus == nil { + return sdkerrors.Wrap(commitment.ErrInvalidProof, "cannot submit an empty proof") } - if msg.ProofTry == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof try cannot be nil")) + if err := msg.ProofTry.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof try cannot be nil") } - if msg.ProofConsensus == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof consensus cannot be nil")) + if err := msg.ProofConsensus.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof consensus cannot be nil") } if msg.ProofHeight == 0 { - return sdk.ConvertError(ErrInvalidHeight(DefaultCodespace, "proof height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "proof height must be > 0") } if msg.ConsensusHeight == 0 { - return sdk.ConvertError(ErrInvalidHeight(DefaultCodespace, "consensus height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "consensus height must be > 0") } if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("missing signer address") + return sdkerrors.ErrInvalidAddress } return nil } @@ -272,18 +278,21 @@ func (msg MsgConnectionOpenConfirm) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgConnectionOpenConfirm) ValidateBasic() sdk.Error { +func (msg MsgConnectionOpenConfirm) ValidateBasic() error { if err := host.DefaultConnectionIdentifierValidator(msg.ConnectionID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid connection ID")) + return sdkerrors.Wrap(err, "invalid connection ID") } if msg.ProofAck == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof ack cannot be nil")) + return sdkerrors.Wrap(commitment.ErrInvalidProof, "cannot submit an empty proof") + } + if err := msg.ProofAck.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof ack cannot be nil") } if msg.ProofHeight == 0 { - return sdk.ConvertError(ErrInvalidHeight(DefaultCodespace, "proof height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "proof height must be > 0") } if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("missing signer address") + return sdkerrors.ErrInvalidAddress } return nil } diff --git a/x/ibc/03-connection/types/msgs_test.go b/x/ibc/03-connection/types/msgs_test.go index 87fbae8b7276..8bca120769ba 100644 --- a/x/ibc/03-connection/types/msgs_test.go +++ b/x/ibc/03-connection/types/msgs_test.go @@ -4,20 +4,50 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" + + "github.com/cosmos/cosmos-sdk/store/iavl" + "github.com/cosmos/cosmos-sdk/store/rootmulti" + storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" commitment "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment" ) -func TestNewMsgConnectionOpenInit(t *testing.T) { +type MsgTestSuite struct { + suite.Suite - type TestCase = struct { - msg MsgConnectionOpenInit - expected bool - errMsg string - } + proof commitment.Proof +} + +func (suite *MsgTestSuite) SetupTest() { + db := dbm.NewMemDB() + store := rootmulti.NewStore(db) + storeKey := storetypes.NewKVStoreKey("iavlStoreKey") + + store.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, nil) + store.LoadVersion(0) + iavlStore := store.GetCommitStore(storeKey).(*iavl.Store) + + iavlStore.Set([]byte("KEY"), []byte("VALUE")) + _ = store.Commit() + + res := store.Query(abci.RequestQuery{ + Path: fmt.Sprintf("/%s/key", storeKey.Name()), // required path to get key/value+proof + Data: []byte("KEY"), + Prove: true, + }) + + suite.proof = commitment.Proof{Proof: res.Proof} +} + +func TestMsgTestSuite(t *testing.T) { + suite.Run(t, new(MsgTestSuite)) +} +func (suite *MsgTestSuite) TestNewMsgConnectionOpenInit() { prefix := commitment.NewPrefix([]byte("storePrefixKey")) signer, _ := sdk.AccAddressFromBech32("cosmos1ckgw5d7jfj7wwxjzs9fdrdev9vc8dzcw3n2lht") @@ -31,7 +61,11 @@ func TestNewMsgConnectionOpenInit(t *testing.T) { NewMsgConnectionOpenInit("ibcconntest", "clienttotest", "connectiontotest", "clienttotest", prefix, signer), } - var testCases = []TestCase{ + var testCases = []struct { + msg MsgConnectionOpenInit + expPass bool + errMsg string + }{ {testMsgs[0], false, "invalid connection ID"}, {testMsgs[1], false, "invalid client ID"}, {testMsgs[2], false, "invalid counterparty client ID"}, @@ -42,36 +76,41 @@ func TestNewMsgConnectionOpenInit(t *testing.T) { } for i, tc := range testCases { - require.Equal(t, tc.expected, tc.msg.ValidateBasic() == nil, fmt.Sprintf("case: %d,msg: %s,", i, tc.errMsg)) + err := tc.msg.ValidateBasic() + if tc.expPass { + suite.Require().NoError(err, "Msg %d failed: %v", i, err) + } else { + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) + } } } -func TestNewMsgConnectionOpenTry(t *testing.T) { - type TestCase = struct { - msg MsgConnectionOpenTry - expected bool - errMsg string - } - +func (suite *MsgTestSuite) TestNewMsgConnectionOpenTry() { prefix := commitment.NewPrefix([]byte("storePrefixKey")) signer, _ := sdk.AccAddressFromBech32("cosmos1ckgw5d7jfj7wwxjzs9fdrdev9vc8dzcw3n2lht") testMsgs := []MsgConnectionOpenTry{ - NewMsgConnectionOpenTry("test/conn1", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "test/iris", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "ibc/test", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "test/conn1", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", nil, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{}, commitment.Proof{}, commitment.Proof{}, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, nil, commitment.Proof{}, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, nil, 10, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 0, 10, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 0, signer), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 10, nil), - NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{}, commitment.Proof{}, 10, 10, signer), - } - - var testCases = []TestCase{ + NewMsgConnectionOpenTry("test/conn1", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "test/iris", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "ibc/test", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "test/conn1", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", nil, []string{"1.0.0"}, suite.proof, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{}, suite.proof, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, nil, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, commitment.Proof{Proof: nil}, suite.proof, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, nil, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, commitment.Proof{Proof: nil}, 10, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 0, 10, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 10, 0, signer), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 10, 10, nil), + NewMsgConnectionOpenTry("ibcconntest", "clienttotesta", "connectiontotest", "clienttotest", prefix, []string{"1.0.0"}, suite.proof, suite.proof, 10, 10, signer), + } + + var testCases = []struct { + msg MsgConnectionOpenTry + expPass bool + errMsg string + }{ {testMsgs[0], false, "invalid connection ID"}, {testMsgs[1], false, "invalid client ID"}, {testMsgs[2], false, "invalid counterparty connection ID"}, @@ -79,79 +118,98 @@ func TestNewMsgConnectionOpenTry(t *testing.T) { {testMsgs[4], false, "empty counterparty prefix"}, {testMsgs[5], false, "empty counterpartyVersions"}, {testMsgs[6], false, "empty proofInit"}, - {testMsgs[7], false, "empty proofConsensus"}, - {testMsgs[8], false, "invalid proofHeight"}, - {testMsgs[9], false, "invalid consensusHeight"}, - {testMsgs[10], false, "empty singer"}, - {testMsgs[11], true, "success"}, + {testMsgs[7], false, "empty proofInit"}, + {testMsgs[8], false, "empty proofConsensus"}, + {testMsgs[9], false, "empty proofConsensus"}, + {testMsgs[10], false, "invalid proofHeight"}, + {testMsgs[11], false, "invalid consensusHeight"}, + {testMsgs[12], false, "empty singer"}, + {testMsgs[13], true, "success"}, } for i, tc := range testCases { - require.Equal(t, tc.expected, tc.msg.ValidateBasic() == nil, fmt.Sprintf("case: %d,msg: %s,", i, tc.errMsg)) + err := tc.msg.ValidateBasic() + if tc.expPass { + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) + } else { + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) + } } } -func TestNewMsgConnectionOpenAck(t *testing.T) { - type TestCase = struct { - msg MsgConnectionOpenAck - expected bool - errMsg string - } - +func (suite *MsgTestSuite) TestNewMsgConnectionOpenAck() { signer, _ := sdk.AccAddressFromBech32("cosmos1ckgw5d7jfj7wwxjzs9fdrdev9vc8dzcw3n2lht") testMsgs := []MsgConnectionOpenAck{ - NewMsgConnectionOpenAck("test/conn1", commitment.Proof{}, commitment.Proof{}, 10, 10, "1.0.0", signer), - NewMsgConnectionOpenAck("ibcconntest", nil, commitment.Proof{}, 10, 10, "1.0.0", signer), - NewMsgConnectionOpenAck("ibcconntest", commitment.Proof{}, nil, 10, 10, "1.0.0", signer), - NewMsgConnectionOpenAck("ibcconntest", commitment.Proof{}, commitment.Proof{}, 0, 10, "1.0.0", signer), - NewMsgConnectionOpenAck("ibcconntest", commitment.Proof{}, commitment.Proof{}, 10, 0, "1.0.0", signer), - NewMsgConnectionOpenAck("ibcconntest", commitment.Proof{}, commitment.Proof{}, 10, 10, "", signer), - NewMsgConnectionOpenAck("ibcconntest", commitment.Proof{}, commitment.Proof{}, 10, 10, "1.0.0", nil), - NewMsgConnectionOpenAck("ibcconntest", commitment.Proof{}, commitment.Proof{}, 10, 10, "1.0.0", signer), - } - var testCases = []TestCase{ + NewMsgConnectionOpenAck("test/conn1", suite.proof, suite.proof, 10, 10, "1.0.0", signer), + NewMsgConnectionOpenAck("ibcconntest", nil, suite.proof, 10, 10, "1.0.0", signer), + NewMsgConnectionOpenAck("ibcconntest", commitment.Proof{Proof: nil}, suite.proof, 10, 10, "1.0.0", signer), + NewMsgConnectionOpenAck("ibcconntest", suite.proof, nil, 10, 10, "1.0.0", signer), + NewMsgConnectionOpenAck("ibcconntest", suite.proof, commitment.Proof{Proof: nil}, 10, 10, "1.0.0", signer), + NewMsgConnectionOpenAck("ibcconntest", suite.proof, suite.proof, 0, 10, "1.0.0", signer), + NewMsgConnectionOpenAck("ibcconntest", suite.proof, suite.proof, 10, 0, "1.0.0", signer), + NewMsgConnectionOpenAck("ibcconntest", suite.proof, suite.proof, 10, 10, "", signer), + NewMsgConnectionOpenAck("ibcconntest", suite.proof, suite.proof, 10, 10, "1.0.0", nil), + NewMsgConnectionOpenAck("ibcconntest", suite.proof, suite.proof, 10, 10, "1.0.0", signer), + } + var testCases = []struct { + msg MsgConnectionOpenAck + expPass bool + errMsg string + }{ {testMsgs[0], false, "invalid connection ID"}, {testMsgs[1], false, "empty proofTry"}, - {testMsgs[2], false, "empty proofConsensus"}, - {testMsgs[3], false, "invalid proofHeight"}, - {testMsgs[4], false, "invalid consensusHeight"}, - {testMsgs[5], false, "invalid version"}, - {testMsgs[6], false, "empty signer"}, - {testMsgs[7], true, "success"}, + {testMsgs[2], false, "empty proofTry"}, + {testMsgs[3], false, "empty proofConsensus"}, + {testMsgs[4], false, "empty proofConsensus"}, + {testMsgs[5], false, "invalid proofHeight"}, + {testMsgs[6], false, "invalid consensusHeight"}, + {testMsgs[7], false, "invalid version"}, + {testMsgs[8], false, "empty signer"}, + {testMsgs[9], true, "success"}, } for i, tc := range testCases { - require.Equal(t, tc.expected, tc.msg.ValidateBasic() == nil, fmt.Sprintf("case: %d,msg: %s,", i, tc.errMsg)) + err := tc.msg.ValidateBasic() + if tc.expPass { + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) + } else { + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) + } } } -func TestNewMsgConnectionOpenConfirm(t *testing.T) { - type TestCase = struct { - msg MsgConnectionOpenConfirm - expected bool - errMsg string - } - +func (suite *MsgTestSuite) TestNewMsgConnectionOpenConfirm() { signer, _ := sdk.AccAddressFromBech32("cosmos1ckgw5d7jfj7wwxjzs9fdrdev9vc8dzcw3n2lht") testMsgs := []MsgConnectionOpenConfirm{ - NewMsgConnectionOpenConfirm("test/conn1", commitment.Proof{}, 10, signer), + NewMsgConnectionOpenConfirm("test/conn1", suite.proof, 10, signer), NewMsgConnectionOpenConfirm("ibcconntest", nil, 10, signer), - NewMsgConnectionOpenConfirm("ibcconntest", commitment.Proof{}, 0, signer), - NewMsgConnectionOpenConfirm("ibcconntest", commitment.Proof{}, 10, nil), - NewMsgConnectionOpenConfirm("ibcconntest", commitment.Proof{}, 10, signer), + NewMsgConnectionOpenConfirm("ibcconntest", commitment.Proof{Proof: nil}, 10, signer), + NewMsgConnectionOpenConfirm("ibcconntest", suite.proof, 0, signer), + NewMsgConnectionOpenConfirm("ibcconntest", suite.proof, 10, nil), + NewMsgConnectionOpenConfirm("ibcconntest", suite.proof, 10, signer), } - var testCases = []TestCase{ + var testCases = []struct { + msg MsgConnectionOpenConfirm + expPass bool + errMsg string + }{ {testMsgs[0], false, "invalid connection ID"}, {testMsgs[1], false, "empty proofTry"}, - {testMsgs[2], false, "invalid proofHeight"}, - {testMsgs[3], false, "empty signer"}, - {testMsgs[4], true, "success"}, + {testMsgs[2], false, "empty proofTry"}, + {testMsgs[3], false, "invalid proofHeight"}, + {testMsgs[4], false, "empty signer"}, + {testMsgs[5], true, "success"}, } for i, tc := range testCases { - require.Equal(t, tc.expected, tc.msg.ValidateBasic() == nil, fmt.Sprintf("case: %d,msg: %s,", i, tc.errMsg)) + err := tc.msg.ValidateBasic() + if tc.expPass { + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) + } else { + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) + } } } diff --git a/x/ibc/04-channel/alias.go b/x/ibc/04-channel/alias.go index f2d6a7f49d24..73e18df48d0c 100644 --- a/x/ibc/04-channel/alias.go +++ b/x/ibc/04-channel/alias.go @@ -12,84 +12,75 @@ import ( ) const ( - UNINITIALIZED = types.UNINITIALIZED - UNORDERED = types.UNORDERED - ORDERED = types.ORDERED - OrderNone = types.OrderNone - OrderUnordered = types.OrderUnordered - OrderOrdered = types.OrderOrdered - CLOSED = types.CLOSED - INIT = types.INIT - TRYOPEN = types.TRYOPEN - OPEN = types.OPEN - StateUninitialized = types.StateUninitialized - StateInit = types.StateInit - StateTryOpen = types.StateTryOpen - StateOpen = types.StateOpen - StateClosed = types.StateClosed - DefaultCodespace = types.DefaultCodespace - CodeChannelExists = types.CodeChannelExists - CodeChannelNotFound = types.CodeChannelNotFound - CodeInvalidCounterpartyChannel = types.CodeInvalidCounterpartyChannel - CodeChannelCapabilityNotFound = types.CodeChannelCapabilityNotFound - CodeInvalidPacket = types.CodeInvalidPacket - CodeSequenceNotFound = types.CodeSequenceNotFound - CodePacketTimeout = types.CodePacketTimeout - CodeInvalidChannel = types.CodeInvalidChannel - CodeInvalidChannelState = types.CodeInvalidChannelState - AttributeKeySenderPort = types.AttributeKeySenderPort - AttributeKeyReceiverPort = types.AttributeKeyReceiverPort - AttributeKeyChannelID = types.AttributeKeyChannelID - AttributeKeySequence = types.AttributeKeySequence - SubModuleName = types.SubModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute - QueryAllChannels = types.QueryAllChannels - QueryChannel = types.QueryChannel + UNINITIALIZED = types.UNINITIALIZED + UNORDERED = types.UNORDERED + ORDERED = types.ORDERED + OrderNone = types.OrderNone + OrderUnordered = types.OrderUnordered + OrderOrdered = types.OrderOrdered + CLOSED = types.CLOSED + INIT = types.INIT + TRYOPEN = types.TRYOPEN + OPEN = types.OPEN + StateUninitialized = types.StateUninitialized + StateInit = types.StateInit + StateTryOpen = types.StateTryOpen + StateOpen = types.StateOpen + StateClosed = types.StateClosed + AttributeKeySenderPort = types.AttributeKeySenderPort + AttributeKeyReceiverPort = types.AttributeKeyReceiverPort + AttributeKeyChannelID = types.AttributeKeyChannelID + AttributeKeySequence = types.AttributeKeySequence + SubModuleName = types.SubModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + QueryAllChannels = types.QueryAllChannels + QueryChannel = types.QueryChannel ) var ( // functions aliases - NewKeeper = keeper.NewKeeper - QuerierChannels = keeper.QuerierChannels - QuerierChannel = keeper.QuerierChannel - NewChannel = types.NewChannel - NewCounterparty = types.NewCounterparty - OrderFromString = types.OrderFromString - StateFromString = types.StateFromString - RegisterCodec = types.RegisterCodec - ErrChannelExists = types.ErrChannelExists - ErrChannelNotFound = types.ErrChannelNotFound - ErrInvalidCounterpartyChannel = types.ErrInvalidCounterpartyChannel - ErrChannelCapabilityNotFound = types.ErrChannelCapabilityNotFound - ErrInvalidPacket = types.ErrInvalidPacket - ErrSequenceNotFound = types.ErrSequenceNotFound - ErrPacketTimeout = types.ErrPacketTimeout - ErrInvalidChannel = types.ErrInvalidChannel - ErrInvalidChannelState = types.ErrInvalidChannelState - ChannelPath = types.ChannelPath - ChannelCapabilityPath = types.ChannelCapabilityPath - NextSequenceSendPath = types.NextSequenceSendPath - NextSequenceRecvPath = types.NextSequenceRecvPath - PacketCommitmentPath = types.PacketCommitmentPath - PacketAcknowledgementPath = types.PacketAcknowledgementPath - KeyChannel = types.KeyChannel - KeyChannelCapabilityPath = types.KeyChannelCapabilityPath - KeyNextSequenceSend = types.KeyNextSequenceSend - KeyNextSequenceRecv = types.KeyNextSequenceRecv - KeyPacketCommitment = types.KeyPacketCommitment - KeyPacketAcknowledgement = types.KeyPacketAcknowledgement - NewMsgChannelOpenInit = types.NewMsgChannelOpenInit - NewMsgChannelOpenTry = types.NewMsgChannelOpenTry - NewMsgChannelOpenAck = types.NewMsgChannelOpenAck - NewMsgChannelOpenConfirm = types.NewMsgChannelOpenConfirm - NewMsgChannelCloseInit = types.NewMsgChannelCloseInit - NewMsgChannelCloseConfirm = types.NewMsgChannelCloseConfirm - NewPacket = types.NewPacket - NewOpaquePacket = types.NewOpaquePacket - NewChannelResponse = types.NewChannelResponse - NewQueryChannelParams = types.NewQueryChannelParams + NewKeeper = keeper.NewKeeper + QuerierChannels = keeper.QuerierChannels + QuerierChannel = keeper.QuerierChannel + NewChannel = types.NewChannel + NewCounterparty = types.NewCounterparty + OrderFromString = types.OrderFromString + StateFromString = types.StateFromString + RegisterCodec = types.RegisterCodec + ErrChannelExists = types.ErrChannelExists + ErrChannelNotFound = types.ErrChannelNotFound + ErrInvalidCounterparty = types.ErrInvalidCounterparty + ErrChannelCapabilityNotFound = types.ErrChannelCapabilityNotFound + ErrInvalidPacket = types.ErrInvalidPacket + ErrSequenceSendNotFound = types.ErrSequenceSendNotFound + ErrSequenceReceiveNotFound = types.ErrSequenceReceiveNotFound + ErrPacketTimeout = types.ErrPacketTimeout + ErrInvalidChannel = types.ErrInvalidChannel + ErrInvalidChannelState = types.ErrInvalidChannelState + ChannelPath = types.ChannelPath + ChannelCapabilityPath = types.ChannelCapabilityPath + NextSequenceSendPath = types.NextSequenceSendPath + NextSequenceRecvPath = types.NextSequenceRecvPath + PacketCommitmentPath = types.PacketCommitmentPath + PacketAcknowledgementPath = types.PacketAcknowledgementPath + KeyChannel = types.KeyChannel + KeyChannelCapabilityPath = types.KeyChannelCapabilityPath + KeyNextSequenceSend = types.KeyNextSequenceSend + KeyNextSequenceRecv = types.KeyNextSequenceRecv + KeyPacketCommitment = types.KeyPacketCommitment + KeyPacketAcknowledgement = types.KeyPacketAcknowledgement + NewMsgChannelOpenInit = types.NewMsgChannelOpenInit + NewMsgChannelOpenTry = types.NewMsgChannelOpenTry + NewMsgChannelOpenAck = types.NewMsgChannelOpenAck + NewMsgChannelOpenConfirm = types.NewMsgChannelOpenConfirm + NewMsgChannelCloseInit = types.NewMsgChannelCloseInit + NewMsgChannelCloseConfirm = types.NewMsgChannelCloseConfirm + NewPacket = types.NewPacket + NewOpaquePacket = types.NewOpaquePacket + NewChannelResponse = types.NewChannelResponse + NewQueryChannelParams = types.NewQueryChannelParams // variable aliases SubModuleCdc = types.SubModuleCdc diff --git a/x/ibc/04-channel/client/cli/cli.go b/x/ibc/04-channel/client/cli/cli.go index 35bd02203a1d..7c24dff1e95f 100644 --- a/x/ibc/04-channel/client/cli/cli.go +++ b/x/ibc/04-channel/client/cli/cli.go @@ -3,7 +3,7 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" ) @@ -15,7 +15,7 @@ func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command { DisableFlagParsing: true, } - ics04ChannelQueryCmd.AddCommand(client.GetCommands( + ics04ChannelQueryCmd.AddCommand(flags.GetCommands( GetCmdQueryChannel(storeKey, cdc), )...) @@ -29,7 +29,7 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { Short: "IBC channel transaction subcommands", } - ics04ChannelTxCmd.AddCommand(client.PostCommands( + ics04ChannelTxCmd.AddCommand(flags.PostCommands( GetMsgChannelOpenInitCmd(storeKey, cdc), GetMsgChannelOpenTryCmd(storeKey, cdc), GetMsgChannelOpenAckCmd(storeKey, cdc), diff --git a/x/ibc/04-channel/client/utils/utils.go b/x/ibc/04-channel/client/utils/utils.go index 0084f57376a1..e7e9568e4add 100644 --- a/x/ibc/04-channel/client/utils/utils.go +++ b/x/ibc/04-channel/client/utils/utils.go @@ -3,13 +3,13 @@ package utils import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" ) // QueryPacket returns a packet from the store func QueryPacket( - ctx client.CLIContext, portID, channelID string, sequence, timeout uint64, prove bool, + ctx context.CLIContext, portID, channelID string, sequence, timeout uint64, prove bool, ) (types.PacketResponse, error) { req := abci.RequestQuery{ Path: "store/ibc/key", @@ -46,7 +46,7 @@ func QueryPacket( // QueryChannel queries the store to get a channel and a merkle proof. func QueryChannel( - ctx client.CLIContext, portID, channelID string, prove bool, + ctx context.CLIContext, portID, channelID string, prove bool, ) (types.ChannelResponse, error) { req := abci.RequestQuery{ Path: "store/ibc/key", diff --git a/x/ibc/04-channel/handler.go b/x/ibc/04-channel/handler.go index 31c97b668e1a..fb35ef8e5fbe 100644 --- a/x/ibc/04-channel/handler.go +++ b/x/ibc/04-channel/handler.go @@ -7,13 +7,13 @@ import ( ) // HandleMsgChannelOpenInit defines the sdk.Handler for MsgChannelOpenInit -func HandleMsgChannelOpenInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenInit) sdk.Result { +func HandleMsgChannelOpenInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenInit) (*sdk.Result, error) { err := k.ChanOpenInit( ctx, msg.Channel.Ordering, msg.Channel.ConnectionHops, msg.PortID, msg.ChannelID, msg.Channel.Counterparty, msg.Channel.Version, ) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -29,16 +29,18 @@ func HandleMsgChannelOpenInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgCha ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgChannelOpenTry defines the sdk.Handler for MsgChannelOpenTry -func HandleMsgChannelOpenTry(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenTry) sdk.Result { +func HandleMsgChannelOpenTry(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenTry) (*sdk.Result, error) { err := k.ChanOpenTry(ctx, msg.Channel.Ordering, msg.Channel.ConnectionHops, msg.PortID, msg.ChannelID, msg.Channel.Counterparty, msg.Channel.Version, msg.CounterpartyVersion, msg.ProofInit, msg.ProofHeight, ) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -55,16 +57,18 @@ func HandleMsgChannelOpenTry(ctx sdk.Context, k keeper.Keeper, msg types.MsgChan ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgChannelOpenAck defines the sdk.Handler for MsgChannelOpenAck -func HandleMsgChannelOpenAck(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenAck) sdk.Result { +func HandleMsgChannelOpenAck(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenAck) (*sdk.Result, error) { err := k.ChanOpenAck( ctx, msg.PortID, msg.ChannelID, msg.CounterpartyVersion, msg.ProofTry, msg.ProofHeight, ) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -80,14 +84,16 @@ func HandleMsgChannelOpenAck(ctx sdk.Context, k keeper.Keeper, msg types.MsgChan ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgChannelOpenConfirm defines the sdk.Handler for MsgChannelOpenConfirm -func HandleMsgChannelOpenConfirm(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenConfirm) sdk.Result { +func HandleMsgChannelOpenConfirm(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelOpenConfirm) (*sdk.Result, error) { err := k.ChanOpenConfirm(ctx, msg.PortID, msg.ChannelID, msg.ProofAck, msg.ProofHeight) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -103,14 +109,16 @@ func HandleMsgChannelOpenConfirm(ctx sdk.Context, k keeper.Keeper, msg types.Msg ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgChannelCloseInit defines the sdk.Handler for MsgChannelCloseInit -func HandleMsgChannelCloseInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelCloseInit) sdk.Result { +func HandleMsgChannelCloseInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelCloseInit) (*sdk.Result, error) { err := k.ChanCloseInit(ctx, msg.PortID, msg.ChannelID) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -126,14 +134,16 @@ func HandleMsgChannelCloseInit(ctx sdk.Context, k keeper.Keeper, msg types.MsgCh ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgChannelCloseConfirm defines the sdk.Handler for MsgChannelCloseConfirm -func HandleMsgChannelCloseConfirm(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelCloseConfirm) sdk.Result { +func HandleMsgChannelCloseConfirm(ctx sdk.Context, k keeper.Keeper, msg types.MsgChannelCloseConfirm) (*sdk.Result, error) { err := k.ChanCloseConfirm(ctx, msg.PortID, msg.ChannelID, msg.ProofInit, msg.ProofHeight) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ @@ -149,5 +159,7 @@ func HandleMsgChannelCloseConfirm(ctx sdk.Context, k keeper.Keeper, msg types.Ms ), }) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } diff --git a/x/ibc/04-channel/keeper/handshake.go b/x/ibc/04-channel/keeper/handshake.go index 5deef767e415..c09dac9344f7 100644 --- a/x/ibc/04-channel/keeper/handshake.go +++ b/x/ibc/04-channel/keeper/handshake.go @@ -2,11 +2,12 @@ package keeper import ( "errors" - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" connection "github.com/cosmos/cosmos-sdk/x/ibc/03-connection" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" + port "github.com/cosmos/cosmos-sdk/x/ibc/05-port" commitment "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment" ) @@ -38,18 +39,18 @@ func (k Keeper) ChanOpenInit( // TODO: abortTransactionUnless(validateChannelIdentifier(portIdentifier, channelIdentifier)) _, found := k.GetChannel(ctx, portID, channelID) if found { - return types.ErrChannelExists(k.codespace, channelID) + return sdkerrors.Wrap(types.ErrChannelExists, channelID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, connectionHops[0]) if !found { - return connection.ErrConnectionNotFound(k.codespace, connectionHops[0]) + return sdkerrors.Wrap(connection.ErrConnectionNotFound, connectionHops[0]) } if connectionEnd.State == connection.UNINITIALIZED { - return connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state cannot be NONE"), + return sdkerrors.Wrap( + connection.ErrInvalidConnectionState, + "connection state cannot be UNINITIALIZED", ) } @@ -58,7 +59,7 @@ func (k Keeper) ChanOpenInit( key := sdk.NewKVStoreKey(portID) if !k.portKeeper.Authenticate(key, portID) { - return errors.New("port is not valid") + return sdkerrors.Wrap(port.ErrInvalidPort, portID) } */ @@ -88,25 +89,25 @@ func (k Keeper) ChanOpenTry( ) error { _, found := k.GetChannel(ctx, portID, channelID) if found { - return types.ErrChannelExists(k.codespace, channelID) + return sdkerrors.Wrap(types.ErrChannelExists, channelID) } // TODO: Maybe not right key := sdk.NewKVStoreKey(portID) if !k.portKeeper.Authenticate(key, portID) { - return errors.New("port is not valid") + return sdkerrors.Wrap(port.ErrInvalidPort, portID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, connectionHops[0]) if !found { - return connection.ErrConnectionNotFound(k.codespace, connectionHops[0]) + return sdkerrors.Wrap(connection.ErrConnectionNotFound, connectionHops[0]) } if connectionEnd.State != connection.OPEN { - return connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not OPEN (got %s)", connectionEnd.State.String()), + return sdkerrors.Wrapf( + connection.ErrInvalidConnectionState, + "connection state is not OPEN (got %s)", connectionEnd.State.String(), ) } @@ -130,7 +131,7 @@ func (k Keeper) ChanOpenTry( bz, err := k.cdc.MarshalBinaryLengthPrefixed(expectedChannel) if err != nil { - return errors.New("failed to marshal expected channel") + return err } if !k.connectionKeeper.VerifyMembership( @@ -138,7 +139,7 @@ func (k Keeper) ChanOpenTry( types.ChannelPath(counterparty.PortID, counterparty.ChannelID), bz, ) { - return types.ErrInvalidCounterpartyChannel(k.codespace, "channel membership verification failed") + return sdkerrors.Wrap(types.ErrInvalidCounterparty, "channel membership verification failed") } k.SetChannel(ctx, portID, channelID, channel) @@ -162,13 +163,13 @@ func (k Keeper) ChanOpenAck( ) error { channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return types.ErrChannelNotFound(k.codespace, portID, channelID) + return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) } if channel.State != types.INIT { - return types.ErrInvalidChannelState( - k.codespace, - fmt.Sprintf("channel state is not INIT (got %s)", channel.State.String()), + return sdkerrors.Wrapf( + types.ErrInvalidChannelState, + "channel state is not INIT (got %s)", channel.State.String(), ) } @@ -176,18 +177,18 @@ func (k Keeper) ChanOpenAck( key := sdk.NewKVStoreKey(portID) if !k.portKeeper.Authenticate(key, portID) { - return errors.New("port is not valid") + return sdkerrors.Wrap(port.ErrInvalidPort, portID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if connectionEnd.State != connection.OPEN { - return connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not OPEN (got %s)", connectionEnd.State.String()), + return sdkerrors.Wrapf( + connection.ErrInvalidConnectionState, + "connection state is not OPEN (got %s)", connectionEnd.State.String(), ) } @@ -206,7 +207,7 @@ func (k Keeper) ChanOpenAck( bz, err := k.cdc.MarshalBinaryLengthPrefixed(expectedChannel) if err != nil { - return errors.New("failed to marshal expected channel") + return err } if !k.connectionKeeper.VerifyMembership( @@ -214,7 +215,9 @@ func (k Keeper) ChanOpenAck( types.ChannelPath(channel.Counterparty.PortID, channel.Counterparty.ChannelID), bz, ) { - return types.ErrInvalidCounterpartyChannel(k.codespace, "channel membership verification failed") + return sdkerrors.Wrap( + types.ErrInvalidCounterparty, "channel membership verification failed", + ) } channel.State = types.OPEN @@ -235,13 +238,13 @@ func (k Keeper) ChanOpenConfirm( ) error { channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return types.ErrChannelNotFound(k.codespace, portID, channelID) + return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) } if channel.State != types.TRYOPEN { - return types.ErrInvalidChannelState( - k.codespace, - fmt.Sprintf("channel state is not OPENTRY (got %s)", channel.State.String()), + return sdkerrors.Wrapf( + types.ErrInvalidChannelState, + "channel state is not OPENTRY (got %s)", channel.State.String(), ) } @@ -249,18 +252,18 @@ func (k Keeper) ChanOpenConfirm( key := sdk.NewKVStoreKey(portID) if !k.portKeeper.Authenticate(key, portID) { - return errors.New("port is not valid") + return sdkerrors.Wrap(port.ErrInvalidPort, portID) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if connectionEnd.State != connection.OPEN { - return connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not OPEN (got %s)", connectionEnd.State.String()), + return sdkerrors.Wrapf( + connection.ErrInvalidConnectionState, + "connection state is not OPEN (got %s)", connectionEnd.State.String(), ) } @@ -278,7 +281,7 @@ func (k Keeper) ChanOpenConfirm( bz, err := k.cdc.MarshalBinaryLengthPrefixed(expectedChannel) if err != nil { - return errors.New("failed to marshal expected channel") + return err } if !k.connectionKeeper.VerifyMembership( @@ -286,7 +289,7 @@ func (k Keeper) ChanOpenConfirm( types.ChannelPath(channel.Counterparty.PortID, channel.Counterparty.ChannelID), bz, ) { - return types.ErrInvalidCounterpartyChannel(k.codespace, "channel membership verification failed") + return sdkerrors.Wrap(types.ErrInvalidCounterparty, "channel membership verification failed") } channel.State = types.OPEN @@ -311,27 +314,27 @@ func (k Keeper) ChanCloseInit( key := sdk.NewKVStoreKey(portID) if !k.portKeeper.Authenticate(key, portID) { - return errors.New("port is not valid") + return sdkerrors.Wrap(port.ErrInvalidPort, portID) } channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return types.ErrChannelNotFound(k.codespace, portID, channelID) + return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) } if channel.State == types.CLOSED { - return types.ErrInvalidChannelState(k.codespace, "channel is already CLOSED") + return sdkerrors.Wrap(types.ErrInvalidChannelState, "channel is already CLOSED") } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if connectionEnd.State != connection.OPEN { - return connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not OPEN (got %s)", connectionEnd.State.String()), + return sdkerrors.Wrapf( + connection.ErrInvalidConnectionState, + "connection state is not OPEN (got %s)", connectionEnd.State.String(), ) } @@ -354,27 +357,27 @@ func (k Keeper) ChanCloseConfirm( key := sdk.NewKVStoreKey(portID) if !k.portKeeper.Authenticate(key, portID) { - return errors.New("port is not valid") + return sdkerrors.Wrap(port.ErrInvalidPort, portID) } channel, found := k.GetChannel(ctx, portID, channelID) if !found { - return types.ErrChannelNotFound(k.codespace, portID, channelID) + return sdkerrors.Wrap(types.ErrChannelNotFound, channelID) } if channel.State == types.CLOSED { - return types.ErrInvalidChannelState(k.codespace, "channel is already CLOSED") + return sdkerrors.Wrap(types.ErrInvalidChannelState, "channel is already CLOSED") } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if connectionEnd.State != connection.OPEN { - return connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not OPEN (got %s)", connectionEnd.State.String()), + return sdkerrors.Wrapf( + connection.ErrInvalidConnectionState, + "connection state is not OPEN (got %s)", connectionEnd.State.String(), ) } @@ -400,7 +403,7 @@ func (k Keeper) ChanCloseConfirm( types.ChannelPath(channel.Counterparty.PortID, channel.Counterparty.ChannelID), bz, ) { - return types.ErrInvalidCounterpartyChannel(k.codespace, "channel membership verification failed") + return sdkerrors.Wrap(types.ErrInvalidCounterparty, "channel membership verification failed") } channel.State = types.CLOSED diff --git a/x/ibc/04-channel/keeper/keeper.go b/x/ibc/04-channel/keeper/keeper.go index 5d72ab76cc60..92b1a3bca1f1 100644 --- a/x/ibc/04-channel/keeper/keeper.go +++ b/x/ibc/04-channel/keeper/keeper.go @@ -16,7 +16,6 @@ import ( type Keeper struct { storeKey sdk.StoreKey cdc *codec.Codec - codespace sdk.CodespaceType clientKeeper types.ClientKeeper connectionKeeper types.ConnectionKeeper portKeeper types.PortKeeper @@ -24,14 +23,13 @@ type Keeper struct { // NewKeeper creates a new IBC channel Keeper instance func NewKeeper( - cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType, + cdc *codec.Codec, key sdk.StoreKey, clientKeeper types.ClientKeeper, connectionKeeper types.ConnectionKeeper, portKeeper types.PortKeeper, ) Keeper { return Keeper{ storeKey: key, cdc: cdc, - codespace: sdk.CodespaceType(fmt.Sprintf("%s/%s", codespace, types.DefaultCodespace)), // "ibc/channel", clientKeeper: clientKeeper, connectionKeeper: connectionKeeper, portKeeper: portKeeper, diff --git a/x/ibc/04-channel/keeper/packet.go b/x/ibc/04-channel/keeper/packet.go index 515b7ecdf107..2703f283a814 100644 --- a/x/ibc/04-channel/keeper/packet.go +++ b/x/ibc/04-channel/keeper/packet.go @@ -3,13 +3,14 @@ package keeper import ( "bytes" "errors" - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" client "github.com/cosmos/cosmos-sdk/x/ibc/02-client" connection "github.com/cosmos/cosmos-sdk/x/ibc/03-connection" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/exported" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" + port "github.com/cosmos/cosmos-sdk/x/ibc/05-port" commitment "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment" ) @@ -34,51 +35,50 @@ func (k Keeper) CleanupPacket( ) (exported.PacketI, error) { channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return nil, types.ErrChannelNotFound(k.codespace, packet.GetSourcePort(), packet.GetSourceChannel()) + return nil, sdkerrors.Wrap(types.ErrChannelNotFound, packet.GetSourceChannel()) } if channel.State != types.OPEN { - return nil, types.ErrInvalidChannelState( - k.codespace, - fmt.Sprintf("channel state is not OPEN (got %s)", channel.State.String()), + return nil, sdkerrors.Wrapf( + types.ErrInvalidChannelState, + "channel state is not OPEN (got %s)", channel.State.String(), ) } _, found = k.GetChannelCapability(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return nil, types.ErrChannelCapabilityNotFound(k.codespace) + return nil, types.ErrChannelCapabilityNotFound } if !k.portKeeper.Authenticate(portCapability, packet.GetSourcePort()) { - return nil, errors.New("port is not valid") + return nil, sdkerrors.Wrapf(port.ErrInvalidPort, "invalid source port: %s", packet.GetSourcePort()) } if packet.GetDestChannel() != channel.Counterparty.ChannelID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID, ) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return nil, connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return nil, sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if packet.GetDestPort() != channel.Counterparty.PortID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID), + return nil, sdkerrors.Wrapf(types.ErrInvalidPacket, + "packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID, ) } if nextSequenceRecv >= packet.GetSequence() { - return nil, types.ErrInvalidPacket(k.codespace, "packet already received") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet already received") } commitment := k.GetPacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) if !bytes.Equal(commitment, packet.GetData()) { // TODO: hash packet data - return nil, types.ErrInvalidPacket(k.codespace, "packet hasn't been sent") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet hasn't been sent") } var ok bool @@ -96,11 +96,11 @@ func (k Keeper) CleanupPacket( acknowledgement, ) default: - panic(fmt.Sprintf("invalid channel ordering type %v", channel.Ordering)) + panic(sdkerrors.Wrapf(types.ErrInvalidChannelOrdering, channel.Ordering.String())) } if !ok { - return nil, types.ErrInvalidPacket(k.codespace, "packet verification failed") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet verification failed") } k.deletePacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) @@ -121,64 +121,64 @@ func (k Keeper) SendPacket( channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return types.ErrChannelNotFound(k.codespace, packet.GetSourcePort(), packet.GetSourceChannel()) + return sdkerrors.Wrap(types.ErrChannelNotFound, packet.GetSourceChannel()) } if channel.State == types.CLOSED { - return types.ErrInvalidChannelState( - k.codespace, - fmt.Sprintf("channel is CLOSED (got %s)", channel.State.String()), + return sdkerrors.Wrapf( + types.ErrInvalidChannelState, + "channel is CLOSED (got %s)", channel.State.String(), ) } if !k.portKeeper.Authenticate(portCapability, packet.GetSourcePort()) { - return errors.New("port is not valid") + return sdkerrors.Wrap(port.ErrInvalidPort, packet.GetSourcePort()) } if packet.GetDestPort() != channel.Counterparty.PortID { - return types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID), + return sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID, ) } if packet.GetDestChannel() != channel.Counterparty.ChannelID { - return types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID), + return sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID, ) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if connectionEnd.State == connection.UNINITIALIZED { - return connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection is closed (i.e NONE)"), + return sdkerrors.Wrap( + connection.ErrInvalidConnectionState, + "connection is closed (i.e NONE)", ) } - consensusState, found := k.clientKeeper.GetConsensusState(ctx, connectionEnd.ClientID) + _, found = k.clientKeeper.GetConsensusState(ctx, connectionEnd.ClientID) if !found { - return client.ErrConsensusStateNotFound(k.codespace) + return client.ErrConsensusStateNotFound } - if consensusState.GetHeight() >= packet.GetTimeoutHeight() { - return types.ErrPacketTimeout(k.codespace) + if uint64(ctx.BlockHeight()) >= packet.GetTimeoutHeight() { + return types.ErrPacketTimeout } nextSequenceSend, found := k.GetNextSequenceSend(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return types.ErrSequenceNotFound(k.codespace, "send") + return types.ErrSequenceSendNotFound } if packet.GetSequence() != nextSequenceSend { - return types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet sequence ≠ next send sequence (%d ≠ %d)", packet.GetSequence(), nextSequenceSend), + return sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet sequence ≠ next send sequence (%d ≠ %d)", packet.GetSequence(), nextSequenceSend, ) } @@ -202,49 +202,49 @@ func (k Keeper) RecvPacket( channel, found := k.GetChannel(ctx, packet.GetDestPort(), packet.GetDestChannel()) if !found { - return nil, types.ErrChannelNotFound(k.codespace, packet.GetDestPort(), packet.GetDestChannel()) + return nil, sdkerrors.Wrap(types.ErrChannelNotFound, packet.GetDestChannel()) } if channel.State != types.OPEN { - return nil, types.ErrInvalidChannelState( - k.codespace, - fmt.Sprintf("channel state is not OPEN (got %s)", channel.State.String()), + return nil, sdkerrors.Wrapf( + types.ErrInvalidChannelState, + "channel state is not OPEN (got %s)", channel.State.String(), ) } if !k.portKeeper.Authenticate(portCapability, packet.GetDestPort()) { - return nil, errors.New("port is not valid") + return nil, sdkerrors.Wrap(port.ErrInvalidPort, packet.GetDestPort()) } // packet must come from the channel's counterparty if packet.GetSourcePort() != channel.Counterparty.PortID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet source port doesn't match the counterparty's port (%s ≠ %s)", packet.GetSourcePort(), channel.Counterparty.PortID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet source port doesn't match the counterparty's port (%s ≠ %s)", packet.GetSourcePort(), channel.Counterparty.PortID, ) } if packet.GetSourceChannel() != channel.Counterparty.ChannelID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet source channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetSourceChannel(), channel.Counterparty.ChannelID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet source channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetSourceChannel(), channel.Counterparty.ChannelID, ) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return nil, connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return nil, sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if connectionEnd.State != connection.OPEN { - return nil, connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not OPEN (got %s)", connectionEnd.State.String()), + return nil, sdkerrors.Wrapf( + connection.ErrInvalidConnectionState, + "connection state is not OPEN (got %s)", connectionEnd.State.String(), ) } if uint64(ctx.BlockHeight()) >= packet.GetTimeoutHeight() { - return nil, types.ErrPacketTimeout(k.codespace) + return nil, types.ErrPacketTimeout } if !k.connectionKeeper.VerifyMembership( @@ -265,13 +265,13 @@ func (k Keeper) RecvPacket( if channel.Ordering == types.ORDERED { nextSequenceRecv, found := k.GetNextSequenceRecv(ctx, packet.GetDestPort(), packet.GetDestChannel()) if !found { - return nil, types.ErrSequenceNotFound(k.codespace, "receive") + return nil, types.ErrSequenceReceiveNotFound } if packet.GetSequence() != nextSequenceRecv { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet sequence ≠ next receive sequence (%d ≠ %d)", packet.GetSequence(), nextSequenceRecv), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet sequence ≠ next receive sequence (%d ≠ %d)", packet.GetSequence(), nextSequenceRecv, ) } @@ -298,13 +298,13 @@ func (k Keeper) AcknowledgePacket( ) (exported.PacketI, error) { channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return nil, types.ErrChannelNotFound(k.codespace, packet.GetSourcePort(), packet.GetSourceChannel()) + return nil, sdkerrors.Wrap(types.ErrChannelNotFound, packet.GetSourceChannel()) } if channel.State != types.OPEN { - return nil, types.ErrInvalidChannelState( - k.codespace, - fmt.Sprintf("channel state is not OPEN (got %s)", channel.State.String()), + return nil, sdkerrors.Wrapf( + types.ErrInvalidChannelState, + "channel state is not OPEN (got %s)", channel.State.String(), ) } @@ -314,34 +314,34 @@ func (k Keeper) AcknowledgePacket( // packet must come from the channel's counterparty if packet.GetSourcePort() != channel.Counterparty.PortID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet source port doesn't match the counterparty's port (%s ≠ %s)", packet.GetSourcePort(), channel.Counterparty.PortID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet source port doesn't match the counterparty's port (%s ≠ %s)", packet.GetSourcePort(), channel.Counterparty.PortID, ) } if packet.GetSourceChannel() != channel.Counterparty.ChannelID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet source channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetSourceChannel(), channel.Counterparty.ChannelID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet source channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetSourceChannel(), channel.Counterparty.ChannelID, ) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return nil, connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return nil, sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if connectionEnd.State != connection.OPEN { - return nil, connection.ErrInvalidConnectionState( - k.codespace, - fmt.Sprintf("connection state is not OPEN (got %s)", connectionEnd.State.String()), + return nil, sdkerrors.Wrapf( + connection.ErrInvalidConnectionState, + "connection state is not OPEN (got %s)", connectionEnd.State.String(), ) } commitment := k.GetPacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) if !bytes.Equal(commitment, packet.GetData()) { // TODO: hash packet data - return nil, types.ErrInvalidPacket(k.codespace, "packet hasn't been sent") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet hasn't been sent") } if !k.connectionKeeper.VerifyMembership( diff --git a/x/ibc/04-channel/keeper/querier.go b/x/ibc/04-channel/keeper/querier.go index 8aef90c879ad..8c8cac783cec 100644 --- a/x/ibc/04-channel/keeper/querier.go +++ b/x/ibc/04-channel/keeper/querier.go @@ -20,7 +20,7 @@ func QuerierChannel(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, e channel, found := k.GetChannel(ctx, params.PortID, params.ChannelID) if !found { - return nil, types.ErrChannelNotFound(k.codespace, params.PortID, params.ChannelID) + return nil, sdkerrors.Wrap(types.ErrChannelNotFound, params.ChannelID) } bz, err := codec.MarshalJSONIndent(k.cdc, channel) diff --git a/x/ibc/04-channel/keeper/timeout.go b/x/ibc/04-channel/keeper/timeout.go index 3ae481373de3..af54040dad2c 100644 --- a/x/ibc/04-channel/keeper/timeout.go +++ b/x/ibc/04-channel/keeper/timeout.go @@ -3,9 +3,9 @@ package keeper import ( "bytes" "errors" - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" connection "github.com/cosmos/cosmos-sdk/x/ibc/03-connection" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/exported" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" @@ -27,19 +27,19 @@ func (k Keeper) TimeoutPacket( ) (exported.PacketI, error) { channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return nil, types.ErrChannelNotFound(k.codespace, packet.GetSourcePort(), packet.GetSourceChannel()) + return nil, sdkerrors.Wrap(types.ErrChannelNotFound, packet.GetSourceChannel()) } if channel.State != types.OPEN { - return nil, types.ErrInvalidChannelState( - k.codespace, - fmt.Sprintf("channel state is not OPEN (got %s)", channel.State.String()), + return nil, sdkerrors.Wrapf( + types.ErrInvalidChannelState, + "channel state is not OPEN (got %s)", channel.State.String(), ) } _, found = k.GetChannelCapability(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return nil, types.ErrChannelCapabilityNotFound(k.codespace) + return nil, types.ErrChannelCapabilityNotFound } if !k.portKeeper.Authenticate(portCapability, packet.GetSourcePort()) { @@ -47,35 +47,35 @@ func (k Keeper) TimeoutPacket( } if packet.GetDestChannel() != channel.Counterparty.ChannelID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID, ) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return nil, connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return nil, sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if packet.GetDestPort() != channel.Counterparty.PortID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID, ) } if proofHeight < packet.GetTimeoutHeight() { - return nil, types.ErrPacketTimeout(k.codespace) + return nil, types.ErrPacketTimeout } if nextSequenceRecv >= packet.GetSequence() { - return nil, types.ErrInvalidPacket(k.codespace, "packet already received") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet already received") } commitment := k.GetPacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) if !bytes.Equal(commitment, packet.GetData()) { // TODO: hash packet data - return nil, types.ErrInvalidPacket(k.codespace, "packet hasn't been sent") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet hasn't been sent") } var ok bool @@ -92,11 +92,11 @@ func (k Keeper) TimeoutPacket( types.PacketAcknowledgementPath(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()), ) default: - panic(fmt.Sprintf("invalid channel ordering type %v", channel.Ordering)) + panic(sdkerrors.Wrapf(types.ErrInvalidChannelOrdering, channel.Ordering.String())) } if !ok { - return nil, types.ErrInvalidPacket(k.codespace, "packet verification failed") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet verification failed") } k.deletePacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) @@ -122,12 +122,12 @@ func (k Keeper) TimeoutOnClose( ) (exported.PacketI, error) { channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return nil, types.ErrChannelNotFound(k.codespace, packet.GetSourcePort(), packet.GetSourceChannel()) + return nil, sdkerrors.Wrap(types.ErrChannelNotFound, packet.GetSourceChannel()) } _, found = k.GetChannelCapability(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) if !found { - return nil, types.ErrChannelCapabilityNotFound(k.codespace) + return nil, types.ErrChannelCapabilityNotFound } if !k.portKeeper.Authenticate(portCapability, packet.GetSourcePort()) { @@ -135,27 +135,27 @@ func (k Keeper) TimeoutOnClose( } if packet.GetDestChannel() != channel.Counterparty.ChannelID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet destination channel doesn't match the counterparty's channel (%s ≠ %s)", packet.GetDestChannel(), channel.Counterparty.ChannelID, ) } connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { - return nil, connection.ErrConnectionNotFound(k.codespace, channel.ConnectionHops[0]) + return nil, sdkerrors.Wrap(connection.ErrConnectionNotFound, channel.ConnectionHops[0]) } if packet.GetDestPort() != channel.Counterparty.PortID { - return nil, types.ErrInvalidPacket( - k.codespace, - fmt.Sprintf("packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID), + return nil, sdkerrors.Wrapf( + types.ErrInvalidPacket, + "packet destination port doesn't match the counterparty's port (%s ≠ %s)", packet.GetDestPort(), channel.Counterparty.PortID, ) } commitment := k.GetPacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) if !bytes.Equal(commitment, packet.GetData()) { // TODO: hash packet data - return nil, types.ErrInvalidPacket(k.codespace, "packet hasn't been sent") + return nil, sdkerrors.Wrap(types.ErrInvalidPacket, "packet hasn't been sent") } counterpartyHops, found := k.CounterpartyHops(ctx, channel) @@ -179,7 +179,10 @@ func (k Keeper) TimeoutOnClose( types.ChannelPath(channel.Counterparty.PortID, channel.Counterparty.ChannelID), bz, ) { - return nil, types.ErrInvalidCounterpartyChannel(k.codespace, "channel membership verification failed") + return nil, sdkerrors.Wrap( + types.ErrInvalidCounterparty, + "channel membership verification failed", + ) } if !k.connectionKeeper.VerifyNonMembership( diff --git a/x/ibc/04-channel/types/channel.go b/x/ibc/04-channel/types/channel.go index 1250d1208808..ae38cb2212df 100644 --- a/x/ibc/04-channel/types/channel.go +++ b/x/ibc/04-channel/types/channel.go @@ -2,11 +2,11 @@ package types import ( "encoding/json" - "fmt" "strings" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" + ibctypes "github.com/cosmos/cosmos-sdk/x/ibc/types" ) type Channel struct { @@ -34,25 +34,25 @@ func NewChannel( // ValidateBasic performs a basic validation of the channel fields func (ch Channel) ValidateBasic() error { if ch.State.String() == "" { - return ErrInvalidChannelState( - DefaultCodespace, - "channel order should be either 'ORDERED' or 'UNORDERED'", - ) + return sdkerrors.Wrap(ErrInvalidChannel, ErrInvalidChannelState.Error()) } if ch.Ordering.String() == "" { - return ErrInvalidChannel( - DefaultCodespace, - "channel order should be either 'ORDERED' or 'UNORDERED'", - ) + return sdkerrors.Wrap(ErrInvalidChannel, ErrInvalidChannelOrdering.Error()) } if len(ch.ConnectionHops) != 1 { - return ErrInvalidChannel(DefaultCodespace, "IBC v1 only supports one connection hop") + return sdkerrors.Wrap(ErrInvalidChannel, "IBC v1 only supports one connection hop") } if err := host.DefaultConnectionIdentifierValidator(ch.ConnectionHops[0]); err != nil { - return sdkerrors.Wrap(err, "invalid connection hop ID") + return sdkerrors.Wrap( + ErrInvalidChannel, + sdkerrors.Wrap(err, "invalid connection hop ID").Error(), + ) } if strings.TrimSpace(ch.Version) == "" { - return ErrInvalidChannel(DefaultCodespace, "channel version can't be blank") + return sdkerrors.Wrap( + ErrInvalidChannel, + sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "channel version can't be blank").Error(), + ) } return ch.Counterparty.ValidateBasic() } @@ -74,10 +74,16 @@ func NewCounterparty(portID, channelID string) Counterparty { // ValidateBasic performs a basic validation check of the identifiers func (c Counterparty) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(c.PortID); err != nil { - return sdkerrors.Wrap(err, "invalid counterparty connection ID") + return sdkerrors.Wrap( + ErrInvalidCounterparty, + sdkerrors.Wrap(err, "invalid counterparty connection ID").Error(), + ) } if err := host.DefaultChannelIdentifierValidator(c.ChannelID); err != nil { - return sdkerrors.Wrap(err, "invalid counterparty client ID") + return sdkerrors.Wrap( + ErrInvalidCounterparty, + sdkerrors.Wrap(err, "invalid counterparty client ID").Error(), + ) } return nil } @@ -126,7 +132,7 @@ func (o *Order) UnmarshalJSON(data []byte) error { order := OrderFromString(s) if order == 0 { - return fmt.Errorf("invalid channel ordering '%s'", s) + return sdkerrors.Wrap(ErrInvalidChannelOrdering, s) } *o = order diff --git a/x/ibc/04-channel/types/errors.go b/x/ibc/04-channel/types/errors.go index 318c78017d34..40e526476eae 100644 --- a/x/ibc/04-channel/types/errors.go +++ b/x/ibc/04-channel/types/errors.go @@ -1,104 +1,20 @@ package types import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// channel error codes -const ( - DefaultCodespace sdk.CodespaceType = SubModuleName - - CodeChannelExists sdk.CodeType = 219 - CodeChannelNotFound sdk.CodeType = 220 - CodeInvalidCounterpartyChannel sdk.CodeType = 221 - CodeChannelCapabilityNotFound sdk.CodeType = 222 - CodeInvalidPacket sdk.CodeType = 223 - CodeSequenceNotFound sdk.CodeType = 224 - CodePacketTimeout sdk.CodeType = 225 - CodeInvalidChannel sdk.CodeType = 226 - CodeInvalidChannelState sdk.CodeType = 227 +// IBC channel sentinel errors +var ( + ErrChannelExists = sdkerrors.Register(SubModuleName, 1, "channel already exists") + ErrChannelNotFound = sdkerrors.Register(SubModuleName, 2, "channel not found") + ErrInvalidChannel = sdkerrors.Register(SubModuleName, 3, "invalid channel") + ErrInvalidChannelState = sdkerrors.Register(SubModuleName, 4, "invalid channel state") + ErrInvalidChannelOrdering = sdkerrors.Register(SubModuleName, 5, "invalid channel ordering") + ErrInvalidCounterparty = sdkerrors.Register(SubModuleName, 6, "invalid counterparty channel") + ErrChannelCapabilityNotFound = sdkerrors.Register(SubModuleName, 7, "channel capability not found") + ErrSequenceSendNotFound = sdkerrors.Register(SubModuleName, 8, "sequence send not found") + ErrSequenceReceiveNotFound = sdkerrors.Register(SubModuleName, 9, "sequence receive not found") + ErrInvalidPacket = sdkerrors.Register(SubModuleName, 10, "invalid packet") + ErrPacketTimeout = sdkerrors.Register(SubModuleName, 11, "packet timeout") ) - -// ErrChannelExists implements sdk.Error -func ErrChannelExists(codespace sdk.CodespaceType, channelID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeChannelExists), - fmt.Sprintf("channel with ID %s already exists", channelID), - ) -} - -// ErrChannelNotFound implements sdk.Error -func ErrChannelNotFound(codespace sdk.CodespaceType, portID, channelID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeChannelNotFound), - fmt.Sprintf("channel with ID %s on port %s not found", channelID, portID), - ) -} - -// ErrInvalidCounterpartyChannel implements sdk.Error -func ErrInvalidCounterpartyChannel(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidCounterpartyChannel), - msg, - ) -} - -// ErrChannelCapabilityNotFound implements sdk.Error -func ErrChannelCapabilityNotFound(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodeChannelCapabilityNotFound), - "channel capability key not found", - ) -} - -// ErrInvalidPacket implements sdk.Error -func ErrInvalidPacket(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidPacket), - msg, - ) -} - -// ErrSequenceNotFound implements sdk.Error -func ErrSequenceNotFound(codespace sdk.CodespaceType, seqType string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeSequenceNotFound), - fmt.Sprintf("next %s sequence counter not found", seqType), - ) -} - -// ErrPacketTimeout implements sdk.Error -func ErrPacketTimeout(codespace sdk.CodespaceType) error { - return sdkerrors.New( - string(codespace), - uint32(CodePacketTimeout), - "packet timeout", - ) -} - -// ErrInvalidChannel implements sdk.Error -func ErrInvalidChannel(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidChannel), - msg, - ) -} - -// ErrInvalidChannelState implements sdk.Error -func ErrInvalidChannelState(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidChannelState), - msg, - ) -} diff --git a/x/ibc/04-channel/types/msgs.go b/x/ibc/04-channel/types/msgs.go index 16a7a1943999..d0a9e71955ba 100644 --- a/x/ibc/04-channel/types/msgs.go +++ b/x/ibc/04-channel/types/msgs.go @@ -45,15 +45,15 @@ func (msg MsgChannelOpenInit) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgChannelOpenInit) ValidateBasic() sdk.Error { +func (msg MsgChannelOpenInit) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(msg.PortID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid port ID")) + return sdkerrors.Wrap(err, "invalid port ID") } if err := host.DefaultChannelIdentifierValidator(msg.ChannelID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid channel ID")) + return sdkerrors.Wrap(err, "invalid channel ID") } // Signer can be empty - return sdk.ConvertError(msg.Channel.ValidateBasic()) + return msg.Channel.ValidateBasic() } // GetSignBytes implements sdk.Msg @@ -108,24 +108,27 @@ func (msg MsgChannelOpenTry) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgChannelOpenTry) ValidateBasic() sdk.Error { +func (msg MsgChannelOpenTry) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(msg.PortID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid port ID")) + return sdkerrors.Wrap(err, "invalid port ID") } if err := host.DefaultChannelIdentifierValidator(msg.ChannelID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid channel ID")) + return sdkerrors.Wrap(err, "invalid channel ID") } if strings.TrimSpace(msg.CounterpartyVersion) == "" { - return sdk.ConvertError(ErrInvalidCounterpartyChannel(DefaultCodespace, "counterparty version cannot be blank")) + return sdkerrors.Wrap(ErrInvalidCounterparty, "counterparty version cannot be blank") } if msg.ProofInit == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "cannot submit an empty proof")) + return sdkerrors.Wrap(commitment.ErrInvalidProof, "cannot submit an empty proof") + } + if err := msg.ProofInit.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof init cannot be nil") } if msg.ProofHeight == 0 { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "proof height must be > 0") } // Signer can be empty - return sdk.ConvertError(msg.Channel.ValidateBasic()) + return msg.Channel.ValidateBasic() } // GetSignBytes implements sdk.Msg @@ -175,21 +178,24 @@ func (msg MsgChannelOpenAck) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgChannelOpenAck) ValidateBasic() sdk.Error { +func (msg MsgChannelOpenAck) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(msg.PortID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid port ID")) + return sdkerrors.Wrap(err, "invalid port ID") } if err := host.DefaultChannelIdentifierValidator(msg.ChannelID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid channel ID")) + return sdkerrors.Wrap(err, "invalid channel ID") } if strings.TrimSpace(msg.CounterpartyVersion) == "" { - return sdk.ConvertError(ErrInvalidCounterpartyChannel(DefaultCodespace, "counterparty version cannot be blank")) + return sdkerrors.Wrap(ErrInvalidCounterparty, "counterparty version cannot be blank") } if msg.ProofTry == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "cannot submit an empty proof")) + return sdkerrors.Wrap(commitment.ErrInvalidProof, "cannot submit an empty proof") + } + if err := msg.ProofTry.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof try cannot be nil") } if msg.ProofHeight == 0 { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "proof height must be > 0") } // Signer can be empty return nil @@ -240,18 +246,21 @@ func (msg MsgChannelOpenConfirm) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgChannelOpenConfirm) ValidateBasic() sdk.Error { +func (msg MsgChannelOpenConfirm) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(msg.PortID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid port ID")) + return sdkerrors.Wrap(err, "invalid port ID") } if err := host.DefaultChannelIdentifierValidator(msg.ChannelID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid channel ID")) + return sdkerrors.Wrap(err, "invalid channel ID") } if msg.ProofAck == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "cannot submit an empty proof")) + return sdkerrors.Wrap(commitment.ErrInvalidProof, "cannot submit an empty proof") + } + if err := msg.ProofAck.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof ack cannot be nil") } if msg.ProofHeight == 0 { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "proof height must be > 0") } // Signer can be empty return nil @@ -295,12 +304,12 @@ func (msg MsgChannelCloseInit) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgChannelCloseInit) ValidateBasic() sdk.Error { +func (msg MsgChannelCloseInit) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(msg.PortID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid port ID")) + return sdkerrors.Wrap(err, "invalid port ID") } if err := host.DefaultChannelIdentifierValidator(msg.ChannelID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid channel ID")) + return sdkerrors.Wrap(err, "invalid channel ID") } // Signer can be empty return nil @@ -351,18 +360,21 @@ func (msg MsgChannelCloseConfirm) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgChannelCloseConfirm) ValidateBasic() sdk.Error { +func (msg MsgChannelCloseConfirm) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(msg.PortID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid port ID")) + return sdkerrors.Wrap(err, "invalid port ID") } if err := host.DefaultChannelIdentifierValidator(msg.ChannelID); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid channel ID")) + return sdkerrors.Wrap(err, "invalid channel ID") } if msg.ProofInit == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "cannot submit an empty proof")) + return sdkerrors.Wrap(commitment.ErrInvalidProof, "cannot submit an empty proof") + } + if err := msg.ProofInit.ValidateBasic(); err != nil { + return sdkerrors.Wrap(err, "proof init cannot be nil") } if msg.ProofHeight == 0 { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "proof height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "proof height must be > 0") } // Signer can be empty return nil diff --git a/x/ibc/04-channel/types/msgs_test.go b/x/ibc/04-channel/types/msgs_test.go index 3754ea4efa1a..2165f8c4eb40 100644 --- a/x/ibc/04-channel/types/msgs_test.go +++ b/x/ibc/04-channel/types/msgs_test.go @@ -1,10 +1,17 @@ package types import ( + "fmt" "testing" - "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" + + "github.com/cosmos/cosmos-sdk/store/iavl" + "github.com/cosmos/cosmos-sdk/store/rootmulti" + storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" commitment "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment" ) @@ -36,8 +43,39 @@ var ( addr = sdk.AccAddress("testaddr") ) +type MsgTestSuite struct { + suite.Suite + + proof commitment.Proof +} + +func (suite *MsgTestSuite) SetupTest() { + db := dbm.NewMemDB() + store := rootmulti.NewStore(db) + storeKey := storetypes.NewKVStoreKey("iavlStoreKey") + + store.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, nil) + store.LoadVersion(0) + iavlStore := store.GetCommitStore(storeKey).(*iavl.Store) + + iavlStore.Set([]byte("KEY"), []byte("VALUE")) + _ = store.Commit() + + res := store.Query(abci.RequestQuery{ + Path: fmt.Sprintf("/%s/key", storeKey.Name()), // required path to get key/value+proof + Data: []byte("KEY"), + Prove: true, + }) + + suite.proof = commitment.Proof{Proof: res.Proof} +} + +func TestMsgTestSuite(t *testing.T) { + suite.Run(t, new(MsgTestSuite)) +} + // TestMsgChannelOpenInit tests ValidateBasic for MsgChannelOpenInit -func TestMsgChannelOpenInit(t *testing.T) { +func (suite *MsgTestSuite) TestMsgChannelOpenInit() { testMsgs := []MsgChannelOpenInit{ NewMsgChannelOpenInit("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", addr), // valid msg NewMsgChannelOpenInit(invalidShortPort, "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", addr), // too short port id @@ -81,34 +119,34 @@ func TestMsgChannelOpenInit(t *testing.T) { for i, tc := range testCases { err := tc.msg.ValidateBasic() if tc.expPass { - require.Nil(t, err, "Msg %d failed: %v", i, err) + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) } else { - require.NotNil(t, err, "Invalid Msg %d passed: %s", i, tc.errMsg) + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) } } } // TestMsgChannelOpenTry tests ValidateBasic for MsgChannelOpenTry -func TestMsgChannelOpenTry(t *testing.T) { +func (suite *MsgTestSuite) TestMsgChannelOpenTry() { testMsgs := []MsgChannelOpenTry{ - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // valid msg - NewMsgChannelOpenTry(invalidShortPort, "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // too short port id - NewMsgChannelOpenTry(invalidLongPort, "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // too long port id - NewMsgChannelOpenTry(invalidPort, "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // port id contains non-alpha - NewMsgChannelOpenTry("testportid", invalidShortChannel, "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // too short channel id - NewMsgChannelOpenTry("testportid", invalidLongChannel, "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // too long channel id - NewMsgChannelOpenTry("testportid", invalidChannel, "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // channel id contains non-alpha - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "", proof, 1, addr), // empty counterparty version - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", nil, 1, addr), // empty proof - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 0, addr), // proof height is zero - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", Order(4), connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // invalid channel order - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, invalidConnHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // connection hops more than 1 - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, invalidShortConnHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // too short connection id - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, invalidLongConnHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // too long connection id - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, []string{invalidConnection}, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // connection id contains non-alpha - NewMsgChannelOpenTry("testportid", "testchannel", "", UNORDERED, connHops, "testcpport", "testcpchannel", "1.0", proof, 1, addr), // empty channel version - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, connHops, invalidPort, "testcpchannel", "1.0", proof, 1, addr), // invalid counterparty port id - NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, connHops, "testcpport", invalidChannel, "1.0", proof, 1, addr), // invalid counterparty channel id + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // valid msg + NewMsgChannelOpenTry(invalidShortPort, "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // too short port id + NewMsgChannelOpenTry(invalidLongPort, "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // too long port id + NewMsgChannelOpenTry(invalidPort, "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // port id contains non-alpha + NewMsgChannelOpenTry("testportid", invalidShortChannel, "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // too short channel id + NewMsgChannelOpenTry("testportid", invalidLongChannel, "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // too long channel id + NewMsgChannelOpenTry("testportid", invalidChannel, "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // channel id contains non-alpha + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "", suite.proof, 1, addr), // empty counterparty version + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", nil, 1, addr), // empty suite.proof + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", ORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 0, addr), // suite.proof height is zero + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", Order(4), connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // invalid channel order + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, invalidConnHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // connection hops more than 1 + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, invalidShortConnHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // too short connection id + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, invalidLongConnHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // too long connection id + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, []string{invalidConnection}, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // connection id contains non-alpha + NewMsgChannelOpenTry("testportid", "testchannel", "", UNORDERED, connHops, "testcpport", "testcpchannel", "1.0", suite.proof, 1, addr), // empty channel version + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, connHops, invalidPort, "testcpchannel", "1.0", suite.proof, 1, addr), // invalid counterparty port id + NewMsgChannelOpenTry("testportid", "testchannel", "1.0", UNORDERED, connHops, "testcpport", invalidChannel, "1.0", suite.proof, 1, addr), // invalid counterparty channel id } testCases := []struct { @@ -139,26 +177,27 @@ func TestMsgChannelOpenTry(t *testing.T) { for i, tc := range testCases { err := tc.msg.ValidateBasic() if tc.expPass { - require.Nil(t, err, "Msg %d failed: %v", i, err) + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) } else { - require.NotNil(t, err, "Invalid Msg %d passed: %s", i, tc.errMsg) + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) } } } // TestMsgChannelOpenAck tests ValidateBasic for MsgChannelOpenAck -func TestMsgChannelOpenAck(t *testing.T) { +func (suite *MsgTestSuite) TestMsgChannelOpenAck() { testMsgs := []MsgChannelOpenAck{ - NewMsgChannelOpenAck("testportid", "testchannel", "1.0", proof, 1, addr), // valid msg - NewMsgChannelOpenAck(invalidShortPort, "testchannel", "1.0", proof, 1, addr), // too short port id - NewMsgChannelOpenAck(invalidLongPort, "testchannel", "1.0", proof, 1, addr), // too long port id - NewMsgChannelOpenAck(invalidPort, "testchannel", "1.0", proof, 1, addr), // port id contains non-alpha - NewMsgChannelOpenAck("testportid", invalidShortChannel, "1.0", proof, 1, addr), // too short channel id - NewMsgChannelOpenAck("testportid", invalidLongChannel, "1.0", proof, 1, addr), // too long channel id - NewMsgChannelOpenAck("testportid", invalidChannel, "1.0", proof, 1, addr), // channel id contains non-alpha - NewMsgChannelOpenAck("testportid", "testchannel", "", proof, 1, addr), // empty counterparty version - NewMsgChannelOpenAck("testportid", "testchannel", "1.0", nil, 1, addr), // empty proof - NewMsgChannelOpenAck("testportid", "testchannel", "1.0", proof, 0, addr), // proof height is zero + NewMsgChannelOpenAck("testportid", "testchannel", "1.0", suite.proof, 1, addr), // valid msg + NewMsgChannelOpenAck(invalidShortPort, "testchannel", "1.0", suite.proof, 1, addr), // too short port id + NewMsgChannelOpenAck(invalidLongPort, "testchannel", "1.0", suite.proof, 1, addr), // too long port id + NewMsgChannelOpenAck(invalidPort, "testchannel", "1.0", suite.proof, 1, addr), // port id contains non-alpha + NewMsgChannelOpenAck("testportid", invalidShortChannel, "1.0", suite.proof, 1, addr), // too short channel id + NewMsgChannelOpenAck("testportid", invalidLongChannel, "1.0", suite.proof, 1, addr), // too long channel id + NewMsgChannelOpenAck("testportid", invalidChannel, "1.0", suite.proof, 1, addr), // channel id contains non-alpha + NewMsgChannelOpenAck("testportid", "testchannel", "", suite.proof, 1, addr), // empty counterparty version + NewMsgChannelOpenAck("testportid", "testchannel", "1.0", nil, 1, addr), // empty proof + NewMsgChannelOpenAck("testportid", "testchannel", "1.0", commitment.Proof{Proof: nil}, 1, addr), // empty proof + NewMsgChannelOpenAck("testportid", "testchannel", "1.0", suite.proof, 0, addr), // proof height is zero } testCases := []struct { @@ -175,31 +214,33 @@ func TestMsgChannelOpenAck(t *testing.T) { {testMsgs[6], false, "channel id contains non-alpha"}, {testMsgs[7], false, "empty counterparty version"}, {testMsgs[8], false, "empty proof"}, - {testMsgs[9], false, "proof height is zero"}, + {testMsgs[9], false, "empty proof"}, + {testMsgs[10], false, "proof height is zero"}, } for i, tc := range testCases { err := tc.msg.ValidateBasic() if tc.expPass { - require.Nil(t, err, "Msg %d failed: %v", i, err) + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) } else { - require.NotNil(t, err, "Invalid Msg %d passed: %s", i, tc.errMsg) + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) } } } // TestMsgChannelOpenConfirm tests ValidateBasic for MsgChannelOpenConfirm -func TestMsgChannelOpenConfirm(t *testing.T) { +func (suite *MsgTestSuite) TestMsgChannelOpenConfirm() { testMsgs := []MsgChannelOpenConfirm{ - NewMsgChannelOpenConfirm("testportid", "testchannel", proof, 1, addr), // valid msg - NewMsgChannelOpenConfirm(invalidShortPort, "testchannel", proof, 1, addr), // too short port id - NewMsgChannelOpenConfirm(invalidLongPort, "testchannel", proof, 1, addr), // too long port id - NewMsgChannelOpenConfirm(invalidPort, "testchannel", proof, 1, addr), // port id contains non-alpha - NewMsgChannelOpenConfirm("testportid", invalidShortChannel, proof, 1, addr), // too short channel id - NewMsgChannelOpenConfirm("testportid", invalidLongChannel, proof, 1, addr), // too long channel id - NewMsgChannelOpenConfirm("testportid", invalidChannel, proof, 1, addr), // channel id contains non-alpha - NewMsgChannelOpenConfirm("testportid", "testchannel", nil, 1, addr), // empty proof - NewMsgChannelOpenConfirm("testportid", "testchannel", proof, 0, addr), // proof height is zero + NewMsgChannelOpenConfirm("testportid", "testchannel", suite.proof, 1, addr), // valid msg + NewMsgChannelOpenConfirm(invalidShortPort, "testchannel", suite.proof, 1, addr), // too short port id + NewMsgChannelOpenConfirm(invalidLongPort, "testchannel", suite.proof, 1, addr), // too long port id + NewMsgChannelOpenConfirm(invalidPort, "testchannel", suite.proof, 1, addr), // port id contains non-alpha + NewMsgChannelOpenConfirm("testportid", invalidShortChannel, suite.proof, 1, addr), // too short channel id + NewMsgChannelOpenConfirm("testportid", invalidLongChannel, suite.proof, 1, addr), // too long channel id + NewMsgChannelOpenConfirm("testportid", invalidChannel, suite.proof, 1, addr), // channel id contains non-alpha + NewMsgChannelOpenConfirm("testportid", "testchannel", nil, 1, addr), // empty proof + NewMsgChannelOpenConfirm("testportid", "testchannel", commitment.Proof{Proof: nil}, 1, addr), // empty proof + NewMsgChannelOpenConfirm("testportid", "testchannel", suite.proof, 0, addr), // proof height is zero } testCases := []struct { @@ -215,21 +256,22 @@ func TestMsgChannelOpenConfirm(t *testing.T) { {testMsgs[5], false, "too long channel id"}, {testMsgs[6], false, "channel id contains non-alpha"}, {testMsgs[7], false, "empty proof"}, - {testMsgs[8], false, "proof height is zero"}, + {testMsgs[8], false, "empty proof"}, + {testMsgs[9], false, "proof height is zero"}, } for i, tc := range testCases { err := tc.msg.ValidateBasic() if tc.expPass { - require.Nil(t, err, "Msg %d failed: %v", i, err) + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) } else { - require.NotNil(t, err, "Invalid Msg %d passed: %s", i, tc.errMsg) + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) } } } // TestMsgChannelCloseInit tests ValidateBasic for MsgChannelCloseInit -func TestMsgChannelCloseInit(t *testing.T) { +func (suite *MsgTestSuite) TestMsgChannelCloseInit() { testMsgs := []MsgChannelCloseInit{ NewMsgChannelCloseInit("testportid", "testchannel", addr), // valid msg NewMsgChannelCloseInit(invalidShortPort, "testchannel", addr), // too short port id @@ -257,25 +299,26 @@ func TestMsgChannelCloseInit(t *testing.T) { for i, tc := range testCases { err := tc.msg.ValidateBasic() if tc.expPass { - require.Nil(t, err, "Msg %d failed: %v", i, err) + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) } else { - require.NotNil(t, err, "Invalid Msg %d passed: %s", i, tc.errMsg) + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) } } } // TestMsgChannelCloseConfirm tests ValidateBasic for MsgChannelCloseConfirm -func TestMsgChannelCloseConfirm(t *testing.T) { +func (suite *MsgTestSuite) TestMsgChannelCloseConfirm() { testMsgs := []MsgChannelCloseConfirm{ - NewMsgChannelCloseConfirm("testportid", "testchannel", proof, 1, addr), // valid msg - NewMsgChannelCloseConfirm(invalidShortPort, "testchannel", proof, 1, addr), // too short port id - NewMsgChannelCloseConfirm(invalidLongPort, "testchannel", proof, 1, addr), // too long port id - NewMsgChannelCloseConfirm(invalidPort, "testchannel", proof, 1, addr), // port id contains non-alpha - NewMsgChannelCloseConfirm("testportid", invalidShortChannel, proof, 1, addr), // too short channel id - NewMsgChannelCloseConfirm("testportid", invalidLongChannel, proof, 1, addr), // too long channel id - NewMsgChannelCloseConfirm("testportid", invalidChannel, proof, 1, addr), // channel id contains non-alpha - NewMsgChannelCloseConfirm("testportid", "testchannel", nil, 1, addr), // empty proof - NewMsgChannelCloseConfirm("testportid", "testchannel", proof, 0, addr), // proof height is zero + NewMsgChannelCloseConfirm("testportid", "testchannel", suite.proof, 1, addr), // valid msg + NewMsgChannelCloseConfirm(invalidShortPort, "testchannel", suite.proof, 1, addr), // too short port id + NewMsgChannelCloseConfirm(invalidLongPort, "testchannel", suite.proof, 1, addr), // too long port id + NewMsgChannelCloseConfirm(invalidPort, "testchannel", suite.proof, 1, addr), // port id contains non-alpha + NewMsgChannelCloseConfirm("testportid", invalidShortChannel, suite.proof, 1, addr), // too short channel id + NewMsgChannelCloseConfirm("testportid", invalidLongChannel, suite.proof, 1, addr), // too long channel id + NewMsgChannelCloseConfirm("testportid", invalidChannel, suite.proof, 1, addr), // channel id contains non-alpha + NewMsgChannelCloseConfirm("testportid", "testchannel", nil, 1, addr), // empty proof + NewMsgChannelCloseConfirm("testportid", "testchannel", commitment.Proof{Proof: nil}, 1, addr), // empty proof + NewMsgChannelCloseConfirm("testportid", "testchannel", suite.proof, 0, addr), // proof height is zero } testCases := []struct { @@ -291,15 +334,16 @@ func TestMsgChannelCloseConfirm(t *testing.T) { {testMsgs[5], false, "too long channel id"}, {testMsgs[6], false, "channel id contains non-alpha"}, {testMsgs[7], false, "empty proof"}, - {testMsgs[8], false, "proof height is zero"}, + {testMsgs[8], false, "empty proof"}, + {testMsgs[9], false, "proof height is zero"}, } for i, tc := range testCases { err := tc.msg.ValidateBasic() if tc.expPass { - require.Nil(t, err, "Msg %d failed: %v", i, err) + suite.Require().NoError(err, "Msg %d failed: %s", i, tc.errMsg) } else { - require.NotNil(t, err, "Invalid Msg %d passed: %s", i, tc.errMsg) + suite.Require().Error(err, "Invalid Msg %d passed: %s", i, tc.errMsg) } } } diff --git a/x/ibc/04-channel/types/packet.go b/x/ibc/04-channel/types/packet.go index 8cfadf458487..7d8242d8db30 100644 --- a/x/ibc/04-channel/types/packet.go +++ b/x/ibc/04-channel/types/packet.go @@ -1,8 +1,7 @@ package types import ( - "fmt" - + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/exported" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" ) @@ -11,13 +10,13 @@ var _ exported.PacketI = Packet{} // Packet defines a type that carries data across different chains through IBC type Packet struct { - Sequence uint64 `json:"sequence"` // number corresponds to the order of sends and receives, where a Packet with an earlier sequence number must be sent and received before a Packet with a later sequence number. - Timeout uint64 `json:"timeout"` // indicates a consensus height on the destination chain after which the Packet will no longer be processed, and will instead count as having timed-out. - SourcePort string `json:"source_port"` // identifies the port on the sending chain. - SourceChannel string `json:"source_channel"` // identifies the channel end on the sending chain. - DestinationPort string `json:"destination_port"` // identifies the port on the receiving chain. - DestinationChannel string `json:"destination_channel"` // identifies the channel end on the receiving chain. - Data []byte `json:"data"` // opaque value which can be defined by the application logic of the associated modules. + Sequence uint64 `json:"sequence" yaml:"sequence"` // number corresponds to the order of sends and receives, where a Packet with an earlier sequence number must be sent and received before a Packet with a later sequence number. + Timeout uint64 `json:"timeout" yaml:"timeout"` // indicates a consensus height on the destination chain after which the Packet will no longer be processed, and will instead count as having timed-out. + SourcePort string `json:"source_port" yaml:"source_port"` // identifies the port on the sending chain. + SourceChannel string `json:"source_channel" yaml:"source_channel"` // identifies the channel end on the sending chain. + DestinationPort string `json:"destination_port" yaml:"destination_port"` // identifies the port on the receiving chain. + DestinationChannel string `json:"destination_channel" yaml:"destination_channel"` // identifies the channel end on the receiving chain. + Data []byte `json:"data" yaml:"data"` // opaque value which can be defined by the application logic of the associated modules. } // NewPacket creates a new Packet instance @@ -26,13 +25,13 @@ func NewPacket( destinationPort, destinationChannel string, data []byte, ) Packet { return Packet{ - sequence, - timeout, - sourcePort, - sourceChannel, - destinationPort, - destinationChannel, - data, + Sequence: sequence, + Timeout: timeout, + SourcePort: sourcePort, + SourceChannel: sourceChannel, + DestinationPort: destinationPort, + DestinationChannel: destinationChannel, + Data: data, } } @@ -60,25 +59,37 @@ func (p Packet) GetData() []byte { return p.Data } // ValidateBasic implements PacketI interface func (p Packet) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(p.SourcePort); err != nil { - return ErrInvalidPacket(DefaultCodespace, fmt.Sprintf("invalid source port ID: %s", err.Error())) + return sdkerrors.Wrapf( + ErrInvalidPacket, + sdkerrors.Wrapf(err, "invalid source port ID: %s", p.SourcePort).Error(), + ) } if err := host.DefaultPortIdentifierValidator(p.DestinationPort); err != nil { - return ErrInvalidPacket(DefaultCodespace, fmt.Sprintf("invalid destination port ID: %s", err.Error())) + return sdkerrors.Wrapf( + ErrInvalidPacket, + sdkerrors.Wrapf(err, "invalid destination port ID: %s", p.DestinationPort).Error(), + ) } if err := host.DefaultChannelIdentifierValidator(p.SourceChannel); err != nil { - return ErrInvalidPacket(DefaultCodespace, fmt.Sprintf("invalid source channel ID: %s", err.Error())) + return sdkerrors.Wrapf( + ErrInvalidPacket, + sdkerrors.Wrapf(err, "invalid source channel ID: %s", p.SourceChannel).Error(), + ) } if err := host.DefaultChannelIdentifierValidator(p.DestinationChannel); err != nil { - return ErrInvalidPacket(DefaultCodespace, fmt.Sprintf("invalid destination channel ID: %s", err.Error())) + return sdkerrors.Wrapf( + ErrInvalidPacket, + sdkerrors.Wrapf(err, "invalid destination channel ID: %s", p.DestinationChannel).Error(), + ) } if p.Sequence == 0 { - return ErrInvalidPacket(DefaultCodespace, "packet sequence cannot be 0") + return sdkerrors.Wrap(ErrInvalidPacket, "packet sequence cannot be 0") } if p.Timeout == 0 { - return ErrPacketTimeout(DefaultCodespace) + return sdkerrors.Wrap(ErrInvalidPacket, "packet timeout cannot be 0") } if len(p.Data) == 0 { - return ErrInvalidPacket(DefaultCodespace, "packet data cannot be empty") + return sdkerrors.Wrap(ErrInvalidPacket, "packet data cannot be empty") } return nil } diff --git a/x/ibc/05-port/alias.go b/x/ibc/05-port/alias.go index ef3b6be60633..f53d7a41f9ee 100644 --- a/x/ibc/05-port/alias.go +++ b/x/ibc/05-port/alias.go @@ -12,13 +12,10 @@ import ( ) const ( - DefaultCodespace = types.DefaultCodespace - CodePortExists = types.CodePortExists - CodePortNotFound = types.CodePortNotFound - SubModuleName = types.SubModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute + SubModuleName = types.SubModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute ) var ( diff --git a/x/ibc/05-port/keeper/keeper.go b/x/ibc/05-port/keeper/keeper.go index 3d17a6881be8..45f0817f7702 100644 --- a/x/ibc/05-port/keeper/keeper.go +++ b/x/ibc/05-port/keeper/keeper.go @@ -5,25 +5,22 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/ibc/05-port/types" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" ) // Keeper defines the IBC connection keeper type Keeper struct { - storeKey sdk.StoreKey - cdc *codec.Codec - codespace sdk.CodespaceType - ports map[string]bool + storeKey sdk.StoreKey + cdc *codec.Codec + ports map[string]bool } // NewKeeper creates a new IBC connection Keeper instance -func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Keeper { +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { return Keeper{ - storeKey: key, - cdc: cdc, - codespace: sdk.CodespaceType(fmt.Sprintf("%s/%s", codespace, types.DefaultCodespace)), // "ibc/port", - ports: make(map[string]bool), // map of capability key names to port ids + storeKey: key, + cdc: cdc, + ports: make(map[string]bool), // map of capability key names to port ids } } diff --git a/x/ibc/05-port/types/errors.go b/x/ibc/05-port/types/errors.go index d15b07bf0791..a0778ecd6b01 100644 --- a/x/ibc/05-port/types/errors.go +++ b/x/ibc/05-port/types/errors.go @@ -1,44 +1,12 @@ package types import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// port error codes -const ( - DefaultCodespace sdk.CodespaceType = SubModuleName - - CodePortExists sdk.CodeType = 228 - CodePortNotFound sdk.CodeType = 229 - CodeInvalidPort sdk.CodeType = 230 +// IBC port sentinel errors +var ( + ErrPortExists = sdkerrors.Register(SubModuleName, 1, "port is already binded") + ErrPortNotFound = sdkerrors.Register(SubModuleName, 2, "port not found") + ErrInvalidPort = sdkerrors.Register(SubModuleName, 3, "invalid port") ) - -// ErrPortExists implements sdk.Error -func ErrPortExists(codespace sdk.CodespaceType, portID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodePortExists), - fmt.Sprintf("port with ID %s is already binded", portID), - ) -} - -// ErrPortNotFound implements sdk.Error -func ErrPortNotFound(codespace sdk.CodespaceType, portID string) error { - return sdkerrors.New( - string(codespace), - uint32(CodePortNotFound), - fmt.Sprintf("port with ID %s not found", portID), - ) -} - -// ErrInvalidPort implements sdk.Error -func ErrInvalidPort(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodePortNotFound), - msg, - ) -} diff --git a/x/ibc/20-transfer/alias.go b/x/ibc/20-transfer/alias.go index ee87c56d8b3e..00333d69f4b2 100644 --- a/x/ibc/20-transfer/alias.go +++ b/x/ibc/20-transfer/alias.go @@ -13,7 +13,6 @@ import ( const ( DefaultPacketTimeout = keeper.DefaultPacketTimeout - DefaultCodespace = types.DefaultCodespace AttributeKeyReceiver = types.AttributeKeyReceiver SubModuleName = types.SubModuleName StoreKey = types.StoreKey diff --git a/x/ibc/20-transfer/client/cli/cli.go b/x/ibc/20-transfer/client/cli/cli.go index 2007ed31908d..45a41239f974 100644 --- a/x/ibc/20-transfer/client/cli/cli.go +++ b/x/ibc/20-transfer/client/cli/cli.go @@ -3,7 +3,7 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" ) @@ -14,7 +14,7 @@ func GetQueryCmd(cdc *codec.Codec, queryRoute string) *cobra.Command { Short: "IBC fungible token transfer query subcommands", } - ics20TransferQueryCmd.AddCommand(client.GetCommands( + ics20TransferQueryCmd.AddCommand(flags.GetCommands( GetCmdQueryNextSequence(cdc, queryRoute), )...) @@ -28,7 +28,7 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command { Short: "IBC fungible token transfer transaction subcommands", } - ics20TransferTxCmd.AddCommand(client.PostCommands( + ics20TransferTxCmd.AddCommand(flags.PostCommands( GetTransferTxCmd(cdc), // GetMsgRecvPacketCmd(cdc), )...) diff --git a/x/ibc/20-transfer/handler.go b/x/ibc/20-transfer/handler.go index 731a6c27e7f5..6dfcf0470e4d 100644 --- a/x/ibc/20-transfer/handler.go +++ b/x/ibc/20-transfer/handler.go @@ -6,10 +6,10 @@ import ( ) // HandleMsgTransfer defines the sdk.Handler for MsgTransfer -func HandleMsgTransfer(ctx sdk.Context, k Keeper, msg MsgTransfer) (res sdk.Result) { +func HandleMsgTransfer(ctx sdk.Context, k Keeper, msg MsgTransfer) (*sdk.Result, error) { err := k.SendTransfer(ctx, msg.SourcePort, msg.SourceChannel, msg.Amount, msg.Sender, msg.Receiver, msg.Source) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvent( @@ -21,14 +21,16 @@ func HandleMsgTransfer(ctx sdk.Context, k Keeper, msg MsgTransfer) (res sdk.Resu ), ) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } // HandleMsgRecvPacket defines the sdk.Handler for MsgRecvPacket -func HandleMsgRecvPacket(ctx sdk.Context, k Keeper, msg MsgRecvPacket) (res sdk.Result) { +func HandleMsgRecvPacket(ctx sdk.Context, k Keeper, msg MsgRecvPacket) (*sdk.Result, error) { err := k.ReceivePacket(ctx, msg.Packet, msg.Proofs[0], msg.Height) if err != nil { - return sdk.ResultFromError(err) + return nil, err } ctx.EventManager().EmitEvent( @@ -39,5 +41,7 @@ func HandleMsgRecvPacket(ctx sdk.Context, k Keeper, msg MsgRecvPacket) (res sdk. ), ) - return sdk.Result{Events: ctx.EventManager().Events()} + return &sdk.Result{ + Events: ctx.EventManager().Events(), + }, nil } diff --git a/x/ibc/20-transfer/handler_test.go b/x/ibc/20-transfer/handler_test.go index 46ef6f08558b..d3db1ed739fc 100644 --- a/x/ibc/20-transfer/handler_test.go +++ b/x/ibc/20-transfer/handler_test.go @@ -160,35 +160,41 @@ func (suite *HandlerTestSuite) TestHandleMsgTransfer() { source := true msg := transfer.NewMsgTransfer(testPort1, testChannel1, testCoins, testAddr1, testAddr2, source) - res := transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // channel does not exist + res, err := transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // channel does not exist suite.createChannel(testPort1, testChannel1, testConnection, testPort2, testChannel2, channel.OPEN) - res = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // next send sequence not found + res, err = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // next send sequence not found nextSeqSend := uint64(1) suite.app.IBCKeeper.ChannelKeeper.SetNextSequenceSend(suite.ctx, testPort1, testChannel1, nextSeqSend) - res = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // sender has insufficient coins + res, err = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // sender has insufficient coins _ = suite.app.BankKeeper.SetCoins(suite.ctx, testAddr1, testCoins) - res = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.True(res.Code.IsOK(), "%v", res) // successfully executed + res, err = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().NoError(err) + suite.Require().NotNil(res, "%v", res) // successfully executed // test when the source is false source = false msg = transfer.NewMsgTransfer(testPort1, testChannel1, testPrefixedCoins2, testAddr1, testAddr2, source) _ = suite.app.BankKeeper.SetCoins(suite.ctx, testAddr1, testPrefixedCoins2) - res = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // incorrect denom prefix + res, err = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // incorrect denom prefix msg = transfer.NewMsgTransfer(testPort1, testChannel1, testPrefixedCoins1, testAddr1, testAddr2, source) suite.app.SupplyKeeper.SetSupply(suite.ctx, supply.NewSupply(testPrefixedCoins1)) _ = suite.app.BankKeeper.SetCoins(suite.ctx, testAddr1, testPrefixedCoins1) - res = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.True(res.Code.IsOK(), "%v", res) // successfully executed + res, err = transfer.HandleMsgTransfer(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().NoError(err) + suite.Require().NotNil(res, "%v", res) // successfully executed } func (suite *HandlerTestSuite) TestHandleRecvPacket() { @@ -205,16 +211,18 @@ func (suite *HandlerTestSuite) TestHandleRecvPacket() { msg := types.NewMsgRecvPacket(packet, []commitment.Proof{proofPacket}, uint64(proofHeight), testAddr1) suite.createChannel(testPort1, testChannel1, testConnection, testPort2, testChannel2, channel.OPEN) - res := transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // packet membership verification failed due to invalid counterparty packet commitment + res, err := transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // packet membership verification failed due to invalid counterparty packet commitment suite.app.IBCKeeper.ChannelKeeper.SetPacketCommitment(suite.ctx, testPort2, testChannel2, packetSeq, packetDataBz) suite.updateClient() proofPacket, proofHeight = suite.queryProof(packetCommitmentPath) msg = types.NewMsgRecvPacket(packet, []commitment.Proof{proofPacket}, uint64(proofHeight), testAddr1) - res = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // invalid packet data + res, err = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // invalid packet data // test when the source is true source := true @@ -228,8 +236,9 @@ func (suite *HandlerTestSuite) TestHandleRecvPacket() { proofPacket, proofHeight = suite.queryProof(packetCommitmentPath) msg = types.NewMsgRecvPacket(packet, []commitment.Proof{proofPacket}, uint64(proofHeight), testAddr1) - res = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // invalid denom prefix + res, err = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // invalid denom prefix packetData = types.NewPacketData(testPrefixedCoins1, testAddr1, testAddr2, source) packetDataBz, _ = suite.cdc.MarshalBinaryBare(packetData) @@ -240,8 +249,9 @@ func (suite *HandlerTestSuite) TestHandleRecvPacket() { proofPacket, proofHeight = suite.queryProof(packetCommitmentPath) msg = types.NewMsgRecvPacket(packet, []commitment.Proof{proofPacket}, uint64(proofHeight), testAddr1) - res = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.True(res.Code.IsOK(), "%v", res) // successfully executed + res, err = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().NoError(err) + suite.Require().NotNil(res, "%v", res) // successfully executed // test when the source is false source = false @@ -255,8 +265,9 @@ func (suite *HandlerTestSuite) TestHandleRecvPacket() { proofPacket, proofHeight = suite.queryProof(packetCommitmentPath) msg = types.NewMsgRecvPacket(packet, []commitment.Proof{proofPacket}, uint64(proofHeight), testAddr1) - res = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // invalid denom prefix + res, err = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // invalid denom prefix packetData = types.NewPacketData(testPrefixedCoins2, testAddr1, testAddr2, source) packetDataBz, _ = suite.cdc.MarshalBinaryBare(packetData) @@ -267,13 +278,15 @@ func (suite *HandlerTestSuite) TestHandleRecvPacket() { proofPacket, proofHeight = suite.queryProof(packetCommitmentPath) msg = types.NewMsgRecvPacket(packet, []commitment.Proof{proofPacket}, uint64(proofHeight), testAddr1) - res = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.False(res.Code.IsOK(), "%v", res) // insufficient coins in the corresponding escrow account + res, err = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().Error(err) + suite.Require().Nil(res, "%v", res) // insufficient coins in the corresponding escrow account escrowAddress := types.GetEscrowAddress(testPort1, testChannel1) _ = suite.app.BankKeeper.SetCoins(suite.ctx, escrowAddress, testCoins) - res = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) - suite.True(res.Code.IsOK(), "%v", res) // successfully executed + res, err = transfer.HandleMsgRecvPacket(suite.ctx, suite.app.IBCKeeper.TransferKeeper, msg) + suite.Require().NoError(err) + suite.Require().NotNil(res, "%v", res) // successfully executed } func TestHandlerTestSuite(t *testing.T) { diff --git a/x/ibc/20-transfer/keeper/callbacks.go b/x/ibc/20-transfer/keeper/callbacks.go index 57c772e67b2f..b4c0675bed78 100644 --- a/x/ibc/20-transfer/keeper/callbacks.go +++ b/x/ibc/20-transfer/keeper/callbacks.go @@ -1,7 +1,6 @@ package keeper import ( - "fmt" "strings" sdk "github.com/cosmos/cosmos-sdk/types" @@ -24,18 +23,19 @@ func (k Keeper) OnChanOpenInit( version string, ) error { if order != channel.UNORDERED { - return channel.ErrInvalidChannel(k.codespace, "channel must be UNORDERED") + return sdkerrors.Wrap(channel.ErrInvalidChannel, "channel must be UNORDERED") } // NOTE: here the capability key name defines the port ID of the counterparty if counterparty.PortID != k.boundedCapability.Name() { - return port.ErrInvalidPort( - k.codespace, - fmt.Sprintf("counterparty port ID doesn't match the capability key (%s ≠ %s)", counterparty.PortID, k.boundedCapability.Name())) + return sdkerrors.Wrapf( + port.ErrInvalidPort, + "counterparty port ID doesn't match the capability key (%s ≠ %s)", counterparty.PortID, k.boundedCapability.Name(), + ) } if strings.TrimSpace(version) != "" { - return ibctypes.ErrInvalidVersion(k.codespace, "version must be blank") + return sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "version must be blank") } // NOTE: as the escrow address is generated from both the port and channel IDs @@ -55,22 +55,23 @@ func (k Keeper) OnChanOpenTry( counterpartyVersion string, ) error { if order != channel.UNORDERED { - return channel.ErrInvalidChannel(k.codespace, "channel must be UNORDERED") + return sdkerrors.Wrap(channel.ErrInvalidChannel, "channel must be UNORDERED") } // NOTE: here the capability key name defines the port ID of the counterparty if counterparty.PortID != k.boundedCapability.Name() { - return port.ErrInvalidPort( - k.codespace, - fmt.Sprintf("counterparty port ID doesn't match the capability key (%s ≠ %s)", counterparty.PortID, k.boundedCapability.Name())) + return sdkerrors.Wrapf( + port.ErrInvalidPort, + "counterparty port ID doesn't match the capability key (%s ≠ %s)", counterparty.PortID, k.boundedCapability.Name(), + ) } if strings.TrimSpace(version) != "" { - return ibctypes.ErrInvalidVersion(k.codespace, "version must be blank") + return sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "version must be blank") } if strings.TrimSpace(counterpartyVersion) != "" { - return ibctypes.ErrInvalidVersion(k.codespace, "counterparty version must be blank") + return sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "counterparty version must be blank") } // NOTE: as the escrow address is generated from both the port and channel IDs @@ -86,7 +87,7 @@ func (k Keeper) OnChanOpenAck( version string, ) error { if strings.TrimSpace(version) != "" { - return ibctypes.ErrInvalidVersion(k.codespace, "version must be blank") + return sdkerrors.Wrap(ibctypes.ErrInvalidVersion, "version must be blank") } return nil @@ -169,7 +170,10 @@ func (k Keeper) OnTimeoutPacket( for i, coin := range data.Amount { coin := coin if !strings.HasPrefix(coin.Denom, prefix) { - return sdk.ErrInvalidCoins(fmt.Sprintf("%s doesn't contain the prefix '%s'", coin.Denom, prefix)) + return sdkerrors.Wrapf( + sdkerrors.ErrInvalidCoins, + "%s doesn't contain the prefix '%s'", coin.Denom, prefix, + ) } coins[i] = sdk.NewCoin(coin.Denom[len(prefix):], coin.Amount) } diff --git a/x/ibc/20-transfer/keeper/keeper.go b/x/ibc/20-transfer/keeper/keeper.go index c42786f42741..341f75374881 100644 --- a/x/ibc/20-transfer/keeper/keeper.go +++ b/x/ibc/20-transfer/keeper/keeper.go @@ -19,9 +19,8 @@ const ( // Keeper defines the IBC transfer keeper type Keeper struct { - storeKey sdk.StoreKey - cdc *codec.Codec - codespace sdk.CodespaceType + storeKey sdk.StoreKey + cdc *codec.Codec // Capability key and port to which ICS20 is binded. Used for packet relaying. boundedCapability sdk.CapabilityKey @@ -35,7 +34,7 @@ type Keeper struct { // NewKeeper creates a new IBC transfer Keeper instance func NewKeeper( - cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType, + cdc *codec.Codec, key sdk.StoreKey, capKey sdk.CapabilityKey, clientKeeper types.ClientKeeper, connnectionKeeper types.ConnectionKeeper, channelKeeper types.ChannelKeeper, bankKeeper types.BankKeeper, supplyKeeper types.SupplyKeeper, @@ -49,7 +48,6 @@ func NewKeeper( return Keeper{ storeKey: key, cdc: cdc, - codespace: sdk.CodespaceType(fmt.Sprintf("%s/%s", codespace, types.DefaultCodespace)), // "ibc/transfer", boundedCapability: capKey, clientKeeper: clientKeeper, connectionKeeper: connnectionKeeper, diff --git a/x/ibc/20-transfer/keeper/relay.go b/x/ibc/20-transfer/keeper/relay.go index 8c3a6bb2ea5b..f30d59de04fb 100644 --- a/x/ibc/20-transfer/keeper/relay.go +++ b/x/ibc/20-transfer/keeper/relay.go @@ -1,7 +1,6 @@ package keeper import ( - "fmt" "strings" sdk "github.com/cosmos/cosmos-sdk/types" @@ -25,7 +24,7 @@ func (k Keeper) SendTransfer( // get the port and channel of the counterparty sourceChan, found := k.channelKeeper.GetChannel(ctx, sourcePort, sourceChannel) if !found { - return channel.ErrChannelNotFound(k.codespace, sourcePort, sourceChannel) + return sdkerrors.Wrap(channel.ErrChannelNotFound, sourceChannel) } destinationPort := sourceChan.Counterparty.PortID @@ -34,7 +33,7 @@ func (k Keeper) SendTransfer( // get the next sequence sequence, found := k.channelKeeper.GetNextSequenceSend(ctx, sourcePort, sourceChannel) if !found { - return channel.ErrSequenceNotFound(k.codespace, "send") + return channel.ErrSequenceSendNotFound } coins := make(sdk.Coins, len(amount)) @@ -81,7 +80,10 @@ func (k Keeper) ReceiveTransfer( prefix := types.GetDenomPrefix(destinationPort, destinationChannel) for _, coin := range data.Amount { if !strings.HasPrefix(coin.Denom, prefix) { - return sdk.ErrInvalidCoins(fmt.Sprintf("%s doesn't contain the prefix '%s'", coin.Denom, prefix)) + return sdkerrors.Wrapf( + sdkerrors.ErrInvalidCoins, + "%s doesn't contain the prefix '%s'", coin.Denom, prefix, + ) } } @@ -102,7 +104,10 @@ func (k Keeper) ReceiveTransfer( coins := make(sdk.Coins, len(data.Amount)) for i, coin := range data.Amount { if !strings.HasPrefix(coin.Denom, prefix) { - return sdk.ErrInvalidCoins(fmt.Sprintf("%s doesn't contain the prefix '%s'", coin.Denom, prefix)) + return sdkerrors.Wrapf( + sdkerrors.ErrInvalidCoins, + "%s doesn't contain the prefix '%s'", coin.Denom, prefix, + ) } coins[i] = sdk.NewCoin(coin.Denom[len(prefix):], coin.Amount) } @@ -132,7 +137,10 @@ func (k Keeper) createOutgoingPacket( coins := make(sdk.Coins, len(amount)) for i, coin := range amount { if !strings.HasPrefix(coin.Denom, prefix) { - return sdk.ErrInvalidCoins(fmt.Sprintf("%s doesn't contain the prefix '%s'", coin.Denom, prefix)) + return sdkerrors.Wrapf( + sdkerrors.ErrInvalidCoins, + "%s doesn't contain the prefix '%s'", coin.Denom, prefix, + ) } coins[i] = sdk.NewCoin(coin.Denom[len(prefix):], coin.Amount) } @@ -147,7 +155,10 @@ func (k Keeper) createOutgoingPacket( prefix := types.GetDenomPrefix(sourcePort, sourceChannel) for _, coin := range amount { if !strings.HasPrefix(coin.Denom, prefix) { - return sdk.ErrInvalidCoins(fmt.Sprintf("%s doesn't contain the prefix '%s'", coin.Denom, prefix)) + return sdkerrors.Wrapf( + sdkerrors.ErrInvalidCoins, + "%s doesn't contain the prefix '%s'", coin.Denom, prefix, + ) } } diff --git a/x/ibc/20-transfer/types/expected_keepers.go b/x/ibc/20-transfer/types/expected_keepers.go index 252eb8060645..e7c709306228 100644 --- a/x/ibc/20-transfer/types/expected_keepers.go +++ b/x/ibc/20-transfer/types/expected_keepers.go @@ -12,7 +12,7 @@ import ( // BankKeeper defines the expected bank keeper type BankKeeper interface { - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) sdk.Error + SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error } // ChannelKeeper defines the expected IBC channel keeper @@ -37,8 +37,8 @@ type ConnectionKeeper interface { type SupplyKeeper interface { GetModuleAddress(name string) sdk.AccAddress GetModuleAccount(ctx sdk.Context, name string) supplyexported.ModuleAccountI - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) sdk.Error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) sdk.Error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) sdk.Error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) sdk.Error + MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error } diff --git a/x/ibc/20-transfer/types/keys.go b/x/ibc/20-transfer/types/keys.go index 469456bbd946..1a3a8458ae53 100644 --- a/x/ibc/20-transfer/types/keys.go +++ b/x/ibc/20-transfer/types/keys.go @@ -21,9 +21,6 @@ const ( // QuerierRoute is the querier route for IBC transfer QuerierRoute = SubModuleName - - // DefaultCodespace is the default error codespace for the ibc transfers - DefaultCodespace sdk.CodespaceType = SubModuleName ) // GetEscrowAddress returns the escrow address for the specified channel diff --git a/x/ibc/20-transfer/types/msgs.go b/x/ibc/20-transfer/types/msgs.go index 2a353de56cff..42a56e0f30a6 100644 --- a/x/ibc/20-transfer/types/msgs.go +++ b/x/ibc/20-transfer/types/msgs.go @@ -3,7 +3,6 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - connectiontypes "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" channelexported "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/exported" commitment "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment" host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" @@ -44,24 +43,24 @@ func (MsgTransfer) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgTransfer) ValidateBasic() sdk.Error { +func (msg MsgTransfer) ValidateBasic() error { if err := host.DefaultPortIdentifierValidator(msg.SourcePort); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid source port ID")) + return sdkerrors.Wrap(err, "invalid source port ID") } if err := host.DefaultChannelIdentifierValidator(msg.SourceChannel); err != nil { - return sdk.ConvertError(sdkerrors.Wrap(err, "invalid source channel ID")) + return sdkerrors.Wrap(err, "invalid source channel ID") } if !msg.Amount.IsAllPositive() { - return sdk.ErrInsufficientCoins("transfer amount must be positive") + return sdkerrors.ErrInsufficientFunds } if !msg.Amount.IsValid() { - return sdk.ErrInvalidCoins("transfer amount is invalid") + return sdkerrors.ErrInvalidCoins } if msg.Sender.Empty() { - return sdk.ErrInvalidAddress("missing sender address") + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing sender address") } if msg.Receiver.Empty() { - return sdk.ErrInvalidAddress("missing recipient address") + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing recipient address") } return nil } @@ -104,26 +103,22 @@ func (MsgRecvPacket) Type() string { } // ValidateBasic implements sdk.Msg -func (msg MsgRecvPacket) ValidateBasic() sdk.Error { +func (msg MsgRecvPacket) ValidateBasic() error { if msg.Height == 0 { - return sdk.ConvertError(connectiontypes.ErrInvalidHeight(DefaultCodespace, "height must be > 0")) + return sdkerrors.Wrap(ibctypes.ErrInvalidHeight, "height must be > 0") } - if msg.Proofs == nil || len(msg.Proofs) == 0 { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "missing proofs")) + return sdkerrors.Wrap(commitment.ErrInvalidProof, "missing proof") } - for _, proof := range msg.Proofs { - if proof.Proof == nil { - return sdk.ConvertError(ibctypes.ErrInvalidProof(DefaultCodespace, "cannot submit an empty proof")) + if err := proof.ValidateBasic(); err != nil { + return err } } - if msg.Signer.Empty() { - return sdk.ErrInvalidAddress("missing signer address") + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing sender address") } - - return sdk.ConvertError(msg.Packet.ValidateBasic()) + return msg.Packet.ValidateBasic() } // GetSignBytes implements sdk.Msg diff --git a/x/ibc/20-transfer/types/packet.go b/x/ibc/20-transfer/types/packet.go index f7c79b9be07e..19aed7c60343 100644 --- a/x/ibc/20-transfer/types/packet.go +++ b/x/ibc/20-transfer/types/packet.go @@ -4,6 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // PacketData defines a struct for the packet payload @@ -38,18 +39,18 @@ func (pd PacketData) String() string { } // ValidateBasic performs a basic check of the packet fields -func (pd PacketData) ValidateBasic() sdk.Error { +func (pd PacketData) ValidateBasic() error { if !pd.Amount.IsAllPositive() { - return sdk.ErrInsufficientCoins("transfer amount must be positive") + return sdkerrors.ErrInsufficientFunds } if !pd.Amount.IsValid() { - return sdk.ErrInvalidCoins("transfer amount is invalid") + return sdkerrors.ErrInvalidCoins } if pd.Sender.Empty() { - return sdk.ErrInvalidAddress("missing sender address") + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing sender address") } if pd.Receiver.Empty() { - return sdk.ErrInvalidAddress("missing recipient address") + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing receiver address") } return nil } diff --git a/x/ibc/23-commitment/errors.go b/x/ibc/23-commitment/errors.go new file mode 100644 index 000000000000..89b2bf0b0ad7 --- /dev/null +++ b/x/ibc/23-commitment/errors.go @@ -0,0 +1,14 @@ +package commitment + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// SubModuleName is the error codespace +const SubModuleName string = "ibc/commitment" + +// IBC connection sentinel errors +var ( + ErrInvalidProof = sdkerrors.Register(SubModuleName, 1, "invalid proof") + ErrInvalidPrefix = sdkerrors.Register(SubModuleName, 2, "invalid prefix") +) diff --git a/x/ibc/23-commitment/merkle.go b/x/ibc/23-commitment/merkle.go index 33d84408f997..39a355fc9ce8 100644 --- a/x/ibc/23-commitment/merkle.go +++ b/x/ibc/23-commitment/merkle.go @@ -151,3 +151,11 @@ func (proof Proof) VerifyNonMembership(root RootI, path PathI) bool { err := runtime.VerifyAbsence(proof.Proof, root.GetHash(), path.String()) return err == nil } + +// ValidateBasic checks if the proof is empty. +func (proof Proof) ValidateBasic() error { + if (proof == Proof{}) || proof.Proof == nil { + return ErrInvalidProof + } + return nil +} diff --git a/x/ibc/23-commitment/merkle_test.go b/x/ibc/23-commitment/merkle_test.go index 01dc9f2edcb4..7dcb5cbfd0fc 100644 --- a/x/ibc/23-commitment/merkle_test.go +++ b/x/ibc/23-commitment/merkle_test.go @@ -25,6 +25,8 @@ func (suite *MerkleTestSuite) TestVerifyMembership() { proof := commitment.Proof{ Proof: res.Proof, } + suite.Require().NoError(proof.ValidateBasic()) + suite.Require().Error(commitment.Proof{}.ValidateBasic()) cases := []struct { name string @@ -73,6 +75,7 @@ func (suite *MerkleTestSuite) TestVerifyNonMembership() { proof := commitment.Proof{ Proof: res.Proof, } + suite.Require().NoError(proof.ValidateBasic()) cases := []struct { name string diff --git a/x/ibc/23-commitment/types.go b/x/ibc/23-commitment/types.go index 1b70f4f04d9c..bd2968da88dc 100644 --- a/x/ibc/23-commitment/types.go +++ b/x/ibc/23-commitment/types.go @@ -38,6 +38,8 @@ type ProofI interface { GetCommitmentType() Type VerifyMembership(RootI, PathI, []byte) bool VerifyNonMembership(RootI, PathI) bool + + ValidateBasic() error } // Type defines the type of the commitment diff --git a/x/ibc/24-host/errors.go b/x/ibc/24-host/errors.go index 0ff6ad59d896..26b7919e6cb5 100644 --- a/x/ibc/24-host/errors.go +++ b/x/ibc/24-host/errors.go @@ -1,47 +1,15 @@ package host import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // SubModuleName defines the ICS 24 host const SubModuleName = "host" -// Error codes specific to the ibc host submodule -const ( - DefaultCodespace sdk.CodespaceType = SubModuleName - - CodeInvalidID sdk.CodeType = 231 - CodeInvalidPath sdk.CodeType = 232 - CodeInvalidPacket sdk.CodeType = 233 +// IBC client sentinel errors +var ( + ErrInvalidID = sdkerrors.Register(SubModuleName, 1, "invalid identifier") + ErrInvalidPath = sdkerrors.Register(SubModuleName, 2, "invalid path") + ErrInvalidPacket = sdkerrors.Register(SubModuleName, 3, "invalid packet") ) - -// ErrInvalidID returns a typed ABCI error for an invalid identifier -func ErrInvalidID(codespace sdk.CodespaceType, id string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidID), - fmt.Sprintf("invalid identifier '%s'", id), - ) -} - -// ErrInvalidPath returns a typed ABCI error for an invalid path -func ErrInvalidPath(codespace sdk.CodespaceType, path string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidPath), - fmt.Sprintf("invalid path '%s'", path), - ) -} - -// ErrInvalidPacket returns a typed ABCI error for an invalid identifier -func ErrInvalidPacket(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidPacket), - fmt.Sprintf("invalid packet: '%s'", msg), - ) -} diff --git a/x/ibc/24-host/validate.go b/x/ibc/24-host/validate.go index f6b3d14751e7..c360abf8616f 100644 --- a/x/ibc/24-host/validate.go +++ b/x/ibc/24-host/validate.go @@ -25,15 +25,15 @@ type ValidateFn func(string) error func defaultIdentifierValidator(id string, min, max int) error { // valid id MUST NOT contain "/" separator if strings.Contains(id, "/") { - return sdkerrors.Wrap(ErrInvalidID(DefaultCodespace, id), "identifier cannot contain separator: /") + return sdkerrors.Wrapf(ErrInvalidID, "identifier %s cannot contain separator '/'", id) } // valid id must be between 10 and 20 characters if len(id) < min || len(id) > max { - return sdkerrors.Wrapf(ErrInvalidID(DefaultCodespace, id), "identifier has invalid length: %d, must be between %d-%d characters", len(id), min, max) + return sdkerrors.Wrapf(ErrInvalidID, "identifier %s has invalid length: %d, must be between %d-%d characters", id, len(id), min, max) } // valid id must contain only lower alphabetic characters if !isAlphaLower(id) { - return sdkerrors.Wrap(ErrInvalidID(DefaultCodespace, id), "identifier must contain only lowercase alphabetic characters") + return sdkerrors.Wrapf(ErrInvalidID, "identifier %s must contain only lowercase alphabetic characters", id) } return nil } @@ -76,7 +76,7 @@ func NewPathValidator(idValidator ValidateFn) ValidateFn { // Each path element must either be valid identifier or alphanumeric err := idValidator(p) if err != nil && !isAlphaNumeric(p) { - return sdkerrors.Wrapf(ErrInvalidPath(DefaultCodespace, path), "path contains invalid identifier or non-alphanumeric path element: %s", p) + return sdkerrors.Wrapf(ErrInvalidPath, "path %s contains invalid identifier or non-alphanumeric path element: %s", path, p) } } return nil @@ -89,13 +89,13 @@ func NewPathValidator(idValidator ValidateFn) ValidateFn { func DefaultPathValidator(path string) error { pathArr := strings.Split(path, "/") if pathArr[0] == path { - return sdkerrors.Wrap(ErrInvalidPath(DefaultCodespace, path), "path doesn't contain any separator '/'") + return sdkerrors.Wrapf(ErrInvalidPath, "path %s doesn't contain any separator '/'", path) } for _, p := range pathArr { // Each path element must be alphanumeric and non-blank if strings.TrimSpace(p) == "" || !isAlphaNumeric(p) { - return sdkerrors.Wrapf(ErrInvalidPath(DefaultCodespace, path), "invalid path element containing non-alphanumeric characters: '%s'", p) + return sdkerrors.Wrapf(ErrInvalidPath, "path %s contains an invalid non-alphanumeric character: '%s'", path, p) } } return nil diff --git a/x/ibc/alias.go b/x/ibc/alias.go index abb2aae3c59a..7c1ad02349e2 100644 --- a/x/ibc/alias.go +++ b/x/ibc/alias.go @@ -12,11 +12,10 @@ import ( ) const ( - ModuleName = types.ModuleName - StoreKey = types.StoreKey - QuerierRoute = types.QuerierRoute - RouterKey = types.RouterKey - DefaultCodespace = types.DefaultCodespace + ModuleName = types.ModuleName + StoreKey = types.StoreKey + QuerierRoute = types.QuerierRoute + RouterKey = types.RouterKey ) var ( diff --git a/x/ibc/client/cli/cli.go b/x/ibc/client/cli/cli.go index 4818d68008d6..cb095b788a52 100644 --- a/x/ibc/client/cli/cli.go +++ b/x/ibc/client/cli/cli.go @@ -4,6 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" ibcclient "github.com/cosmos/cosmos-sdk/x/ibc/02-client" connection "github.com/cosmos/cosmos-sdk/x/ibc/03-connection" @@ -22,7 +23,7 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } - ibcTxCmd.AddCommand(client.PostCommands( + ibcTxCmd.AddCommand(flags.PostCommands( ibcclient.GetTxCmd(cdc, storeKey), connection.GetTxCmd(cdc, storeKey), channel.GetTxCmd(cdc, storeKey), @@ -42,7 +43,7 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } - ibcQueryCmd.AddCommand(client.GetCommands( + ibcQueryCmd.AddCommand(flags.GetCommands( ibcclient.GetQueryCmd(cdc, queryRoute), connection.GetQueryCmd(cdc, queryRoute), channel.GetQueryCmd(cdc, queryRoute), diff --git a/x/ibc/handler.go b/x/ibc/handler.go index 1a1e2d0189be..d7d7262a165e 100644 --- a/x/ibc/handler.go +++ b/x/ibc/handler.go @@ -1,9 +1,8 @@ package ibc import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" client "github.com/cosmos/cosmos-sdk/x/ibc/02-client" connection "github.com/cosmos/cosmos-sdk/x/ibc/03-connection" channel "github.com/cosmos/cosmos-sdk/x/ibc/04-channel" @@ -12,7 +11,7 @@ import ( // NewHandler defines the IBC handler func NewHandler(k Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { @@ -63,8 +62,7 @@ func NewHandler(k Keeper) sdk.Handler { return transfer.HandleMsgRecvPacket(ctx, k.TransferKeeper, msg) default: - errMsg := fmt.Sprintf("unrecognized IBC message type: %T", msg) - return sdk.ErrUnknownRequest(errMsg).Result() + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized IBC message type: %T", msg) } } } diff --git a/x/ibc/keeper/keeper.go b/x/ibc/keeper/keeper.go index 2c28b5c9dd51..694dae13b9ec 100644 --- a/x/ibc/keeper/keeper.go +++ b/x/ibc/keeper/keeper.go @@ -22,18 +22,18 @@ type Keeper struct { // NewKeeper creates a new ibc Keeper func NewKeeper( - cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType, + cdc *codec.Codec, key sdk.StoreKey, bk transfer.BankKeeper, sk transfer.SupplyKeeper, ) Keeper { - clientKeeper := client.NewKeeper(cdc, key, codespace) - connectionKeeper := connection.NewKeeper(cdc, key, codespace, clientKeeper) - portKeeper := port.NewKeeper(cdc, key, codespace) - channelKeeper := channel.NewKeeper(cdc, key, codespace, clientKeeper, connectionKeeper, portKeeper) + clientKeeper := client.NewKeeper(cdc, key) + connectionKeeper := connection.NewKeeper(cdc, key, clientKeeper) + portKeeper := port.NewKeeper(cdc, key) + channelKeeper := channel.NewKeeper(cdc, key, clientKeeper, connectionKeeper, portKeeper) // TODO: move out of IBC keeper. Blocked on ADR15 capKey := portKeeper.BindPort(bank.ModuleName) transferKeeper := transfer.NewKeeper( - cdc, key, codespace, capKey, + cdc, key, capKey, clientKeeper, connectionKeeper, channelKeeper, bk, sk, ) diff --git a/x/ibc/keeper/querier.go b/x/ibc/keeper/querier.go index 02b468cdb031..68447885bbd1 100644 --- a/x/ibc/keeper/querier.go +++ b/x/ibc/keeper/querier.go @@ -12,7 +12,7 @@ import ( // NewQuerier creates a querier for the IBC module func NewQuerier(k Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { var ( res []byte err error @@ -56,6 +56,6 @@ func NewQuerier(k Keeper) sdk.Querier { err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown IBC query endpoint") } - return res, sdk.ConvertError(err) + return res, err } } diff --git a/x/ibc/types/errors.go b/x/ibc/types/errors.go index 086851321b6a..5246b3c5a206 100644 --- a/x/ibc/types/errors.go +++ b/x/ibc/types/errors.go @@ -1,33 +1,11 @@ package types import ( - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// common IBC error codes -const ( - // DefaultCodespace of the IBC module - DefaultCodespace sdk.CodespaceType = ModuleName - - CodeInvalidProof sdk.CodeType = 234 - CodeInvalidVersion sdk.CodeType = 235 +// ibc module common sentinel errors +var ( + ErrInvalidHeight = sdkerrors.Register(ModuleName, 1, "invalid height") + ErrInvalidVersion = sdkerrors.Register(ModuleName, 2, "invalid version") ) - -// ErrInvalidProof implements sdk.Error -func ErrInvalidProof(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidProof), - msg, - ) -} - -// ErrInvalidVersion implements sdk.Error -func ErrInvalidVersion(codespace sdk.CodespaceType, msg string) error { - return sdkerrors.New( - string(codespace), - uint32(CodeInvalidVersion), - msg, - ) -}