github.com/fiagdao/tendermint@v0.32.11-0.20220824195748-2087fcc480c1/cmd/tendermint/commands/init.go (about)

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