github.com/line/ostracon@v1.0.10-0.20230328032236-7f20145f065d/cmd/ostracon/commands/show_validator.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/line/ostracon/node"
     7  	"github.com/line/ostracon/types"
     8  	"github.com/spf13/cobra"
     9  
    10  	cfg "github.com/line/ostracon/config"
    11  	tmjson "github.com/line/ostracon/libs/json"
    12  	tmos "github.com/line/ostracon/libs/os"
    13  	"github.com/line/ostracon/privval"
    14  )
    15  
    16  // ShowValidatorCmd adds capabilities for showing the validator info.
    17  var ShowValidatorCmd = &cobra.Command{
    18  	Use:     "show-validator",
    19  	Aliases: []string{"show_validator"},
    20  	Short:   "Show this node's validator info",
    21  	RunE: func(cmd *cobra.Command, args []string) error {
    22  		return showValidator(cmd, args, config)
    23  	},
    24  	PreRun: deprecateSnakeCase,
    25  }
    26  
    27  func showValidator(cmd *cobra.Command, args []string, config *cfg.Config) error {
    28  	var pv types.PrivValidator
    29  	if config.PrivValidatorListenAddr != "" {
    30  		chainID, err := loadChainID(config)
    31  		if err != nil {
    32  			return err
    33  		}
    34  		pv, err = node.CreateAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, chainID, logger)
    35  		if err != nil {
    36  			return err
    37  		}
    38  	} else {
    39  		keyFilePath := config.PrivValidatorKeyFile()
    40  		if !tmos.FileExists(keyFilePath) {
    41  			return fmt.Errorf("private validator file %s does not exist", keyFilePath)
    42  		}
    43  		pv = privval.LoadFilePV(keyFilePath, config.PrivValidatorStateFile())
    44  	}
    45  
    46  	pubKey, err := pv.GetPubKey()
    47  	if err != nil {
    48  		return fmt.Errorf("can't get pubkey: %w", err)
    49  	}
    50  
    51  	bz, err := tmjson.Marshal(pubKey)
    52  	if err != nil {
    53  		return fmt.Errorf("failed to marshal private validator pubkey: %w", err)
    54  	}
    55  
    56  	fmt.Println(string(bz))
    57  	return nil
    58  }
    59  
    60  func loadChainID(config *cfg.Config) (string, error) {
    61  	stateDB, err := node.DefaultDBProvider(&node.DBContext{ID: "state", Config: config})
    62  	if err != nil {
    63  		return "", err
    64  	}
    65  	defer func() {
    66  		var _ = stateDB.Close()
    67  	}()
    68  	genesisDocProvider := node.DefaultGenesisDocProviderFunc(config)
    69  	_, genDoc, err := node.LoadStateFromDBOrGenesisDocProvider(stateDB, genesisDocProvider)
    70  	if err != nil {
    71  		return "", err
    72  	}
    73  	return genDoc.ChainID, nil
    74  }