OSDN Git Service

fix fed membership order (#328)
[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:56656",
174                 SkipUPNP:         false,
175                 LANDiscover:      true,
176                 MaxNumPeers:      20,
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("580daf48fa8962100047cb1391da890bb7f2c849fdbc9b368cb4394a4c7cbb0977e2e7ebbf055dc0ef90af6a0d2af01ce7ec56b735d016aab597815ec48552e5"),
247                         xpub("f3f6bcf61b65fa9d1566455a5688ca8b395efdc22e654963134b5e5cb0a45d8be522d21abc384a73177a7b9d64eba915fcfe2862d86a508a3c46dc410bdd72ad"),
248                         xpub("53559612f2b7bcada18948b7de39d63947a0e2bd7336d07db1350c54ba5743996b84bf9d18ff7a2457e1a5c70ce5013e4a3b62666ddb03294c53051d5f5c70c0"),
249                         xpub("7c88cc58adfc71818b08308d43c29de22460b0ea6895449cbec6e458d7dc09e0aea243fa5075ee6621da0d805bd047f6bb207329c5bd2ca3253b172fb323b512"),
250                 },
251                 Quorum: 2,
252         }
253 }
254
255 func xpub(str string) (xpub chainkd.XPub) {
256         if err := xpub.UnmarshalText([]byte(str)); err != nil {
257                 log.Panicf("Fail converts a string to xpub")
258         }
259         return xpub
260 }
261
262 //-----------------------------------------------------------------------------
263 // Utils
264
265 // helper function to make config creation independent of root dir
266 func rootify(path, root string) string {
267         if filepath.IsAbs(path) {
268                 return path
269         }
270         return filepath.Join(root, path)
271 }
272
273 // DefaultDataDir is the default data directory to use for the databases and other
274 // persistence requirements.
275 func DefaultDataDir() string {
276         // Try to place the data folder in the user's home dir
277         home := homeDir()
278         if home == "" {
279                 return "./.vapor"
280         }
281         switch runtime.GOOS {
282         case "darwin":
283                 return filepath.Join(home, "Library", "Application Support", "Vapor")
284         case "windows":
285                 return filepath.Join(home, "AppData", "Roaming", "Vapor")
286         default:
287                 return filepath.Join(home, ".vapor")
288         }
289 }
290
291 func isFolderNotExists(path string) bool {
292         _, err := os.Stat(path)
293         return os.IsNotExist(err)
294 }
295
296 func homeDir() string {
297         if home := os.Getenv("HOME"); home != "" {
298                 return home
299         }
300         if usr, err := user.Current(); err == nil {
301                 return usr.HomeDir
302         }
303         return ""
304 }