-
Notifications
You must be signed in to change notification settings - Fork 249
/
config.go
707 lines (569 loc) · 19.6 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
package params
import (
"bytes"
"crypto/ecdsa"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/discv5"
"github.com/status-im/status-go/static"
)
// errors
var (
ErrMissingDataDir = errors.New("missing required 'DataDir' parameter")
ErrMissingNetworkID = errors.New("missing required 'NetworkID' parameter")
ErrEmptyPasswordFile = errors.New("password file cannot be empty")
ErrNoPasswordFileValueSet = errors.New("password file path not set")
ErrEmptyAuthorizationKeyFile = errors.New("authorization key file cannot be empty")
ErrAuthorizationKeyFileNotSet = errors.New("authorization key file is not set")
)
// ----------
// LightEthConfig
// ----------
// LightEthConfig holds LES-related configuration
// Status nodes are always lightweight clients (due to mobile platform constraints)
type LightEthConfig struct {
// Enabled flag specifies whether protocol is enabled
Enabled bool
// Genesis is JSON to seed the chain database with
Genesis string
// DatabaseCache is memory (in MBs) allocated to internal caching (min 16MB / database forced)
DatabaseCache int
}
// ----------
// FirebaseConfig
// ----------
// FirebaseConfig holds FCM-related configuration
type FirebaseConfig struct {
// AuthorizationKeyFile file path that contains FCM authorization key
AuthorizationKeyFile string
// NotificationTriggerURL URL used to send push notification requests to
NotificationTriggerURL string
}
// ReadAuthorizationKeyFile reads and loads FCM authorization key
func (c *FirebaseConfig) ReadAuthorizationKeyFile() ([]byte, error) {
if len(c.AuthorizationKeyFile) == 0 {
return nil, ErrAuthorizationKeyFileNotSet
}
key, err := ioutil.ReadFile(c.AuthorizationKeyFile)
if err != nil {
return nil, err
}
key = bytes.TrimRight(key, "\n")
if len(key) == 0 {
return nil, ErrEmptyAuthorizationKeyFile
}
return key, nil
}
// ----------
// WhisperConfig
// ----------
// WhisperConfig holds SHH-related configuration
type WhisperConfig struct {
// Enabled flag specifies whether protocol is enabled
Enabled bool
// LightClient should be true if the node should start with an empty bloom filter and not forward messages from other nodes
LightClient bool
// EnableMailServer is mode when node is capable of delivering expired messages on demand
EnableMailServer bool
// DataDir is the file system folder Whisper should use for any data storage needs.
// For instance, MailServer will use this directory to store its data.
DataDir string
// MinimumPoW minimum PoW for Whisper messages
MinimumPoW float64
// MailServerPasswordFile contains a password for symmetric encryption with MailServer.
MailServerPasswordFile string
// MailServerPassword for symmetric encryption with MailServer.
// (if no account file selected, then this password is used for symmetric encryption).
MailServerPassword string
// MailServerAsymKeyFile is a file with an asymmetric key to decrypt messages sent to MailServer.
MailServerAsymKeyFile string
// MailServerAsymKey is an asymmetric key to decrypt messages sent to MailServer.
MailServerAsymKey *ecdsa.PrivateKey
// RateLimit minimum time between queries to mail server per peer
MailServerRateLimit int
// MailServerCleanupPeriod time in seconds to wait to run mail server cleanup
MailServerCleanupPeriod int
// TTL time to live for messages, in seconds
TTL int
// FirebaseConfig extra configuration for Firebase Cloud Messaging
FirebaseConfig *FirebaseConfig `json:"FirebaseConfig,"`
// EnableNTPSync enables NTP synchronizations
EnableNTPSync bool
}
// ReadMailServerPasswordFile reads and returns content of the password file
func (c *WhisperConfig) ReadMailServerPasswordFile() error {
if len(c.MailServerPasswordFile) == 0 {
return ErrNoPasswordFileValueSet
}
password, err := ioutil.ReadFile(c.MailServerPasswordFile)
if err != nil {
return err
}
password = bytes.TrimRight(password, "\n")
if len(password) == 0 {
return ErrEmptyPasswordFile
}
c.MailServerPassword = string(password)
return nil
}
// ReadMailServerAsymKeyFile reads and returns a private key from a given file.
func (c *WhisperConfig) ReadMailServerAsymKeyFile() (err error) {
c.MailServerAsymKey, err = crypto.LoadECDSA(c.MailServerAsymKeyFile)
return
}
// String dumps config object as nicely indented JSON
func (c *WhisperConfig) String() string {
data, _ := json.MarshalIndent(c, "", " ") // nolint: gas
return string(data)
}
// ----------
// SwarmConfig
// ----------
// SwarmConfig holds Swarm-related configuration
type SwarmConfig struct {
// Enabled flag specifies whether protocol is enabled
Enabled bool
}
// String dumps config object as nicely indented JSON
func (c *SwarmConfig) String() string {
data, _ := json.MarshalIndent(c, "", " ") // nolint: gas
return string(data)
}
// ----------
// ClusterConfig
// ----------
// ClusterConfig holds configuration for supporting cluster peers, which is a temporary
// means for mobile devices to get connected to Ethereum network (UDP-based discovery
// may not be available, so we need means to discover the network manually).
type ClusterConfig struct {
// Enabled flag specifies whether feature is enabled
Enabled bool
// Fleet is a type of selected fleet.
Fleet string
// StaticNodes lists the static nodes taken from compiled or passed cluster.json
StaticNodes []string
// BootNodes list of cluster peer nodes for a given network (Mainnet, Ropsten, Rinkeby, Homestead),
// for a given mode (production vs development)
BootNodes []string
// TrustedMailServers is a list of verified Mail Servers.
TrustedMailServers []string
// RendezvousNodes is a rendezvous discovery server.
RendezvousNodes []string
}
// String dumps config object as nicely indented JSON
func (c *ClusterConfig) String() string {
data, _ := json.MarshalIndent(c, "", " ") // nolint: gas
return string(data)
}
// Limits represent min and max amount of peers
type Limits struct {
Min, Max int
}
// NewLimits creates new Limits config with given min and max values.
func NewLimits(min, max int) Limits {
return Limits{
Min: min,
Max: max,
}
}
// ----------
// UpstreamRPCConfig
// ----------
// UpstreamRPCConfig stores configuration for upstream rpc connection.
type UpstreamRPCConfig struct {
// Enabled flag specifies whether feature is enabled
Enabled bool
// URL sets the rpc upstream host address for communication with
// a non-local infura endpoint.
URL string
}
// ----------
// NodeConfig
// ----------
// NodeConfig stores configuration options for a node
type NodeConfig struct {
// NetworkID sets network to use for selecting peers to connect to
NetworkID uint64 `json:"NetworkId" validate:"required"`
// DataDir is the file system folder the node should use for any data storage needs.
DataDir string `validate:"required"`
// KeyStoreDir is the file system folder that contains private keys.
// If KeyStoreDir is empty, the default location is the "keystore" subdirectory of DataDir.
KeyStoreDir string
// NodeKeyFile is a filename with node ID (private key)
// This file should contain a valid secp256k1 private key that will be used for both
// remote peer identification as well as network traffic encryption.
NodeKeyFile string
// NoDiscovery set to true will disable discovery protocol.
NoDiscovery bool
// Rendezvous enables discovery protocol.
Rendezvous bool
// ListenAddr is an IP address and port of this node (e.g. 127.0.0.1:30303).
ListenAddr string
// Name sets the instance name of the node. It must not contain the / character.
Name string `validate:"excludes=/"`
// Version exposes program's version. It is used in the devp2p node identifier.
Version string
// APIModules is a comma-separated list of API modules exposed via *any* (HTTP/WS/IPC) RPC interface.
APIModules string
// HTTPHost is the host interface on which to start the HTTP RPC server.
// Pass empty string if no HTTP RPC interface needs to be started.
HTTPHost string
// RPCEnabled specifies whether the http RPC server is to be enabled by default.
RPCEnabled bool
// HTTPPort is the TCP port number on which to start the Geth's HTTP RPC server.
HTTPPort int
// IPCFile is filename of exposed IPC RPC Server
IPCFile string
// IPCEnabled specifies whether IPC-RPC Server is enabled or not
IPCEnabled bool
// TLSEnabled specifies whether TLS support should be enabled on node or not
// TLS support is only planned in go-ethereum, so we are using our own patch.
TLSEnabled bool
// MaxPeers is the maximum number of (global) peers that can be connected.
// Set to zero, if only static or trusted peers are allowed to connect.
MaxPeers int
// MaxPendingPeers is the maximum number of peers that can be pending in the
// handshake phase, counted separately for inbound and outbound connections.
MaxPendingPeers int
log log.Logger
// LogEnabled enables the logger
LogEnabled bool `json:"LogEnabled"`
// LogFile is filename where exposed logs get written to
LogFile string
// LogLevel defines minimum log level. Valid names are "ERROR", "WARN", "INFO", "DEBUG", and "TRACE".
LogLevel string `validate:"eq=ERROR|eq=WARN|eq=INFO|eq=DEBUG|eq=TRACE"`
// LogToStderr defines whether logged info should also be output to os.Stderr
LogToStderr bool
// UpstreamConfig extra config for providing upstream infura server.
UpstreamConfig UpstreamRPCConfig `json:"UpstreamConfig"`
// ClusterConfigFile contains the file name of the cluster configuration. If
// empty the statical configuration data will be taken.
ClusterConfigFile string `json:"ClusterConfigFile"`
// ClusterConfig extra configuration for supporting cluster peers.
ClusterConfig *ClusterConfig `json:"ClusterConfig," validate:"structonly"`
// LightEthConfig extra configuration for LES
LightEthConfig *LightEthConfig `json:"LightEthConfig," validate:"structonly"`
// WhisperConfig extra configuration for SHH
WhisperConfig *WhisperConfig `json:"WhisperConfig," validate:"structonly"`
// SwarmConfig extra configuration for Swarm and ENS
SwarmConfig *SwarmConfig `json:"SwarmConfig," validate:"structonly"`
// RegisterTopics a list of specific topics where the peer wants to be
// discoverable.
RegisterTopics []discv5.Topic `json:"RegisterTopics"`
// RequiredTopics list of topics where a client wants to search for
// discoverable peers with the discovery limits.
RequireTopics map[discv5.Topic]Limits `json:"RequireTopics"`
// StatusServiceEnabled enables status service api
StatusServiceEnabled bool
// DebugAPIEnabled enables debug api
DebugAPIEnabled bool
}
// NewNodeConfig creates new node configuration object
func NewNodeConfig(dataDir, clstrCfgFile, fleet string, networkID uint64) (*NodeConfig, error) {
nodeConfig := &NodeConfig{
NetworkID: networkID,
DataDir: dataDir,
Name: ClientIdentifier,
Version: Version,
RPCEnabled: RPCEnabledDefault,
HTTPHost: HTTPHost,
HTTPPort: HTTPPort,
ListenAddr: ListenAddr,
APIModules: APIModules,
MaxPeers: MaxPeers,
MaxPendingPeers: MaxPendingPeers,
IPCFile: IPCFile,
log: log.New("package", "status-go/params.NodeConfig"),
LogFile: LogFile,
LogLevel: LogLevel,
LogToStderr: LogToStderr,
ClusterConfigFile: clstrCfgFile,
ClusterConfig: &ClusterConfig{
Enabled: true,
Fleet: fleet,
StaticNodes: []string{},
BootNodes: []string{},
},
LightEthConfig: &LightEthConfig{
Enabled: true,
DatabaseCache: DatabaseCache,
},
WhisperConfig: &WhisperConfig{
Enabled: true,
MinimumPoW: WhisperMinimumPoW,
TTL: WhisperTTL,
FirebaseConfig: &FirebaseConfig{
NotificationTriggerURL: FirebaseNotificationTriggerURL,
},
EnableNTPSync: true,
},
SwarmConfig: &SwarmConfig{},
RegisterTopics: []discv5.Topic{},
RequireTopics: map[discv5.Topic]Limits{},
}
// adjust dependent values
if err := nodeConfig.updateConfig(); err != nil {
return nil, err
}
return nodeConfig, nil
}
// LoadNodeConfig parses incoming JSON and returned it as Config
func LoadNodeConfig(configJSON string) (*NodeConfig, error) {
nodeConfig, err := loadNodeConfig(configJSON)
if err != nil {
return nil, err
}
if err := nodeConfig.Validate(); err != nil {
return nil, err
}
return nodeConfig, nil
}
func loadNodeConfig(configJSON string) (*NodeConfig, error) {
nodeConfig, err := NewNodeConfig("", "", FleetBeta, 0)
if err != nil {
return nil, err
}
decoder := json.NewDecoder(strings.NewReader(configJSON))
// override default configuration with values by JSON input
if err := decoder.Decode(&nodeConfig); err != nil {
return nil, err
}
// repopulate
if err := nodeConfig.updateConfig(); err != nil {
return nil, err
}
return nodeConfig, nil
}
// Validate checks if NodeConfig fields have valid values.
//
// It returns nil if there are no errors, otherwise one or more errors
// can be returned. Multiple errors are joined with a new line.
//
// A single error for a struct:
//
// type TestStruct struct {
// TestField string `validate:"required"`
// }
//
// has the following format:
//
// Key: 'TestStruct.TestField' Error:Field validation for 'TestField' failed on the 'required' tag
//
func (c *NodeConfig) Validate() error {
validate := NewValidator()
if err := validate.Struct(c); err != nil {
return err
}
if c.ClusterConfig.Enabled {
if err := validate.Struct(c.ClusterConfig); err != nil {
return err
}
}
if c.LightEthConfig.Enabled {
if err := validate.Struct(c.LightEthConfig); err != nil {
return err
}
}
if c.WhisperConfig.Enabled {
if err := validate.Struct(c.WhisperConfig); err != nil {
return err
}
}
if c.SwarmConfig.Enabled {
if err := validate.Struct(c.SwarmConfig); err != nil {
return err
}
}
return nil
}
// Save dumps configuration to the disk
func (c *NodeConfig) Save() error {
data, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
if err := os.MkdirAll(c.DataDir, os.ModePerm); err != nil {
return err
}
configFilePath := filepath.Join(c.DataDir, "config.json")
if err := ioutil.WriteFile(configFilePath, data, os.ModePerm); err != nil {
return err
}
c.log.Info("config file saved", "path", configFilePath)
return nil
}
// updateConfig traverses configuration and adjusts dependent fields
// (we have a development/production and mobile/full node dependent configurations)
func (c *NodeConfig) updateConfig() error {
// Update separate configurations.
if err := c.updateGenesisConfig(); err != nil {
return err
}
if err := c.updateUpstreamConfig(); err != nil {
return err
}
if err := c.updateClusterConfig(); err != nil {
return err
}
c.updatePeerLimits()
return c.updateRelativeDirsConfig()
}
// updateGenesisConfig does necessary adjustments to config object (depending on network node will be running on)
func (c *NodeConfig) updateGenesisConfig() error {
var genesis *core.Genesis
switch c.NetworkID {
case MainNetworkID:
genesis = core.DefaultGenesisBlock()
case RopstenNetworkID:
genesis = core.DefaultTestnetGenesisBlock()
case RinkebyNetworkID:
genesis = core.DefaultRinkebyGenesisBlock()
case StatusChainNetworkID:
var err error
genesis, err = c.DefaultStatusChainGenesisBlock()
if err != nil {
return err
}
default:
return nil
}
// encode the genesis into JSON
enc, err := json.Marshal(genesis)
if err != nil {
return err
}
c.LightEthConfig.Genesis = string(enc)
return nil
}
// DefaultStatusChainGenesisBlock returns the StatusChain network genesis block.
func (c *NodeConfig) DefaultStatusChainGenesisBlock() (*core.Genesis, error) {
genesisJSON, err := static.Asset("config/status-chain-genesis.json")
if err != nil {
return nil, fmt.Errorf("status-chain-genesis.json could not be loaded: %s", err)
}
var genesis *core.Genesis
err = json.Unmarshal(genesisJSON, &genesis)
if err != nil {
return nil, fmt.Errorf("cannot unmarshal status-chain-genesis.json: %s", err)
}
return genesis, nil
}
// updateUpstreamConfig sets the proper UpstreamConfig.URL for the network id being used.
func (c *NodeConfig) updateUpstreamConfig() error {
// If we have a URL already set then keep URL incase
// of custom server.
if c.UpstreamConfig.URL != "" {
return nil
}
switch c.NetworkID {
case MainNetworkID:
c.UpstreamConfig.URL = MainnetEthereumNetworkURL
case RopstenNetworkID:
c.UpstreamConfig.URL = RopstenEthereumNetworkURL
case RinkebyNetworkID:
c.UpstreamConfig.URL = RinkebyEthereumNetworkURL
}
return nil
}
// updateClusterConfig loads static peer nodes and CHT for a given network and mode.
// This is necessary until we have LES protocol support CHT sync, and better node
// discovery on mobile devices)
func (c *NodeConfig) updateClusterConfig() error {
if !c.ClusterConfig.Enabled {
return nil
}
c.log.Debug(
"update cluster config",
"configFile", c.ClusterConfigFile,
"fleet", c.ClusterConfig.Fleet)
var (
clusters []cluster
err error
)
if c.ClusterConfigFile != "" {
// Load cluster configuration from external file.
configFile, err := ioutil.ReadFile(c.ClusterConfigFile)
if err != nil {
return fmt.Errorf("cluster configuration file '%s' could not be loaded: %s", c.ClusterConfigFile, err)
}
err = json.Unmarshal(configFile, &clusters)
if err != nil {
return fmt.Errorf("failed to unmarshal cluster configuration file: %s", err)
}
} else {
clusters, err = clusterForFleet(c.ClusterConfig.Fleet)
if err != nil {
return fmt.Errorf("getting fleet '%s' failed: %v", c.ClusterConfig.Fleet, err)
}
}
for _, cluster := range clusters {
if cluster.NetworkID == int(c.NetworkID) {
// allow to override bootnodes only if they were not defined earlier
if len(c.ClusterConfig.BootNodes) == 0 {
c.ClusterConfig.BootNodes = cluster.BootNodes
}
// allow to override static nodes only if they were not defined earlier
if len(c.ClusterConfig.StaticNodes) == 0 {
c.ClusterConfig.StaticNodes = cluster.StaticNodes
}
// no point in running discovery if we don't have bootnodes.
// but in case if we do have nodes and NoDiscovery=true we will preserve that value
if len(cluster.BootNodes) == 0 {
c.NoDiscovery = true
}
c.ClusterConfig.TrustedMailServers = cluster.MailServers
break
}
}
return nil
}
// updateRelativeDirsConfig updates directories that should be wrt to DataDir
func (c *NodeConfig) updateRelativeDirsConfig() error {
makeSubDirPath := func(baseDir, subDir string) string {
if len(baseDir) == 0 {
return ""
}
return filepath.Join(baseDir, subDir)
}
if len(c.KeyStoreDir) == 0 {
c.KeyStoreDir = makeSubDirPath(c.DataDir, KeyStoreDir)
}
if len(c.WhisperConfig.DataDir) == 0 {
c.WhisperConfig.DataDir = makeSubDirPath(c.DataDir, WhisperDataDir)
}
return nil
}
// updatePeerLimits will set default peer limits expectations based on enabled services.
func (c *NodeConfig) updatePeerLimits() {
if c.NoDiscovery {
return
}
if c.WhisperConfig.Enabled {
c.RequireTopics[WhisperDiscv5Topic] = WhisperDiscv5Limits
// TODO(dshulyak) register mailserver limits when we will change how they are handled.
}
}
// String dumps config object as nicely indented JSON
func (c *NodeConfig) String() string {
data, _ := json.MarshalIndent(c, "", " ")
return string(data)
}
// FormatAPIModules returns a slice of APIModules.
func (c *NodeConfig) FormatAPIModules() []string {
if len(c.APIModules) == 0 {
return nil
}
return strings.Split(c.APIModules, ",")
}
// AddAPIModule adds a mobule to APIModules
func (c *NodeConfig) AddAPIModule(m string) {
c.APIModules = fmt.Sprintf("%s,%s", c.APIModules, m)
}