github.com/Finschia/ostracon@v1.1.5/cmd/ostracon/commands/show_validator.go (about)

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