github.com/vipernet-xyz/tm@v0.34.24/cmd/tendermint/commands/init.go (about)

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