/
cli.go
320 lines (292 loc) 路 8.5 KB
/
cli.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
package lib
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"net"
nhttp "net/http"
"os"
"path"
"strings"
"github.com/BurntSushi/toml"
"github.com/google/uuid"
bds "github.com/ipfs/go-ds-badger2"
pubsub "github.com/libp2p/go-libp2p-pubsub"
ma "github.com/multiformats/go-multiaddr"
"github.com/urfave/cli/v2"
"github.com/drand/drand/chain"
"github.com/drand/drand/client"
"github.com/drand/drand/client/grpc"
"github.com/drand/drand/client/http"
commonutils "github.com/drand/drand/common"
"github.com/drand/drand/key"
"github.com/drand/drand/log"
"github.com/drand/drand/lp2p"
gclient "github.com/drand/drand/lp2p/client"
)
var (
// URLFlag is the CLI flag for root URL(s) for fetching randomness.
URLFlag = &cli.StringSliceFlag{
Name: "url",
Usage: "root URL(s) for fetching randomness",
Aliases: []string{"http-failover"}, // DEPRECATED
}
// GRPCConnectFlag is the CLI flag for host:port to dial a gRPC randomness
// provider.
GRPCConnectFlag = &cli.StringFlag{
Name: "grpc-connect",
Usage: "host:port to dial a gRPC randomness provider",
Aliases: []string{"connect"}, // DEPRECATED
}
// CertFlag is the CLI flag for the path to a file containing gRPC transport
// credentials of peer.
CertFlag = &cli.StringFlag{
Name: "cert",
Usage: "Path to a file containing gRPC transport credentials of peer",
}
// HashFlag is the CLI flag for the hash (in hex) of the targeted chain.
HashFlag = &cli.StringFlag{
Name: "hash",
Usage: "The hash (in hex) of the chain to follow",
Aliases: []string{"chain-hash"},
}
// HashListFlag is the CLI flag for the hashes list (in hex) for the relay to follow.
HashListFlag = &cli.StringSliceFlag{
Name: "hash-list",
Usage: "Specify one hash in the list (in hex) of hashes the relay should follow",
}
// GroupConfFlag is the CLI flag for specifying the path to the drand group configuration (TOML encoded) or chain info (JSON encoded).
GroupConfFlag = &cli.PathFlag{
Name: "group-conf",
Usage: "Path to a drand group configuration (TOML encoded) or chain info (JSON encoded)," +
" can be used instead of `-hash` flag to verify the chain.",
}
// InsecureFlag is the CLI flag to allow autodetection of the chain
// information.
InsecureFlag = &cli.BoolFlag{
Name: "insecure",
Usage: "Allow autodetection of the chain information",
}
// RelayFlag is the CLI flag for relay peer multiaddr(s) to connect with.
RelayFlag = &cli.StringSliceFlag{
Name: "relay",
Usage: "relay peer multiaddr(s) to connect with",
}
// PortFlag is the CLI flag for local address for client to bind to, when
// connecting to relays. (specified as a numeric port, or a host:port)
PortFlag = &cli.StringFlag{
Name: "port",
Usage: "Local (host:)port for constructed libp2p host to listen on",
}
// JSONFlag is the value of the CLI flag `json` enabling JSON output of the loggers
JSONFlag = &cli.BoolFlag{
Name: "json",
Usage: "Set the output as json format",
}
)
// ClientFlags is a list of common flags for client creation
var ClientFlags = []cli.Flag{
URLFlag,
GRPCConnectFlag,
CertFlag,
HashFlag,
GroupConfFlag,
InsecureFlag,
RelayFlag,
PortFlag,
JSONFlag,
}
// Create builds a client, and can be invoked from a cli action supplied
// with ClientFlags
func Create(c *cli.Context, withInstrumentation bool, opts ...client.Option) (client.Client, error) {
clients := make([]client.Client, 0)
var info *chain.Info
var err error
if c.IsSet(GroupConfFlag.Name) {
info, err = chainInfoFromGroupTOML(c.Path(GroupConfFlag.Name))
if err != nil {
info, _ = chainInfoFromChainInfoJSON(c.Path(GroupConfFlag.Name))
if info == nil {
return nil, fmt.Errorf("failed to decode group configuration: %w", err)
}
}
opts = append(opts, client.WithChainInfo(info))
}
gc, err := buildGrpcClient(c, &info)
if err != nil {
return nil, err
}
clients = append(clients, gc...)
var hash []byte
if c.IsSet(HashFlag.Name) && c.String(HashFlag.Name) != "" {
hash, err = hex.DecodeString(c.String(HashFlag.Name))
if err != nil {
return nil, err
}
if info != nil && !bytes.Equal(hash, info.Hash()) {
return nil, fmt.Errorf(
"%w %v != %v", commonutils.ErrInvalidChainHash,
c.String(HashFlag.Name),
hex.EncodeToString(info.Hash()),
)
}
opts = append(opts, client.WithChainHash(hash))
}
if c.Bool(InsecureFlag.Name) {
opts = append(opts, client.Insecurely())
}
clients = append(clients, buildHTTPClients(c, &info, hash, withInstrumentation)...)
gopt, err := buildGossipClient(c)
if err != nil {
return nil, err
}
opts = append(opts, gopt...)
return client.Wrap(clients, opts...)
}
func buildGrpcClient(c *cli.Context, info **chain.Info) ([]client.Client, error) {
if c.IsSet(GRPCConnectFlag.Name) {
hash := make([]byte, 0)
if c.IsSet(HashFlag.Name) {
var err error
hash, err = hex.DecodeString(c.String(HashFlag.Name))
if err != nil {
return nil, err
}
}
if *info != nil && len(hash) == 0 {
hash = (*info).Hash()
}
gc, err := grpc.New(c.String(GRPCConnectFlag.Name), c.String(CertFlag.Name), c.Bool(InsecureFlag.Name), hash)
if err != nil {
return nil, err
}
if *info == nil {
*info, err = gc.Info(context.Background())
if err != nil {
return nil, err
}
}
return []client.Client{gc}, nil
}
return []client.Client{}, nil
}
func buildHTTPClients(c *cli.Context, info **chain.Info, hash []byte, withInstrumentation bool) []client.Client {
clients := make([]client.Client, 0)
var err error
skipped := []string{}
var hc client.Client
for _, url := range c.StringSlice(URLFlag.Name) {
if *info != nil {
hc, err = http.NewWithInfo(url, *info, nhttp.DefaultTransport)
if err != nil {
log.DefaultLogger().Warnw("", "client", "failed to load URL", "url", url, "err", err)
continue
}
} else {
hc, err = http.New(url, hash, nhttp.DefaultTransport)
if err != nil {
log.DefaultLogger().Warnw("", "client", "failed to load URL", "url", url, "err", err)
skipped = append(skipped, url)
continue
}
*info, err = hc.Info(context.Background())
if err != nil {
log.DefaultLogger().Warnw("", "client", "failed to load Info from URL", "url", url, "err", err)
continue
}
}
clients = append(clients, hc)
}
if *info != nil {
for _, url := range skipped {
hc, err = http.NewWithInfo(url, *info, nhttp.DefaultTransport)
if err != nil {
log.DefaultLogger().Warnw("", "client", "failed to load URL", "url", url, "err", err)
continue
}
clients = append(clients, hc)
}
}
if withInstrumentation {
http.MeasureHeartbeats(c.Context, clients)
}
return clients
}
func buildGossipClient(c *cli.Context) ([]client.Option, error) {
if c.IsSet(RelayFlag.Name) {
addrs := c.StringSlice(RelayFlag.Name)
if len(addrs) > 0 {
relayPeers, err := lp2p.ParseMultiaddrSlice(addrs)
if err != nil {
return nil, err
}
listen := ""
if c.IsSet(PortFlag.Name) {
listen = c.String(PortFlag.Name)
}
ps, err := buildClientHost(listen, relayPeers)
if err != nil {
return nil, err
}
return []client.Option{gclient.WithPubsub(ps)}, nil
}
}
return []client.Option{}, nil
}
func buildClientHost(clientListenAddr string, relayMultiaddr []ma.Multiaddr) (*pubsub.PubSub, error) {
clientID := uuid.New().String()
ds, err := bds.NewDatastore(path.Join(os.TempDir(), "drand-"+clientID+"-datastore"), nil)
if err != nil {
return nil, err
}
priv, err := lp2p.LoadOrCreatePrivKey(path.Join(os.TempDir(), "drand-"+clientID+"-id"), log.DefaultLogger())
if err != nil {
return nil, err
}
listen := ""
if clientListenAddr != "" {
bindHost := "0.0.0.0"
if strings.Contains(clientListenAddr, ":") {
host, port, err := net.SplitHostPort(clientListenAddr)
if err != nil {
return nil, err
}
bindHost = host
clientListenAddr = port
}
listen = fmt.Sprintf("/ip4/%s/tcp/%s", bindHost, clientListenAddr)
}
_, ps, err := lp2p.ConstructHost(
ds,
priv,
listen,
relayMultiaddr,
log.DefaultLogger(),
)
if err != nil {
return nil, err
}
return ps, nil
}
// chainInfoFromGroupTOML reads a drand group TOML file and returns the chain info.
func chainInfoFromGroupTOML(filePath string) (*chain.Info, error) {
gt := &key.GroupTOML{}
_, err := toml.DecodeFile(filePath, gt)
if err != nil {
return nil, err
}
g := &key.Group{}
err = g.FromTOML(gt)
if err != nil {
return nil, err
}
return chain.NewChainInfo(g), nil
}
func chainInfoFromChainInfoJSON(filePath string) (*chain.Info, error) {
b, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
return chain.InfoFromJSON(bytes.NewBuffer(b))
}