OSDN Git Service

add edge test for CalcReorganizeNodes (#1654)
[bytom/bytom.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/bytom/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         Simd      *SimdConfig      `mapstructure:"simd"`
30         Websocket *WebsocketConfig `mapstructure:"ws"`
31 }
32
33 // Default configurable parameters.
34 func DefaultConfig() *Config {
35         return &Config{
36                 BaseConfig: DefaultBaseConfig(),
37                 P2P:        DefaultP2PConfig(),
38                 Wallet:     DefaultWalletConfig(),
39                 Auth:       DefaultRPCAuthConfig(),
40                 Web:        DefaultWebConfig(),
41                 Simd:       DefaultSimdConfig(),
42                 Websocket:  DefaultWebsocketConfig(),
43         }
44 }
45
46 // Set the RootDir for all Config structs
47 func (cfg *Config) SetRoot(root string) *Config {
48         cfg.BaseConfig.RootDir = root
49         return cfg
50 }
51
52 // NodeKey retrieves the currently configured private key of the node, checking
53 // first any manually set key, falling back to the one found in the configured
54 // data folder. If no key can be found, a new one is generated.
55 func (cfg *Config) NodeKey() (string, error) {
56         // Use any specifically configured key.
57         if cfg.P2P.PrivateKey != "" {
58                 return cfg.P2P.PrivateKey, nil
59         }
60
61         keyFile := rootify(cfg.P2P.NodeKeyFile, cfg.BaseConfig.RootDir)
62         buf := make([]byte, ed25519.PrivateKeySize*2)
63         fd, err := os.Open(keyFile)
64         defer fd.Close()
65         if err == nil {
66                 if _, err = io.ReadFull(fd, buf); err == nil {
67                         return string(buf), nil
68                 }
69         }
70
71         log.WithField("err", err).Warning("key file access failed")
72         _, privKey, err := ed25519.GenerateKey(nil)
73         if err != nil {
74                 return "", err
75         }
76
77         if err = ioutil.WriteFile(keyFile, []byte(privKey.String()), 0600); err != nil {
78                 return "", err
79         }
80         return privKey.String(), nil
81 }
82
83 //-----------------------------------------------------------------------------
84 // BaseConfig
85 type BaseConfig struct {
86         // The root directory for all data.
87         // This should be set in viper so it can unmarshal into this struct
88         RootDir string `mapstructure:"home"`
89
90         //The ID of the network to json
91         ChainID string `mapstructure:"chain_id"`
92
93         //log level to set
94         LogLevel string `mapstructure:"log_level"`
95
96         // A custom human readable name for this node
97         Moniker string `mapstructure:"moniker"`
98
99         // TCP or UNIX socket address for the profiling server to listen on
100         ProfListenAddress string `mapstructure:"prof_laddr"`
101
102         Mining bool `mapstructure:"mining"`
103
104         // Database backend: leveldb | memdb
105         DBBackend string `mapstructure:"db_backend"`
106
107         // Database directory
108         DBPath string `mapstructure:"db_dir"`
109
110         // Keystore directory
111         KeysPath string `mapstructure:"keys_dir"`
112
113         ApiAddress string `mapstructure:"api_addr"`
114
115         VaultMode bool `mapstructure:"vault_mode"`
116
117         // log file name
118         LogFile string `mapstructure:"log_file"`
119 }
120
121 // Default configurable base parameters.
122 func DefaultBaseConfig() BaseConfig {
123         return BaseConfig{
124                 Moniker:           "anonymous",
125                 ProfListenAddress: "",
126                 Mining:            false,
127                 DBBackend:         "leveldb",
128                 DBPath:            "data",
129                 KeysPath:          "keystore",
130         }
131 }
132
133 func (b BaseConfig) DBDir() string {
134         return rootify(b.DBPath, b.RootDir)
135 }
136
137 func (b BaseConfig) KeysDir() string {
138         return rootify(b.KeysPath, b.RootDir)
139 }
140
141 // P2PConfig
142 type P2PConfig struct {
143         ListenAddress    string `mapstructure:"laddr"`
144         Seeds            string `mapstructure:"seeds"`
145         PrivateKey       string `mapstructure:"node_key"`
146         NodeKeyFile      string `mapstructure:"node_key_file"`
147         SkipUPNP         bool   `mapstructure:"skip_upnp"`
148         MaxNumPeers      int    `mapstructure:"max_num_peers"`
149         HandshakeTimeout int    `mapstructure:"handshake_timeout"`
150         DialTimeout      int    `mapstructure:"dial_timeout"`
151         ProxyAddress     string `mapstructure:"proxy_address"`
152         ProxyUsername    string `mapstructure:"proxy_username"`
153         ProxyPassword    string `mapstructure:"proxy_password"`
154 }
155
156 // Default configurable p2p parameters.
157 func DefaultP2PConfig() *P2PConfig {
158         return &P2PConfig{
159                 ListenAddress:    "tcp://0.0.0.0:46656",
160                 NodeKeyFile:      "nodekey",
161                 SkipUPNP:         false,
162                 MaxNumPeers:      50,
163                 HandshakeTimeout: 30,
164                 DialTimeout:      3,
165                 ProxyAddress:     "",
166                 ProxyUsername:    "",
167                 ProxyPassword:    "",
168         }
169 }
170
171 //-----------------------------------------------------------------------------
172 type WalletConfig struct {
173         Disable  bool   `mapstructure:"disable"`
174         Rescan   bool   `mapstructure:"rescan"`
175         MaxTxFee uint64 `mapstructure:"max_tx_fee"`
176 }
177
178 type RPCAuthConfig struct {
179         Disable bool `mapstructure:"disable"`
180 }
181
182 type WebConfig struct {
183         Closed bool `mapstructure:"closed"`
184 }
185
186 type SimdConfig struct {
187         Enable bool `mapstructure:"enable"`
188 }
189
190 type WebsocketConfig struct {
191         MaxNumWebsockets     int `mapstructure:"max_num_websockets"`
192         MaxNumConcurrentReqs int `mapstructure:"max_num_concurrent_reqs"`
193 }
194
195 // Default configurable rpc's auth parameters.
196 func DefaultRPCAuthConfig() *RPCAuthConfig {
197         return &RPCAuthConfig{
198                 Disable: false,
199         }
200 }
201
202 // Default configurable web parameters.
203 func DefaultWebConfig() *WebConfig {
204         return &WebConfig{
205                 Closed: false,
206         }
207 }
208
209 // Default configurable wallet parameters.
210 func DefaultWalletConfig() *WalletConfig {
211         return &WalletConfig{
212                 Disable:  false,
213                 Rescan:   false,
214                 MaxTxFee: uint64(1000000000),
215         }
216 }
217
218 // Default configurable web parameters.
219 func DefaultSimdConfig() *SimdConfig {
220         return &SimdConfig{
221                 Enable: false,
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 }