Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding router v2 #7392

Merged
merged 3 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions modules/core/04-channel/v2/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package keeper

import (
"context"

errorsmod "cosmossdk.io/errors"

sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -41,16 +42,16 @@ func (k *Keeper) SendPacket(ctx context.Context, msg *channeltypesv2.MsgSendPack
return &channeltypesv2.MsgSendPacketResponse{Sequence: sequence}, nil
}

func (k Keeper) Acknowledgement(ctx context.Context, acknowledgement *channeltypesv2.MsgAcknowledgement) (*channeltypesv2.MsgAcknowledgementResponse, error) {
func (*Keeper) Acknowledgement(ctx context.Context, acknowledgement *channeltypesv2.MsgAcknowledgement) (*channeltypesv2.MsgAcknowledgementResponse, error) {
panic("implement me")
}

// RecvPacket implements the PacketMsgServer RecvPacket method.
func (k *Keeper) RecvPacket(ctx context.Context, packet *channeltypesv2.MsgRecvPacket) (*channeltypesv2.MsgRecvPacketResponse, error) {
func (*Keeper) RecvPacket(ctx context.Context, packet *channeltypesv2.MsgRecvPacket) (*channeltypesv2.MsgRecvPacketResponse, error) {
panic("implement me")
}

// Timeout implements the PacketMsgServer Timeout method.
func (k *Keeper) Timeout(ctx context.Context, timeout *channeltypesv2.MsgTimeout) (*channeltypesv2.MsgTimeoutResponse, error) {
func (*Keeper) Timeout(ctx context.Context, timeout *channeltypesv2.MsgTimeout) (*channeltypesv2.MsgTimeoutResponse, error) {
panic("implement me")
}
12 changes: 6 additions & 6 deletions modules/core/04-channel/v2/keeper/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (k *Keeper) sendPacket(
}

destID := counterparty.CounterpartyChannelId
clientId := counterparty.ClientId
clientID := counterparty.ClientId

// retrieve the sequence send for this channel
// if no packets have been sent yet, initialize the sequence to 1.
Expand All @@ -55,17 +55,17 @@ func (k *Keeper) sendPacket(
}

// check that the client of counterparty chain is still active
if status := k.ClientKeeper.GetClientStatus(ctx, clientId); status != exported.Active {
return 0, errorsmod.Wrapf(clienttypes.ErrClientNotActive, "client (%s) status is %s", clientId, status)
if status := k.ClientKeeper.GetClientStatus(ctx, clientID); status != exported.Active {
return 0, errorsmod.Wrapf(clienttypes.ErrClientNotActive, "client (%s) status is %s", clientID, status)
}

// retrieve latest height and timestamp of the client of counterparty chain
latestHeight := k.ClientKeeper.GetClientLatestHeight(ctx, clientId)
latestHeight := k.ClientKeeper.GetClientLatestHeight(ctx, clientID)
if latestHeight.IsZero() {
return 0, errorsmod.Wrapf(clienttypes.ErrInvalidHeight, "cannot send packet using client (%s) with zero height", clientId)
return 0, errorsmod.Wrapf(clienttypes.ErrInvalidHeight, "cannot send packet using client (%s) with zero height", clientID)
}

latestTimestamp, err := k.ClientKeeper.GetClientTimestampAtHeight(ctx, clientId, latestHeight)
latestTimestamp, err := k.ClientKeeper.GetClientTimestampAtHeight(ctx, clientID, latestHeight)
if err != nil {
return 0, err
}
Expand Down
15 changes: 15 additions & 0 deletions modules/core/api/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package api_test

import (
"testing"

testifysuite "github.com/stretchr/testify/suite"
)

type APITestSuite struct {
testifysuite.Suite
}

func TestApiTestSuite(t *testing.T) {
testifysuite.Run(t, new(APITestSuite))
}
2 changes: 2 additions & 0 deletions modules/core/api/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package api

import (
"context"

sdk "github.com/cosmos/cosmos-sdk/types"

channeltypesv2 "github.com/cosmos/ibc-go/v9/modules/core/04-channel/v2/types"
)

Expand Down
69 changes: 69 additions & 0 deletions modules/core/api/router.go
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't router be in 05-port/types? Or is there some problem with that?

Would expect api to be as dumb as possible wrt to type defintions/interfaces.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the idea was to move all the new stuff to API package, we can re-visit structure after all the types are in place though I think.

Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package api

import (
"errors"
"fmt"
"strings"

sdk "github.com/cosmos/cosmos-sdk/types"
)

// Router contains all the module-defined callbacks required by IBC Protocol V2.
type Router struct {
routes map[string]IBCModule
}

// NewRouter creates a new Router instance.
func NewRouter() *Router {
return &Router{
routes: make(map[string]IBCModule),
}
}

// AddRoute registers a route for a given module name.
func (rtr *Router) AddRoute(module string, cbs IBCModule) *Router {
if !sdk.IsAlphaNumeric(module) {
panic(errors.New("route expressions can only contain alphanumeric characters"))
}

if rtr.HasRoute(module) {
panic(fmt.Errorf("route %s has already been registered", module))
}

rtr.routes[module] = cbs

return rtr
}

// Route returns the IBCModule for a given module name.
func (rtr *Router) Route(module string) IBCModule {
route, ok := rtr.routeOrPrefixedRoute(module)
if !ok {
panic(fmt.Sprintf("no route for %s", module))
}
return route
}

// HasRoute returns true if the Router has a module registered or false otherwise.
func (rtr *Router) HasRoute(module string) bool {
_, ok := rtr.routeOrPrefixedRoute(module)
return ok
}

// routeOrPrefixedRoute returns the IBCModule for a given module name.
// if an exact match is not found, a route with the provided prefix is searched for instead.
func (rtr *Router) routeOrPrefixedRoute(module string) (IBCModule, bool) {
route, ok := rtr.routes[module]
if ok {
return route, true
}

// it's possible that some routes have been dynamically added e.g. with interchain accounts.
// in this case, we need to check if the module has the specified prefix.
for prefix, ibcModule := range rtr.routes {
if strings.HasPrefix(module, prefix) {
return ibcModule, true
}
}
return nil, false
}
81 changes: 81 additions & 0 deletions modules/core/api/router_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package api_test

import (
"github.com/cosmos/ibc-go/v9/modules/core/api"
mockv2 "github.com/cosmos/ibc-go/v9/testing/mock/v2"
)

func (suite *APITestSuite) TestRouter() {
var router *api.Router

testCases := []struct {
name string
malleate func()
assertionFn func()
}{
{
name: "success",
malleate: func() {
router.AddRoute("module01", &mockv2.IBCModule{})
},
assertionFn: func() {
suite.Require().True(router.HasRoute("module01"))
},
},
{
name: "success: multiple modules",
malleate: func() {
router.AddRoute("module01", &mockv2.IBCModule{})
router.AddRoute("module02", &mockv2.IBCModule{})
router.AddRoute("module03", &mockv2.IBCModule{})
},
assertionFn: func() {
suite.Require().True(router.HasRoute("module01"))
suite.Require().True(router.HasRoute("module02"))
suite.Require().True(router.HasRoute("module03"))
},
},
{
name: "success: find by prefix",
malleate: func() {
router.AddRoute("module01", &mockv2.IBCModule{})
},
assertionFn: func() {
suite.Require().True(router.HasRoute("module01-foo"))
},
},
{
name: "failure: panics on duplicate module",
malleate: func() {
router.AddRoute("module01", &mockv2.IBCModule{})
},
assertionFn: func() {
suite.Require().PanicsWithError("route module01 has already been registered", func() {
router.AddRoute("module01", &mockv2.IBCModule{})
})
},
},
{
name: "failure: panics invalid-name",
malleate: func() {
router.AddRoute("module01", &mockv2.IBCModule{})
},
assertionFn: func() {
suite.Require().PanicsWithError("route expressions can only contain alphanumeric characters", func() {
router.AddRoute("module-02", &mockv2.IBCModule{})
})
},
},
}
for _, tc := range testCases {
tc := tc

suite.Run(tc.name, func() {
router = api.NewRouter()

tc.malleate()

tc.assertionFn()
})
}
}
20 changes: 9 additions & 11 deletions modules/core/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (

sdk "github.com/cosmos/cosmos-sdk/types"

capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types"
clienttypes "github.com/cosmos/ibc-go/v9/modules/core/02-client/types"
connectiontypes "github.com/cosmos/ibc-go/v9/modules/core/03-connection/types"
"github.com/cosmos/ibc-go/v9/modules/core/04-channel/keeper"
Expand Down Expand Up @@ -446,7 +445,7 @@ func (k *Keeper) RecvPacket(goCtx context.Context, msg *channeltypes.MsgRecvPack
return nil, errorsmod.Wrap(err, "Invalid address for msg Signer")
}

packetHandler, _, _, err = k.getPacketHandlerAndModule(ctx, msg.Packet.ProtocolVersion, msg.Packet.DestinationPort, msg.Packet.DestinationChannel)
packetHandler, err = k.getPacketHandlerAndModule(msg.Packet.ProtocolVersion)
if err != nil {
ctx.Logger().Error("receive packet failed", "port-id", msg.Packet.DestinationPort, "channel-id", msg.Packet.DestinationChannel, "error", errorsmod.Wrap(err, "could not retrieve module from port-id"))
return nil, errorsmod.Wrap(err, "could not retrieve module from port-id")
Expand Down Expand Up @@ -518,7 +517,7 @@ func (k *Keeper) Timeout(goCtx context.Context, msg *channeltypes.MsgTimeout) (*
return nil, errorsmod.Wrap(err, "Invalid address for msg Signer")
}

packetHandler, _, _, err = k.getPacketHandlerAndModule(ctx, msg.Packet.ProtocolVersion, msg.Packet.SourcePort, msg.Packet.SourceChannel)
packetHandler, err = k.getPacketHandlerAndModule(msg.Packet.ProtocolVersion)
if err != nil {
ctx.Logger().Error("timeout failed", "port-id", msg.Packet.SourcePort, "channel-id", msg.Packet.SourceChannel, "error", errorsmod.Wrap(err, "could not retrieve module from port-id"))
return nil, errorsmod.Wrap(err, "could not retrieve module from port-id")
Expand Down Expand Up @@ -627,7 +626,7 @@ func (k *Keeper) Acknowledgement(goCtx context.Context, msg *channeltypes.MsgAck
return nil, errorsmod.Wrap(err, "Invalid address for msg Signer")
}

packetHandler, _, _, err = k.getPacketHandlerAndModule(ctx, msg.Packet.ProtocolVersion, msg.Packet.SourcePort, msg.Packet.SourceChannel)
packetHandler, err = k.getPacketHandlerAndModule(msg.Packet.ProtocolVersion)
if err != nil {
ctx.Logger().Error("acknowledgement failed", "port-id", msg.Packet.SourcePort, "channel-id", msg.Packet.SourceChannel, "error", errorsmod.Wrap(err, "could not retrieve module from port-id"))
return nil, errorsmod.Wrap(err, "could not retrieve module from port-id")
Expand Down Expand Up @@ -1065,17 +1064,16 @@ func convertToErrorEvents(events sdk.Events) sdk.Events {
return newEvents
}

// getPacketHandlerAndModule returns the appropriate packet handler, module name, and capability
// given the provided port and channel identifiers. The packet handler is determined by the
// provided protocol version. An error is returned if the module cannot be found or if the protocol
// getPacketHandlerAndModule returns the appropriate packet handler
// given the protocol version. An error is returned if the protocol
// version is not supported.
func (k *Keeper) getPacketHandlerAndModule(ctx sdk.Context, protocolVersion channeltypes.IBCVersion, port, channel string) (PacketHandler, string, *capabilitytypes.Capability, error) {
func (k *Keeper) getPacketHandlerAndModule(protocolVersion channeltypes.IBCVersion) (PacketHandler, error) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed linter errors 'cause they were driving me nuts :D

switch protocolVersion {
case channeltypes.IBC_VERSION_UNSPECIFIED, channeltypes.IBC_VERSION_1:
return k.ChannelKeeper, "", nil, nil
return k.ChannelKeeper, nil
case channeltypes.IBC_VERSION_2:
return k.PacketServerKeeper, port, nil, nil
return k.PacketServerKeeper, nil
default:
return nil, "", nil, fmt.Errorf("unsupported protocol %s", protocolVersion)
return nil, fmt.Errorf("unsupported protocol %s", protocolVersion)
}
}
18 changes: 18 additions & 0 deletions testing/mock/v2/ibc_module.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package mock

import (
"context"

sdk "github.com/cosmos/cosmos-sdk/types"

channeltypesv2 "github.com/cosmos/ibc-go/v9/modules/core/04-channel/v2/types"
"github.com/cosmos/ibc-go/v9/modules/core/api"
)

var _ api.IBCModule = (*IBCModule)(nil)

type IBCModule struct{}

func (IBCModule) OnSendPacket(ctx context.Context, sourceID string, destinationID string, sequence uint64, data channeltypesv2.PacketData, signer sdk.AccAddress) error {
panic("implement me")
}
Loading