OSDN Git Service

little edit (#107)
[bytom/vapor.git] / cmd / bytomd / 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/vapor/config"
13         "github.com/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 [vapor] 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}).Panic("Already exists config file.")
32         }
33
34         switch config.ChainID {
35         case "vapor":
36                 cfg.EnsureRoot(config.RootDir, config.ChainID)
37         default:
38                 cfg.EnsureRoot(config.RootDir, "solonet")
39         }
40
41         //generate the federation config file
42         fedFilePath := config.FederationFile()
43         if _, err := os.Stat(fedFilePath); os.IsNotExist(err) {
44                 if err := cfg.ExportFederationFile(fedFilePath, config); err != nil {
45                         log.WithFields(log.Fields{"module": logModule, "config": fedFilePath, "error": err}).Panic("fail on export federation file")
46                 }
47         }
48
49         //generate the node private key
50         keyFilePath := path.Join(config.RootDir, config.PrivateKeyFile)
51         if _, err := os.Stat(keyFilePath); os.IsNotExist(err) {
52                 xprv, err := chainkd.NewXPrv(nil)
53                 if err != nil {
54                         log.WithFields(log.Fields{"module": logModule, "err": err}).Panic("fail on generate private key")
55                 }
56
57                 if err := ioutil.WriteFile(keyFilePath, []byte(hex.EncodeToString(xprv[:])), 0600); err != nil {
58                         log.WithFields(log.Fields{"module": logModule, "err": err}).Panic("fail on save private key")
59                 }
60
61                 log.WithFields(log.Fields{"pubkey": xprv.XPub()}).Info("success generate private")
62         }
63
64         log.WithFields(log.Fields{"module": logModule, "config": configFilePath}).Info("Initialized bytom")
65 }