OSDN Git Service

V0.1 pk interface (#58)
[bytom/vapor.git] / config / config.go
1 package config
2
3 import (
4         "io"
5         "io/ioutil"
6         "os"
7         "os/user"
8         "path/filepath"
9         "runtime"
10
11         log "github.com/sirupsen/logrus"
12
13         "github.com/vapor/crypto/ed25519"
14 )
15
16 var (
17         // CommonConfig means config object
18         CommonConfig *Config
19 )
20
21 type Config struct {
22         // Top level options use an anonymous struct
23         BaseConfig `mapstructure:",squash"`
24         // Options for services
25         P2P       *P2PConfig       `mapstructure:"p2p"`
26         Wallet    *WalletConfig    `mapstructure:"wallet"`
27         Auth      *RPCAuthConfig   `mapstructure:"auth"`
28         Web       *WebConfig       `mapstructure:"web"`
29         Websocket *WebsocketConfig `mapstructure:"ws"`
30 }
31
32 // Default configurable parameters.
33 func DefaultConfig() *Config {
34         return &Config{
35                 BaseConfig: DefaultBaseConfig(),
36                 P2P:        DefaultP2PConfig(),
37                 Wallet:     DefaultWalletConfig(),
38                 Auth:       DefaultRPCAuthConfig(),
39                 Web:        DefaultWebConfig(),
40                 Websocket:  DefaultWebsocketConfig(),
41         }
42 }
43
44 // Set the RootDir for all Config structs
45 func (cfg *Config) SetRoot(root string) *Config {
46         cfg.BaseConfig.RootDir = root
47         return cfg
48 }
49
50 // NodeKey retrieves the currently configured private key of the node, checking
51 // first any manually set key, falling back to the one found in the configured
52 // data folder. If no key can be found, a new one is generated.
53 func (cfg *Config) NodeKey() (string, error) {
54         // Use any specifically configured key.
55         if cfg.P2P.PrivateKey != "" {
56                 return cfg.P2P.PrivateKey, nil
57         }
58
59         keyFile := rootify(cfg.P2P.NodeKeyFile, cfg.BaseConfig.RootDir)
60         buf := make([]byte, ed25519.PrivateKeySize*2)
61         fd, err := os.Open(keyFile)
62         defer fd.Close()
63         if err == nil {
64                 if _, err = io.ReadFull(fd, buf); err == nil {
65                         return string(buf), nil
66                 }
67         }
68
69         log.WithField("err", err).Warning("key file access failed")
70         _, privKey, err := ed25519.GenerateKey(nil)
71         if err != nil {
72                 return "", err
73         }
74
75         if err = ioutil.WriteFile(keyFile, []byte(privKey.String()), 0600); err != nil {
76                 return "", err
77         }
78         return privKey.String(), nil
79 }
80
81 //-----------------------------------------------------------------------------
82 // BaseConfig
83 type BaseConfig struct {
84         // The root directory for all data.
85         // This should be set in viper so it can unmarshal into this struct
86         RootDir string `mapstructure:"home"`
87
88         //The alias of the node
89         NodeAlias string `mapstructure:"node_alias"`
90
91         //The ID of the network to json
92         ChainID string `mapstructure:"chain_id"`
93
94         //log level to set
95         LogLevel string `mapstructure:"log_level"`
96
97         // A custom human readable name for this node
98         Moniker string `mapstructure:"moniker"`
99
100         // TCP or UNIX socket address for the profiling server to listen on
101         ProfListenAddress string `mapstructure:"prof_laddr"`
102
103         Mining bool `mapstructure:"mining"`
104
105         // Database backend: leveldb | memdb
106         DBBackend string `mapstructure:"db_backend"`
107
108         // Database directory
109         DBPath string `mapstructure:"db_dir"`
110
111         // Keystore directory
112         KeysPath string `mapstructure:"keys_dir"`
113
114         ApiAddress string `mapstructure:"api_addr"`
115
116         VaultMode bool `mapstructure:"vault_mode"`
117
118         // log file name
119         LogFile string `mapstructure:"log_file"`
120
121         // Cipher Service Provider
122         // CipherServiceProvider string `mapstructure:"csp"`
123 }
124
125 // Default configurable base parameters.
126 func DefaultBaseConfig() BaseConfig {
127         return BaseConfig{
128                 Moniker:           "anonymous",
129                 ProfListenAddress: "",
130                 Mining:            false,
131                 DBBackend:         "leveldb",
132                 DBPath:            "data",
133                 KeysPath:          "keystore",
134                 NodeAlias:         "",
135                 // CipherServiceProvider: "ed25519",
136         }
137 }
138
139 func (b BaseConfig) DBDir() string {
140         return rootify(b.DBPath, b.RootDir)
141 }
142
143 func (b BaseConfig) KeysDir() string {
144         return rootify(b.KeysPath, b.RootDir)
145 }
146
147 // P2PConfig
148 type P2PConfig struct {
149         ListenAddress    string `mapstructure:"laddr"`
150         Seeds            string `mapstructure:"seeds"`
151         PrivateKey       string `mapstructure:"node_key"`
152         NodeKeyFile      string `mapstructure:"node_key_file"`
153         SkipUPNP         bool   `mapstructure:"skip_upnp"`
154         LANDiscover      bool   `mapstructure:"lan_discoverable"`
155         MaxNumPeers      int    `mapstructure:"max_num_peers"`
156         HandshakeTimeout int    `mapstructure:"handshake_timeout"`
157         DialTimeout      int    `mapstructure:"dial_timeout"`
158         ProxyAddress     string `mapstructure:"proxy_address"`
159         ProxyUsername    string `mapstructure:"proxy_username"`
160         ProxyPassword    string `mapstructure:"proxy_password"`
161         KeepDial         string `mapstructure:"keep_dial"`
162 }
163
164 // Default configurable p2p parameters.
165 func DefaultP2PConfig() *P2PConfig {
166         return &P2PConfig{
167                 ListenAddress:    "tcp://0.0.0.0:46656",
168                 NodeKeyFile:      "nodekey",
169                 SkipUPNP:         false,
170                 LANDiscover:      true,
171                 MaxNumPeers:      50,
172                 HandshakeTimeout: 30,
173                 DialTimeout:      3,
174                 ProxyAddress:     "",
175                 ProxyUsername:    "",
176                 ProxyPassword:    "",
177         }
178 }
179
180 //-----------------------------------------------------------------------------
181 type WalletConfig struct {
182         Disable  bool   `mapstructure:"disable"`
183         Rescan   bool   `mapstructure:"rescan"`
184         TxIndex  bool   `mapstructure:"txindex"`
185         MaxTxFee uint64 `mapstructure:"max_tx_fee"`
186 }
187
188 type RPCAuthConfig struct {
189         Disable bool `mapstructure:"disable"`
190 }
191
192 type WebConfig struct {
193         Closed bool `mapstructure:"closed"`
194 }
195
196 type WebsocketConfig struct {
197         MaxNumWebsockets     int `mapstructure:"max_num_websockets"`
198         MaxNumConcurrentReqs int `mapstructure:"max_num_concurrent_reqs"`
199 }
200
201 // Default configurable rpc's auth parameters.
202 func DefaultRPCAuthConfig() *RPCAuthConfig {
203         return &RPCAuthConfig{
204                 Disable: false,
205         }
206 }
207
208 // Default configurable web parameters.
209 func DefaultWebConfig() *WebConfig {
210         return &WebConfig{
211                 Closed: false,
212         }
213 }
214
215 // Default configurable wallet parameters.
216 func DefaultWalletConfig() *WalletConfig {
217         return &WalletConfig{
218                 Disable:  false,
219                 Rescan:   false,
220                 TxIndex:  false,
221                 MaxTxFee: uint64(1000000000),
222         }
223 }
224
225 func DefaultWebsocketConfig() *WebsocketConfig {
226         return &WebsocketConfig{
227                 MaxNumWebsockets:     25,
228                 MaxNumConcurrentReqs: 20,
229         }
230 }
231
232 //-----------------------------------------------------------------------------
233 // Utils
234
235 // helper function to make config creation independent of root dir
236 func rootify(path, root string) string {
237         if filepath.IsAbs(path) {
238                 return path
239         }
240         return filepath.Join(root, path)
241 }
242
243 // DefaultDataDir is the default data directory to use for the databases and other
244 // persistence requirements.
245 func DefaultDataDir() string {
246         // Try to place the data folder in the user's home dir
247         home := homeDir()
248         if home == "" {
249                 return "./.bytom"
250         }
251         switch runtime.GOOS {
252         case "darwin":
253                 // In order to be compatible with old data path,
254                 // copy the data from the old path to the new path
255                 oldPath := filepath.Join(home, "Library", "Bytom")
256                 newPath := filepath.Join(home, "Library", "Application Support", "Bytom")
257                 if !isFolderNotExists(oldPath) && isFolderNotExists(newPath) {
258                         if err := os.Rename(oldPath, newPath); err != nil {
259                                 log.Errorf("DefaultDataDir: %v", err)
260                                 return oldPath
261                         }
262                 }
263                 return newPath
264         case "windows":
265                 return filepath.Join(home, "AppData", "Roaming", "Bytom")
266         default:
267                 return filepath.Join(home, ".bytom")
268         }
269 }
270
271 func isFolderNotExists(path string) bool {
272         _, err := os.Stat(path)
273         return os.IsNotExist(err)
274 }
275
276 func homeDir() string {
277         if home := os.Getenv("HOME"); home != "" {
278                 return home
279         }
280         if usr, err := user.Current(); err == nil {
281                 return usr.HomeDir
282         }
283         return ""
284 }