-
Notifications
You must be signed in to change notification settings - Fork 797
/
ibc.go
485 lines (412 loc) · 12.4 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
package ibc
import (
"bytes"
"embed"
"errors"
"fmt"
"math/big"
"github.com/cosmos/ibc-go/v3/modules/apps/transfer/types"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/sei-protocol/sei-chain/utils"
"github.com/sei-protocol/sei-chain/x/evm/state"
sdk "github.com/cosmos/cosmos-sdk/types"
clienttypes "github.com/cosmos/ibc-go/v3/modules/core/02-client/types"
connectiontypes "github.com/cosmos/ibc-go/v3/modules/core/03-connection/types"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/tracing"
"github.com/ethereum/go-ethereum/core/vm"
pcommon "github.com/sei-protocol/sei-chain/precompiles/common"
)
const (
TransferMethod = "transfer"
TransferWithDefaultTimeoutMethod = "transferWithDefaultTimeout"
)
const (
IBCAddress = "0x0000000000000000000000000000000000001009"
)
var _ vm.PrecompiledContract = &Precompile{}
var _ vm.DynamicGasPrecompiledContract = &Precompile{}
// Embed abi json file to the executable binary. Needed when importing as dependency.
//
//go:embed abi.json
var f embed.FS
func GetABI() abi.ABI {
abiBz, err := f.ReadFile("abi.json")
if err != nil {
panic(err)
}
newAbi, err := abi.JSON(bytes.NewReader(abiBz))
if err != nil {
panic(err)
}
return newAbi
}
type Precompile struct {
pcommon.Precompile
address common.Address
transferKeeper pcommon.TransferKeeper
evmKeeper pcommon.EVMKeeper
clientKeeper pcommon.ClientKeeper
connectionKeeper pcommon.ConnectionKeeper
channelKeeper pcommon.ChannelKeeper
TransferID []byte
TransferWithDefaultTimeoutID []byte
}
func NewPrecompile(
transferKeeper pcommon.TransferKeeper,
evmKeeper pcommon.EVMKeeper,
clientKeeper pcommon.ClientKeeper,
connectionKeeper pcommon.ConnectionKeeper,
channelKeeper pcommon.ChannelKeeper) (*Precompile, error) {
newAbi := GetABI()
p := &Precompile{
Precompile: pcommon.Precompile{ABI: newAbi},
address: common.HexToAddress(IBCAddress),
transferKeeper: transferKeeper,
evmKeeper: evmKeeper,
clientKeeper: clientKeeper,
connectionKeeper: connectionKeeper,
channelKeeper: channelKeeper,
}
for name, m := range newAbi.Methods {
switch name {
case TransferMethod:
p.TransferID = m.ID
case TransferWithDefaultTimeoutMethod:
p.TransferWithDefaultTimeoutID = m.ID
}
}
return p, nil
}
// RequiredGas returns the required bare minimum gas to execute the precompile.
func (p Precompile) RequiredGas(input []byte) uint64 {
methodID, err := pcommon.ExtractMethodID(input)
if err != nil {
return pcommon.UnknownMethodCallGas
}
method, err := p.ABI.MethodById(methodID)
if err != nil {
// This should never happen since this method is going to fail during Run
return pcommon.UnknownMethodCallGas
}
return p.Precompile.RequiredGas(input, p.IsTransaction(method.Name))
}
func (p Precompile) RunAndCalculateGas(evm *vm.EVM, caller common.Address, callingContract common.Address, input []byte, suppliedGas uint64, _ *big.Int, _ *tracing.Hooks, readOnly bool) (ret []byte, remainingGas uint64, err error) {
defer func() {
if err != nil {
evm.StateDB.(*state.DBImpl).SetPrecompileError(err)
}
}()
if readOnly {
return nil, 0, errors.New("cannot call IBC precompile from staticcall")
}
ctx, method, args, err := p.Prepare(evm, input)
if err != nil {
return nil, 0, err
}
if caller.Cmp(callingContract) != 0 {
return nil, 0, errors.New("cannot delegatecall IBC")
}
gasMultiplier := p.evmKeeper.GetPriorityNormalizer(ctx)
gasLimitBigInt := new(big.Int).Mul(new(big.Int).SetUint64(suppliedGas), gasMultiplier.TruncateInt().BigInt())
if gasLimitBigInt.Cmp(utils.BigMaxU64) > 0 {
gasLimitBigInt = utils.BigMaxU64
}
ctx = ctx.WithGasMeter(sdk.NewGasMeterWithMultiplier(ctx, gasLimitBigInt.Uint64()))
switch method.Name {
case TransferMethod:
return p.transfer(ctx, method, args, caller)
case TransferWithDefaultTimeoutMethod:
return p.transferWithDefaultTimeout(ctx, method, args, caller)
}
return
}
func (p Precompile) Run(*vm.EVM, common.Address, common.Address, []byte, *big.Int, bool) (bz []byte, err error) {
panic("static gas Run is not implemented for dynamic gas precompile")
}
func (p Precompile) transfer(ctx sdk.Context, method *abi.Method, args []interface{}, caller common.Address) (ret []byte, remainingGas uint64, rerr error) {
defer func() {
if err := recover(); err != nil {
ret = nil
remainingGas = 0
rerr = fmt.Errorf("%s", err)
return
}
}()
if err := pcommon.ValidateArgsLength(args, 9); err != nil {
rerr = err
return
}
validatedArgs, err := p.validateCommonArgs(ctx, args, caller)
if err != nil {
rerr = err
return
}
if validatedArgs.amount.Cmp(big.NewInt(0)) == 0 {
// short circuit
remainingGas = pcommon.GetRemainingGas(ctx, p.evmKeeper)
ret, rerr = method.Outputs.Pack(true)
return
}
coin := sdk.Coin{
Denom: validatedArgs.denom,
Amount: sdk.NewIntFromBigInt(validatedArgs.amount),
}
revisionNumber, ok := args[5].(uint64)
if !ok {
rerr = errors.New("revisionNumber is not a uint64")
return
}
revisionHeight, ok := args[6].(uint64)
if !ok {
rerr = errors.New("revisionHeight is not a uint64")
return
}
height := clienttypes.Height{
RevisionNumber: revisionNumber,
RevisionHeight: revisionHeight,
}
timeoutTimestamp, ok := args[7].(uint64)
if !ok {
rerr = errors.New("timeoutTimestamp is not a uint64")
return
}
msg := types.MsgTransfer{
SourcePort: validatedArgs.port,
SourceChannel: validatedArgs.channelID,
Token: coin,
Sender: validatedArgs.senderSeiAddr.String(),
Receiver: validatedArgs.receiverAddressString,
TimeoutHeight: height,
TimeoutTimestamp: timeoutTimestamp,
}
msg = addMemo(args[8], msg)
err = msg.ValidateBasic()
if err != nil {
rerr = err
return
}
_, err = p.transferKeeper.Transfer(sdk.WrapSDKContext(ctx), &msg)
if err != nil {
rerr = err
return
}
remainingGas = pcommon.GetRemainingGas(ctx, p.evmKeeper)
ret, rerr = method.Outputs.Pack(true)
return
}
func (p Precompile) transferWithDefaultTimeout(ctx sdk.Context, method *abi.Method, args []interface{}, caller common.Address) (ret []byte, remainingGas uint64, rerr error) {
defer func() {
if err := recover(); err != nil {
ret = nil
remainingGas = 0
rerr = fmt.Errorf("%s", err)
return
}
}()
if err := pcommon.ValidateArgsLength(args, 6); err != nil {
rerr = err
return
}
validatedArgs, err := p.validateCommonArgs(ctx, args, caller)
if err != nil {
rerr = err
return
}
if validatedArgs.amount.Cmp(big.NewInt(0)) == 0 {
// short circuit
remainingGas = pcommon.GetRemainingGas(ctx, p.evmKeeper)
ret, rerr = method.Outputs.Pack(true)
return
}
coin := sdk.Coin{
Denom: validatedArgs.denom,
Amount: sdk.NewIntFromBigInt(validatedArgs.amount),
}
connection, err := p.getChannelConnection(ctx, validatedArgs.port, validatedArgs.channelID)
if err != nil {
rerr = err
return
}
latestConsensusHeight, err := p.getConsensusLatestHeight(ctx, *connection)
if err != nil {
rerr = err
return
}
height, err := GetAdjustedHeight(*latestConsensusHeight)
if err != nil {
rerr = err
return
}
timeoutTimestamp, err := p.GetAdjustedTimestamp(ctx, connection.ClientId, *latestConsensusHeight)
if err != nil {
rerr = err
return
}
msg := types.MsgTransfer{
SourcePort: validatedArgs.port,
SourceChannel: validatedArgs.channelID,
Token: coin,
Sender: validatedArgs.senderSeiAddr.String(),
Receiver: validatedArgs.receiverAddressString,
TimeoutHeight: height,
TimeoutTimestamp: timeoutTimestamp,
}
msg = addMemo(args[5], msg)
err = msg.ValidateBasic()
if err != nil {
rerr = err
return
}
_, err = p.transferKeeper.Transfer(sdk.WrapSDKContext(ctx), &msg)
if err != nil {
rerr = err
return
}
remainingGas = pcommon.GetRemainingGas(ctx, p.evmKeeper)
ret, rerr = method.Outputs.Pack(true)
return
}
func (Precompile) IsTransaction(method string) bool {
switch method {
case TransferMethod:
return true
case TransferWithDefaultTimeoutMethod:
return true
default:
return false
}
}
func (p Precompile) Address() common.Address {
return p.address
}
func (p Precompile) GetName() string {
return "ibc"
}
func (p Precompile) accAddressFromArg(ctx sdk.Context, arg interface{}) (sdk.AccAddress, error) {
addr := arg.(common.Address)
if addr == (common.Address{}) {
return nil, errors.New("invalid addr")
}
seiAddr, found := p.evmKeeper.GetSeiAddress(ctx, addr)
if !found {
return nil, fmt.Errorf("EVM address %s is not associated", addr.Hex())
}
return seiAddr, nil
}
func (p Precompile) getChannelConnection(ctx sdk.Context, port string, channelID string) (*connectiontypes.ConnectionEnd, error) {
channel, found := p.channelKeeper.GetChannel(ctx, port, channelID)
if !found {
return nil, errors.New("channel not found")
}
connection, found := p.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0])
if !found {
return nil, errors.New("connection not found")
}
return &connection, nil
}
func (p Precompile) getConsensusLatestHeight(ctx sdk.Context, connection connectiontypes.ConnectionEnd) (*clienttypes.Height, error) {
clientState, found := p.clientKeeper.GetClientState(ctx, connection.ClientId)
if !found {
return nil, errors.New("could not get the client state")
}
latestHeight := clientState.GetLatestHeight()
return &clienttypes.Height{
RevisionNumber: latestHeight.GetRevisionNumber(),
RevisionHeight: latestHeight.GetRevisionHeight(),
}, nil
}
func GetAdjustedHeight(latestConsensusHeight clienttypes.Height) (clienttypes.Height, error) {
defaultTimeoutHeight, err := clienttypes.ParseHeight(types.DefaultRelativePacketTimeoutHeight)
if err != nil {
return clienttypes.Height{}, err
}
absoluteHeight := latestConsensusHeight
absoluteHeight.RevisionNumber += defaultTimeoutHeight.RevisionNumber
absoluteHeight.RevisionHeight += defaultTimeoutHeight.RevisionHeight
return absoluteHeight, nil
}
func (p Precompile) GetAdjustedTimestamp(ctx sdk.Context, clientId string, height clienttypes.Height) (uint64, error) {
consensusState, found := p.clientKeeper.GetClientConsensusState(ctx, clientId, height)
var consensusStateTimestamp uint64
if found {
consensusStateTimestamp = consensusState.GetTimestamp()
}
defaultRelativePacketTimeoutTimestamp := types.DefaultRelativePacketTimeoutTimestamp
blockTime := ctx.BlockTime().UnixNano()
if blockTime > 0 {
now := uint64(blockTime)
if now > consensusStateTimestamp {
return now + defaultRelativePacketTimeoutTimestamp, nil
} else {
return consensusStateTimestamp + defaultRelativePacketTimeoutTimestamp, nil
}
} else {
return 0, errors.New("block time is not greater than Jan 1st, 1970 12:00 AM")
}
}
type ValidatedArgs struct {
senderSeiAddr sdk.AccAddress
receiverAddressString string
port string
channelID string
denom string
amount *big.Int
}
func (p Precompile) validateCommonArgs(ctx sdk.Context, args []interface{}, caller common.Address) (*ValidatedArgs, error) {
senderSeiAddr, ok := p.evmKeeper.GetSeiAddress(ctx, caller)
if !ok {
return nil, errors.New("caller is not a valid SEI address")
}
receiverAddressString, ok := args[0].(string)
if !ok {
return nil, errors.New("receiverAddress is not a string")
}
_, bz, err := bech32.DecodeAndConvert(receiverAddressString)
if err != nil {
return nil, err
}
err = sdk.VerifyAddressFormat(bz)
if err != nil {
return nil, err
}
port, ok := args[1].(string)
if !ok {
return nil, errors.New("port is not a string")
}
if port == "" {
return nil, errors.New("port cannot be empty")
}
channelID, ok := args[2].(string)
if !ok {
return nil, errors.New("channelID is not a string")
}
if channelID == "" {
return nil, errors.New("channelID cannot be empty")
}
denom := args[3].(string)
if denom == "" {
return nil, errors.New("invalid denom")
}
amount, ok := args[4].(*big.Int)
if !ok {
return nil, errors.New("amount is not a big.Int")
}
return &ValidatedArgs{
senderSeiAddr: senderSeiAddr,
receiverAddressString: receiverAddressString,
port: port,
channelID: channelID,
denom: denom,
amount: amount,
}, nil
}
func addMemo(memoArg interface{}, transferMsg types.MsgTransfer) types.MsgTransfer {
memo := ""
if memoArg != nil {
memo = memoArg.(string)
}
transferMsg.Memo = memo
return transferMsg
}