-
Notifications
You must be signed in to change notification settings - Fork 26
/
chain.go
458 lines (384 loc) · 12.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
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
package tendermint
import (
"context"
"fmt"
"os"
"path"
"sync"
"time"
"github.com/avast/retry-go"
sdkCtx "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/codec"
keys "github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authTypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/go-bip39"
clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types"
ibcexported "github.com/cosmos/ibc-go/v4/modules/core/exported"
"github.com/tendermint/tendermint/libs/log"
rpcclient "github.com/tendermint/tendermint/rpc/client"
rpchttp "github.com/tendermint/tendermint/rpc/client/http"
libclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
"github.com/hyperledger-labs/yui-relayer/core"
)
var (
rtyAttNum = uint(5)
rtyAtt = retry.Attempts(rtyAttNum)
rtyDel = retry.Delay(time.Millisecond * 400)
rtyErr = retry.LastErrorOnly(true)
)
// Chain represents the necessary data for connecting to and indentifying a chain and its counterparites
type Chain struct {
config ChainConfig
// TODO: make these private
HomePath string `yaml:"-" json:"-"`
PathEnd *core.PathEnd `yaml:"-" json:"-"`
Keybase keys.Keyring `yaml:"-" json:"-"`
Client rpcclient.Client `yaml:"-" json:"-"`
codec codec.ProtoCodecMarshaler `yaml:"-" json:"-"`
msgEventListener core.MsgEventListener
address sdk.AccAddress
logger log.Logger
timeout time.Duration
debug bool
// stores facuet addresses that have been used reciently
faucetAddrs map[string]time.Time
}
var _ core.Chain = (*Chain)(nil)
func (c *Chain) ChainID() string {
return c.config.ChainId
}
func (c *Chain) Config() ChainConfig {
return c.config
}
func (c *Chain) ClientID() string {
return c.PathEnd.ClientID
}
func (c *Chain) Codec() codec.ProtoCodecMarshaler {
return c.codec
}
// GetAddress returns the sdk.AccAddress associated with the configred key
func (c *Chain) GetAddress() (sdk.AccAddress, error) {
defer c.UseSDKContext()()
if c.address != nil {
return c.address, nil
}
// Signing key for c chain
srcAddr, err := c.Keybase.Key(c.config.Key)
if err != nil {
return nil, err
}
return srcAddr.GetAddress(), nil
}
// 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 c.ErrCantSetPath(err)
}
c.PathEnd = p
return nil
}
// ErrCantSetPath returns an error if the path doesn't set properly
func (c *Chain) ErrCantSetPath(err error) error {
return fmt.Errorf("path on chain %s failed to set: %w", c.ChainID(), err)
}
func (c *Chain) Path() *core.PathEnd {
return c.PathEnd
}
func (c *Chain) Init(homePath string, timeout time.Duration, codec codec.ProtoCodecMarshaler, debug bool) error {
keybase, err := keys.New(c.config.ChainId, "test", keysDir(homePath, c.config.ChainId), nil)
if err != nil {
return err
}
client, err := newRPCClient(c.config.RpcAddr, timeout)
if err != nil {
return err
}
_, err = sdk.ParseDecCoins(c.config.GasPrices)
if err != nil {
return fmt.Errorf("failed to parse gas prices (%s) for chain %s", c.config.GasPrices, c.ChainID())
}
c.Keybase = keybase
c.Client = client
c.HomePath = homePath
c.codec = codec
c.logger = defaultChainLogger()
c.timeout = timeout
c.debug = debug
c.faucetAddrs = make(map[string]time.Time)
return nil
}
func (c *Chain) SetupForRelay(ctx context.Context) error {
return nil
}
// LatestHeight queries the chain for the latest height and returns it
func (c *Chain) LatestHeight() (ibcexported.Height, error) {
res, err := c.Client.Status(context.Background())
if err != nil {
return nil, err
} else if res.SyncInfo.CatchingUp {
return nil, fmt.Errorf("node at %s running chain %s not caught up", c.config.RpcAddr, c.ChainID())
}
version := clienttypes.ParseChainID(c.ChainID())
return clienttypes.NewHeight(version, uint64(res.SyncInfo.LatestBlockHeight)), nil
}
// RegisterMsgEventListener registers a given EventListener to the chain
func (c *Chain) RegisterMsgEventListener(listener core.MsgEventListener) {
c.msgEventListener = listener
}
func (c *Chain) sendMsgs(msgs []sdk.Msg) (*sdk.TxResponse, error) {
res, _, err := c.rawSendMsgs(msgs)
if err != nil {
return nil, err
}
if res.Code == 0 && c.msgEventListener != nil {
if err := c.msgEventListener.OnSentMsg(msgs); err != nil {
c.logger.Error("failed to OnSendMsg call", "msgs", msgs, "err", err)
return res, nil
}
}
return res, nil
}
func (c *Chain) rawSendMsgs(msgs []sdk.Msg) (*sdk.TxResponse, bool, error) {
// Instantiate the client context
ctx := c.CLIContext(0)
// Query account details
txf, err := prepareFactory(ctx, c.TxFactory(0))
if err != nil {
return nil, false, err
}
// TODO: Make this work with new CalculateGas method
// https://github.com/cosmos/cosmos-sdk/blob/5725659684fc93790a63981c653feee33ecf3225/client/tx/tx.go#L297
// If users pass gas adjustment, then calculate gas
_, adjusted, err := CalculateGas(ctx.QueryWithData, txf, msgs...)
if err != nil {
return nil, false, err
}
// Set the gas amount on the transaction factory
txf = txf.WithGas(adjusted)
// Build the transaction builder
txb, err := tx.BuildUnsignedTx(txf, msgs...)
if err != nil {
return nil, false, err
}
// Attach the signature to the transaction
err = tx.Sign(txf, c.config.Key, txb, false)
if err != nil {
return nil, false, err
}
// Generate the transaction bytes
txBytes, err := ctx.TxConfig.TxEncoder()(txb.GetTx())
if err != nil {
return nil, false, err
}
// Broadcast those bytes
res, err := ctx.BroadcastTx(txBytes)
if err != nil {
return nil, false, err
}
// 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 res.Code != 0 {
c.LogFailedTx(res, err, msgs)
return res, false, nil
}
c.LogSuccessTx(res, msgs)
return res, true, nil
}
func prepareFactory(clientCtx sdkCtx.Context, txf tx.Factory) (tx.Factory, error) {
from := clientCtx.GetFromAddress()
if err := txf.AccountRetriever().EnsureExists(clientCtx, from); err != nil {
return txf, err
}
initNum, initSeq := txf.AccountNumber(), txf.Sequence()
if initNum == 0 || initSeq == 0 {
num, seq, err := txf.AccountRetriever().GetAccountNumberSequence(clientCtx, from)
if err != nil {
return txf, err
}
if initNum == 0 {
txf = txf.WithAccountNumber(num)
}
if initSeq == 0 {
txf = txf.WithSequence(seq)
}
}
return txf, nil
}
// protoTxProvider is a type which can provide a proto transaction. It is a
// workaround to get access to the wrapper TxBuilder's method GetProtoTx().
type protoTxProvider interface {
GetProtoTx() *txtypes.Tx
}
// BuildSimTx creates an unsigned tx with an empty single signature and returns
// the encoded transaction or an error if the unsigned transaction cannot be
// built.
func BuildSimTx(txf tx.Factory, msgs ...sdk.Msg) ([]byte, error) {
txb, err := tx.BuildUnsignedTx(txf, msgs...)
if err != nil {
return nil, err
}
// Create an empty signature literal as the ante handler will populate with a
// sentinel pubkey.
sig := signing.SignatureV2{
PubKey: &secp256k1.PubKey{},
Data: &signing.SingleSignatureData{
SignMode: txf.SignMode(),
},
Sequence: txf.Sequence(),
}
if err := txb.SetSignatures(sig); err != nil {
return nil, err
}
protoProvider, ok := txb.(protoTxProvider)
if !ok {
return nil, fmt.Errorf("cannot simulate amino tx")
}
simReq := txtypes.SimulateRequest{Tx: protoProvider.GetProtoTx()}
return simReq.Marshal()
}
// CalculateGas simulates the execution of a transaction and returns the
// simulation response obtained by the query and the adjusted gas amount.
func CalculateGas(
queryFunc func(string, []byte) ([]byte, int64, error), txf tx.Factory, msgs ...sdk.Msg,
) (txtypes.SimulateResponse, uint64, error) {
txBytes, err := BuildSimTx(txf, msgs...)
if err != nil {
return txtypes.SimulateResponse{}, 0, err
}
bz, _, err := queryFunc("/cosmos.tx.v1beta1.Service/Simulate", txBytes)
if err != nil {
return txtypes.SimulateResponse{}, 0, err
}
var simRes txtypes.SimulateResponse
if err := simRes.Unmarshal(bz); err != nil {
return txtypes.SimulateResponse{}, 0, err
}
return simRes, uint64(txf.GasAdjustment() * float64(simRes.GasInfo.GasUsed)), nil
}
func (c *Chain) SendMsgs(msgs []sdk.Msg) ([]byte, error) {
// Broadcast those bytes
res, err := c.sendMsgs(msgs)
if err != nil {
return nil, err
}
return []byte(res.Logs.String()), nil
}
func (c *Chain) Send(msgs []sdk.Msg) bool {
res, err := c.sendMsgs(msgs)
if err != nil || res.Code != 0 {
c.LogFailedTx(res, err, msgs)
return false
}
// NOTE: Add more data to this such as identifiers
c.LogSuccessTx(res, msgs)
return true
}
// ------------------------------- //
func (c *Chain) Key() string {
return c.config.Key
}
// KeyExists returns true if there is a specified key in chain's keybase
func (c *Chain) KeyExists(name string) bool {
k, err := c.Keybase.Key(name)
if err != nil {
return false
}
return k.GetName() == name
}
// MustGetAddress used for brevity
func (c *Chain) MustGetAddress() sdk.AccAddress {
srcAddr, err := c.GetAddress()
if err != nil {
panic(err)
}
return srcAddr
}
var sdkContextMutex sync.Mutex
// UseSDKContext uses a custom Bech32 account prefix and returns a restore func
// CONTRACT: When using this function, caller must ensure that lock contention
// doesn't cause program to hang. This function is only for use in codec calls
func (c *Chain) UseSDKContext() func() {
// Ensure we're the only one using the global context,
// lock context to begin function
sdkContextMutex.Lock()
// Mutate the sdkConf
sdkConf := sdk.GetConfig()
sdkConf.SetBech32PrefixForAccount(c.config.AccountPrefix, c.config.AccountPrefix+"pub")
sdkConf.SetBech32PrefixForValidator(c.config.AccountPrefix+"valoper", c.config.AccountPrefix+"valoperpub")
sdkConf.SetBech32PrefixForConsensusNode(c.config.AccountPrefix+"valcons", c.config.AccountPrefix+"valconspub")
// Return the unlock function, caller must lock and ensure that lock is released
// before any other function needs to use c.UseSDKContext
return sdkContextMutex.Unlock
}
// CLIContext returns an instance of client.Context derived from Chain
func (c *Chain) CLIContext(height int64) sdkCtx.Context {
return sdkCtx.Context{}.
WithChainID(c.config.ChainId).
WithJSONCodec(newContextualStdCodec(c.codec, c.UseSDKContext)).
WithInterfaceRegistry(c.codec.InterfaceRegistry()).
WithTxConfig(authtx.NewTxConfig(c.codec, authtx.DefaultSignModes)).
WithInput(os.Stdin).
WithNodeURI(c.config.RpcAddr).
WithClient(c.Client).
WithAccountRetriever(authTypes.AccountRetriever{}).
WithBroadcastMode(flags.BroadcastBlock).
WithKeyring(c.Keybase).
WithOutputFormat("json").
WithFrom(c.config.Key).
WithFromName(c.config.Key).
WithFromAddress(c.MustGetAddress()).
WithSkipConfirmation(true).
WithNodeURI(c.config.RpcAddr).
WithHeight(height)
}
// TxFactory returns an instance of tx.Factory derived from
func (c *Chain) TxFactory(height int64) tx.Factory {
ctx := c.CLIContext(height)
return tx.Factory{}.
WithAccountRetriever(ctx.AccountRetriever).
WithChainID(c.config.ChainId).
WithTxConfig(ctx.TxConfig).
WithGasAdjustment(c.config.GasAdjustment).
WithGasPrices(c.config.GasPrices).
WithKeybase(c.Keybase).
WithSignMode(signing.SignMode_SIGN_MODE_DIRECT)
}
// KeysDir returns the path to the keys for this chain
func keysDir(home, chainID string) string {
return path.Join(home, "keys", chainID)
}
func newRPCClient(addr string, timeout time.Duration) (*rpchttp.HTTP, error) {
httpClient, err := libclient.DefaultHTTPClient(addr)
if err != nil {
return nil, err
}
httpClient.Timeout = timeout
rpcClient, err := rpchttp.NewWithClient(addr, "/websocket", httpClient)
if err != nil {
return nil, err
}
return rpcClient, nil
}
func defaultChainLogger() log.Logger {
return log.NewTMLogger(log.NewSyncWriter(os.Stdout))
}
// CreateMnemonic creates a new mnemonic
func CreateMnemonic() (string, error) {
entropySeed, err := bip39.NewEntropy(256)
if err != nil {
return "", err
}
mnemonic, err := bip39.NewMnemonic(entropySeed)
if err != nil {
return "", err
}
return mnemonic, nil
}