forked from strangelove-ventures/lens
/
chain_info.go
236 lines (208 loc) · 5.64 KB
/
chain_info.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
package chain_registry
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"time"
"github.com/spf13/viper"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"github.com/Anmol1696/lens/client"
)
type ChainInfo struct {
log *zap.Logger
Schema string `json:"$schema"`
ChainName string `json:"chain_name"`
Status string `json:"status"`
NetworkType string `json:"network_type"`
PrettyName string `json:"pretty_name"`
ChainID string `json:"chain_id"`
Bech32Prefix string `json:"bech32_prefix"`
DaemonName string `json:"daemon_name"`
NodeHome string `json:"node_home"`
Genesis struct {
GenesisURL string `json:"genesis_url"`
} `json:"genesis"`
Slip44 int `json:"slip44"`
Codebase struct {
GitRepo string `json:"git_repo"`
RecommendedVersion string `json:"recommended_version"`
CompatibleVersions []string `json:"compatible_versions"`
} `json:"codebase"`
Peers struct {
Seeds []struct {
ID string `json:"id"`
Address string `json:"address"`
Provider string `json:"provider,omitempty"`
} `json:"seeds"`
PersistentPeers []struct {
ID string `json:"id"`
Address string `json:"address"`
} `json:"persistent_peers"`
} `json:"peers"`
Apis struct {
RPC []struct {
Address string `json:"address"`
Provider string `json:"provider"`
} `json:"rpc"`
Rest []struct {
Address string `json:"address"`
Provider string `json:"provider"`
} `json:"rest"`
} `json:"apis"`
}
// NewChainInfo returns a ChainInfo that is uninitialized other than the provided zap.Logger.
// Typically, the caller will unmarshal JSON content into the ChainInfo after initialization.
func NewChainInfo(log *zap.Logger) ChainInfo {
return ChainInfo{log: log}
}
func (c ChainInfo) GetAllRPCEndpoints() (out []string, err error) {
for _, endpoint := range c.Apis.RPC {
u, err := url.Parse(endpoint.Address)
if err != nil {
return nil, err
}
var port string
if u.Port() == "" {
switch u.Scheme {
case "https":
port = "443"
case "http":
port = "80"
default:
return nil, fmt.Errorf("invalid or unsupported url scheme: %v", u.Scheme)
}
} else {
port = u.Port()
}
out = append(out, fmt.Sprintf("%s://%s:%s%s", u.Scheme, u.Hostname(), port, u.Path))
}
return
}
func IsHealthyRPC(ctx context.Context, endpoint string) error {
cl, err := client.NewRPCClient(endpoint, 5*time.Second)
if err != nil {
return err
}
stat, err := cl.Status(ctx)
if err != nil {
return err
}
if stat.SyncInfo.CatchingUp {
return errors.New("still catching up")
}
return nil
}
func (c ChainInfo) GetRPCEndpoints(ctx context.Context) (out []string, err error) {
allRPCEndpoints, err := c.GetAllRPCEndpoints()
if err != nil {
return nil, err
}
var eg errgroup.Group
var endpoints []string
healthy := 0
unhealthy := 0
for _, endpoint := range allRPCEndpoints {
endpoint := endpoint
eg.Go(func() error {
err := IsHealthyRPC(ctx, endpoint)
if err != nil {
unhealthy += 1
c.log.Debug(
"Ignoring endpoint due to error",
zap.String("endpoint", endpoint),
zap.Error(err),
)
return nil
}
healthy += 1
c.log.Debug("Verified healthy endpoint", zap.String("endpoint", endpoint))
endpoints = append(endpoints, endpoint)
return nil
})
}
if err := eg.Wait(); err != nil {
return nil, err
}
c.log.Info("Endpoints queried",
zap.String("chain_name", c.ChainName),
zap.Int("healthy", healthy),
zap.Int("unhealthy", unhealthy),
)
return endpoints, nil
}
func (c ChainInfo) GetRandomRPCEndpoint(ctx context.Context) (string, error) {
rpcs, err := c.GetRPCEndpoints(ctx)
if err != nil {
return "", err
}
if len(rpcs) == 0 {
return "", fmt.Errorf("no working RPCs found")
}
randomGenerator := rand.New(rand.NewSource(time.Now().UnixNano()))
endpoint := rpcs[randomGenerator.Intn(len(rpcs))]
c.log.Info("Endpoint selected",
zap.String("chain_name", c.ChainName),
zap.String("endpoint", endpoint),
)
return endpoint, nil
}
func (c ChainInfo) GetAssetList(ctx context.Context) (AssetList, error) {
chainRegURL := fmt.Sprintf("https://raw.githubusercontent.com/cosmos/chain-registry/master/%s/assetlist.json", c.ChainName)
res, err := http.Get(chainRegURL)
if err != nil {
return AssetList{}, err
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
return AssetList{}, fmt.Errorf("chain not found on registry: response code: %d: GET failed: %s", res.StatusCode, chainRegURL)
}
if res.StatusCode != http.StatusOK {
return AssetList{}, fmt.Errorf("response code: %d: GET failed: %s", res.StatusCode, chainRegURL)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return AssetList{}, err
}
var assetList AssetList
if err := json.Unmarshal([]byte(body), &assetList); err != nil {
return AssetList{}, err
}
return assetList, nil
}
func (c ChainInfo) GetChainConfig(ctx context.Context) (*client.ChainClientConfig, error) {
debug := viper.GetBool("debug")
home := viper.GetString("home")
assetList, err := c.GetAssetList(ctx)
if err != nil {
return nil, err
}
var gasPrices string
if len(assetList.Assets) > 0 {
gasPrices = fmt.Sprintf("%.2f%s", 0.01, assetList.Assets[0].Base)
}
rpc, err := c.GetRandomRPCEndpoint(ctx)
if err != nil {
return nil, err
}
return &client.ChainClientConfig{
Key: "default",
ChainID: c.ChainID,
RPCAddr: rpc,
AccountPrefix: c.Bech32Prefix,
KeyringBackend: "test",
GasAdjustment: 1.2,
GasPrices: gasPrices,
KeyDirectory: home,
Debug: debug,
Timeout: "20s",
OutputFormat: "json",
SignModeStr: "direct",
Slip44: c.Slip44,
}, nil
}