OSDN Git Service

rename (#465)
[bytom/vapor.git] / cmd / vapord / commands / init.go
1 package commands
2
3 import (
4         "encoding/hex"
5         "io/ioutil"
6         "os"
7         "path"
8
9         log "github.com/sirupsen/logrus"
10         "github.com/spf13/cobra"
11
12         cfg "github.com/bytom/vapor/config"
13         "github.com/bytom/vapor/crypto/ed25519/chainkd"
14 )
15
16 var initFilesCmd = &cobra.Command{
17         Use:   "init",
18         Short: "Initialize blockchain",
19         Run:   initFiles,
20 }
21
22 func init() {
23         initFilesCmd.Flags().String("chain_id", config.ChainID, "Select [mainnet], [testnet] or [solonet]")
24
25         RootCmd.AddCommand(initFilesCmd)
26 }
27
28 func initFiles(cmd *cobra.Command, args []string) {
29         configFilePath := path.Join(config.RootDir, "config.toml")
30         if _, err := os.Stat(configFilePath); !os.IsNotExist(err) {
31                 log.WithFields(log.Fields{"module": logModule, "config": configFilePath}).Fatal("Already exists config file.")
32         }
33
34         switch config.ChainID {
35         case "mainnet":
36                 cfg.EnsureRoot(config.RootDir, config.ChainID)
37         case "testnet":
38                 cfg.EnsureRoot(config.RootDir, config.ChainID)
39         default:
40                 cfg.EnsureRoot(config.RootDir, "solonet")
41         }
42
43         //generate the federation config file
44         fedFilePath := config.FederationFile()
45         if _, err := os.Stat(fedFilePath); os.IsNotExist(err) {
46                 if err := cfg.ExportFederationFile(fedFilePath, config); err != nil {
47                         log.WithFields(log.Fields{"module": logModule, "config": fedFilePath, "error": err}).Fatal("fail on export federation file")
48                 }
49         }
50
51         //generate the node private key
52         keyFilePath := path.Join(config.RootDir, config.PrivateKeyFile)
53         if _, err := os.Stat(keyFilePath); os.IsNotExist(err) {
54                 xprv, err := chainkd.NewXPrv(nil)
55                 if err != nil {
56                         log.WithFields(log.Fields{"module": logModule, "err": err}).Fatal("fail on generate private key")
57                 }
58
59                 if err := ioutil.WriteFile(keyFilePath, []byte(hex.EncodeToString(xprv[:])), 0600); err != nil {
60                         log.WithFields(log.Fields{"module": logModule, "err": err}).Fatal("fail on save private key")
61                 }
62
63                 log.WithFields(log.Fields{"pubkey": xprv.XPub()}).Info("success generate private")
64         }
65
66         log.WithFields(log.Fields{"module": logModule, "config": configFilePath}).Info("Initialized bytom")
67 }