-
Notifications
You must be signed in to change notification settings - Fork 428
/
Copy pathibc.go
487 lines (434 loc) · 16.5 KB
/
ibc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package wasm
import (
"math"
wasmvmtypes "github.com/CosmWasm/wasmvm/v2/types"
clienttypes "github.com/cosmos/ibc-go/v10/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v10/modules/core/04-channel/types"
porttypes "github.com/cosmos/ibc-go/v10/modules/core/05-port/types"
ibcexported "github.com/cosmos/ibc-go/v10/modules/core/exported"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/CosmWasm/wasmd/x/wasm/keeper"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
// DefaultMaxIBCCallbackGas is the default value of maximum gas that an IBC callback can use.
// If the callback uses more gas, it will be out of gas and the contract state changes will be reverted,
// but the transaction will be committed.
// Pass this to the callbacks middleware or choose a custom value.
const DefaultMaxIBCCallbackGas = uint64(1_000_000)
var _ porttypes.IBCModule = IBCHandler{}
// internal interface that is implemented by ibc middleware
type appVersionGetter interface {
// GetAppVersion returns the application level version with all middleware data stripped out
GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool)
}
type IBCHandler struct {
keeper types.IBCContractKeeper
channelKeeper types.ChannelKeeper
appVersionGetter appVersionGetter
}
func NewIBCHandler(k types.IBCContractKeeper, ck types.ChannelKeeper, vg appVersionGetter) IBCHandler {
return IBCHandler{keeper: k, channelKeeper: ck, appVersionGetter: vg}
}
// OnChanOpenInit implements the IBCModule interface
func (i IBCHandler) OnChanOpenInit(
ctx sdk.Context,
order channeltypes.Order,
connectionHops []string,
portID string,
channelID string,
counterParty channeltypes.Counterparty,
version string,
) (string, error) {
// ensure port, version, capability
if err := ValidateChannelParams(channelID); err != nil {
return "", err
}
contractAddr, err := keeper.ContractFromPortID(portID)
if err != nil {
return "", errorsmod.Wrapf(err, "contract port id")
}
msg := wasmvmtypes.IBCChannelOpenMsg{
OpenInit: &wasmvmtypes.IBCOpenInit{
Channel: wasmvmtypes.IBCChannel{
Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID},
CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: counterParty.PortId, ChannelID: counterParty.ChannelId},
Order: order.String(),
// DESIGN V3: this may be "" ??
Version: version,
ConnectionID: connectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported.
},
},
}
// Allow contracts to return a version (or default to proposed version if unset)
acceptedVersion, err := i.keeper.OnOpenChannel(ctx, contractAddr, msg)
if err != nil {
return "", err
}
if acceptedVersion == "" { // accept incoming version when nothing returned by contract
if version == "" {
return "", types.ErrEmpty.Wrap("version")
}
acceptedVersion = version
}
return acceptedVersion, nil
}
// OnChanOpenTry implements the IBCModule interface
func (i IBCHandler) OnChanOpenTry(
ctx sdk.Context,
order channeltypes.Order,
connectionHops []string,
portID, channelID string,
counterParty channeltypes.Counterparty,
counterpartyVersion string,
) (string, error) {
// ensure port, version, capability
if err := ValidateChannelParams(channelID); err != nil {
return "", err
}
contractAddr, err := keeper.ContractFromPortID(portID)
if err != nil {
return "", errorsmod.Wrapf(err, "contract port id")
}
msg := wasmvmtypes.IBCChannelOpenMsg{
OpenTry: &wasmvmtypes.IBCOpenTry{
Channel: wasmvmtypes.IBCChannel{
Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID},
CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: counterParty.PortId, ChannelID: counterParty.ChannelId},
Order: order.String(),
Version: counterpartyVersion,
ConnectionID: connectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported.
},
CounterpartyVersion: counterpartyVersion,
},
}
// Allow contracts to return a version (or default to counterpartyVersion if unset)
version, err := i.keeper.OnOpenChannel(ctx, contractAddr, msg)
if err != nil {
return "", err
}
if version == "" {
version = counterpartyVersion
}
return version, nil
}
// OnChanOpenAck implements the IBCModule interface
func (i IBCHandler) OnChanOpenAck(
ctx sdk.Context,
portID, channelID string,
counterpartyChannelID string,
counterpartyVersion string,
) error {
contractAddr, err := keeper.ContractFromPortID(portID)
if err != nil {
return errorsmod.Wrapf(err, "contract port id")
}
channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID)
}
channelInfo.Counterparty.ChannelId = counterpartyChannelID
appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID)
}
msg := wasmvmtypes.IBCChannelConnectMsg{
OpenAck: &wasmvmtypes.IBCOpenAck{
Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion),
CounterpartyVersion: counterpartyVersion,
},
}
return i.keeper.OnConnectChannel(ctx, contractAddr, msg)
}
// OnChanOpenConfirm implements the IBCModule interface
func (i IBCHandler) OnChanOpenConfirm(ctx sdk.Context, portID, channelID string) error {
contractAddr, err := keeper.ContractFromPortID(portID)
if err != nil {
return errorsmod.Wrapf(err, "contract port id")
}
channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID)
}
appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID)
}
msg := wasmvmtypes.IBCChannelConnectMsg{
OpenConfirm: &wasmvmtypes.IBCOpenConfirm{
Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion),
},
}
return i.keeper.OnConnectChannel(ctx, contractAddr, msg)
}
// OnChanCloseInit implements the IBCModule interface
func (i IBCHandler) OnChanCloseInit(ctx sdk.Context, portID, channelID string) error {
contractAddr, err := keeper.ContractFromPortID(portID)
if err != nil {
return errorsmod.Wrapf(err, "contract port id")
}
channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID)
}
appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID)
}
msg := wasmvmtypes.IBCChannelCloseMsg{
CloseInit: &wasmvmtypes.IBCCloseInit{Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion)},
}
err = i.keeper.OnCloseChannel(ctx, contractAddr, msg)
if err != nil {
return err
}
// emit events?
return err
}
// OnChanCloseConfirm implements the IBCModule interface
func (i IBCHandler) OnChanCloseConfirm(ctx sdk.Context, portID, channelID string) error {
// counterparty has closed the channel
contractAddr, err := keeper.ContractFromPortID(portID)
if err != nil {
return errorsmod.Wrapf(err, "contract port id")
}
channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID)
}
appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID)
if !ok {
return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID)
}
msg := wasmvmtypes.IBCChannelCloseMsg{
CloseConfirm: &wasmvmtypes.IBCCloseConfirm{Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion)},
}
err = i.keeper.OnCloseChannel(ctx, contractAddr, msg)
if err != nil {
return err
}
// emit events?
return err
}
func toWasmVMChannel(portID, channelID string, channelInfo channeltypes.Channel, appVersion string) wasmvmtypes.IBCChannel {
return wasmvmtypes.IBCChannel{
Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID},
CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: channelInfo.Counterparty.PortId, ChannelID: channelInfo.Counterparty.ChannelId},
Order: channelInfo.Ordering.String(),
Version: appVersion,
ConnectionID: channelInfo.ConnectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported.
}
}
// OnRecvPacket implements the IBCModule interface
func (i IBCHandler) OnRecvPacket(
ctx sdk.Context,
channelVersion string,
packet channeltypes.Packet,
relayer sdk.AccAddress,
) ibcexported.Acknowledgement {
contractAddr, err := keeper.ContractFromPortID(packet.DestinationPort)
if err != nil {
// this must not happen as ports were registered before
panic(errorsmod.Wrapf(err, "contract port id"))
}
em := sdk.NewEventManager()
msg := wasmvmtypes.IBCPacketReceiveMsg{Packet: newIBCPacket(packet), Relayer: relayer.String()}
ack, err := i.keeper.OnRecvPacket(ctx.WithEventManager(em), contractAddr, msg)
if err != nil {
ack = CreateErrorAcknowledgement(err)
// the state gets reverted, so we drop all captured events
} else if ack == nil || ack.Success() {
// emit all contract and submessage events on success
// nil ack is a success case, see: https://github.com/cosmos/ibc-go/blob/v7.0.0/modules/core/keeper/msg_server.go#L453
ctx.EventManager().EmitEvents(em.Events())
}
types.EmitAcknowledgementEvent(ctx, contractAddr, ack, err)
return ack
}
// OnAcknowledgementPacket implements the IBCModule interface
func (i IBCHandler) OnAcknowledgementPacket(
ctx sdk.Context,
channelVersion string,
packet channeltypes.Packet,
acknowledgement []byte,
relayer sdk.AccAddress,
) error {
contractAddr, err := keeper.ContractFromPortID(packet.SourcePort)
if err != nil {
return errorsmod.Wrapf(err, "contract port id")
}
err = i.keeper.OnAckPacket(ctx, contractAddr, wasmvmtypes.IBCPacketAckMsg{
Acknowledgement: wasmvmtypes.IBCAcknowledgement{Data: acknowledgement},
OriginalPacket: newIBCPacket(packet),
Relayer: relayer.String(),
})
if err != nil {
return errorsmod.Wrap(err, "on ack")
}
return nil
}
// OnTimeoutPacket implements the IBCModule interface
func (i IBCHandler) OnTimeoutPacket(ctx sdk.Context, channelVersion string, packet channeltypes.Packet, relayer sdk.AccAddress) error {
contractAddr, err := keeper.ContractFromPortID(packet.SourcePort)
if err != nil {
return errorsmod.Wrapf(err, "contract port id")
}
msg := wasmvmtypes.IBCPacketTimeoutMsg{Packet: newIBCPacket(packet), Relayer: relayer.String()}
err = i.keeper.OnTimeoutPacket(ctx, contractAddr, msg)
if err != nil {
return errorsmod.Wrap(err, "on timeout")
}
return nil
}
// IBCSendPacketCallback implements the IBC Callbacks ContractKeeper interface
// see https://github.com/cosmos/ibc-go/blob/main/docs/architecture/adr-008-app-caller-cbs.md#contractkeeper
func (i IBCHandler) IBCSendPacketCallback(
cachedCtx sdk.Context,
sourcePort string,
sourceChannel string,
timeoutHeight clienttypes.Height,
timeoutTimestamp uint64,
packetData []byte,
contractAddress,
packetSenderAddress string,
version string,
) error {
_, err := validateSender(contractAddress, packetSenderAddress)
if err != nil {
return err
}
// no-op, since we are not interested in this callback
return nil
}
// IBCOnAcknowledgementPacketCallback implements the IBC Callbacks ContractKeeper interface
// see https://github.com/cosmos/ibc-go/blob/main/docs/architecture/adr-008-app-caller-cbs.md#contractkeeper
func (i IBCHandler) IBCOnAcknowledgementPacketCallback(
cachedCtx sdk.Context,
packet channeltypes.Packet,
acknowledgement []byte,
relayer sdk.AccAddress,
contractAddress,
packetSenderAddress string,
version string,
) error {
contractAddr, err := validateSender(contractAddress, packetSenderAddress)
if err != nil {
return err
}
msg := wasmvmtypes.IBCSourceCallbackMsg{
Acknowledgement: &wasmvmtypes.IBCAckCallbackMsg{
Acknowledgement: wasmvmtypes.IBCAcknowledgement{Data: acknowledgement},
OriginalPacket: newIBCPacket(packet),
Relayer: relayer.String(),
},
}
err = i.keeper.IBCSourceCallback(cachedCtx, contractAddr, msg)
if err != nil {
return errorsmod.Wrap(err, "on source chain callback ack")
}
return nil
}
// IBCOnTimeoutPacketCallback implements the IBC Callbacks ContractKeeper interface
// see https://github.com/cosmos/ibc-go/blob/main/docs/architecture/adr-008-app-caller-cbs.md#contractkeeper
func (i IBCHandler) IBCOnTimeoutPacketCallback(
cachedCtx sdk.Context,
packet channeltypes.Packet,
relayer sdk.AccAddress,
contractAddress,
packetSenderAddress string,
version string,
) error {
contractAddr, err := validateSender(contractAddress, packetSenderAddress)
if err != nil {
return err
}
msg := wasmvmtypes.IBCSourceCallbackMsg{
Timeout: &wasmvmtypes.IBCTimeoutCallbackMsg{
Packet: newIBCPacket(packet),
Relayer: relayer.String(),
},
}
err = i.keeper.IBCSourceCallback(cachedCtx, contractAddr, msg)
if err != nil {
return errorsmod.Wrap(err, "on source chain callback timeout")
}
return nil
}
// IBCReceivePacketCallback implements the IBC Callbacks ContractKeeper interface
// see https://github.com/cosmos/ibc-go/blob/main/docs/architecture/adr-008-app-caller-cbs.md#contractkeeper
func (i IBCHandler) IBCReceivePacketCallback(
cachedCtx sdk.Context,
packet ibcexported.PacketI,
ack ibcexported.Acknowledgement,
contractAddress string,
version string,
) error {
// sender validation makes no sense here, as the receiver is never the sender
contractAddr, err := sdk.AccAddressFromBech32(contractAddress)
if err != nil {
return err
}
msg := wasmvmtypes.IBCDestinationCallbackMsg{
Ack: wasmvmtypes.IBCAcknowledgement{Data: ack.Acknowledgement()},
Packet: newIBCPacket(packet),
}
err = i.keeper.IBCDestinationCallback(cachedCtx, contractAddr, msg)
if err != nil {
return errorsmod.Wrap(err, "on destination chain callback")
}
return nil
}
func validateSender(contractAddr, senderAddr string) (sdk.AccAddress, error) {
contractAddress, err := sdk.AccAddressFromBech32(contractAddr)
if err != nil {
return nil, errorsmod.Wrapf(err, "contract address")
}
senderAddress, err := sdk.AccAddressFromBech32(senderAddr)
if err != nil {
return nil, errorsmod.Wrapf(err, "packet sender address")
}
// We only allow the contract that sent the message to receive source chain callbacks for it.
if !contractAddress.Equals(senderAddress) {
return nil, errorsmod.Wrapf(types.ErrExecuteFailed, "contract address %s does not match packet sender %s", contractAddr, senderAddress)
}
return contractAddress, nil
}
func newIBCPacket(packet ibcexported.PacketI) wasmvmtypes.IBCPacket {
timeout := wasmvmtypes.IBCTimeout{
Timestamp: packet.GetTimeoutTimestamp(),
}
timeoutHeight := packet.GetTimeoutHeight()
if !timeoutHeight.IsZero() {
timeout.Block = &wasmvmtypes.IBCTimeoutBlock{
Height: timeoutHeight.GetRevisionHeight(),
Revision: timeoutHeight.GetRevisionNumber(),
}
}
return wasmvmtypes.IBCPacket{
Data: packet.GetData(),
Src: wasmvmtypes.IBCEndpoint{ChannelID: packet.GetSourceChannel(), PortID: packet.GetSourcePort()},
Dest: wasmvmtypes.IBCEndpoint{ChannelID: packet.GetDestChannel(), PortID: packet.GetDestPort()},
Sequence: packet.GetSequence(),
Timeout: timeout,
}
}
func ValidateChannelParams(channelID string) error {
// NOTE: for escrow address security only 2^32 channels are allowed to be created
// Issue: https://github.com/cosmos/cosmos-sdk/issues/7737
channelSequence, err := channeltypes.ParseChannelSequence(channelID)
if err != nil {
return err
}
if channelSequence > math.MaxUint32 {
return errorsmod.Wrapf(types.ErrMaxIBCChannels, "channel sequence %d is greater than max allowed transfer channels %d", channelSequence, math.MaxUint32)
}
return nil
}
// CreateErrorAcknowledgement turns an error into an error acknowledgement.
//
// This function is x/wasm specific and might include the full error text in the future
// as we gain confidence that it is deterministic. Don't use it in other contexts.
// See also https://github.com/CosmWasm/wasmd/issues/1740.
func CreateErrorAcknowledgement(err error) ibcexported.Acknowledgement {
return channeltypes.NewErrorAcknowledgementWithCodespace(err)
}