forked from Dirbaio/gominer
-
Notifications
You must be signed in to change notification settings - Fork 79
/
config.go
651 lines (574 loc) · 21.3 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
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015-2023 The Decred developers
package main
import (
"errors"
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/slog"
"github.com/jessevdk/go-flags"
)
const (
defaultConfigFilename = "gominer.conf"
defaultLogLevel = "info"
defaultLogDirname = "logs"
defaultLogFilename = "gominer.log"
defaultClKernel = "blake3.cl"
// defaultCudaThreadCount is the default number of threads to execute
// in a CUDA batch job. This has been empirically determined to be
// a reasonable default in current Nvidia hardware.
defaultCudaThreadCount = "256"
)
var (
minerHomeDir = dcrutil.AppDataDir("gominer", false)
dcrdHomeDir = dcrutil.AppDataDir("dcrd", false)
defaultConfigFile = filepath.Join(minerHomeDir, defaultConfigFilename)
defaultRPCServer = "localhost"
defaultRPCCertFile = filepath.Join(dcrdHomeDir, "rpc.cert")
defaultRPCPortMainNet = "9109"
defaultRPCPortTestNet = "19109"
defaultRPCPortSimNet = "19556"
defaultAPIPort = "3333"
defaultLogDir = filepath.Join(minerHomeDir, defaultLogDirname)
defaultAutocalibrate = 500
minIntensity = 8
maxIntensity = 31
minTempTarget = uint32(60)
maxTempTarget = uint32(84)
maxWorkSize = uint32(0xFFFFFFFF - 255)
)
type config struct {
ListDevices bool `short:"l" long:"listdevices" description:"List number of devices."`
ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
// Config / log options
Experimental bool `long:"experimental" description:"enable EXPERIMENTAL features such as setting a temperature target with (-t/--temptarget) which may DAMAGE YOUR DEVICE(S)."`
ConfigFile string `short:"C" long:"configfile" description:"Path to configuration file"`
LogDir string `long:"logdir" description:"Directory to log output."`
DebugLevel string `short:"d" long:"debuglevel" description:"Logging level for all subsystems {trace, debug, info, warn, error, critical} -- You may also specify <subsystem>=<level>,<subsystem2>=<level>,... to set the log level for individual subsystems -- Use show to list available subsystems"`
ClKernel string `short:"k" long:"kernel" description:"File with cl kernel to use"`
// Debugging options
Profile string `long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65536"`
CPUProfile string `long:"cpuprofile" description:"Write CPU profile to the specified file"`
MemProfile string `long:"memprofile" description:"Write mem profile to the specified file"`
// Status API options
APIListeners []string `long:"apilisten" description:"Add an interface/port to expose miner status API"`
// RPC connection options
RPCUser string `short:"u" long:"rpcuser" description:"RPC username"`
RPCPassword string `short:"P" long:"rpcpass" default-mask:"-" description:"RPC password"`
RPCServer string `short:"s" long:"rpcserver" description:"RPC server to connect to"`
RPCCert string `short:"c" long:"rpccert" description:"RPC server certificate chain for validation"`
NoTLS bool `long:"notls" description:"Disable TLS"`
Proxy string `long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
ProxyUser string `long:"proxyuser" description:"Username for proxy server"`
ProxyPass string `long:"proxypass" default-mask:"-" description:"Password for proxy server"`
Benchmark bool `short:"B" long:"benchmark" description:"Run in benchmark mode."`
TestNet bool `long:"testnet" description:"Connect to testnet"`
SimNet bool `long:"simnet" description:"Connect to the simulation test network"`
TLSSkipVerify bool `long:"skipverify" description:"Do not verify tls certificates (not recommended!)"`
Autocalibrate string `short:"A" long:"autocalibrate" description:"Time target in milliseconds to spend executing hashes on the device during each iteration. Single global value or a comma separated list."`
AutocalibrateInts []int
Devices string `short:"D" long:"devices" description:"Single device ID or a comma separated list of device IDs to use."`
DeviceIDs []int
Intensity string `short:"i" long:"intensity" description:"Intensities (the work size is 2^intensity) per device. Single global value or a comma separated list."`
IntensityInts []int
TempTarget string `short:"t" long:"temptarget" description:"Target temperature in Celsius to maintain via automatic fan control. (Requires --experimental flag)"`
TempTargetInts []uint32
WorkSize string `short:"W" long:"worksize" description:"The explicitly declared sizes of the work to do per device (overrides intensity). Single global value or a comma separated list."`
WorkSizeInts []uint32
// CUDA-related config parameters.
CudaGridSize string `long:"cudagridsize" description:"Size of the CUDA grid to use per device. Single global value or a comma separated list"`
CudaGridSizeInts []int
CudaThreadCount string `long:"cudathreadcount" description:"Number of CUDA threads to use per device. Single global value or a comma separated list"`
CudaThreadCountInts []int
// Pool related options
Pool string `short:"o" long:"pool" description:"Pool to connect to (e.g.stratum+tcp://pool:port)"`
PoolUser string `short:"m" long:"pooluser" description:"Pool username"`
PoolPassword string `short:"n" long:"poolpass" default-mask:"-" description:"Pool password"`
}
// removeDuplicateAddresses returns a new slice with all duplicate entries in
// addrs removed.
func removeDuplicateAddresses(addrs []string) []string {
result := make([]string, 0, len(addrs))
seen := map[string]struct{}{}
for _, val := range addrs {
if _, ok := seen[val]; !ok {
result = append(result, val)
seen[val] = struct{}{}
}
}
return result
}
// normalizeAddress returns addr with the passed default port appended if
// there is not already a port specified.
func normalizeAddress(addr string, defaultPort string) string {
_, _, err := net.SplitHostPort(addr)
if err != nil {
return net.JoinHostPort(addr, defaultPort)
}
return addr
}
// normalizeAddresses returns a new slice with all the passed peer addresses
// normalized with the given default port, and all duplicates removed.
func normalizeAddresses(addrs []string, defaultPort string) []string {
for i, addr := range addrs {
addrs[i] = normalizeAddress(addr, defaultPort)
}
return removeDuplicateAddresses(addrs)
}
// validLogLevel returns whether or not logLevel is a valid debug log level.
func validLogLevel(logLevel string) bool {
_, ok := slog.LevelFromString(logLevel)
return ok
}
// supportedSubsystems returns a sorted slice of the supported subsystems for
// logging purposes.
func supportedSubsystems() []string {
// Convert the subsystemLoggers map keys to a slice.
subsystems := make([]string, 0, len(subsystemLoggers))
for subsysID := range subsystemLoggers {
subsystems = append(subsystems, subsysID)
}
// Sort the subsytems for stable display.
sort.Strings(subsystems)
return subsystems
}
// parseAndSetDebugLevels attempts to parse the specified debug level and set
// the levels accordingly. An appropriate error is returned if anything is
// invalid.
func parseAndSetDebugLevels(debugLevel string) error {
// When the specified string doesn't have any delimters, treat it as
// the log level for all subsystems.
if !strings.Contains(debugLevel, ",") && !strings.Contains(debugLevel, "=") {
// Validate debug log level.
if !validLogLevel(debugLevel) {
str := "The specified debug level [%v] is invalid"
return fmt.Errorf(str, debugLevel)
}
// Change the logging level for all subsystems.
setLogLevels(debugLevel)
return nil
}
// Split the specified string into subsystem/level pairs while detecting
// issues and update the log levels accordingly.
for _, logLevelPair := range strings.Split(debugLevel, ",") {
if !strings.Contains(logLevelPair, "=") {
str := "The specified debug level contains an invalid " +
"subsystem/level pair [%v]"
return fmt.Errorf(str, logLevelPair)
}
// Extract the specified subsystem and log level.
fields := strings.Split(logLevelPair, "=")
subsysID, logLevel := fields[0], fields[1]
// Validate subsystem.
if _, exists := subsystemLoggers[subsysID]; !exists {
str := "The specified subsystem [%v] is invalid -- " +
"supported subsytems %v"
return fmt.Errorf(str, subsysID, supportedSubsystems())
}
// Validate log level.
if !validLogLevel(logLevel) {
str := "The specified debug level [%v] is invalid"
return fmt.Errorf(str, logLevel)
}
setLogLevel(subsysID, logLevel)
}
return nil
}
// cleanAndExpandPath expands environement variables and leading ~ in the
// passed path, cleans the result, and returns it.
func cleanAndExpandPath(path string) string {
// Expand initial ~ to OS specific home directory.
if strings.HasPrefix(path, "~") {
homeDir := filepath.Dir(minerHomeDir)
path = strings.Replace(path, "~", homeDir, 1)
}
// NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
// but they variables can still be expanded via POSIX-style $VARIABLE.
return filepath.Clean(os.ExpandEnv(path))
}
// commaListToInts converts a (possibly) comma separated string-encoded ints
// into a slice of ints.
func commaListToInts(s string) ([]int, error) {
if len(s) == 0 {
return nil, nil
}
// Parse a list like "29,30"
var res []int
if strings.Contains(s, ",") {
split := strings.Split(s, ",")
res = make([]int, len(split))
for i := range split {
j, err := strconv.Atoi(split[i])
if err != nil {
err := fmt.Errorf("item %q is not an int: %w", split[i], err)
return nil, err
}
res[i] = j
}
} else {
i, err := strconv.Atoi(s)
if err != nil {
return nil, fmt.Errorf("%q is not an int: %w", s, err)
}
res = []int{i}
}
return res, nil
}
// loadConfig initializes and parses the config using a config file and command
// line options.
//
// The configuration proceeds as follows:
// 1. Start with a default config with sane settings
// 2. Pre-parse the command line to check for an alternative config file
// 3. Load configuration file overwriting defaults with any specified options
// 4. Parse CLI options and overwrite/add any specified options
//
// The above results in btcd functioning properly without any config settings
// while still allowing the user to override settings with config files and
// command line options. Command line options always take precedence.
func loadConfig() (*config, []string, error) {
// Default config.
cfg := config{
ConfigFile: defaultConfigFile,
DebugLevel: defaultLogLevel,
LogDir: defaultLogDir,
RPCServer: defaultRPCServer,
RPCCert: defaultRPCCertFile,
ClKernel: defaultClKernel,
CudaThreadCount: defaultCudaThreadCount,
}
// Create the home directory if it doesn't already exist.
funcName := "loadConfig"
err := os.MkdirAll(minerHomeDir, 0700)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(-1)
}
// Pre-parse the command line options to see if an alternative config
// file or the version flag was specified.
preCfg := cfg
preParser := flags.NewParser(&preCfg, flags.Default)
_, err = preParser.Parse()
if err != nil {
var e *flags.Error
if !errors.As(err, &e) || e.Type != flags.ErrHelp {
preParser.WriteHelp(os.Stderr)
}
return nil, nil, err
}
// Show the version and exit if the version flag was specified.
appName := filepath.Base(os.Args[0])
appName = strings.TrimSuffix(appName, filepath.Ext(appName))
usageMessage := fmt.Sprintf("Use %s -h to show usage", appName)
if preCfg.ListDevices {
ListDevices()
os.Exit(0)
}
if preCfg.ShowVersion {
fmt.Printf("%s %s version %s (Go version %s %s/%s)\n", appName, gpuLib(),
Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
os.Exit(0)
}
// Load additional config from file.
var configFileError error
parser := flags.NewParser(&cfg, flags.Default)
err = flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile)
if err != nil {
var e *os.PathError
if !errors.As(err, &e) {
fmt.Fprintln(os.Stderr, err)
parser.WriteHelp(os.Stderr)
return nil, nil, err
}
configFileError = err
}
// Parse command line options again to ensure they take precedence.
remainingArgs, err := parser.Parse()
if err != nil {
var e *flags.Error
if !errors.As(err, &e) || e.Type != flags.ErrHelp {
parser.WriteHelp(os.Stderr)
}
return nil, nil, err
}
// Multiple networks can't be selected simultaneously.
numNets := 0
if cfg.TestNet {
numNets++
}
if cfg.SimNet {
numNets++
}
if numNets > 1 {
str := "%s: The testnet and simnet params can't be used " +
"together -- choose one of the two"
err := fmt.Errorf(str, "loadConfig")
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
// Check the autocalibrations if the user is setting that.
if len(cfg.Autocalibrate) > 0 {
// Parse a list like -A 450,600
if strings.Contains(cfg.Autocalibrate, ",") {
specifiedAutocalibrates := strings.Split(cfg.Autocalibrate, ",")
cfg.AutocalibrateInts = make([]int, len(specifiedAutocalibrates))
for i := range specifiedAutocalibrates {
j, err := strconv.Atoi(specifiedAutocalibrates[i])
if err != nil {
err := fmt.Errorf("could not convert autocalibration "+
"(%v) to int: %w", specifiedAutocalibrates[i], err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.AutocalibrateInts[i] = j
}
// Use specified device like -A 600
} else {
cfg.AutocalibrateInts = make([]int, 1)
i, err := strconv.Atoi(cfg.Autocalibrate)
if err != nil {
err := fmt.Errorf("could not convert autocalibration %v "+
"to int: %w", cfg.Autocalibrate, err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.AutocalibrateInts[0] = i
}
// Apply default
} else {
cfg.AutocalibrateInts = []int{defaultAutocalibrate}
}
// Check the devices if the user is setting that.
if len(cfg.Devices) > 0 {
// Parse a list like -D 1,2
if strings.Contains(cfg.Devices, ",") {
specifiedDevices := strings.Split(cfg.Devices, ",")
cfg.DeviceIDs = make([]int, len(specifiedDevices))
for i := range specifiedDevices {
j, err := strconv.Atoi(specifiedDevices[i])
if err != nil {
err := fmt.Errorf("could not convert device number %v "+
"(%v) to int: %w", i+1, specifiedDevices[i], err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.DeviceIDs[i] = j
}
// Use specified device like -D 1
} else {
cfg.DeviceIDs = make([]int, 1)
i, err := strconv.Atoi(cfg.Devices)
if err != nil {
err := fmt.Errorf("could not convert specified device %v "+
"to int: %w", cfg.Devices, err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.DeviceIDs[0] = i
}
}
// Check the intensity if the user is setting that.
if len(cfg.Intensity) > 0 {
// Parse a list like -i 29,30
if strings.Contains(cfg.Intensity, ",") {
specifiedIntensities := strings.Split(cfg.Intensity, ",")
cfg.IntensityInts = make([]int, len(specifiedIntensities))
for i := range specifiedIntensities {
j, err := strconv.Atoi(specifiedIntensities[i])
if err != nil {
err := fmt.Errorf("could not convert intensity "+
"(%v) to int: %w", specifiedIntensities[i], err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.IntensityInts[i] = j
}
// Use specified intensity like -i 29
} else {
cfg.IntensityInts = make([]int, 1)
i, err := strconv.Atoi(cfg.Intensity)
if err != nil {
err := fmt.Errorf("could not convert intensity %v "+
"to int: %w", cfg.Intensity, err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.IntensityInts[0] = i
}
}
for i := range cfg.IntensityInts {
if (cfg.IntensityInts[i] < minIntensity) ||
(cfg.IntensityInts[i] > maxIntensity) {
err := fmt.Errorf("intensity %v not within "+
"range %v to %v", cfg.IntensityInts[i], minIntensity,
maxIntensity)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
}
// Check the temptarget if the user is setting that.
if len(cfg.TempTarget) > 0 {
if !cfg.Experimental {
err := fmt.Errorf("temperature targets / automatic fan control " +
"is an EXPERIMENTAL feature and requires the --experimental " +
"flag to acknowledge that you accept the risk of possibly " +
"DAMAGING YOUR DEVICE(S) due to software bugs")
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
// Parse a list like -t 80,75
if strings.Contains(cfg.TempTarget, ",") {
specifiedTempTargets := strings.Split(cfg.TempTarget, ",")
cfg.TempTargetInts = make([]uint32, len(specifiedTempTargets))
for i := range specifiedTempTargets {
j, err := strconv.Atoi(specifiedTempTargets[i])
if err != nil {
err := fmt.Errorf("could not convert temptarget "+
"(%v) to int: %w", specifiedTempTargets[i], err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.TempTargetInts[i] = uint32(j)
}
// Use specified temptarget like -t 75
} else {
cfg.TempTargetInts = make([]uint32, 1)
i, err := strconv.Atoi(cfg.TempTarget)
if err != nil {
err := fmt.Errorf("could not convert temptarget %v "+
"to int: %w", cfg.TempTarget, err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.TempTargetInts[0] = uint32(i)
}
}
if cfg.Experimental {
fmt.Fprintln(os.Stderr, "enabling EXPERIMENTAL features "+
"that may possibly DAMAGE YOUR DEVICE(S)")
time.Sleep(time.Second * 3)
}
for i := range cfg.TempTargetInts {
if cfg.TempTargetInts[i] < minTempTarget {
err := fmt.Errorf("temp target %v is lower than minimum %v",
cfg.TempTargetInts[i], minTempTarget)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
if cfg.TempTargetInts[i] > maxTempTarget {
err := fmt.Errorf("temp target %v is higher than maximum %v",
cfg.TempTargetInts[i], maxTempTarget)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
}
// Check the work size if the user is setting that.
if len(cfg.WorkSize) > 0 {
// Parse a list like -W 536870912,1073741824
if strings.Contains(cfg.WorkSize, ",") {
specifiedWorkSizes := strings.Split(cfg.WorkSize, ",")
cfg.WorkSizeInts = make([]uint32, len(specifiedWorkSizes))
for i := range specifiedWorkSizes {
j, err := strconv.Atoi(specifiedWorkSizes[i])
if err != nil {
err := fmt.Errorf("could not convert worksize "+
"(%v) to int: %w", specifiedWorkSizes[i], err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.WorkSizeInts[i] = uint32(j)
}
// Use specified worksize like -W 1073741824
} else {
cfg.WorkSizeInts = make([]uint32, 1)
i, err := strconv.Atoi(cfg.WorkSize)
if err != nil {
err := fmt.Errorf("could not convert worksize %v "+
"to int: %w", cfg.WorkSize, err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
cfg.WorkSizeInts[0] = uint32(i)
}
}
for i := range cfg.WorkSizeInts {
if cfg.WorkSizeInts[i] < 256 {
err := fmt.Errorf("too small WorkSize passed: %v, min 256",
cfg.WorkSizeInts[i])
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
if cfg.WorkSizeInts[i] > maxWorkSize {
err := fmt.Errorf("too big WorkSize passed: %v, max %v",
cfg.WorkSizeInts[i], maxWorkSize)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
if cfg.WorkSizeInts[i]%256 != 0 {
err := fmt.Errorf("work size %v not a multiple of 256",
cfg.WorkSizeInts[i])
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
}
cfg.CudaGridSizeInts, err = commaListToInts(cfg.CudaGridSize)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot convert CUDA grid size to int: %v\n", err)
return nil, nil, err
}
cfg.CudaThreadCountInts, err = commaListToInts(cfg.CudaThreadCount)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot convert CUDA thread count to int: %v\n", err)
return nil, nil, err
}
// Special show command to list supported subsystems and exit.
if cfg.DebugLevel == "show" {
fmt.Println("Supported subsystems", supportedSubsystems())
os.Exit(0)
}
// Initialize log rotation. After log rotation has been initialized,
// the logger variables may be used.
initLogRotator(filepath.Join(cfg.LogDir, defaultLogFilename))
// Parse, validate, and set debug log level(s).
if err := parseAndSetDebugLevels(cfg.DebugLevel); err != nil {
err := fmt.Errorf("%s: %w", funcName, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
if len(cfg.APIListeners) != 0 {
cfg.APIListeners = normalizeAddresses(cfg.APIListeners, defaultAPIPort)
}
// Handle environment variable expansion in the RPC certificate path.
cfg.RPCCert = cleanAndExpandPath(cfg.RPCCert)
var defaultRPCPort string
switch {
case cfg.TestNet:
defaultRPCPort = defaultRPCPortTestNet
chainParams = chaincfg.TestNet3Params()
case cfg.SimNet:
defaultRPCPort = defaultRPCPortSimNet
chainParams = chaincfg.SimNetParams()
default:
defaultRPCPort = defaultRPCPortMainNet
}
// Add default port to RPC server based on --testnet flag
// if needed.
cfg.RPCServer = normalizeAddress(cfg.RPCServer, defaultRPCPort)
// Warn about missing config file only after all other configuration is
// done. This prevents the warning on help messages and invalid
// options. Note this should go directly before the return.
if configFileError != nil {
mainLog.Warnf("%v", configFileError)
}
return &cfg, remainingArgs, nil
}