github.com/sunriselayer/sunrise-da@v0.13.1-sr3/cmd/rpc.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  
     8  	"github.com/spf13/cobra"
     9  	flag "github.com/spf13/pflag"
    10  
    11  	rpc "github.com/sunriselayer/sunrise-da/api/rpc/client"
    12  	"github.com/sunriselayer/sunrise-da/api/rpc/perms"
    13  	nodemod "github.com/sunriselayer/sunrise-da/nodebuilder/node"
    14  )
    15  
    16  const (
    17  	// defaultRPCAddress is a default address to dial to
    18  	defaultRPCAddress = "http://localhost:26658"
    19  )
    20  
    21  var (
    22  	requestURL    string
    23  	authTokenFlag string
    24  )
    25  
    26  func RPCFlags() *flag.FlagSet {
    27  	fset := &flag.FlagSet{}
    28  
    29  	fset.StringVar(
    30  		&requestURL,
    31  		"url",
    32  		defaultRPCAddress,
    33  		"Request URL",
    34  	)
    35  
    36  	fset.StringVar(
    37  		&authTokenFlag,
    38  		"token",
    39  		"",
    40  		"Authorization token",
    41  	)
    42  
    43  	storeFlag := NodeFlags().Lookup(nodeStoreFlag)
    44  	fset.AddFlag(storeFlag)
    45  	return fset
    46  }
    47  
    48  func InitClient(cmd *cobra.Command, _ []string) error {
    49  	if authTokenFlag == "" {
    50  		storePath := ""
    51  		if !cmd.Flag(nodeStoreFlag).Changed {
    52  			return errors.New("cant get the access to the auth token: token/node-store flag was not specified")
    53  		}
    54  		storePath = cmd.Flag(nodeStoreFlag).Value.String()
    55  		token, err := getToken(storePath)
    56  		if err != nil {
    57  			return fmt.Errorf("cant get the access to the auth token: %v", err)
    58  		}
    59  		authTokenFlag = token
    60  	}
    61  
    62  	client, err := rpc.NewClient(cmd.Context(), requestURL, authTokenFlag)
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	ctx := context.WithValue(cmd.Context(), rpcClientKey{}, client)
    68  	cmd.SetContext(ctx)
    69  	return nil
    70  }
    71  
    72  func getToken(path string) (string, error) {
    73  	if path == "" {
    74  		return "", errors.New("root directory was not specified")
    75  	}
    76  
    77  	ks, err := newKeystore(path)
    78  	if err != nil {
    79  		return "", err
    80  	}
    81  
    82  	key, err := ks.Get(nodemod.SecretName)
    83  	if err != nil {
    84  		fmt.Printf("error getting the JWT secret: %v", err)
    85  		return "", err
    86  	}
    87  	return buildJWTToken(key.Body, perms.AllPerms)
    88  }
    89  
    90  type rpcClientKey struct{}
    91  
    92  func ParseClientFromCtx(ctx context.Context) (*rpc.Client, error) {
    93  	client, ok := ctx.Value(rpcClientKey{}).(*rpc.Client)
    94  	if !ok {
    95  		return nil, errors.New("rpc client was not set")
    96  	}
    97  	return client, nil
    98  }