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

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/spf13/cobra"
     7  
     8  	cfg "github.com/line/ostracon/config"
     9  	tmos "github.com/line/ostracon/libs/os"
    10  	tmrand "github.com/line/ostracon/libs/rand"
    11  	"github.com/line/ostracon/p2p"
    12  	"github.com/line/ostracon/privval"
    13  	"github.com/line/ostracon/types"
    14  	tmtime "github.com/line/ostracon/types/time"
    15  )
    16  
    17  func NewInitCmd() *cobra.Command {
    18  	cmd := &cobra.Command{
    19  		Use:   "init",
    20  		Short: "Initialize Ostracon",
    21  		RunE:  initFiles,
    22  	}
    23  
    24  	return cmd
    25  }
    26  
    27  func initFiles(cmd *cobra.Command, args []string) error {
    28  	return initFilesWithConfig(config)
    29  }
    30  
    31  func initFilesWithConfig(config *cfg.Config) error {
    32  	// private validator
    33  	privValKeyFile := config.PrivValidatorKeyFile()
    34  	privValStateFile := config.PrivValidatorStateFile()
    35  	var pv *privval.FilePV
    36  	if tmos.FileExists(privValKeyFile) {
    37  		pv = privval.LoadFilePV(privValKeyFile, privValStateFile)
    38  		logger.Info("Found private validator", "keyFile", privValKeyFile,
    39  			"stateFile", privValStateFile)
    40  	} else {
    41  		pv = privval.GenFilePV(privValKeyFile, privValStateFile)
    42  		pv.Save()
    43  		logger.Info("Generated private validator", "keyFile", privValKeyFile,
    44  			"stateFile", privValStateFile)
    45  	}
    46  
    47  	nodeKeyFile := config.NodeKeyFile()
    48  	if tmos.FileExists(nodeKeyFile) {
    49  		logger.Info("Found node key", "path", nodeKeyFile)
    50  	} else {
    51  		if _, err := p2p.LoadOrGenNodeKey(nodeKeyFile); err != nil {
    52  			return err
    53  		}
    54  		logger.Info("Generated node key", "path", nodeKeyFile)
    55  	}
    56  
    57  	// genesis file
    58  	genFile := config.GenesisFile()
    59  	if tmos.FileExists(genFile) {
    60  		logger.Info("Found genesis file", "path", genFile)
    61  	} else {
    62  		genDoc := types.GenesisDoc{
    63  			ChainID:         fmt.Sprintf("test-chain-%v", tmrand.Str(6)),
    64  			GenesisTime:     tmtime.Now(),
    65  			ConsensusParams: types.DefaultConsensusParams(),
    66  		}
    67  		pubKey, err := pv.GetPubKey()
    68  		if err != nil {
    69  			return fmt.Errorf("can't get pubkey: %w", err)
    70  		}
    71  		genDoc.Validators = []types.GenesisValidator{{
    72  			Address: pubKey.Address(),
    73  			PubKey:  pubKey,
    74  			Power:   10,
    75  		}}
    76  
    77  		if err := genDoc.SaveAs(genFile); err != nil {
    78  			return err
    79  		}
    80  		logger.Info("Generated genesis file", "path", genFile)
    81  	}
    82  
    83  	return nil
    84  }