forked from datachainlab/ethereum-ibc-relay-chain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
363 lines (318 loc) · 11.1 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
package ethereum
import (
"context"
"crypto/ecdsa"
"fmt"
"math/big"
"time"
"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/neoiss/ethereum-ibc-relay-chain/pkg/client"
"github.com/neoiss/ethereum-ibc-relay-chain/pkg/contract/ibchandler"
"github.com/neoiss/ethereum-ibc-relay-chain/pkg/contract/ics20bank"
"github.com/neoiss/ethereum-ibc-relay-chain/pkg/contract/ics20transferbank"
"github.com/neoiss/ethereum-ibc-relay-chain/pkg/wallet"
)
type Chain struct {
config ChainConfig
pathEnd *core.PathEnd
homePath string
chainID *big.Int
codec codec.ProtoCodecMarshaler
msgEventListener core.MsgEventListener
relayerPrvKey *ecdsa.PrivateKey
client *client.ETHClient
ibcHandler *ibchandler.Ibchandler
ics20Bank *ics20bank.Ics20bank
ics20TransferBank *ics20transferbank.Ics20transferbank
}
var _ core.Chain = (*Chain)(nil)
func NewChain(config ChainConfig) (*Chain, error) {
id := big.NewInt(config.EthChainId)
cli, err := client.NewETHClient(config.RpcAddr)
if err != nil {
return nil, err
}
key, err := wallet.GetPrvKeyFromMnemonicAndHDWPath(config.HdwMnemonic, config.HdwPath)
if err != nil {
return nil, err
}
ibcHandler, err := ibchandler.NewIbchandler(config.IBCAddress(), cli)
if err != nil {
return nil, err
}
ics20Bank, err := ics20bank.NewIcs20bank(config.ICS20BankAddress(), cli)
if err != nil {
return nil, err
}
ics20TransferBank, err := ics20transferbank.NewIcs20transferbank(config.ICS20BankAddress(), cli)
if err != nil {
return nil, err
}
return &Chain{
config: config,
client: cli,
relayerPrvKey: key,
chainID: id,
ibcHandler: ibcHandler,
ics20Bank: ics20Bank,
ics20TransferBank: ics20TransferBank,
}, 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) {
bn, err := c.client.BlockNumber(context.TODO())
if err != nil {
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
}
}
// 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 {
if err := p.Validate(); err != nil {
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) {
s, found, err := c.ibcHandler.GetConsensusState(c.callOptsFromQueryContext(ctx), c.pathEnd.ClientID, pbToHostHeight(dstClientConsHeight))
if err != nil {
return nil, err
} else if !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 {
return nil, err
}
any, err := clienttypes.PackConsensusState(consensusState)
if err != nil {
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) {
s, found, err := c.ibcHandler.GetClientState(c.callOptsFromQueryContext(ctx), c.pathEnd.ClientID)
if err != nil {
return nil, err
} else if !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 {
return nil, err
}
any, err := clienttypes.PackClientState(clientState)
if err != nil {
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) {
conn, found, err := c.ibcHandler.GetConnection(c.callOptsFromQueryContext(ctx), c.pathEnd.ConnectionID)
if err != nil {
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) {
chann, found, err := c.ibcHandler.GetChannel(c.callOptsFromQueryContext(ctx), c.pathEnd.PortID, c.pathEnd.ChannelID)
if err != nil {
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) {
var ret []uint64
for _, seq := range seqs {
found, err := c.ibcHandler.HasPacketReceipt(c.callOptsFromQueryContext(ctx), c.pathEnd.PortID, c.pathEnd.ChannelID, seq)
if err != nil {
return nil, err
} else if !found {
ret = append(ret, seq)
}
}
return ret, nil
}
// QueryUnfinalizedRelayPackets returns packets and heights that are sent but not received at the latest finalized block on the counterparty chain
// todo QueryPacket batch
func (c *Chain) QueryUnfinalizedRelayPackets(ctx core.QueryContext, counterparty core.LightClientICS04Querier) (core.PacketInfoList, error) {
checkpoint, err := c.loadCheckpoint(sendCheckpoint)
if err != nil {
return nil, err
}
packets, err := c.findSentPackets(ctx, checkpoint)
if err != nil {
return nil, err
}
counterpartyHeader, err := counterparty.GetLatestFinalizedHeader()
if err != nil {
return nil, err
}
counterpartyCtx := core.NewQueryContext(context.TODO(), counterpartyHeader.GetHeight())
seqs, err := counterparty.QueryUnreceivedPackets(counterpartyCtx, packets.ExtractSequenceList())
if err != nil {
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 {
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) {
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 {
return nil, err
} else if found {
ret = append(ret, seq)
}
}
return ret, nil
}
// QueryUnfinalizedRelayAcknowledgements returns acks and heights that are sent but not received at the latest finalized block on the counterpartychain
// todo QueryPacketAcknowledgement batch
func (c *Chain) QueryUnfinalizedRelayAcknowledgements(ctx core.QueryContext, counterparty core.LightClientICS04Querier) (core.PacketInfoList, error) {
checkpoint, err := c.loadCheckpoint(recvCheckpoint)
if err != nil {
return nil, err
}
packets, err := c.findReceivedPackets(ctx, checkpoint)
if err != nil {
return nil, err
}
counterpartyHeader, err := counterparty.GetLatestFinalizedHeader()
if err != nil {
return nil, err
}
counterpartyCtx := core.NewQueryContext(context.TODO(), counterpartyHeader.GetHeight())
seqs, err := counterparty.QueryUnreceivedAcknowledgements(counterpartyCtx, packets.ExtractSequenceList())
if err != nil {
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 {
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) {
// todo unimpl
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) {
// todo unimpl
panic("not supported")
}
func (c *Chain) callOptsFromQueryContext(ctx core.QueryContext) *bind.CallOpts {
return c.CallOpts(ctx.Context(), int64(ctx.Height().GetRevisionHeight()))
}