-
Notifications
You must be signed in to change notification settings - Fork 901
/
rpc.go
97 lines (80 loc) · 1.98 KB
/
rpc.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
package cmd
import (
"context"
"errors"
"fmt"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
rpc "github.com/celestiaorg/celestia-node/api/rpc/client"
"github.com/celestiaorg/celestia-node/api/rpc/perms"
nodemod "github.com/celestiaorg/celestia-node/nodebuilder/node"
)
const (
// defaultRPCAddress is a default address to dial to
defaultRPCAddress = "http://localhost:26658"
)
var (
requestURL string
authTokenFlag string
)
func RPCFlags() *flag.FlagSet {
fset := &flag.FlagSet{}
fset.StringVar(
&requestURL,
"url",
defaultRPCAddress,
"Request URL",
)
fset.StringVar(
&authTokenFlag,
"token",
"",
"Authorization token",
)
storeFlag := NodeFlags().Lookup(nodeStoreFlag)
fset.AddFlag(storeFlag)
return fset
}
func InitClient(cmd *cobra.Command, _ []string) error {
if authTokenFlag == "" {
if !cmd.Flag(nodeStoreFlag).Changed {
return errors.New("cant get the access to the auth token: token/node-store flag was not specified")
}
storePath := cmd.Flag(nodeStoreFlag).Value.String()
token, err := getToken(storePath)
if err != nil {
return fmt.Errorf("cant get the access to the auth token: %w", err)
}
authTokenFlag = token
}
client, err := rpc.NewClient(cmd.Context(), requestURL, authTokenFlag)
if err != nil {
return err
}
ctx := context.WithValue(cmd.Context(), rpcClientKey{}, client)
cmd.SetContext(ctx)
return nil
}
func getToken(path string) (string, error) {
if path == "" {
return "", errors.New("root directory was not specified")
}
ks, err := newKeystore(path)
if err != nil {
return "", err
}
key, err := ks.Get(nodemod.SecretName)
if err != nil {
fmt.Printf("error getting the JWT secret: %v", err)
return "", err
}
return buildJWTToken(key.Body, perms.AllPerms)
}
type rpcClientKey struct{}
func ParseClientFromCtx(ctx context.Context) (*rpc.Client, error) {
client, ok := ctx.Value(rpcClientKey{}).(*rpc.Client)
if !ok {
return nil, errors.New("rpc client was not set")
}
return client, nil
}