-
Notifications
You must be signed in to change notification settings - Fork 12
/
chain.go
426 lines (376 loc) · 13.5 KB
/
chain.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
package ethereum
import (
"context"
"errors"
"fmt"
"math/big"
"time"
"github.com/avast/retry-go"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types"
conntypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types"
chantypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types"
committypes "github.com/cosmos/ibc-go/v7/modules/core/23-commitment/types"
ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/hyperledger-labs/yui-relayer/core"
"github.com/hyperledger-labs/yui-relayer/log"
"github.com/datachainlab/ethereum-ibc-relay-chain/pkg/client"
"github.com/datachainlab/ethereum-ibc-relay-chain/pkg/contract/ibchandler"
)
type Chain struct {
config ChainConfig
pathEnd *core.PathEnd
homePath string
chainID *big.Int
codec codec.ProtoCodecMarshaler
msgEventListener core.MsgEventListener
client *client.ETHClient
ibcHandler *ibchandler.Ibchandler
signer Signer
}
var _ core.Chain = (*Chain)(nil)
func NewChain(config ChainConfig) (*Chain, error) {
id := big.NewInt(int64(config.EthChainId))
client, err := client.NewETHClient(
config.RpcAddr,
client.WithRetryOption(
retry.Attempts(uint(config.MaxRetryForInclusion)),
retry.Delay(time.Duration(config.AverageBlockTimeMsec)*time.Millisecond),
),
)
if err != nil {
return nil, err
}
ibcHandler, err := ibchandler.NewIbchandler(config.IBCAddress(), client)
if err != nil {
return nil, err
}
signer, err := config.Signer.GetCachedValue().(SignerConfig).Build(big.NewInt(int64(config.EthChainId)))
if err != nil {
return nil, fmt.Errorf("failed to build signer: %v", err)
}
return &Chain{
config: config,
client: client,
chainID: id,
ibcHandler: ibcHandler,
signer: signer,
}, nil
}
// Config returns ChainConfig
func (c *Chain) Config() ChainConfig {
return c.config
}
// Init ...
func (c *Chain) Init(homePath string, timeout time.Duration, codec codec.ProtoCodecMarshaler, debug bool) error {
c.homePath = homePath
c.codec = codec
return nil
}
// SetupForRelay ...
func (c *Chain) SetupForRelay(ctx context.Context) error {
return nil
}
// ChainID returns ID of the chain
func (c *Chain) ChainID() string {
return c.config.ChainId
}
// GetLatestHeight gets the chain for the latest height and returns it
func (c *Chain) LatestHeight() (ibcexported.Height, error) {
logger := c.GetChainLogger()
bn, err := c.client.BlockNumber(context.TODO())
if err != nil {
logger.Error("failed to get block number", err)
return nil, err
}
return clienttypes.NewHeight(0, bn), nil
}
func (c *Chain) Timestamp(height ibcexported.Height) (time.Time, error) {
ht := big.NewInt(int64(height.GetRevisionHeight()))
if header, err := c.client.HeaderByNumber(context.TODO(), ht); err != nil {
return time.Time{}, err
} else {
return time.Unix(int64(header.Time), 0), nil
}
}
func (c *Chain) AverageBlockTime() time.Duration {
return time.Duration(c.config.AverageBlockTimeMsec) * time.Millisecond
}
// GetAddress returns the address of relayer
func (c *Chain) GetAddress() (sdk.AccAddress, error) {
addr := make([]byte, 20)
return addr, nil
}
// Marshaler returns the marshaler
func (c *Chain) Codec() codec.ProtoCodecMarshaler {
return c.codec
}
// Client returns the RPC client for ethereum
func (c *Chain) Client() *client.ETHClient {
return c.client
}
// SetRelayInfo sets source's path and counterparty's info to the chain
func (c *Chain) SetRelayInfo(p *core.PathEnd, _ *core.ProvableChain, _ *core.PathEnd) error {
logger := c.GetChainLogger()
if err := p.Validate(); err != nil {
logger.Error("invalid path", err)
return fmt.Errorf("path on chain %s failed to set: %w", c.ChainID(), err)
}
c.pathEnd = p
return nil
}
func (c *Chain) Path() *core.PathEnd {
return c.pathEnd
}
// RegisterMsgEventListener registers a given EventListener to the chain
func (c *Chain) RegisterMsgEventListener(listener core.MsgEventListener) {
c.msgEventListener = listener
}
// QueryClientConsensusState retrevies the latest consensus state for a client in state at a given height
func (c *Chain) QueryClientConsensusState(ctx core.QueryContext, dstClientConsHeight ibcexported.Height) (*clienttypes.QueryConsensusStateResponse, error) {
logger := c.GetChainLogger()
defer logger.TimeTrack(time.Now(), "QueryClientConsensusState")
s, found, err := c.ibcHandler.GetConsensusState(c.callOptsFromQueryContext(ctx), c.pathEnd.ClientID, pbToHostHeight(dstClientConsHeight))
if err != nil {
logger.Error("failed to get consensus state", err)
return nil, err
} else if !found {
logger.Error("client consensus not found", errors.New("client consensus not found"))
return nil, fmt.Errorf("client consensus not found: %v", c.pathEnd.ClientID)
}
var consensusState ibcexported.ConsensusState
if err := c.Codec().UnmarshalInterface(s, &consensusState); err != nil {
logger.Error("failed to unmarshal consensus state", err)
return nil, err
}
any, err := clienttypes.PackConsensusState(consensusState)
if err != nil {
logger.Error("failed to pack consensus state", err)
return nil, err
}
return clienttypes.NewQueryConsensusStateResponse(any, nil, ctx.Height().(clienttypes.Height)), nil
}
// QueryClientState returns the client state of dst chain
// height represents the height of dst chain
func (c *Chain) QueryClientState(ctx core.QueryContext) (*clienttypes.QueryClientStateResponse, error) {
logger := c.GetChainLogger()
defer logger.TimeTrack(time.Now(), "QueryClientState")
s, found, err := c.ibcHandler.GetClientState(c.callOptsFromQueryContext(ctx), c.pathEnd.ClientID)
if err != nil {
logger.Error("failed to get client state", err)
return nil, err
} else if !found {
logger.Error("client not found", errors.New("client not found"))
return nil, fmt.Errorf("client not found: %v", c.pathEnd.ClientID)
}
var clientState ibcexported.ClientState
if err := c.Codec().UnmarshalInterface(s, &clientState); err != nil {
logger.Error("failed to unmarshal client state", err)
return nil, err
}
any, err := clienttypes.PackClientState(clientState)
if err != nil {
logger.Error("failed to pack client state", err)
return nil, err
}
return clienttypes.NewQueryClientStateResponse(any, nil, ctx.Height().(clienttypes.Height)), nil
}
var emptyConnRes = conntypes.NewQueryConnectionResponse(
conntypes.NewConnectionEnd(
conntypes.UNINITIALIZED,
"client",
conntypes.NewCounterparty(
"client",
"connection",
committypes.NewMerklePrefix([]byte{}),
),
[]*conntypes.Version{},
0,
),
[]byte{},
clienttypes.NewHeight(0, 0),
)
// QueryConnection returns the remote end of a given connection
func (c *Chain) QueryConnection(ctx core.QueryContext) (*conntypes.QueryConnectionResponse, error) {
logger := c.GetChainLogger()
defer logger.TimeTrack(time.Now(), "QueryConnection")
conn, found, err := c.ibcHandler.GetConnection(c.callOptsFromQueryContext(ctx), c.pathEnd.ConnectionID)
if err != nil {
logger.Error("failed to get connection", err)
return nil, err
} else if !found {
return emptyConnRes, nil
}
return conntypes.NewQueryConnectionResponse(connectionEndToPB(conn), nil, ctx.Height().(clienttypes.Height)), nil
}
var emptyChannelRes = chantypes.NewQueryChannelResponse(
chantypes.NewChannel(
chantypes.UNINITIALIZED,
chantypes.UNORDERED,
chantypes.NewCounterparty(
"port",
"channel",
),
[]string{},
"version",
),
[]byte{},
clienttypes.NewHeight(0, 0),
)
// QueryChannel returns the channel associated with a channelID
func (c *Chain) QueryChannel(ctx core.QueryContext) (chanRes *chantypes.QueryChannelResponse, err error) {
logger := c.GetChainLogger()
defer logger.TimeTrack(time.Now(), "QueryChannel")
chann, found, err := c.ibcHandler.GetChannel(c.callOptsFromQueryContext(ctx), c.pathEnd.PortID, c.pathEnd.ChannelID)
if err != nil {
logger.Error("failed to get channel", err)
return nil, err
} else if !found {
return emptyChannelRes, nil
}
return chantypes.NewQueryChannelResponse(channelToPB(chann), nil, ctx.Height().(clienttypes.Height)), nil
}
// QueryUnreceivedPackets returns a list of unrelayed packet commitments
func (c *Chain) QueryUnreceivedPackets(ctx core.QueryContext, seqs []uint64) ([]uint64, error) {
logger := c.GetChannelLogger()
var ret []uint64
var nextSequenceRecv uint64
for _, seq := range seqs {
var received bool
var err error
// With UNORDERED channel, we can use receipts to check if packets are already received.
// With ORDERED channel, since IBC impls don't record receipts, we need to check nextSequenceRecv.
switch c.Path().GetOrder() {
case chantypes.UNORDERED:
if received, err = c.ibcHandler.HasPacketReceipt(c.callOptsFromQueryContext(ctx), c.pathEnd.PortID, c.pathEnd.ChannelID, seq); err != nil {
logger.Error("failed to get packet receipt", err)
return nil, err
}
case chantypes.ORDERED:
if nextSequenceRecv == 0 {
// queried only once
nextSequenceRecv, err = c.ibcHandler.GetNextSequenceRecv(c.callOptsFromQueryContext(ctx), c.pathEnd.PortID, c.pathEnd.ChannelID)
if err != nil {
logger.Error("failed to get nextSequenceRecv", err)
return nil, err
}
}
received = seq < nextSequenceRecv
default:
panic(fmt.Sprintf("unexpected order type: %d", c.Path().GetOrder()))
}
if !received {
ret = append(ret, seq)
}
}
return ret, nil
}
// QueryUnfinalizedRelayedPackets returns packets and heights that are sent but not received at the latest finalized block on the counterparty chain
func (c *Chain) QueryUnfinalizedRelayPackets(ctx core.QueryContext, counterparty core.LightClientICS04Querier) (core.PacketInfoList, error) {
logger := c.GetChannelLogger()
checkpoint, err := c.loadCheckpoint(sendCheckpoint)
if err != nil {
logger.Error("failed to load checkpoint", err)
return nil, err
}
packets, err := c.findSentPackets(ctx, checkpoint)
if err != nil {
logger.Error("failed to find sent packets", err)
return nil, err
}
counterpartyHeader, err := counterparty.GetFinalizedHeader(0)
if err != nil {
logger.Error("failed to get latest finalized header", err)
return nil, err
}
counterpartyCtx := core.NewQueryContext(context.TODO(), counterpartyHeader.GetHeight())
seqs, err := counterparty.QueryUnreceivedPackets(counterpartyCtx, packets.ExtractSequenceList())
if err != nil {
logger.Error("failed to query unreceived packets", err)
return nil, err
}
packets = packets.Filter(seqs)
if len(packets) == 0 {
checkpoint = ctx.Height().GetRevisionHeight() + 1
} else {
checkpoint = packets[0].EventHeight.GetRevisionHeight()
}
if err := c.saveCheckpoint(checkpoint, sendCheckpoint); err != nil {
logger.Error("failed to save checkpoint", err)
return nil, err
}
return packets, nil
}
// QueryUnreceivedAcknowledgements returns a list of unrelayed packet acks
func (c *Chain) QueryUnreceivedAcknowledgements(ctx core.QueryContext, seqs []uint64) ([]uint64, error) {
logger := c.GetChannelLogger()
var ret []uint64
for _, seq := range seqs {
_, found, err := c.ibcHandler.GetHashedPacketCommitment(c.callOptsFromQueryContext(ctx), c.pathEnd.PortID, c.pathEnd.ChannelID, seq)
if err != nil {
logger.Error("failed to get hashed packet commitment", err)
return nil, err
} else if found {
ret = append(ret, seq)
}
}
return ret, nil
}
// QueryUnfinalizedRelayedAcknowledgements returns acks and heights that are sent but not received at the latest finalized block on the counterpartychain
func (c *Chain) QueryUnfinalizedRelayAcknowledgements(ctx core.QueryContext, counterparty core.LightClientICS04Querier) (core.PacketInfoList, error) {
logger := c.GetChannelLogger()
checkpoint, err := c.loadCheckpoint(recvCheckpoint)
if err != nil {
logger.Error("failed to load checkpoint", err)
return nil, err
}
packets, err := c.findReceivedPackets(ctx, checkpoint)
if err != nil {
logger.Error("failed to find received packets", err)
return nil, err
}
counterpartyHeader, err := counterparty.GetFinalizedHeader(0)
if err != nil {
logger.Error("failed to get latest finalized header", err)
return nil, err
}
counterpartyCtx := core.NewQueryContext(context.TODO(), counterpartyHeader.GetHeight())
seqs, err := counterparty.QueryUnreceivedAcknowledgements(counterpartyCtx, packets.ExtractSequenceList())
if err != nil {
logger.Error("failed to query unreceived acknowledgements", err)
return nil, err
}
packets = packets.Filter(seqs)
if len(packets) == 0 {
checkpoint = ctx.Height().GetRevisionHeight() + 1
} else {
checkpoint = packets[0].EventHeight.GetRevisionHeight()
}
if err := c.saveCheckpoint(checkpoint, recvCheckpoint); err != nil {
logger.Error("failed to save checkpoint", err)
return nil, err
}
return packets, nil
}
// QueryBalance returns the amount of coins in the relayer account
func (c *Chain) QueryBalance(ctx core.QueryContext, address sdk.AccAddress) (sdk.Coins, error) {
panic("not supported")
}
// QueryDenomTraces returns all the denom traces from a given chain
func (c *Chain) QueryDenomTraces(ctx core.QueryContext, offset uint64, limit uint64) (*transfertypes.QueryDenomTracesResponse, error) {
panic("not supported")
}
func (c *Chain) callOptsFromQueryContext(ctx core.QueryContext) *bind.CallOpts {
return c.CallOpts(ctx.Context(), int64(ctx.Height().GetRevisionHeight()))
}
func (c *Chain) GetChainLogger() *log.RelayLogger {
logger := GetModuleLogger()
if c.Path() == nil {
return logger
}
chainID := c.Path().ChainID
return logger.WithChain(chainID)
}