-
Notifications
You must be signed in to change notification settings - Fork 292
/
config.go
1400 lines (1244 loc) · 51.7 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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2024 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"context"
"crypto/elliptic"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/decred/dcrd/connmgr/v3"
"github.com/decred/dcrd/database/v3"
_ "github.com/decred/dcrd/database/v3/ffldb"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/internal/mempool"
"github.com/decred/dcrd/internal/version"
"github.com/decred/dcrd/rpc/jsonrpc/types/v4"
"github.com/decred/dcrd/sampleconfig"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/go-socks/socks"
"github.com/decred/slog"
flags "github.com/jessevdk/go-flags"
)
const (
// Defaults for general application behavior options.
defaultConfigFilename = "dcrd.conf"
defaultDataDirname = "data"
defaultLogDirname = "logs"
defaultLogFilename = "dcrd.log"
defaultLogSize = "10M"
defaultDbType = "ffldb"
defaultLogLevel = "info"
defaultSigCacheMaxSize = 100000
defaultUtxoCacheMaxSize = 150
minUtxoCacheMaxSize = 25
maxUtxoCacheMaxSize = 32768 // 32 GiB
// Defaults for RPC server options and policy.
defaultTLSCurve = "P-256"
defaultMaxRPCClients = 10
defaultMaxRPCWebsockets = 25
defaultMaxRPCConcurrentReqs = 20
// Defaults for P2P network options.
defaultMaxSameIP = 5
defaultMaxPeers = 125
defaultDialTimeout = time.Second * 30
defaultPeerIdleTimeout = time.Second * 120
// Defaults for banning options.
defaultBanDuration = time.Hour * 24
defaultBanThreshold = 100
// Defaults for relay and mempool policy options.
defaultMaxOrphanTransactions = 100
defaultAllowOldVotes = false
// Defaults for mining options and policy.
defaultGenerate = false
defaultBlockMaxSize = 375000
blockMaxSizeMin = 1000
defaultNoMiningStateSync = false
defaultAllowUnsyncedMining = false
// Defaults for indexing options.
defaultTxIndex = false
defaultNoExistsAddrIndex = false
// Authorization types.
authTypeBasic = "basic"
authTypeClientCert = "clientcert"
)
var (
// Constructed defaults for general application behavior options.
defaultHomeDir = dcrutil.AppDataDir("dcrd", false)
defaultConfigFile = filepath.Join(defaultHomeDir, defaultConfigFilename)
defaultDataDir = filepath.Join(defaultHomeDir, defaultDataDirname)
defaultLogDir = filepath.Join(defaultHomeDir, defaultLogDirname)
knownDbTypes = database.SupportedDrivers()
// Constructed defaults for RPC server options and policy.
defaultRPCKeyFile = filepath.Join(defaultHomeDir, "rpc.key")
defaultRPCCertFile = filepath.Join(defaultHomeDir, "rpc.cert")
defaultRPCAuthType = authTypeBasic
defaultRPCClientCAs = filepath.Join(defaultHomeDir, "clients.pem")
)
// runServiceCommand is only set to a real function on Windows. It is used
// to parse and execute service commands specified via the -s flag.
var runServiceCommand func(string) error
// config defines the configuration options for dcrd.
//
// See loadConfig for details on the configuration load process.
type config struct {
// General application behavior.
ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
HomeDir string `short:"A" long:"appdata" description:"Path to application home directory" env:"DCRD_APPDATA"`
ConfigFile string `short:"C" long:"configfile" description:"Path to configuration file"`
DataDir string `short:"b" long:"datadir" description:"Directory to store data"`
LogDir string `long:"logdir" description:"Directory to log output"`
LogSize string `long:"logsize" description:"Maximum size of log file before it is rotated"`
NoFileLogging bool `long:"nofilelogging" description:"Disable file logging"`
DbType string `long:"dbtype" description:"Database backend to use for the block chain"`
Profile string `long:"profile" description:"Enable HTTP profiling on given [addr:]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"`
TestNet bool `long:"testnet" description:"Use the test network"`
SimNet bool `long:"simnet" description:"Use the simulation test network"`
RegNet bool `long:"regnet" description:"Use the regression test network"`
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"`
SigCacheMaxSize uint `long:"sigcachemaxsize" description:"The maximum number of entries in the signature verification cache"`
UtxoCacheMaxSize uint `long:"utxocachemaxsize" description:"The maximum size in MiB of the utxo cache; (min: 25, max: 32768)"`
// RPC server options and policy.
DisableRPC bool `long:"norpc" description:"Disable built-in RPC server -- NOTE: The RPC server is disabled by default if no rpcuser/rpcpass or rpclimituser/rpclimitpass is specified"`
RPCListeners []string `long:"rpclisten" description:"Add an interface/port to listen for RPC connections (default port: 9109, testnet: 19109)"`
RPCUser string `short:"u" long:"rpcuser" description:"Username for RPC connections"`
RPCPass string `short:"P" long:"rpcpass" default-mask:"-" description:"Password for RPC connections"`
RPCAuthType string `long:"authtype" description:"Method for RPC client authentication (basic or clientcert)"`
RPCClientCAs string `long:"clientcafile" description:"File containing Certificate Authorities to verify TLS client certificates; requires authtype=clientcert"`
RPCLimitUser string `long:"rpclimituser" description:"Username for limited RPC connections"`
RPCLimitPass string `long:"rpclimitpass" default-mask:"-" description:"Password for limited RPC connections"`
RPCCert string `long:"rpccert" description:"File containing the certificate file"`
RPCKey string `long:"rpckey" description:"File containing the certificate key"`
TLSCurve string `long:"tlscurve" description:"Curve to use when generating TLS keypairs"`
AltDNSNames []string `long:"altdnsnames" description:"Specify additional DNS names to use when generating the RPC server certificate" env:"DCRD_ALT_DNSNAMES" env-delim:","`
DisableTLS bool `long:"notls" description:"Disable TLS for the RPC server -- NOTE: This is only allowed if the RPC server is bound to localhost"`
RPCMaxClients int `long:"rpcmaxclients" description:"Max number of RPC clients for standard connections"`
RPCMaxWebsockets int `long:"rpcmaxwebsockets" description:"Max number of RPC websocket connections"`
RPCMaxConcurrentReqs int `long:"rpcmaxconcurrentreqs" description:"Max number of concurrent RPC requests that may be processed concurrently"`
// P2P proxy and Tor settings.
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"`
OnionProxy string `long:"onion" description:"Connect to tor hidden services via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
OnionProxyUser string `long:"onionuser" description:"Username for onion proxy server"`
OnionProxyPass string `long:"onionpass" default-mask:"-" description:"Password for onion proxy server"`
NoOnion bool `long:"noonion" description:"Disable connecting to tor hidden services"`
TorIsolation bool `long:"torisolation" description:"Enable Tor stream isolation by randomizing user credentials for each connection"`
// P2P network options.
AddPeers []string `short:"a" long:"addpeer" description:"Add a peer to connect with at startup"`
ConnectPeers []string `long:"connect" description:"Connect only to the specified peers at startup"`
DisableListen bool `long:"nolisten" description:"Disable listening for incoming connections -- NOTE: Listening is automatically disabled if the --connect or --proxy options are used without also specifying listen interfaces via --listen"`
Listeners []string `long:"listen" description:"Add an interface/port to listen for connections (default all interfaces port: 9108, testnet: 19108)"`
MaxSameIP int `long:"maxsameip" description:"Max number of connections with the same IP -- 0 to disable"`
MaxPeers int `long:"maxpeers" description:"Max number of inbound and outbound peers"`
DialTimeout time.Duration `long:"dialtimeout" description:"How long to wait for TCP connection completion. Valid time units are {s, m, h}. Minimum 1 second"`
PeerIdleTimeout time.Duration `long:"peeridletimeout" description:"The duration of inactivity before a peer is timed out. Valid time units are {s,m,h}. Minimum 15 seconds"`
// P2P network discovery options.
DisableSeeders bool `long:"noseeders" description:"Disable seeding for peer discovery"`
DisableDNSSeed bool `long:"nodnsseed" description:"DEPRECATED: use --noseeders"`
ExternalIPs []string `long:"externalip" description:"Add a public-facing IP to the list of local external IPs that dcrd will advertise to other peers"`
NoDiscoverIP bool `long:"nodiscoverip" description:"Disable automatic network address discovery of local external IPs"`
Upnp bool `long:"upnp" description:"Use UPnP to map our listening port outside of NAT"`
// Banning options.
DisableBanning bool `long:"nobanning" description:"Disable banning of misbehaving peers"`
BanDuration time.Duration `long:"banduration" description:"How long to ban misbehaving peers. Valid time units are {s, m, h}. Minimum 1 second"`
BanThreshold uint32 `long:"banthreshold" description:"Maximum allowed ban score before disconnecting and banning misbehaving peers"`
Whitelists []string `long:"whitelist" description:"Add an IP network or IP that will not be banned (eg. 192.168.1.0/24 or ::1)"`
// Chain related options.
AllowOldForks bool `long:"allowoldforks" description:"Process forks deep in history. Don't do this unless you know what you're doing"`
DumpBlockchain string `long:"dumpblockchain" description:"Write blockchain as a flat file of blocks for use with addblock, to the specified filename"`
AssumeValid string `long:"assumevalid" description:"Hash of an assumed valid block. Defaults to the hard-coded assumed valid block that is updated periodically with new releases. Don't use a different hash unless you understand the implications. Set to 0 to disable"`
// Relay and mempool policy.
MinRelayTxFee float64 `long:"minrelaytxfee" description:"The minimum transaction fee in DCR/kB to be considered a non-zero fee"`
FreeTxRelayLimit float64 `long:"limitfreerelay" description:"DEPRECATED: This behavior is no longer available and this option will be removed in a future version of the software"`
NoRelayPriority bool `long:"norelaypriority" description:"DEPRECATED: This behavior is no longer available and this option will be removed in a future version of the software"`
MaxOrphanTxs int `long:"maxorphantx" description:"Max number of orphan transactions to keep in memory"`
BlocksOnly bool `long:"blocksonly" description:"Do not accept transactions from remote peers"`
AcceptNonStd bool `long:"acceptnonstd" description:"Accept and relay non-standard transactions to the network regardless of the default settings for the active network"`
RejectNonStd bool `long:"rejectnonstd" description:"Reject non-standard transactions regardless of the default settings for the active network"`
AllowOldVotes bool `long:"allowoldvotes" description:"Enable the addition of very old votes to the mempool"`
// Mining options and policy.
Generate bool `long:"generate" description:"Generate (mine) coins using the CPU"`
MiningAddrs []string `long:"miningaddr" description:"Add the specified payment address to the list of addresses to use for generated blocks. At least one address is required if the generate option is set"`
BlockMinSize uint32 `long:"blockminsize" description:"DEPRECATED: This behavior is no longer available and this option will be removed in a future version of the software"`
BlockMaxSize uint32 `long:"blockmaxsize" description:"Maximum block size in bytes to be used when creating a block"`
BlockPrioritySize uint32 `long:"blockprioritysize" description:"DEPRECATED: This behavior is no longer available and this option will be removed in a future version of the software"`
MiningTimeOffset int `long:"miningtimeoffset" description:"Offset the mining timestamp of a block by this many seconds (positive values are in the past)"`
NonAggressive bool `long:"nonaggressive" description:"Disable mining off of the parent block of the blockchain if there aren't enough voters"`
NoMiningStateSync bool `long:"nominingstatesync" description:"Disable synchronizing the mining state with other nodes"`
AllowUnsyncedMining bool `long:"allowunsyncedmining" description:"Allow block templates to be generated even when the chain is not considered synced on networks other than the main network. This is automatically enabled when the simnet option is set. Don't do this unless you know what you're doing"`
// Indexing options.
TxIndex bool `long:"txindex" description:"Maintain a full hash-based transaction index which makes all transactions available via the getrawtransaction RPC"`
DropTxIndex bool `long:"droptxindex" description:"Deletes the hash-based transaction index from the database on start up and then exits"`
NoExistsAddrIndex bool `long:"noexistsaddrindex" description:"Disable the exists address index, which tracks whether or not an address has even been used"`
DropExistsAddrIndex bool `long:"dropexistsaddrindex" description:"Deletes the exists address index from the database on start up and then exits"`
// IPC options.
PipeRx uint `long:"piperx" description:"File descriptor of read end pipe to enable parent -> child process communication"`
PipeTx uint `long:"pipetx" description:"File descriptor of write end pipe to enable parent <- child process communication"`
LifetimeEvents bool `long:"lifetimeevents" description:"Send lifetime notifications over the TX pipe"`
BoundAddrEvents bool `long:"boundaddrevents" description:"Send notifications with the locally bound addresses of the P2P and RPC subsystems over the TX pipe"`
// Cooked options ready for use.
onionlookup func(string) ([]net.IP, error)
lookup func(string) ([]net.IP, error)
oniondial func(context.Context, string, string) (net.Conn, error)
dial func(context.Context, string, string) (net.Conn, error)
miningAddrs []stdaddr.Address
minRelayTxFee dcrutil.Amount
whitelists []*net.IPNet
ipv4NetInfo types.NetworksResult
ipv6NetInfo types.NetworksResult
onionNetInfo types.NetworksResult
params *params
}
// serviceOptions defines the configuration options for the daemon as a service on
// Windows.
type serviceOptions struct {
ServiceCommand string `short:"s" long:"service" description:"Service command {install, remove, start, stop}"`
}
// cleanAndExpandPath expands environment variables and leading ~ in the
// passed path, cleans the result, and returns it.
func cleanAndExpandPath(path string) string {
// Nothing to do when no path is given.
if path == "" {
return path
}
// NOTE: The os.ExpandEnv doesn't work with Windows cmd.exe-style
// %VARIABLE%, but the variables can still be expanded via POSIX-style
// $VARIABLE.
path = os.ExpandEnv(path)
if !strings.HasPrefix(path, "~") {
return filepath.Clean(path)
}
// Expand initial ~ to the current user's home directory, or ~otheruser
// to otheruser's home directory. On Windows, both forward and backward
// slashes can be used.
path = path[1:]
var pathSeparators string
if runtime.GOOS == "windows" {
pathSeparators = string(os.PathSeparator) + "/"
} else {
pathSeparators = string(os.PathSeparator)
}
userName := ""
if i := strings.IndexAny(path, pathSeparators); i != -1 {
userName = path[:i]
path = path[i:]
}
homeDir := ""
var u *user.User
var err error
if userName == "" {
u, err = user.Current()
} else {
u, err = user.Lookup(userName)
}
if err == nil {
homeDir = u.HomeDir
}
// Fallback to CWD if user lookup fails or user has no home directory.
if homeDir == "" {
homeDir = "."
}
return filepath.Join(homeDir, path)
}
// 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 subsystems 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 delimiters, 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 subsystems %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
}
// validDbType returns whether or not dbType is a supported database type.
func validDbType(dbType string) bool {
for _, knownType := range knownDbTypes {
if dbType == knownType {
return true
}
}
return false
}
// 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
}
const (
normalizeInterfaceAddrs = 1 << iota
normalizeInterfaceFirstAddr
)
// normalizeAddresses returns a new slice with all the passed peer addresses
// normalized with the given default port, and all duplicates removed.
//
// If an address is an interface name, and the flags has the
// normalizeInterfaceAddrs bit set, all IP addresses associated with the
// interface will appear in the result. If the normalizeInterfaceFirstAddr
// bit is set, only the first address of the interface is included.
func normalizeAddresses(addrs []string, defaultPort string, flags int) []string {
norm := make([]string, 0, len(addrs))
for _, addr := range addrs {
port := defaultPort
if a, p, err := net.SplitHostPort(addr); err == nil {
addr = a
port = p
}
var iface *net.Interface
if flags != 0 {
iface, _ = net.InterfaceByName(addr)
}
if iface == nil {
norm = append(norm, net.JoinHostPort(addr, port))
continue
}
ifaceAddrs, err := iface.Addrs()
if err != nil {
continue
}
IfaceAddrs:
for _, a := range ifaceAddrs {
if a, ok := a.(*net.IPNet); ok {
lis := a.IP.String()
if a.IP.To4() == nil { // IPv6
zoned := a.IP.IsLinkLocalUnicast() ||
a.IP.IsLinkLocalMulticast()
if zoned {
lis += "%" + strconv.Itoa(iface.Index)
}
}
norm = append(norm, net.JoinHostPort(
lis, port))
if flags&normalizeInterfaceFirstAddr != 0 {
break IfaceAddrs
}
}
}
}
return removeDuplicateAddresses(norm)
}
// fileExists reports whether the named file or directory exists.
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// newConfigParser returns a new command line flags parser.
func newConfigParser(cfg *config, so *serviceOptions, options flags.Options) *flags.Parser {
parser := flags.NewParser(cfg, options)
if runtime.GOOS == "windows" {
parser.AddGroup("Service Options", "Service Options", so)
}
return parser
}
// createDefaultConfig copies the file sample-dcrd.conf to the given destination path,
// and populates it with some randomly generated RPC username and password.
func createDefaultConfigFile(destPath string, authType string) error {
// Create the destination directory if it does not exist.
err := os.MkdirAll(filepath.Dir(destPath), 0700)
if err != nil {
return err
}
cfg := sampleconfig.Dcrd()
// Set a randomized rpcuser and rpcpass if the authorization type is basic.
if authType == authTypeBasic {
// Generate a random user and password for the RPC server credentials.
randomBytes := make([]byte, 20)
_, err = rand.Read(randomBytes)
if err != nil {
return err
}
generatedRPCUser := base64.StdEncoding.EncodeToString(randomBytes)
rpcUserLine := fmt.Sprintf("rpcuser=%v", generatedRPCUser)
_, err = rand.Read(randomBytes)
if err != nil {
return err
}
generatedRPCPass := base64.StdEncoding.EncodeToString(randomBytes)
rpcPassLine := fmt.Sprintf("rpcpass=%v", generatedRPCPass)
// Replace the rpcuser and rpcpass lines in the sample configuration
// file contents with their generated values.
rpcUserRE := regexp.MustCompile(`(?m)^;\s*rpcuser=[^\s]*$`)
rpcPassRE := regexp.MustCompile(`(?m)^;\s*rpcpass=[^\s]*$`)
updatedCfg := rpcUserRE.ReplaceAllString(cfg, rpcUserLine)
updatedCfg = rpcPassRE.ReplaceAllString(updatedCfg, rpcPassLine)
cfg = updatedCfg
}
// Create config file at the provided path.
dest, err := os.OpenFile(destPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer dest.Close()
_, err = dest.WriteString(cfg)
return err
}
// generateNetworkInfo is a convenience function that creates a slice from the
// available networks.
func (cfg *config) generateNetworkInfo() []types.NetworksResult {
return []types.NetworksResult{cfg.ipv4NetInfo, cfg.ipv6NetInfo,
cfg.onionNetInfo}
}
// parseNetworkInterfaces updates all network interface states based on the
// provided configuration.
func parseNetworkInterfaces(cfg *config) error {
var v4Addrs, v6Addrs uint32
listeners, err := parseListeners(cfg.Listeners)
if err != nil {
return err
}
for _, addr := range listeners {
if addr.Network() == "tcp4" {
v4Addrs++
continue
}
if addr.Network() == "tcp6" {
v6Addrs++
}
}
// Set IPV4 interface state.
if v4Addrs > 0 {
ipv4 := &cfg.ipv4NetInfo
ipv4.Reachable = !cfg.DisableListen
ipv4.Limited = v6Addrs == 0
ipv4.Proxy = cfg.Proxy
}
// Set IPV6 interface state.
if v6Addrs > 0 {
ipv6 := &cfg.ipv6NetInfo
ipv6.Reachable = !cfg.DisableListen
ipv6.Limited = v4Addrs == 0
ipv6.Proxy = cfg.Proxy
}
// Set Onion interface state.
if v6Addrs > 0 && (cfg.Proxy != "" || cfg.OnionProxy != "") {
onion := &cfg.onionNetInfo
onion.Reachable = !cfg.DisableListen && !cfg.NoOnion
onion.Limited = v4Addrs == 0
onion.Proxy = cfg.Proxy
if cfg.OnionProxy != "" {
onion.Proxy = cfg.OnionProxy
}
onion.ProxyRandomizeCredentials = cfg.TorIsolation
}
return nil
}
// errSuppressUsage signifies that an error that happened during the initial
// configuration phase should suppress the usage output since it was not caused
// by the user.
type errSuppressUsage string
// Error implements the error interface.
func (e errSuppressUsage) Error() string {
return string(e)
}
// 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. Check if help has been requested, print it and exit if so
// 3. Pre-parse the command line to check for an alternative config file
// 4. Load configuration file overwriting defaults with any specified options
// 5. Parse CLI options and overwrite/add any specified options
//
// The above results in dcrd 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(appName string) (*config, []string, error) {
// Default config.
cfg := config{
// General application behavior.
HomeDir: defaultHomeDir,
ConfigFile: defaultConfigFile,
DataDir: defaultDataDir,
LogDir: defaultLogDir,
LogSize: defaultLogSize,
DbType: defaultDbType,
DebugLevel: defaultLogLevel,
SigCacheMaxSize: defaultSigCacheMaxSize,
UtxoCacheMaxSize: defaultUtxoCacheMaxSize,
// RPC server options and policy.
RPCCert: defaultRPCCertFile,
RPCKey: defaultRPCKeyFile,
RPCAuthType: defaultRPCAuthType,
RPCClientCAs: defaultRPCClientCAs,
TLSCurve: defaultTLSCurve,
RPCMaxClients: defaultMaxRPCClients,
RPCMaxWebsockets: defaultMaxRPCWebsockets,
RPCMaxConcurrentReqs: defaultMaxRPCConcurrentReqs,
// P2P network options.
MaxSameIP: defaultMaxSameIP,
MaxPeers: defaultMaxPeers,
DialTimeout: defaultDialTimeout,
PeerIdleTimeout: defaultPeerIdleTimeout,
// Banning options.
BanDuration: defaultBanDuration,
BanThreshold: defaultBanThreshold,
// Relay and mempool policy.
MinRelayTxFee: mempool.DefaultMinRelayTxFee.ToCoin(),
MaxOrphanTxs: defaultMaxOrphanTransactions,
AllowOldVotes: defaultAllowOldVotes,
// Mining options and policy.
Generate: defaultGenerate,
BlockMaxSize: defaultBlockMaxSize,
NoMiningStateSync: defaultNoMiningStateSync,
AllowUnsyncedMining: defaultAllowUnsyncedMining,
// Indexing options.
TxIndex: defaultTxIndex,
NoExistsAddrIndex: defaultNoExistsAddrIndex,
// Cooked options ready for use.
ipv4NetInfo: types.NetworksResult{Name: "IPV4"},
ipv6NetInfo: types.NetworksResult{Name: "IPV6"},
onionNetInfo: types.NetworksResult{Name: "Onion"},
params: &mainNetParams,
}
// Pre-parse the command line options looking only for the help option. If
// found, print the help message to stdout and exit.
helpOpts := flags.Options(flags.HelpFlag | flags.PrintErrors | flags.IgnoreUnknown)
_, err := flags.NewParser(&cfg, helpOpts).Parse()
if flags.WroteHelp(err) {
os.Exit(0)
}
// Service options which are only added on Windows.
serviceOpts := serviceOptions{}
// Pre-parse the command line options to see if an alternative config file
// or the version flag was specified. Any errors can be ignored here since
// they will be caught by the final parse below.
preCfg := cfg
preParser := newConfigParser(&preCfg, &serviceOpts, flags.None)
_, _ = preParser.Parse()
// Show the version and exit if the version flag was specified.
if preCfg.ShowVersion {
fmt.Printf("%s version %s (Go version %s %s/%s)\n", appName,
version.String(), runtime.Version(), runtime.GOOS, runtime.GOARCH)
os.Exit(0)
}
// Perform service command and exit if specified. Invalid service
// commands show an appropriate error. Only runs on Windows since
// the runServiceCommand function will be nil when not on Windows.
if serviceOpts.ServiceCommand != "" && runServiceCommand != nil {
err := runServiceCommand(serviceOpts.ServiceCommand)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
os.Exit(0)
}
// Update the home directory for dcrd if specified. Since the home
// directory is updated, other variables need to be updated to
// reflect the new changes.
if preCfg.HomeDir != "" {
cfg.HomeDir, _ = filepath.Abs(preCfg.HomeDir)
if preCfg.ConfigFile == defaultConfigFile {
defaultConfigFile = filepath.Join(cfg.HomeDir,
defaultConfigFilename)
preCfg.ConfigFile = defaultConfigFile
cfg.ConfigFile = defaultConfigFile
} else {
cfg.ConfigFile = preCfg.ConfigFile
}
if preCfg.DataDir == defaultDataDir {
cfg.DataDir = filepath.Join(cfg.HomeDir, defaultDataDirname)
} else {
cfg.DataDir = preCfg.DataDir
}
if preCfg.RPCKey == defaultRPCKeyFile {
cfg.RPCKey = filepath.Join(cfg.HomeDir, "rpc.key")
} else {
cfg.RPCKey = preCfg.RPCKey
}
if preCfg.RPCCert == defaultRPCCertFile {
cfg.RPCCert = filepath.Join(cfg.HomeDir, "rpc.cert")
} else {
cfg.RPCCert = preCfg.RPCCert
}
if preCfg.RPCClientCAs == defaultRPCClientCAs {
cfg.RPCClientCAs = filepath.Join(cfg.HomeDir, "clients.pem")
} else {
cfg.RPCClientCAs = preCfg.RPCClientCAs
}
if preCfg.LogDir == defaultLogDir {
cfg.LogDir = filepath.Join(cfg.HomeDir, defaultLogDirname)
} else {
cfg.LogDir = preCfg.LogDir
}
}
// Create a default config file when one does not exist and the user did
// not specify an override.
if !(preCfg.SimNet || preCfg.RegNet) && preCfg.ConfigFile ==
defaultConfigFile && !fileExists(preCfg.ConfigFile) {
err := createDefaultConfigFile(preCfg.ConfigFile, preCfg.RPCAuthType)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating a default "+
"config file: %v\n", err)
}
}
// Load additional config from file.
var configFileError error
parser := newConfigParser(&cfg, &serviceOpts, flags.PassDoubleDash)
if !(cfg.SimNet || cfg.RegNet) || preCfg.ConfigFile != defaultConfigFile {
err := flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile)
if err != nil {
var e *os.PathError
if !errors.As(err, &e) {
err = fmt.Errorf("Error parsing config file: %w", err)
return nil, nil, err
}
configFileError = err
}
}
// Don't add peers from the config file when in regression test mode.
if preCfg.RegNet && len(cfg.AddPeers) > 0 {
cfg.AddPeers = nil
}
// Parse command line options again to ensure they take precedence.
remainingArgs, err := parser.Parse()
if err != nil {
return nil, nil, err
}
// Create the home directory if it doesn't already exist.
funcName := "loadConfig"
err = os.MkdirAll(cfg.HomeDir, 0700)
if err != nil {
// Show a nicer error message if it's because a symlink is
// linked to a directory that does not exist (probably because
// it's not mounted).
var e *os.PathError
if errors.As(err, &e) && os.IsExist(err) {
if link, lerr := os.Readlink(e.Path); lerr == nil {
str := "is symlink %s -> %s mounted?"
err = fmt.Errorf(str, e.Path, link)
}
}
str := "%s: failed to create home directory: %s"
err := errSuppressUsage(fmt.Sprintf(str, funcName, err))
return nil, nil, err
}
if cfg.DisableDNSSeed {
cfg.DisableSeeders = true
fmt.Fprintln(os.Stderr, "The --nodnsseed option is deprecated: use "+
"--noseeders")
}
// Multiple networks can't be selected simultaneously. Count number of
// network flags passed and assign active network params.
numNets := 0
if cfg.TestNet {
numNets++
cfg.params = &testNet3Params
}
if cfg.SimNet {
numNets++
// Also disable dns seeding on the simulation test network.
cfg.params = &simNetParams
cfg.DisableSeeders = true
}
if cfg.RegNet {
numNets++
cfg.params = ®NetParams
}
if numNets > 1 {
str := "%s: the testnet, regnet, and simnet params can't be " +
"used together -- choose one of the three"
err := fmt.Errorf(str, funcName)
return nil, nil, err
}
// Warn on use of deprecated option to modify the rate limit of low-fee/free
// transaction rate limiting.
if cfg.FreeTxRelayLimit != 0 {
fmt.Fprintln(os.Stderr, "The --limitfreerelay option is deprecated "+
"and will be removed in a future version of the software: please "+
"remove it from your config")
}
// Warn on use of deprecated option to disable relaying of low-fee/free
// transactions.
if cfg.NoRelayPriority {
fmt.Fprintln(os.Stderr, "The --norelaypriority option is deprecated "+
"and will be removed in a future version of the software: please "+
"remove it from your config")
}
// Set the default policy for relaying non-standard transactions
// according to the default of the active network. The set
// configuration value takes precedence over the default value for the
// selected network.
acceptNonStd := cfg.params.AcceptNonStdTxs
switch {
case cfg.AcceptNonStd && cfg.RejectNonStd:
str := "%s: rejectnonstd and acceptnonstd cannot be used " +
"together -- choose only one"
err := fmt.Errorf(str, funcName)
return nil, nil, err
case cfg.RejectNonStd:
acceptNonStd = false
case cfg.AcceptNonStd:
acceptNonStd = true
}
cfg.AcceptNonStd = acceptNonStd
// Append the network type to the data directory so it is "namespaced"
// per network. In addition to the block database, there are other
// pieces of data that are saved to disk such as address manager state.
// All data is specific to a network, so namespacing the data directory
// means each individual piece of serialized data does not have to
// worry about changing names per network and such.
//
// Make list of old versions of testnet directories here since the
// network specific DataDir will be used after this.
cfg.DataDir = cleanAndExpandPath(cfg.DataDir)
var oldTestNets []string
oldTestNets = append(oldTestNets, filepath.Join(cfg.DataDir, "testnet"))
oldTestNets = append(oldTestNets, filepath.Join(cfg.DataDir, "testnet2"))
cfg.DataDir = filepath.Join(cfg.DataDir, cfg.params.Name)
logRotator = nil
if !cfg.NoFileLogging {
// Append the network type to the log directory so it is "namespaced"
// per network in the same fashion as the data directory.
cfg.LogDir = cleanAndExpandPath(cfg.LogDir)
cfg.LogDir = filepath.Join(cfg.LogDir, cfg.params.Name)
var units int
for i, r := range cfg.LogSize {
if r < '0' || r > '9' {
units = i
break
}
}
invalidSize := func() (*config, []string, error) {
str := "%s: Invalid logsize: %v "
err := fmt.Errorf(str, funcName, cfg.LogSize)
return nil, nil, err
}
if units == 0 {
return invalidSize()
}
// Parsing a 32-bit number prevents 64-bit overflow after unit
// multiplication.
logsize, err := strconv.ParseInt(cfg.LogSize[:units], 10, 32)
if err != nil {
return invalidSize()
}
switch cfg.LogSize[units:] {
case "k", "K", "KiB":
case "m", "M", "MiB":
logsize <<= 10
case "g", "G", "GiB":
logsize <<= 20
default:
return invalidSize()
}
// Initialize log rotation. After log rotation has been initialized, the
// logger variables may be used.
initLogRotator(filepath.Join(cfg.LogDir, defaultLogFilename), logsize)
}
// Special show command to list supported subsystems and exit.
if cfg.DebugLevel == "show" {
fmt.Println("Supported subsystems", supportedSubsystems())
os.Exit(0)
}
// Parse, validate, and set debug log level(s).
if err := parseAndSetDebugLevels(cfg.DebugLevel); err != nil {
err := fmt.Errorf("%s: %w", funcName, err)
return nil, nil, err
}
// Validate database type.
if !validDbType(cfg.DbType) {
str := "%s: the specified database type [%v] is invalid -- " +
"supported types %v"
err := fmt.Errorf(str, funcName, cfg.DbType, knownDbTypes)
return nil, nil, err
}
// Enforce the minimum and maximum utxo cache max size.
if cfg.UtxoCacheMaxSize < minUtxoCacheMaxSize {
cfg.UtxoCacheMaxSize = minUtxoCacheMaxSize
} else if cfg.UtxoCacheMaxSize > maxUtxoCacheMaxSize {
cfg.UtxoCacheMaxSize = maxUtxoCacheMaxSize
}
// Validate format of profile address. It may either be an address:port or
// just a port. The port also must be between 1024 and 65535.
if cfg.Profile != "" {
cfg.Profile = portToLocalHostAddr(cfg.Profile)
if err := validateProfileAddr(cfg.Profile); err != nil {
str := "%s: profile: %w"
err := fmt.Errorf(str, funcName, err)
return nil, nil, err
}
}
// Don't allow ban durations that are too short.
if cfg.BanDuration < time.Second {
str := "%s: the banduration option may not be less than 1s -- parsed [%v]"
err := fmt.Errorf(str, funcName, cfg.BanDuration)
return nil, nil, err
}
// Don't allow dialtimeout durations that are too short.
if cfg.DialTimeout < time.Second {
str := "%s: the dialtimeout option may not be less than 1s -- parsed [%v]"
err := fmt.Errorf(str, funcName, cfg.DialTimeout)
return nil, nil, err
}
// Don't allow peeridletimeout durations that are too short.
if cfg.PeerIdleTimeout < time.Second*15 {
str := "%s: the peeridletimeout option may not be less " +
"than 15s -- parsed [%v]"
err := fmt.Errorf(str, funcName, cfg.PeerIdleTimeout)
return nil, nil, err
}
// Validate any given whitelisted IP addresses and networks.
if len(cfg.Whitelists) > 0 {
var ip net.IP
cfg.whitelists = make([]*net.IPNet, 0, len(cfg.Whitelists))
for _, addr := range cfg.Whitelists {
_, ipnet, err := net.ParseCIDR(addr)
if err != nil {
ip = net.ParseIP(addr)
if ip == nil {
str := "%s: the whitelist value of '%s' is invalid"
err = fmt.Errorf(str, funcName, addr)
return nil, nil, err
}
var bits int
if ip.To4() == nil {
// IPv6
bits = 128
} else {
bits = 32
}
ipnet = &net.IPNet{
IP: ip,
Mask: net.CIDRMask(bits, bits),
}
}
cfg.whitelists = append(cfg.whitelists, ipnet)
}
}
// --addPeer and --connect do not mix.
if len(cfg.AddPeers) > 0 && len(cfg.ConnectPeers) > 0 {
str := "%s: the --addpeer and --connect options can not be " +
"mixed"