forked from cosmos/relayer
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tx.go
2058 lines (1797 loc) · 64.3 KB
/
tx.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cosmos
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
base64 "encoding/base64"
"github.com/avast/retry-go/v4"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
transfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types"
conntypes "github.com/cosmos/ibc-go/v4/modules/core/03-connection/types"
chantypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types"
commitmenttypes "github.com/cosmos/ibc-go/v4/modules/core/23-commitment/types"
host "github.com/cosmos/ibc-go/v4/modules/core/24-host"
ibcexported "github.com/cosmos/ibc-go/v4/modules/core/exported"
tmclient "github.com/cosmos/ibc-go/v4/modules/light-clients/07-tendermint/types"
interquerytypes "github.com/defund-labs/defund/x/query/types"
"github.com/defund-labs/relayer/v3/relayer/provider"
"github.com/tendermint/tendermint/light"
tmtypes "github.com/tendermint/tendermint/types"
"go.uber.org/zap"
)
// Variables used for retries
var (
rtyAttNum = uint(5)
rtyAtt = retry.Attempts(rtyAttNum)
rtyDel = retry.Delay(time.Millisecond * 400)
rtyErr = retry.LastErrorOnly(true)
)
// Default IBC settings
var (
defaultChainPrefix = commitmenttypes.NewMerklePrefix([]byte("ibc"))
defaultDelayPeriod = uint64(0)
)
// Strings for parsing events
var (
spTag = "send_packet"
waTag = "write_acknowledgement"
srcChanTag = "packet_src_channel"
dstChanTag = "packet_dst_channel"
srcPortTag = "packet_src_port"
dstPortTag = "packet_dst_port"
dataTag = "packet_data"
ackTag = "packet_ack"
toHeightTag = "packet_timeout_height"
toTSTag = "packet_timeout_timestamp"
seqTag = "packet_sequence"
)
// SendMessage attempts to sign, encode & send a RelayerMessage
// This is used extensively in the relayer as an extension of the Provider interface
func (cc *CosmosProvider) SendMessage(ctx context.Context, msg provider.RelayerMessage, memo string) (*provider.RelayerTxResponse, bool, error) {
return cc.SendMessages(ctx, []provider.RelayerMessage{msg}, memo)
}
// SendMessages attempts to sign, encode, & send a slice of RelayerMessages
// This is used extensively in the relayer as an extension of the Provider interface
//
// NOTE: An error is returned if there was an issue sending the transaction. A successfully sent, but failed
// transaction will not return an error. If a transaction is successfully sent, the result of the execution
// of that transaction will be logged. A boolean indicating if a transaction was successfully
// sent and executed successfully is returned.
func (cc *CosmosProvider) SendMessages(ctx context.Context, msgs []provider.RelayerMessage, memo string) (*provider.RelayerTxResponse, bool, error) {
var resp *sdk.TxResponse
if err := retry.Do(func() error {
txBytes, err := cc.buildMessages(ctx, msgs, memo)
if err != nil {
errMsg := err.Error()
// Occasionally the client will be out of date,
// and we will receive an RPC error like:
// rpc error: code = InvalidArgument desc = failed to execute message; message index: 1: channel handshake open try failed: failed channel state verification for client (07-tendermint-0): client state height < proof height ({0 58} < {0 59}), please ensure the client has been updated: invalid height: invalid request
// or
// rpc error: code = InvalidArgument desc = failed to execute message; message index: 1: receive packet verification failed: couldn't verify counterparty packet commitment: failed packet commitment verification for client (07-tendermint-0): client state height < proof height ({0 142} < {0 143}), please ensure the client has been updated: invalid height: invalid request
//
// No amount of retrying will fix this. The client needs to be updated.
// Unfortunately, the entirety of that error message originates on the server,
// so there is not an obvious way to access a more structured error value.
//
// If this logic should ever fail due to the string values of the error messages on the server
// changing from the client's version of the library,
// at worst this will run more unnecessary retries.
if strings.Contains(errMsg, sdkerrors.ErrInvalidHeight.Error()) {
cc.log.Info(
"Skipping retry due to invalid height error",
zap.Error(err),
)
return retry.Unrecoverable(err)
}
// On a fast retry, it is possible to have an invalid connection state.
// Retrying that message also won't fix the underlying state mismatch,
// so log it and mark it as unrecoverable.
if strings.Contains(errMsg, conntypes.ErrInvalidConnectionState.Error()) {
cc.log.Info(
"Skipping retry due to invalid connection state",
zap.Error(err),
)
return retry.Unrecoverable(err)
}
// Also possible to have an invalid channel state on a fast retry.
if strings.Contains(errMsg, chantypes.ErrInvalidChannelState.Error()) {
cc.log.Info(
"Skipping retry due to invalid channel state",
zap.Error(err),
)
return retry.Unrecoverable(err)
}
// If the message reported an invalid proof, back off.
// NOTE: this error string ("invalid proof") will match other errors too,
// but presumably it is safe to stop retrying in those cases as well.
if strings.Contains(errMsg, commitmenttypes.ErrInvalidProof.Error()) {
cc.log.Info(
"Skipping retry due to invalid proof",
zap.Error(err),
)
return retry.Unrecoverable(err)
}
// Invalid packets should not be retried either.
if strings.Contains(errMsg, chantypes.ErrInvalidPacket.Error()) {
cc.log.Info(
"Skipping retry due to invalid packet",
zap.Error(err),
)
return retry.Unrecoverable(err)
}
return err
}
resp, err = cc.BroadcastTx(ctx, txBytes)
if err != nil {
if err == sdkerrors.ErrWrongSequence {
// Allow retrying if we got an invalid sequence error when attempting to broadcast this tx.
return err
}
// Don't retry if BroadcastTx resulted in any other error.
// (This was the previous behavior. Unclear if that is still desired.)
return retry.Unrecoverable(err)
}
return nil
}, retry.Context(ctx), rtyAtt, rtyDel, rtyErr, retry.OnRetry(func(n uint, err error) {
cc.log.Info(
"Error building or broadcasting transaction",
zap.String("chain_id", cc.PCfg.ChainID),
zap.Uint("attempt", n+1),
zap.Uint("max_attempts", rtyAttNum),
zap.Error(err),
)
})); err != nil || resp == nil {
return nil, false, err
}
rlyResp := &provider.RelayerTxResponse{
Height: resp.Height,
TxHash: resp.TxHash,
Code: resp.Code,
Data: resp.Data,
Events: parseEventsFromTxResponse(resp),
}
// transaction was executed, log the success or failure using the tx response code
// NOTE: error is nil, logic should use the returned error to determine if the
// transaction was successfully executed.
if rlyResp.Code != 0 {
cc.LogFailedTx(rlyResp, nil, msgs)
return rlyResp, false, fmt.Errorf("transaction failed with code: %d", resp.Code)
}
cc.LogSuccessTx(resp, msgs)
return rlyResp, true, nil
}
func parseEventsFromTxResponse(resp *sdk.TxResponse) []provider.RelayerEvent {
var events []provider.RelayerEvent
if resp == nil {
return events
}
for _, logs := range resp.Logs {
for _, event := range logs.Events {
attributes := make(map[string]string)
for _, attribute := range event.Attributes {
attributes[attribute.Key] = attribute.Value
}
events = append(events, provider.RelayerEvent{
EventType: event.Type,
Attributes: attributes,
})
}
}
return events
}
func (cc *CosmosProvider) buildMessages(ctx context.Context, msgs []provider.RelayerMessage, memo string) ([]byte, error) {
// Query account details
txf, err := cc.PrepareFactory(cc.TxFactory())
if err != nil {
return nil, err
}
if memo != "" {
txf = txf.WithMemo(memo)
}
// TODO: Make this work with new CalculateGas method
// TODO: This is related to GRPC client stuff?
// https://github.com/cosmos/cosmos-sdk/blob/5725659684fc93790a63981c653feee33ecf3225/client/tx/tx.go#L297
// If users pass gas adjustment, then calculate gas
_, adjusted, err := cc.CalculateGas(ctx, txf, CosmosMsgs(msgs...)...)
if err != nil {
return nil, err
}
// Set the gas amount on the transaction factory
txf = txf.WithGas(adjusted)
var txb client.TxBuilder
// Build the transaction builder & retry on failures
if err := retry.Do(func() error {
txb, err = tx.BuildUnsignedTx(txf, CosmosMsgs(msgs...)...)
if err != nil {
return err
}
return nil
}, retry.Context(ctx), rtyAtt, rtyDel, rtyErr); err != nil {
return nil, err
}
// Attach the signature to the transaction
// Force encoding in the chain specific address
for _, msg := range msgs {
cc.Codec.Marshaler.MustMarshalJSON(CosmosMsg(msg))
}
done := cc.SetSDKContext()
if err := retry.Do(func() error {
if err := tx.Sign(txf, cc.PCfg.Key, txb, false); err != nil {
return err
}
return nil
}, retry.Context(ctx), rtyAtt, rtyDel, rtyErr); err != nil {
return nil, err
}
done()
var txBytes []byte
// Generate the transaction bytes
if err := retry.Do(func() error {
var err error
txBytes, err = cc.Codec.TxConfig.TxEncoder()(txb.GetTx())
if err != nil {
return err
}
return nil
}, retry.Context(ctx), rtyAtt, rtyDel, rtyErr); err != nil {
return nil, err
}
return txBytes, nil
}
// CreateClient creates an sdk.Msg to update the client on src with consensus state from dst
func (cc *CosmosProvider) CreateClient(clientState ibcexported.ClientState, dstHeader ibcexported.Header, signer string) (provider.RelayerMessage, error) {
tmHeader, ok := dstHeader.(*tmclient.Header)
if !ok {
return nil, fmt.Errorf("got data of type %T but wanted tmclient.Header", dstHeader)
}
anyClientState, err := clienttypes.PackClientState(clientState)
if err != nil {
return nil, err
}
anyConsensusState, err := clienttypes.PackConsensusState(tmHeader.ConsensusState())
if err != nil {
return nil, err
}
msg := &clienttypes.MsgCreateClient{
ClientState: anyClientState,
ConsensusState: anyConsensusState,
Signer: signer,
}
return NewCosmosMessage(msg), nil
}
func (cc *CosmosProvider) SubmitMisbehavior( /*TBD*/ ) (provider.RelayerMessage, error) {
return nil, nil
}
func (cc *CosmosProvider) MsgUpdateClient(srcClientId string, dstHeader ibcexported.Header) (provider.RelayerMessage, error) {
acc, err := cc.Address()
if err != nil {
return nil, err
}
anyHeader, err := clienttypes.PackHeader(dstHeader)
if err != nil {
return nil, err
}
msg := &clienttypes.MsgUpdateClient{
ClientId: srcClientId,
Header: anyHeader,
Signer: acc,
}
return NewCosmosMessage(msg), nil
}
func (cc *CosmosProvider) ConnectionOpenInit(srcClientId, dstClientId string, dstHeader ibcexported.Header) ([]provider.RelayerMessage, error) {
var (
acc string
err error
version *conntypes.Version
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
counterparty := conntypes.Counterparty{
ClientId: dstClientId,
ConnectionId: "",
Prefix: defaultChainPrefix,
}
msg := &conntypes.MsgConnectionOpenInit{
ClientId: srcClientId,
Counterparty: counterparty,
Version: version,
DelayPeriod: defaultDelayPeriod,
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ConnectionOpenTry(ctx context.Context, dstQueryProvider provider.QueryProvider, dstHeader ibcexported.Header, srcClientId, dstClientId, srcConnId, dstConnId string) ([]provider.RelayerMessage, error) {
var (
acc string
err error
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
cph, err := dstQueryProvider.QueryLatestHeight(ctx)
if err != nil {
return nil, err
}
clientState, clientStateProof, consensusStateProof, connStateProof, proofHeight, err := dstQueryProvider.GenerateConnHandshakeProof(ctx, cph, dstClientId, dstConnId)
if err != nil {
return nil, err
}
if len(connStateProof) == 0 {
// It is possible that we have asked for a proof too early.
// If the connection state proof is empty, there is no point in returning the MsgConnectionOpenTry.
// We are not using (*conntypes.MsgConnectionOpenTry).ValidateBasic here because
// that chokes on cross-chain bech32 details in ibc-go.
return nil, fmt.Errorf("received invalid zero-length connection state proof")
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
csAny, err := clienttypes.PackClientState(clientState)
if err != nil {
return nil, err
}
counterparty := conntypes.Counterparty{
ClientId: dstClientId,
ConnectionId: dstConnId,
Prefix: defaultChainPrefix,
}
// TODO: Get DelayPeriod from counterparty connection rather than using default value
msg := &conntypes.MsgConnectionOpenTry{
ClientId: srcClientId,
PreviousConnectionId: srcConnId,
ClientState: csAny,
Counterparty: counterparty,
DelayPeriod: defaultDelayPeriod,
CounterpartyVersions: conntypes.ExportedVersionsToProto(conntypes.GetCompatibleVersions()),
ProofHeight: clienttypes.Height{
RevisionNumber: proofHeight.GetRevisionNumber(),
RevisionHeight: proofHeight.GetRevisionHeight(),
},
ProofInit: connStateProof,
ProofClient: clientStateProof,
ProofConsensus: consensusStateProof,
ConsensusHeight: clientState.GetLatestHeight().(clienttypes.Height),
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ConnectionOpenAck(ctx context.Context, dstQueryProvider provider.QueryProvider, dstHeader ibcexported.Header, srcClientId, srcConnId, dstClientId, dstConnId string) ([]provider.RelayerMessage, error) {
var (
acc string
err error
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
cph, err := dstQueryProvider.QueryLatestHeight(ctx)
if err != nil {
return nil, err
}
clientState, clientStateProof, consensusStateProof, connStateProof,
proofHeight, err := dstQueryProvider.GenerateConnHandshakeProof(ctx, cph, dstClientId, dstConnId)
if err != nil {
return nil, err
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
csAny, err := clienttypes.PackClientState(clientState)
if err != nil {
return nil, err
}
msg := &conntypes.MsgConnectionOpenAck{
ConnectionId: srcConnId,
CounterpartyConnectionId: dstConnId,
Version: conntypes.DefaultIBCVersion,
ClientState: csAny,
ProofHeight: clienttypes.Height{
RevisionNumber: proofHeight.GetRevisionNumber(),
RevisionHeight: proofHeight.GetRevisionHeight(),
},
ProofTry: connStateProof,
ProofClient: clientStateProof,
ProofConsensus: consensusStateProof,
ConsensusHeight: clientState.GetLatestHeight().(clienttypes.Height),
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ConnectionOpenConfirm(ctx context.Context, dstQueryProvider provider.QueryProvider, dstHeader ibcexported.Header, dstConnId, srcClientId, srcConnId string) ([]provider.RelayerMessage, error) {
var (
acc string
err error
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
cph, err := dstQueryProvider.QueryLatestHeight(ctx)
if err != nil {
return nil, err
}
counterpartyConnState, err := dstQueryProvider.QueryConnection(ctx, cph, dstConnId)
if err != nil {
return nil, err
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
msg := &conntypes.MsgConnectionOpenConfirm{
ConnectionId: srcConnId,
ProofAck: counterpartyConnState.Proof,
ProofHeight: counterpartyConnState.ProofHeight,
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ChannelOpenInit(srcClientId, srcConnId, srcPortId, srcVersion, dstPortId string, order chantypes.Order, dstHeader ibcexported.Header) ([]provider.RelayerMessage, error) {
var (
acc string
err error
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
msg := &chantypes.MsgChannelOpenInit{
PortId: srcPortId,
Channel: chantypes.Channel{
State: chantypes.INIT,
Ordering: order,
Counterparty: chantypes.Counterparty{
PortId: dstPortId,
ChannelId: "",
},
ConnectionHops: []string{srcConnId},
Version: srcVersion,
},
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ChannelOpenTry(ctx context.Context, dstQueryProvider provider.QueryProvider, dstHeader ibcexported.Header, srcPortId, dstPortId, srcChanId, dstChanId, srcVersion, srcConnectionId, srcClientId string) ([]provider.RelayerMessage, error) {
var (
acc string
err error
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
cph, err := dstQueryProvider.QueryLatestHeight(ctx)
if err != nil {
return nil, err
}
counterpartyChannelRes, err := dstQueryProvider.QueryChannel(ctx, cph, dstChanId, dstPortId)
if err != nil {
return nil, err
}
if len(counterpartyChannelRes.Proof) == 0 {
// It is possible that we have asked for a proof too early.
// If the connection state proof is empty, there is no point in returning the MsgChannelOpenTry.
// We are not using (*conntypes.MsgChannelOpenTry).ValidateBasic here because
// that chokes on cross-chain bech32 details in ibc-go.
return nil, fmt.Errorf("received invalid zero-length channel state proof")
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
msg := &chantypes.MsgChannelOpenTry{
PortId: srcPortId,
PreviousChannelId: srcChanId,
Channel: chantypes.Channel{
State: chantypes.TRYOPEN,
Ordering: counterpartyChannelRes.Channel.Ordering,
Counterparty: chantypes.Counterparty{
PortId: dstPortId,
ChannelId: dstChanId,
},
ConnectionHops: []string{srcConnectionId},
Version: srcVersion,
},
CounterpartyVersion: counterpartyChannelRes.Channel.Version,
ProofInit: counterpartyChannelRes.Proof,
ProofHeight: counterpartyChannelRes.ProofHeight,
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ChannelOpenAck(ctx context.Context, dstQueryProvider provider.QueryProvider, dstHeader ibcexported.Header, srcClientId, srcPortId, srcChanId, dstChanId, dstPortId string) ([]provider.RelayerMessage, error) {
var (
acc string
err error
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
cph, err := dstQueryProvider.QueryLatestHeight(ctx)
if err != nil {
return nil, err
}
counterpartyChannelRes, err := dstQueryProvider.QueryChannel(ctx, cph, dstChanId, dstPortId)
if err != nil {
return nil, err
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
msg := &chantypes.MsgChannelOpenAck{
PortId: srcPortId,
ChannelId: srcChanId,
CounterpartyChannelId: dstChanId,
CounterpartyVersion: counterpartyChannelRes.Channel.Version,
ProofTry: counterpartyChannelRes.Proof,
ProofHeight: counterpartyChannelRes.ProofHeight,
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ChannelOpenConfirm(ctx context.Context, dstQueryProvider provider.QueryProvider, dstHeader ibcexported.Header, srcClientId, srcPortId, srcChanId, dstPortId, dstChanId string) ([]provider.RelayerMessage, error) {
var (
acc string
err error
)
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstHeader)
if err != nil {
return nil, err
}
cph, err := dstQueryProvider.QueryLatestHeight(ctx)
if err != nil {
return nil, err
}
counterpartyChanState, err := dstQueryProvider.QueryChannel(ctx, cph, dstChanId, dstPortId)
if err != nil {
return nil, err
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
msg := &chantypes.MsgChannelOpenConfirm{
PortId: srcPortId,
ChannelId: srcChanId,
ProofAck: counterpartyChanState.Proof,
ProofHeight: counterpartyChanState.ProofHeight,
Signer: acc,
}
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, nil
}
func (cc *CosmosProvider) ChannelCloseInit(srcPortId, srcChanId string) (provider.RelayerMessage, error) {
var (
acc string
err error
)
if acc, err = cc.Address(); err != nil {
return nil, err
}
msg := &chantypes.MsgChannelCloseInit{
PortId: srcPortId,
ChannelId: srcChanId,
Signer: acc,
}
return NewCosmosMessage(msg), nil
}
func (cc *CosmosProvider) ChannelCloseConfirm(ctx context.Context, dstQueryProvider provider.QueryProvider, dsth int64, dstChanId, dstPortId, srcPortId, srcChanId string) (provider.RelayerMessage, error) {
var (
acc string
err error
)
dstChanResp, err := dstQueryProvider.QueryChannel(ctx, dsth, dstChanId, dstPortId)
if err != nil {
return nil, err
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
msg := &chantypes.MsgChannelCloseConfirm{
PortId: srcPortId,
ChannelId: srcChanId,
ProofInit: dstChanResp.Proof,
ProofHeight: dstChanResp.ProofHeight,
Signer: acc,
}
return NewCosmosMessage(msg), nil
}
func (cc *CosmosProvider) MsgUpgradeClient(srcClientId string, consRes *clienttypes.QueryConsensusStateResponse, clientRes *clienttypes.QueryClientStateResponse) (provider.RelayerMessage, error) {
var (
acc string
err error
)
if acc, err = cc.Address(); err != nil {
return nil, err
}
return NewCosmosMessage(&clienttypes.MsgUpgradeClient{ClientId: srcClientId, ClientState: clientRes.ClientState,
ConsensusState: consRes.ConsensusState, ProofUpgradeClient: consRes.GetProof(),
ProofUpgradeConsensusState: consRes.ConsensusState.Value, Signer: acc}), nil
}
// AutoUpdateClient update client automatically to prevent expiry
func (cc *CosmosProvider) AutoUpdateClient(ctx context.Context, dst provider.ChainProvider, thresholdTime time.Duration, srcClientId, dstClientId string) (time.Duration, error) {
srch, err := cc.QueryLatestHeight(ctx)
if err != nil {
return 0, err
}
dsth, err := dst.QueryLatestHeight(ctx)
if err != nil {
return 0, err
}
clientState, err := cc.queryTMClientState(ctx, srch, srcClientId)
if err != nil {
return 0, err
}
if clientState.TrustingPeriod <= thresholdTime {
return 0, fmt.Errorf("client (%s) trusting period time is less than or equal to threshold time", srcClientId)
}
// query the latest consensus state of the potential matching client
var consensusStateResp *clienttypes.QueryConsensusStateResponse
if err = retry.Do(func() error {
if clientState == nil {
return fmt.Errorf("client state for chain (%s) at height (%d) cannot be nil", cc.ChainId(), srch)
}
consensusStateResp, err = cc.QueryConsensusStateABCI(ctx, srcClientId, clientState.GetLatestHeight())
return err
}, retry.Context(ctx), rtyAtt, rtyDel, rtyErr, retry.OnRetry(func(n uint, err error) {
cc.log.Info(
"Error querying consensus state ABCI",
zap.String("chain_id", cc.PCfg.ChainID),
zap.Uint("attempt", n+1),
zap.Uint("max_attempts", rtyAttNum),
zap.Error(err),
)
clientState, err = cc.queryTMClientState(ctx, srch, srcClientId)
if err != nil {
clientState = nil
cc.log.Info(
"Failed to refresh tendermint client state in order to re-query consensus state ABCI",
zap.String("chain_id", cc.PCfg.ChainID),
zap.Error(err),
)
}
})); err != nil {
return 0, err
}
exportedConsState, err := clienttypes.UnpackConsensusState(consensusStateResp.ConsensusState)
if err != nil {
return 0, err
}
consensusState, ok := exportedConsState.(*tmclient.ConsensusState)
if !ok {
return 0, fmt.Errorf("consensus state with clientID %s from chain %s is not IBC tendermint type",
srcClientId, cc.PCfg.ChainID)
}
expirationTime := consensusState.Timestamp.Add(clientState.TrustingPeriod)
timeToExpiry := time.Until(expirationTime)
if timeToExpiry > thresholdTime {
return timeToExpiry, nil
}
if clientState.IsExpired(consensusState.Timestamp, time.Now()) {
return 0, fmt.Errorf("client (%s) is already expired on chain: %s", srcClientId, cc.PCfg.ChainID)
}
srcUpdateHeader, err := cc.GetIBCUpdateHeader(ctx, srch, dst, dstClientId)
if err != nil {
return 0, err
}
dstUpdateHeader, err := dst.GetIBCUpdateHeader(ctx, dsth, cc, srcClientId)
if err != nil {
return 0, err
}
updateMsg, err := cc.MsgUpdateClient(srcClientId, dstUpdateHeader)
if err != nil {
return 0, err
}
msgs := []provider.RelayerMessage{updateMsg}
res, success, err := cc.SendMessages(ctx, msgs, "")
if err != nil {
// cp.LogFailedTx(res, err, CosmosMsgs(msgs...))
return 0, err
}
if !success {
return 0, fmt.Errorf("tx failed: %s", res.Data)
}
cc.log.Info(
"Client updated",
zap.String("provider_chain_id", cc.PCfg.ChainID),
zap.String("src_client_id", srcClientId),
zap.Uint64("prev_height", mustGetHeight(srcUpdateHeader.GetHeight()).GetRevisionHeight()),
zap.Uint64("cur_height", srcUpdateHeader.GetHeight().GetRevisionHeight()),
)
return clientState.TrustingPeriod, nil
}
// mustGetHeight takes the height inteface and returns the actual height
func mustGetHeight(h ibcexported.Height) clienttypes.Height {
height, ok := h.(clienttypes.Height)
if !ok {
panic("height is not an instance of height!")
}
return height
}
// MsgRelayAcknowledgement constructs the MsgAcknowledgement which is to be sent to the sending chain.
// The counterparty represents the receiving chain where the acknowledgement would be stored.
func (cc *CosmosProvider) MsgRelayAcknowledgement(ctx context.Context, dst provider.ChainProvider, dstChanId, dstPortId, srcChanId, srcPortId string, dsth int64, packet provider.RelayPacket) (provider.RelayerMessage, error) {
var (
acc string
err error
)
msgPacketAck, ok := packet.(*relayMsgPacketAck)
if !ok {
return nil, fmt.Errorf("got data of type %T but wanted relayMsgPacketAck", packet)
}
if acc, err = cc.Address(); err != nil {
return nil, err
}
ackRes, err := dst.QueryPacketAcknowledgement(ctx, dsth, dstChanId, dstPortId, packet.Seq())
switch {
case err != nil:
return nil, err
case ackRes.Proof == nil || ackRes.Acknowledgement == nil:
return nil, fmt.Errorf("ack packet acknowledgement query seq(%d) is nil", packet.Seq())
case ackRes == nil:
return nil, fmt.Errorf("ack packet [%s]seq{%d} has no associated proofs", dst.ChainId(), packet.Seq())
default:
msg := &chantypes.MsgAcknowledgement{
Packet: chantypes.Packet{
Sequence: packet.Seq(),
SourcePort: srcPortId,
SourceChannel: srcChanId,
DestinationPort: dstPortId,
DestinationChannel: dstChanId,
Data: packet.Data(),
TimeoutHeight: packet.Timeout(),
TimeoutTimestamp: packet.TimeoutStamp(),
},
Acknowledgement: msgPacketAck.ack,
ProofAcked: ackRes.Proof,
ProofHeight: ackRes.ProofHeight,
Signer: acc,
}
return NewCosmosMessage(msg), nil
}
}
// MsgTransfer creates a new transfer message
func (cc *CosmosProvider) MsgTransfer(amount sdk.Coin, dstChainId, dstAddr, srcPortId, srcChanId string, timeoutHeight, timeoutTimestamp uint64) (provider.RelayerMessage, error) {
var (
acc string
err error
msg sdk.Msg
)
if acc, err = cc.Address(); err != nil {
return nil, err
}
// If the timeoutHeight is 0 then we don't need to explicitly set it on the MsgTransfer
if timeoutHeight == 0 {
msg = &transfertypes.MsgTransfer{
SourcePort: srcPortId,
SourceChannel: srcChanId,
Token: amount,
Sender: acc,
Receiver: dstAddr,
TimeoutTimestamp: timeoutTimestamp,
}
} else {
version := clienttypes.ParseChainID(dstChainId)
msg = &transfertypes.MsgTransfer{
SourcePort: srcPortId,
SourceChannel: srcChanId,
Token: amount,
Sender: acc,
Receiver: dstAddr,
TimeoutHeight: clienttypes.Height{
RevisionNumber: version,
RevisionHeight: timeoutHeight,
},
TimeoutTimestamp: timeoutTimestamp,
}
}
return NewCosmosMessage(msg), nil
}
// MsgRelayTimeout constructs the MsgTimeout which is to be sent to the sending chain.
// The counterparty represents the receiving chain where the receipts would have been
// stored.
func (cc *CosmosProvider) MsgRelayTimeout(
ctx context.Context,
dst provider.ChainProvider,
dsth int64,
packet provider.RelayPacket,
dstChanId, dstPortId, srcChanId, srcPortId string,
order chantypes.Order,
) (provider.RelayerMessage, error) {
var (
acc string
err error
msg provider.RelayerMessage
)
if acc, err = cc.Address(); err != nil {
return nil, err
}
switch order {
case chantypes.UNORDERED:
msg, err = cc.unorderedChannelTimeoutMsg(ctx, dst, dsth, packet, acc, dstChanId, dstPortId, srcChanId, srcPortId)
if err != nil {
return nil, err
}
case chantypes.ORDERED:
msg, err = cc.orderedChannelTimeoutMsg(ctx, dst, dsth, packet, acc, dstChanId, dstPortId, srcChanId, srcPortId)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("invalid order type %s, order should be %s or %s",
order, chantypes.ORDERED, chantypes.UNORDERED)
}
return msg, nil
}
func (cc *CosmosProvider) orderedChannelTimeoutMsg(
ctx context.Context,
dst provider.ChainProvider,
dsth int64,
packet provider.RelayPacket,
acc, dstChanId, dstPortId, srcChanId, srcPortId string,
) (provider.RelayerMessage, error) {
seqRes, err := dst.QueryNextSeqRecv(ctx, dsth, dstChanId, dstPortId)
if err != nil {
return nil, err
}
if seqRes == nil {
return nil, fmt.Errorf("timeout packet [%s]seq{%d} has no associated proofs", cc.PCfg.ChainID, packet.Seq())
}
if seqRes.Proof == nil {
return nil, fmt.Errorf("timeout packet next sequence received proof seq(%d) is nil", packet.Seq())
}
msg := &chantypes.MsgTimeout{
Packet: chantypes.Packet{
Sequence: packet.Seq(),
SourcePort: srcPortId,
SourceChannel: srcChanId,
DestinationPort: dstPortId,
DestinationChannel: dstChanId,
Data: packet.Data(),
TimeoutHeight: packet.Timeout(),
TimeoutTimestamp: packet.TimeoutStamp(),
},
ProofUnreceived: seqRes.Proof,
ProofHeight: seqRes.ProofHeight,