-
Notifications
You must be signed in to change notification settings - Fork 278
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
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f6b1aa3
re-enable IBC
cmwaters 6d15e8c
lint
cmwaters 450d8df
implement token filter ibc middleware
cmwaters 96e8e66
Merge branch 'main' into cal/ibc-middleware
cmwaters 0e62be5
go fumpt
cmwaters 9341f2a
Merge branch 'cal/ibc-middleware' of github.com:celestiaorg/celestia-…
cmwaters 01cfe4b
apply suggestions
cmwaters a835b98
Merge branch 'main' into cal/ibc-middleware
cmwaters eff6927
Merge branch 'main' into cal/ibc-middleware
cmwaters File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
|
||
// 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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
.At the moment its completely bypassing this tokenfilter middleware for
SendPacket
. With the above, theTokenFilterKeeper
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 overridesOnRecvPacket
. 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?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah that was the intention.
I think I understand this. So because I just reference the
ChannelKeeper
directly, any middleware below this would get bypassed? Technically I could removeICS4Wrapper
and the middleware would instead just be anIBCModule
. Which is fine because all it's used for is inAddRoute
which doesn't care that it'sMiddleware
Also, I'm not sure if I really care about
SendPacket
in the case of theTokenFilter
and I would like to avoid having a keeper if possible.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, because
ChannelKeeper
is passed directly as theICS4Wrapper
arg toNewTransferKeeper
thenSendPacket
would bypass all middlewares in the application stack.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.
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.
There was a problem hiding this comment.
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 inNewTransferKeeper
. You'd avoiding having to add a keeper package that way and still stick to convention and adhere to the correct flowsThere was a problem hiding this comment.
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 bothIBCModule
andICS4Wrapper
. 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.