OSDN Git Service

8080371d3bfce6c5b322bc0aca04f6fbd136f77b
[bytom/vapor.git] / config / config.go
1 package config
2
3 import (
4         "encoding/hex"
5         "io"
6         "os"
7         "os/user"
8         "path/filepath"
9         "runtime"
10
11         log "github.com/sirupsen/logrus"
12
13         "github.com/vapor/crypto/ed25519/chainkd"
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         Federation *FederationConfig `mapstructure:"federation"`
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                 Websocket:  DefaultWebsocketConfig(),
42                 Federation: DefaultFederationConfig(),
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) PrivateKey() *chainkd.XPrv {
56         if cfg.XPrv != nil {
57                 return cfg.XPrv
58         }
59
60         filePath := rootify(cfg.PrivateKeyFile, cfg.BaseConfig.RootDir)
61         fildReader, err := os.Open(filePath)
62         if err != nil {
63                 log.WithField("err", err).Panic("fail on open private key file")
64         }
65
66         defer fildReader.Close()
67         buf := make([]byte, 128)
68         if _, err = io.ReadFull(fildReader, buf); err != nil {
69                 log.WithField("err", err).Panic("fail on read private key file")
70         }
71
72         var xprv chainkd.XPrv
73         if _, err := hex.Decode(xprv[:], buf); err != nil {
74                 log.WithField("err", err).Panic("fail on decode private key")
75         }
76
77         cfg.XPrv = &xprv
78         xpub := cfg.XPrv.XPub()
79         cfg.XPub = &xpub
80         return cfg.XPrv
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         PrivateKeyFile string `mapstructure:"private_key_file"`
121         XPrv           *chainkd.XPrv
122         XPub           *chainkd.XPub
123
124         // Federation file name
125         FederationFileName string `mapstructure:"federation_file"`
126 }
127
128 // Default configurable base parameters.
129 func DefaultBaseConfig() BaseConfig {
130         return BaseConfig{
131                 Moniker:            "anonymous",
132                 ProfListenAddress:  "",
133                 Mining:             false,
134                 DBBackend:          "leveldb",
135                 DBPath:             "data",
136                 KeysPath:           "keystore",
137                 PrivateKeyFile:     "node_key.txt",
138                 FederationFileName: "federation.json",
139         }
140 }
141
142 func (b BaseConfig) DBDir() string {
143         return rootify(b.DBPath, b.RootDir)
144 }
145
146 func (b BaseConfig) KeysDir() string {
147         return rootify(b.KeysPath, b.RootDir)
148 }
149
150 func (b BaseConfig) FederationFile() string {
151         return rootify(b.FederationFileName, b.RootDir)
152 }
153
154 // P2PConfig
155 type P2PConfig struct {
156         ListenAddress    string `mapstructure:"laddr"`
157         Seeds            string `mapstructure:"seeds"`
158         SkipUPNP         bool   `mapstructure:"skip_upnp"`
159         LANDiscover      bool   `mapstructure:"lan_discoverable"`
160         MaxNumPeers      int    `mapstructure:"max_num_peers"`
161         HandshakeTimeout int    `mapstructure:"handshake_timeout"`
162         DialTimeout      int    `mapstructure:"dial_timeout"`
163         ProxyAddress     string `mapstructure:"proxy_address"`
164         ProxyUsername    string `mapstructure:"proxy_username"`
165         ProxyPassword    string `mapstructure:"proxy_password"`
166         KeepDial         string `mapstructure:"keep_dial"`
167         Compression      string `mapstructure:"compression_backend"`
168 }
169
170 // Default configurable p2p parameters.
171 func DefaultP2PConfig() *P2PConfig {
172         return &P2PConfig{
173                 ListenAddress:    "tcp://0.0.0.0:46656",
174                 SkipUPNP:         false,
175                 LANDiscover:      true,
176                 MaxNumPeers:      50,
177                 HandshakeTimeout: 30,
178                 DialTimeout:      3,
179                 ProxyAddress:     "",
180                 ProxyUsername:    "",
181                 ProxyPassword:    "",
182                 Compression:      "snappy",
183         }
184 }
185
186 //-----------------------------------------------------------------------------
187 type WalletConfig struct {
188         Disable  bool   `mapstructure:"disable"`
189         Rescan   bool   `mapstructure:"rescan"`
190         TxIndex  bool   `mapstructure:"txindex"`
191         MaxTxFee uint64 `mapstructure:"max_tx_fee"`
192 }
193
194 type RPCAuthConfig struct {
195         Disable bool `mapstructure:"disable"`
196 }
197
198 type WebConfig struct {
199         Closed bool `mapstructure:"closed"`
200 }
201
202 type WebsocketConfig struct {
203         MaxNumWebsockets     int `mapstructure:"max_num_websockets"`
204         MaxNumConcurrentReqs int `mapstructure:"max_num_concurrent_reqs"`
205 }
206
207 type FederationConfig struct {
208         Xpubs  []chainkd.XPub `json:"xpubs"`
209         Quorum int            `json:"quorum"`
210 }
211
212 // Default configurable rpc's auth parameters.
213 func DefaultRPCAuthConfig() *RPCAuthConfig {
214         return &RPCAuthConfig{
215                 Disable: false,
216         }
217 }
218
219 // Default configurable web parameters.
220 func DefaultWebConfig() *WebConfig {
221         return &WebConfig{
222                 Closed: false,
223         }
224 }
225
226 // Default configurable wallet parameters.
227 func DefaultWalletConfig() *WalletConfig {
228         return &WalletConfig{
229                 Disable:  false,
230                 Rescan:   false,
231                 TxIndex:  false,
232                 MaxTxFee: uint64(1000000000),
233         }
234 }
235
236 func DefaultWebsocketConfig() *WebsocketConfig {
237         return &WebsocketConfig{
238                 MaxNumWebsockets:     25,
239                 MaxNumConcurrentReqs: 20,
240         }
241 }
242
243 func DefaultFederationConfig() *FederationConfig {
244         return &FederationConfig{
245                 Xpubs: []chainkd.XPub{
246                         xpub("001784369b39078a898cb596a0f862af8fdfc1b83e1d799b7ced87f63c79186c2b3ca399942dcfbd1f638aa13b994a64bf8886fcbc206e9f90eb4df30c6f4ca5"),
247                         xpub("a8018a1ba4d85fc7118bbd065612da78b2c503e61a1a093d9c659567c5d3a591b3752569fbcafa951b2304b8f576f3f220e03b957ca819840e7c29e4b7fb2c4d"),
248                 },
249                 Quorum: 1,
250         }
251 }
252
253 func xpub(str string) (xpub chainkd.XPub) {
254         if err := xpub.UnmarshalText([]byte(str)); err != nil {
255                 log.Panicf("Fail converts a string to xpub")
256         }
257         return xpub
258 }
259
260 //-----------------------------------------------------------------------------
261 // Utils
262
263 // helper function to make config creation independent of root dir
264 func rootify(path, root string) string {
265         if filepath.IsAbs(path) {
266                 return path
267         }
268         return filepath.Join(root, path)
269 }
270
271 // DefaultDataDir is the default data directory to use for the databases and other
272 // persistence requirements.
273 func DefaultDataDir() string {
274         // Try to place the data folder in the user's home dir
275         home := homeDir()
276         if home == "" {
277                 return "./.vapor"
278         }
279         switch runtime.GOOS {
280         case "darwin":
281                 return filepath.Join(home, "Library", "Application Support", "Vapor")
282         case "windows":
283                 return filepath.Join(home, "AppData", "Roaming", "Vapor")
284         default:
285                 return filepath.Join(home, ".vapor")
286         }
287 }
288
289 func isFolderNotExists(path string) bool {
290         _, err := os.Stat(path)
291         return os.IsNotExist(err)
292 }
293
294 func homeDir() string {
295         if home := os.Getenv("HOME"); home != "" {
296                 return home
297         }
298         if usr, err := user.Current(); err == nil {
299                 return usr.HomeDir
300         }
301         return ""
302 }