-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
chains.go
529 lines (480 loc) · 13.1 KB
/
chains.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
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/cosmos/relayer/v2/relayer"
"github.com/cosmos/relayer/v2/relayer/chains/cosmos"
"github.com/spf13/cobra"
registry "github.com/strangelove-ventures/lens/client/chain_registry"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
)
const (
check = "✔"
xIcon = "✘"
)
func chainsCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "chains",
Aliases: []string{"ch"},
Short: "Manage chain configurations",
}
cmd.AddCommand(
chainsListCmd(a),
chainsRegistryList(a),
chainsDeleteCmd(a),
chainsAddCmd(a),
chainsShowCmd(a),
chainsAddrCmd(a),
chainsAddDirCmd(a),
)
return cmd
}
func chainsAddrCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "address chain_name",
Aliases: []string{"addr"},
Short: "Returns a chain's configured key's address",
Args: withUsage(cobra.ExactArgs(1)),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s chains address ibc-0
$ %s ch addr ibc-0`, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
chain, ok := a.Config.Chains[args[0]]
if !ok {
return errChainNotFound(args[0])
}
address, err := chain.ChainProvider.ShowAddress(chain.ChainProvider.Key())
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), address)
return nil
},
}
return cmd
}
func chainsShowCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "show chain_name",
Aliases: []string{"s"},
Short: "Returns a chain's configuration data",
Args: withUsage(cobra.ExactArgs(1)),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s chains show ibc-0 --json
$ %s chains show ibc-0 --yaml
$ %s ch s ibc-0 --json
$ %s ch s ibc-0 --yaml`, appName, appName, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
c, ok := a.Config.Chains[args[0]]
if !ok {
return errChainNotFound(args[0])
}
jsn, err := cmd.Flags().GetBool(flagJSON)
if err != nil {
return err
}
switch {
case jsn:
pcfgw := &ProviderConfigWrapper{
Type: c.ChainProvider.Type(),
Value: c.ChainProvider.ProviderConfig(),
}
out, err := json.Marshal(pcfgw)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), string(out))
return nil
default:
pcfgw := &ProviderConfigWrapper{
Type: c.ChainProvider.Type(),
Value: c.ChainProvider.ProviderConfig(),
}
out, err := yaml.Marshal(pcfgw)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), string(out))
return nil
}
},
}
return jsonFlag(a.Viper, cmd)
}
func chainsDeleteCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "delete chain_name",
Aliases: []string{"d"},
Short: "Removes chain from config based off chain-id",
Args: withUsage(cobra.ExactArgs(1)),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s chains delete ibc-0
$ %s ch d ibc-0`, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
_, ok := a.Config.Chains[args[0]]
if !ok {
return errChainNotFound(args[0])
}
a.Config.DeleteChain(args[0])
return a.OverwriteConfig(a.Config)
},
}
return cmd
}
func chainsRegistryList(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "registry-list",
Args: withUsage(cobra.NoArgs),
Aliases: []string{"rl"},
Short: "List chains available for configuration from the registry",
RunE: func(cmd *cobra.Command, args []string) error {
jsn, err := cmd.Flags().GetBool(flagJSON)
if err != nil {
return err
}
yml, err := cmd.Flags().GetBool(flagYAML)
if err != nil {
return err
}
chains, err := registry.DefaultChainRegistry(a.Log).ListChains(cmd.Context())
if err != nil {
return err
}
switch {
case yml && jsn:
return fmt.Errorf("can't pass both --json and --yaml, must pick one")
case yml:
out, err := yaml.Marshal(chains)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), string(out))
return nil
case jsn:
out, err := json.Marshal(chains)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), string(out))
return nil
default:
for _, chain := range chains {
fmt.Fprintln(cmd.OutOrStdout(), chain)
}
}
return nil
},
}
return yamlFlag(a.Viper, jsonFlag(a.Viper, cmd))
}
func chainsListCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"l"},
Short: "Returns chain configuration data",
Args: withUsage(cobra.NoArgs),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s chains list
$ %s ch l`, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
jsn, err := cmd.Flags().GetBool(flagJSON)
if err != nil {
return err
}
yml, err := cmd.Flags().GetBool(flagYAML)
if err != nil {
return err
}
configs := a.Config.Wrapped().ProviderConfigs
if len(configs) == 0 {
fmt.Fprintln(cmd.ErrOrStderr(), "warning: no chains found (do you need to run 'rly chains add'?)")
}
switch {
case yml && jsn:
return fmt.Errorf("can't pass both --json and --yaml, must pick one")
case yml:
out, err := yaml.Marshal(configs)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), string(out))
return nil
case jsn:
out, err := json.Marshal(configs)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), string(out))
return nil
default:
i := 0
for _, c := range a.Config.Chains {
var (
key = xIcon
p = xIcon
bal = xIcon
)
// check that the key from config.yaml is set in keychain
if c.ChainProvider.KeyExists(c.ChainProvider.Key()) {
key = check
}
coins, err := c.ChainProvider.QueryBalance(cmd.Context(), c.ChainProvider.Key())
if err == nil && !coins.Empty() {
bal = check
}
for _, pth := range a.Config.Paths {
if pth.Src.ChainID == c.ChainProvider.ChainId() || pth.Dst.ChainID == c.ChainID() {
p = check
}
}
i++
fmt.Fprintf(cmd.OutOrStdout(), "%2d: %-20s -> type(%s) key(%s) bal(%s) path(%s)\n", i, c.ChainID(), c.ChainProvider.Type(), key, bal, p)
}
return nil
}
},
}
return yamlFlag(a.Viper, jsonFlag(a.Viper, cmd))
}
func chainsAddCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "add [chain-name...]",
Aliases: []string{"a"},
Short: "Add a new chain to the configuration file by fetching chain metadata from \n" +
" the chain-registry or passing a file (-f) or url (-u)",
Args: withUsage(cobra.MinimumNArgs(0)),
Example: fmt.Sprintf(` $ %s chains add cosmoshub
$ %s chains add cosmoshub osmosis
$ %s chains add --file chains/ibc0.json ibc0
$ %s chains add --url https://relayer.com/ibc0.json ibc0`, appName, appName, appName, appName),
RunE: func(cmd *cobra.Command, args []string) error {
file, url, err := getAddInputs(cmd)
if err != nil {
return err
}
if ok := a.Config; ok == nil {
return fmt.Errorf("config not initialized, consider running `rly config init`")
}
// default behavior fetch from chain registry
// still allow for adding config from url or file
switch {
case file != "":
var chainName string
switch len(args) {
case 0:
chainName = strings.Split(filepath.Base(file), ".")[0]
case 1:
chainName = args[0]
default:
return errors.New("one chain name is required")
}
if err := addChainFromFile(a, chainName, file); err != nil {
return err
}
case url != "":
if len(args) != 1 {
return errors.New("one chain name is required")
}
if err := addChainFromURL(a, args[0], url); err != nil {
return err
}
default:
if err := addChainsFromRegistry(cmd.Context(), a, args); err != nil {
return err
}
}
if err := validateConfig(a.Config); err != nil {
return err
}
return a.OverwriteConfig(a.Config)
},
}
return chainsAddFlags(a.Viper, cmd)
}
func chainsAddDirCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "add-dir dir",
Aliases: []string{"ad"},
Args: withUsage(cobra.ExactArgs(1)),
Short: `Add chain configuration data in bulk from a directory. Example dir: 'configs/demo/chains'`,
Long: `Add chain configuration data in bulk from a directory housing individual chain config files. This is useful for spinning up testnets.
See 'configs/demo/chains' for an example of individual chain config files.`,
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s chains add-dir configs/demo/chains
$ %s ch ad testnet/chains/`, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) (err error) {
if err := addChainsFromDirectory(cmd.ErrOrStderr(), a, args[0]); err != nil {
return err
}
return a.OverwriteConfig(a.Config)
},
}
return cmd
}
// addChainFromFile reads a JSON-formatted chain from the named file
// and adds it to a's chains.
func addChainFromFile(a *appState, chainName string, file string) error {
// If the user passes in a file, attempt to read the chain config from that file
var pcw ProviderConfigWrapper
if _, err := os.Stat(file); err != nil {
return err
}
byt, err := os.ReadFile(file)
if err != nil {
return err
}
if err = json.Unmarshal(byt, &pcw); err != nil {
return err
}
prov, err := pcw.Value.NewProvider(
a.Log.With(zap.String("provider_type", pcw.Type)),
a.HomePath, a.Debug, chainName,
)
if err != nil {
return fmt.Errorf("failed to build ChainProvider for %s: %w", file, err)
}
c := relayer.NewChain(a.Log, prov, a.Debug)
if err = a.Config.AddChain(c); err != nil {
return err
}
return nil
}
// addChainFromURL fetches a JSON-encoded chain from the given URL
// and adds it to a's chains.
func addChainFromURL(a *appState, chainName string, rawurl string) error {
u, err := url.Parse(rawurl)
if err != nil || u.Scheme == "" || u.Host == "" {
return fmt.Errorf("invalid URL %s", rawurl)
}
// TODO: add a rly user agent to this outgoing request.
resp, err := http.Get(u.String())
if err != nil {
return err
}
defer resp.Body.Close()
var pcw ProviderConfigWrapper
d := json.NewDecoder(resp.Body)
d.DisallowUnknownFields()
err = d.Decode(&pcw)
if err != nil {
return err
}
// build the ChainProvider before initializing the chain
prov, err := pcw.Value.NewProvider(
a.Log.With(zap.String("provider_type", pcw.Type)),
a.HomePath, a.Debug, chainName,
)
if err != nil {
return fmt.Errorf("failed to build ChainProvider for %s: %w", rawurl, err)
}
c := relayer.NewChain(a.Log, prov, a.Debug)
if err := a.Config.AddChain(c); err != nil {
return err
}
return nil
}
func addChainsFromRegistry(ctx context.Context, a *appState, chains []string) error {
chainRegistry := registry.DefaultChainRegistry(a.Log)
allChains, err := chainRegistry.ListChains(ctx)
if err != nil {
return err
}
foundError := false
for _, chain := range chains {
if _, ok := a.Config.Chains[chain]; ok {
a.Log.Warn(
"Chain already exists",
zap.String("chain", chain),
zap.String("source_link", chainRegistry.SourceLink()),
)
continue
}
found := false
for _, possibleChain := range allChains {
if chain == possibleChain {
found = true
}
if !found {
a.Log.Warn(
"Unable to find chain",
zap.String("chain", chain),
zap.String("source_link", chainRegistry.SourceLink()),
)
continue
}
chainInfo, err := chainRegistry.GetChain(ctx, chain)
if err != nil {
a.Log.Warn(
"Error retrieving chain",
zap.String("chain", chain),
zap.Error(err),
)
foundError = true
continue
}
chainConfig, err := chainInfo.GetChainConfig(ctx)
if err != nil {
a.Log.Warn(
"Error generating chain config",
zap.String("chain", chain),
zap.Error(err),
)
foundError = true
continue
}
// build the ChainProvider
pcfg := &cosmos.CosmosProviderConfig{
Key: chainConfig.Key,
ChainName: chainInfo.ChainName,
ChainID: chainConfig.ChainID,
RPCAddr: chainConfig.RPCAddr,
AccountPrefix: chainConfig.AccountPrefix,
KeyringBackend: chainConfig.KeyringBackend,
GasAdjustment: chainConfig.GasAdjustment,
GasPrices: chainConfig.GasPrices,
Debug: chainConfig.Debug,
Timeout: chainConfig.Timeout,
OutputFormat: chainConfig.OutputFormat,
SignModeStr: chainConfig.SignModeStr,
}
prov, err := pcfg.NewProvider(
a.Log.With(zap.String("provider_type", "cosmos")),
a.HomePath, a.Debug, chainInfo.ChainName,
)
if err != nil {
a.Log.Warn(
"Failed to build ChainProvider",
zap.String("chain_id", chainConfig.ChainID),
zap.Error(err),
)
foundError = true
continue
}
// add to config
c := relayer.NewChain(a.Log, prov, a.Debug)
if err = a.Config.AddChain(c); err != nil {
a.Log.Warn(
"Failed to add chain to config",
zap.String("chain", chain),
zap.Error(err),
)
foundError = true
continue
}
// found the correct chain so move on to next chain in chains
break
}
}
if foundError {
return errors.New("some chain(s) failed to be added to config")
}
return nil
}