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

feat! implement token filter IBC middleware #1219

Merged
merged 9 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
11 changes: 9 additions & 2 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ import (
blobmodule "github.com/celestiaorg/celestia-app/x/blob"
blobmodulekeeper "github.com/celestiaorg/celestia-app/x/blob/keeper"
blobmoduletypes "github.com/celestiaorg/celestia-app/x/blob/types"
"github.com/celestiaorg/celestia-app/x/tokenfilter"

qgbmodule "github.com/celestiaorg/celestia-app/x/qgb"
qgbmodulekeeper "github.com/celestiaorg/celestia-app/x/qgb/keeper"
Expand Down Expand Up @@ -354,7 +355,13 @@ func New(
app.AccountKeeper, app.BankKeeper, scopedTransferKeeper,
)
transferModule := transfer.NewAppModule(app.TransferKeeper)
transferIBCModule := transfer.NewIBCModule(app.TransferKeeper)

// transfer stack contains (from top to bottom):
// - Token Filter
// - Transfer
var transferStack ibcporttypes.IBCModule
transferStack = transfer.NewIBCModule(app.TransferKeeper)
transferStack = tokenfilter.NewIBCMiddleware(transferStack, app.IBCKeeper.ChannelKeeper)

// Create evidence Keeper for to register the IBC light client misbehaviour evidence route
evidenceKeeper := evidencekeeper.NewKeeper(
Expand All @@ -380,7 +387,7 @@ func New(

// Create static IBC router, add transfer route, then set and seal it
ibcRouter := ibcporttypes.NewRouter()
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferIBCModule)
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferStack)
app.IBCKeeper.SetRouter(ibcRouter)

/**** Module Options ****/
Expand Down
81 changes: 81 additions & 0 deletions x/tokenfilter/ibc_middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package tokenfilter

import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/ibc-go/v6/modules/apps/transfer/types"
channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types"
porttypes "github.com/cosmos/ibc-go/v6/modules/core/05-port/types"
"github.com/cosmos/ibc-go/v6/modules/core/exported"
)

var _ porttypes.Middleware = &tokenFilterMiddleware{}

const ModuleName = "tokenfilter"

// tokenFilterMiddleware directly inherits the IBCModule and ICS4Wrapper interfaces.
// Only with OnRecvPacket, does it wrap the underlying implementation with additional
// stateless logic for rejecting the inbound transfer of non-native tokens. This
// middleware is unilateral and no handshake is required. If using this middleware
// on an existing chain, tokens that have been routed through this chain will still
// be allowed to unwrap.
type tokenFilterMiddleware struct {
porttypes.IBCModule
porttypes.ICS4Wrapper
}

Choose a reason for hiding this comment

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

Kinda nice trick with the embedding to avoid code boilerplate. Was this the intention here?

I do like the idea of not having to have a keeper package, given its a stateless middleware.
But I would've expected to see the transfer keeper composed with something like app.TokenFilterKeeper.

app.TransferKeeper = ibctransferkeeper.NewKeeper(
	appCodec, keys[ibctransfertypes.StoreKey], app.GetSubspace(ibctransfertypes.ModuleName),
-	app.IBCKeeper.ChannelKeeper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper,
+       app.TokenFilterKeeper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper,
	app.AccountKeeper, app.BankKeeper, scopedTransferKeeper,
)

At the moment its completely bypassing this tokenfilter middleware for SendPacket. With the above, the TokenFilterKeeper would just be a simple struct composed with the ibc channel keeper.

E.g. for packets being received the flow is: ibc core -> token filter -> transfer where token filter essentially inherits transfers callbacks but overrides OnRecvPacket. When transfer sends a packet, the current flow is: transfer -> ibc core.

While its technically fine for this right now, and token filter doesn't care about outbound packets I think the configuration might be a little bit error prone, for example, the ICS4Wrapper in this struct is never actually used. It would definitely become apparent especially if you try to add more middlewares to the transfer application stack in future.

Does this make sense?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Kinda nice trick with the embedding to avoid code boilerplate. Was this the intention here?

Yeah that was the intention.

While its technically fine for this right now, and token filter doesn't care about outbound packets I think the configuration might be a little bit error prone, for example, the ICS4Wrapper in this struct is never actually used. It would definitely become apparent especially if you try to add more middlewares to the transfer application stack in future.

I think I understand this. So because I just reference the ChannelKeeper directly, any middleware below this would get bypassed? Technically I could remove ICS4Wrapper and the middleware would instead just be an IBCModule. Which is fine because all it's used for is in AddRoute which doesn't care that it's Middleware

Also, I'm not sure if I really care about SendPacket in the case of the TokenFilter and I would like to avoid having a keeper if possible.

Copy link

@damiannolan damiannolan Jan 12, 2023

Choose a reason for hiding this comment

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

So because I just reference the ChannelKeeper directly, any middleware below this would get bypassed?

Yes, because ChannelKeeper is passed directly as the ICS4Wrapper arg to NewTransferKeeper then SendPacket would bypass all middlewares in the application stack.

Also, I'm not sure if I really care about SendPacket in the case of the TokenFilter and I would like to avoid having a keeper if possible.

Yeah I understand wanting to avoid a keeper, and like you say, SendPacket is essentially going to be a passthrough anyways and not implement any logic.
I guess its just a general concern that you should be aware of with the current way its wired up, if you decide to make any changes or add additional middlewares in future which will want to implement logic on SendPacket.

I would probably advise for taking the approach where the token filter is invoked bi-directionally (for sends and recvs), even if its a no-op/passthrough.
i.e.

recv: ibc core -> token filter -> transfer
send: transfer -> token filter -> ibc core

This way you avoid any future errors made my devs who are unaware of the call flow.

All that being said, I understand your reasoning for avoiding boilerplate and the need for a keeper package. As long as you're aware of the risks then feel free to go ahead with this.

Choose a reason for hiding this comment

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

fwiw you could define an ICS4Wrapper struct within this package, and use that as the arg in NewTransferKeeper. You'd avoiding having to add a keeper package that way and still stick to convention and adhere to the correct flows

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok I've given what you suggested a go just for conventions sake.

It's does strike me however a bit strange that Middleware is both IBCModule and ICS4Wrapper. This is kind of impossible to implement within the same struct else you'd end with circular dependencies. In this case transfer keeper needs to both import token filter and be imported by token filter.


// NewIBCMiddleware creates a new instance of the token filter middleware for
// the transfer module.
func NewIBCMiddleware(ibcModule porttypes.IBCModule, wrapper porttypes.ICS4Wrapper) porttypes.Middleware {
return &tokenFilterMiddleware{
IBCModule: ibcModule,
ICS4Wrapper: wrapper,
}
}

// OnRecvPacket implements the IBCModule interface. It is called whenever a new packet
// from another chain is received on this chain. Here, the token filter middleware
// unmarshals the FungibleTokenPacketData and checks to see if the denomination being
// transferred to this chain originally came from this chain i.e. is a native token.
// If not, it returns an ErrorAcknowledgement.
func (m *tokenFilterMiddleware) OnRecvPacket(
ctx sdk.Context,
packet channeltypes.Packet,
relayer sdk.AccAddress,
) exported.Acknowledgement {
var data types.FungibleTokenPacketData
if err := types.ModuleCdc.UnmarshalJSON(packet.GetData(), &data); err != nil {
// If this happens either a) a user has crafted an invalid packet, b) a
// software developer has connected the middleware to a stack that does
// not have a transfer module, or c) the transfer module has been modified
// to accept other Packets. The best thing we can do here is pass the packet
// on down the stack.
return m.IBCModule.OnRecvPacket(ctx, packet, relayer)
}

// This checks the first channel and port in the denomination path. If it matches
// our channel and port it means that the token was originally sent from this
// chain. Note that this firewall prevents routing of other transactions through
// the chain so from this logic, the denom has to be a native denom.
if types.ReceiverChainIsSource(packet.GetSourcePort(), packet.GetSourceChannel(), data.Denom) {
cmwaters marked this conversation as resolved.
Show resolved Hide resolved
return m.IBCModule.OnRecvPacket(ctx, packet, relayer)
}

ackErr := sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "only native denom transfers accepted, got %s", data.Denom)

ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypePacket,
sdk.NewAttribute(sdk.AttributeKeyModule, ModuleName),
sdk.NewAttribute(sdk.AttributeKeySender, data.Sender),
sdk.NewAttribute(types.AttributeKeyReceiver, data.Receiver),
sdk.NewAttribute(types.AttributeKeyDenom, data.Denom),
sdk.NewAttribute(types.AttributeKeyAmount, data.Amount),
sdk.NewAttribute(types.AttributeKeyMemo, data.Memo),
sdk.NewAttribute(types.AttributeKeyAckSuccess, "false"),
sdk.NewAttribute(types.AttributeKeyAckError, ackErr.Error()),
),
)

return channeltypes.NewErrorAcknowledgement(ackErr)
}
208 changes: 208 additions & 0 deletions x/tokenfilter/ibc_middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package tokenfilter_test

import (
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"

transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types"
"github.com/cosmos/ibc-go/v6/modules/core/exported"

"github.com/celestiaorg/celestia-app/x/tokenfilter"
)

func TestOnRecvPacket(t *testing.T) {
data := transfertypes.NewFungibleTokenPacketData("portid/channelid/utia", sdk.NewInt(100).String(), "alice", "bob", "gm")
packet := channeltypes.NewPacket(data.GetBytes(), 1, "portid", "channelid", "counterpartyportid", "counterpartychannelid", clienttypes.Height{}, 0)
packetFromOtherChain := channeltypes.NewPacket(data.GetBytes(), 1, "counterpartyportid", "counterpartychannelid", "portid", "channelid", clienttypes.Height{}, 0)
randomPacket := channeltypes.NewPacket([]byte{1, 2, 3, 4}, 1, "portid", "channelid", "counterpartyportid", "counterpartychannelid", clienttypes.Height{}, 0)

testCases := []struct {
name string
packet channeltypes.Packet
err bool
}{
{
name: "packet with native token",
packet: packet,
err: false,
},
{
name: "packet with non-native token",
packet: packetFromOtherChain,
err: true,
},
{
name: "random packet from a different module",
packet: randomPacket,
err: false,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
module := &MockIBCModule{t: t, called: false}
wrapper := &MockICS4Wrapper{t: t}
middleware := tokenfilter.NewIBCMiddleware(module, wrapper)

ctx := sdk.Context{}
ctx = ctx.WithEventManager(sdk.NewEventManager())
ack := middleware.OnRecvPacket(
ctx,
tc.packet,
[]byte{},
)
if tc.err {
if module.MethodCalled() {
t.Fatal("expected error but `OnRecvPacket` was called")
}
if ack.Success() {
t.Fatal("expected error acknowledgement but got success")
}
}
})
}
}

type MockIBCModule struct {
t *testing.T
called bool
}

func (m *MockIBCModule) MethodCalled() bool {
return m.called
}

func (m *MockIBCModule) OnChanOpenInit(
ctx sdk.Context,
order channeltypes.Order,
connectionHops []string,
portID string,
channelID string,
channelCap *capabilitytypes.Capability,
counterparty channeltypes.Counterparty,
version string,
) (string, error) {
m.t.Fatalf("unexpected call to OnChanOpenInit")
return "", nil
}

func (m *MockIBCModule) OnChanOpenTry(
ctx sdk.Context,
order channeltypes.Order,
connectionHops []string,
portID,
channelID string,
channelCap *capabilitytypes.Capability,
counterparty channeltypes.Counterparty,
counterpartyVersion string,
) (version string, err error) {
m.t.Fatalf("unexpected call to OnChanOpenTry")
return "", nil
}

func (m *MockIBCModule) OnChanOpenAck(
ctx sdk.Context,
portID,
channelID string,
counterpartyChannelID string,
counterpartyVersion string,
) error {
m.t.Fatalf("unexpected call to OnChanOpenAck")
return nil
}

func (m *MockIBCModule) OnChanOpenConfirm(
ctx sdk.Context,
portID,
channelID string,
) error {
m.t.Fatalf("unexpected call to OnChanOpenConfirm")
return nil
}

func (m *MockIBCModule) OnChanCloseInit(
ctx sdk.Context,
portID,
channelID string,
) error {
m.t.Fatalf("unexpected call to OnChanCloseInit")
return nil
}

func (m *MockIBCModule) OnChanCloseConfirm(
ctx sdk.Context,
portID,
channelID string,
) error {
m.t.Fatalf("unexpected call to OnChanCloseConfirm")
return nil
}

func (m *MockIBCModule) OnRecvPacket(
ctx sdk.Context,
packet channeltypes.Packet,
relayer sdk.AccAddress,
) exported.Acknowledgement {
m.called = true
return channeltypes.NewResultAcknowledgement([]byte{byte(1)})
}

func (m *MockIBCModule) OnAcknowledgementPacket(
ctx sdk.Context,
packet channeltypes.Packet,
acknowledgement []byte,
relayer sdk.AccAddress,
) error {
m.t.Fatalf("unexpected call to OnAcknowledgementPacket")
return nil
}

func (m *MockIBCModule) OnTimeoutPacket(
ctx sdk.Context,
packet channeltypes.Packet,
relayer sdk.AccAddress,
) error {
m.t.Fatalf("unexpected call to OnTimeoutPacket")
return nil
}

// ICS4Wrapper implements the ICS4 interfaces that IBC applications use to send packets and acknowledgements.
type MockICS4Wrapper struct {
t *testing.T
}

func (m *MockICS4Wrapper) SendPacket(
ctx sdk.Context,
chanCap *capabilitytypes.Capability,
sourcePort string,
sourceChannel string,
timeoutHeight clienttypes.Height,
timeoutTimestamp uint64,
data []byte,
) (sequence uint64, err error) {
m.t.Fatalf("unexpected call to SendPacket")
return 0, nil
}

func (m *MockICS4Wrapper) WriteAcknowledgement(
ctx sdk.Context,
chanCap *capabilitytypes.Capability,
packet exported.PacketI,
ack exported.Acknowledgement,
) error {
m.t.Fatalf("unexpected call to WriteAcknowledgement")
return nil
}

func (m *MockICS4Wrapper) GetAppVersion(
ctx sdk.Context,
portID,
channelID string,
) (string, bool) {
m.t.Fatalf("unexpected call to GetAppVersion")
return "", false
}