2015-08-26 04:03:18 +00:00
// Copyright (c) 2013-2016 The btcsuite developers
main: Update to use all new major module versions.
This updates all code in the main module to use the latest major modules
versions to pull in the latest updates.
A more general high level overview of the changes is provided below,
however, there is one semantic change worth calling out independently.
The verifymessage RPC will now return an error when provided with
an address that is not for the current active network and the RPC server
version has been bumped accordingly.
Previously, it would return false which indicated the signature is
invalid, even when the provided signature was actually valid for the
other network. Said behavior was not really incorrect since the
address, signature, and message combination is in fact invalid for the
current active network, however, that result could be somewhat
misleading since a false result could easily be interpreted to mean the
signature is actually invalid altogether which is distinct from the case
of the address being for a different network. Therefore, it is
preferable to explicitly return an error in the case of an address on
the wrong network to cleanly separate these cases.
The following is a high level overview of the changes:
- Replace all calls to removed blockchain merkle root, pow, subsidy, and
coinbase funcs with their standalone module equivalents
- Introduce a new local func named calcTxTreeMerkleRoot that accepts
dcrutil.Tx as before and defers to the new standalone func
- Update block locator handling to match the new signature required by
the peer/v2 module
- Introduce a new local func named chainBlockLocatorToHashes which
performs the necessary conversion
- Update all references to old v1 chaincfg params global instances to
use the new v2 functions
- Modify all cases that parse addresses to provide the now required
current network params
- Include address params with the wsClientFilter
- Replace removed v1 chaincfg constants with local constants
- Create subsidy cache during server init and pass it to the relevant
subsystems
- blockManagerConfig
- BlkTmplGenerator
- rpcServer
- VotingWallet
- Update mining code that creates the block one coinbase transaction to
create the output scripts as defined in the v2 params
- Replace old v2 dcrjson constant references with new types module
- Fix various comment typos
- Update fees module to use the latest major module versions and bump it v2
2019-08-13 15:50:53 +00:00
// Copyright (c) 2015-2019 The Decred developers
2013-08-06 21:55:22 +00:00
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
2016-07-15 18:09:42 +00:00
"crypto/rand"
"encoding/base64"
2013-12-17 15:10:59 +00:00
"errors"
2013-08-06 21:55:22 +00:00
"fmt"
"net"
"os"
2018-02-16 16:39:31 +00:00
"os/user"
2013-08-06 21:55:22 +00:00
"path/filepath"
2017-08-07 02:44:24 +00:00
"regexp"
2013-11-20 15:35:14 +00:00
"runtime"
2013-11-21 23:03:01 +00:00
"sort"
2013-09-17 21:40:27 +00:00
"strconv"
2013-08-07 23:53:01 +00:00
"strings"
2013-08-06 21:55:22 +00:00
"time"
2014-07-02 13:50:08 +00:00
main: Update to use all new major module versions.
This updates all code in the main module to use the latest major modules
versions to pull in the latest updates.
A more general high level overview of the changes is provided below,
however, there is one semantic change worth calling out independently.
The verifymessage RPC will now return an error when provided with
an address that is not for the current active network and the RPC server
version has been bumped accordingly.
Previously, it would return false which indicated the signature is
invalid, even when the provided signature was actually valid for the
other network. Said behavior was not really incorrect since the
address, signature, and message combination is in fact invalid for the
current active network, however, that result could be somewhat
misleading since a false result could easily be interpreted to mean the
signature is actually invalid altogether which is distinct from the case
of the address being for a different network. Therefore, it is
preferable to explicitly return an error in the case of an address on
the wrong network to cleanly separate these cases.
The following is a high level overview of the changes:
- Replace all calls to removed blockchain merkle root, pow, subsidy, and
coinbase funcs with their standalone module equivalents
- Introduce a new local func named calcTxTreeMerkleRoot that accepts
dcrutil.Tx as before and defers to the new standalone func
- Update block locator handling to match the new signature required by
the peer/v2 module
- Introduce a new local func named chainBlockLocatorToHashes which
performs the necessary conversion
- Update all references to old v1 chaincfg params global instances to
use the new v2 functions
- Modify all cases that parse addresses to provide the now required
current network params
- Include address params with the wsClientFilter
- Replace removed v1 chaincfg constants with local constants
- Create subsidy cache during server init and pass it to the relevant
subsystems
- blockManagerConfig
- BlkTmplGenerator
- rpcServer
- VotingWallet
- Update mining code that creates the block one coinbase transaction to
create the output scripts as defined in the v2 params
- Replace old v2 dcrjson constant references with new types module
- Fix various comment typos
- Update fees module to use the latest major module versions and bump it v2
2019-08-13 15:50:53 +00:00
"github.com/decred/dcrd/connmgr/v2"
"github.com/decred/dcrd/database/v2"
_ "github.com/decred/dcrd/database/v2/ffldb"
"github.com/decred/dcrd/dcrutil/v2"
2018-09-04 20:51:07 +00:00
"github.com/decred/dcrd/internal/version"
main: Update to use all new major module versions.
This updates all code in the main module to use the latest major modules
versions to pull in the latest updates.
A more general high level overview of the changes is provided below,
however, there is one semantic change worth calling out independently.
The verifymessage RPC will now return an error when provided with
an address that is not for the current active network and the RPC server
version has been bumped accordingly.
Previously, it would return false which indicated the signature is
invalid, even when the provided signature was actually valid for the
other network. Said behavior was not really incorrect since the
address, signature, and message combination is in fact invalid for the
current active network, however, that result could be somewhat
misleading since a false result could easily be interpreted to mean the
signature is actually invalid altogether which is distinct from the case
of the address being for a different network. Therefore, it is
preferable to explicitly return an error in the case of an address on
the wrong network to cleanly separate these cases.
The following is a high level overview of the changes:
- Replace all calls to removed blockchain merkle root, pow, subsidy, and
coinbase funcs with their standalone module equivalents
- Introduce a new local func named calcTxTreeMerkleRoot that accepts
dcrutil.Tx as before and defers to the new standalone func
- Update block locator handling to match the new signature required by
the peer/v2 module
- Introduce a new local func named chainBlockLocatorToHashes which
performs the necessary conversion
- Update all references to old v1 chaincfg params global instances to
use the new v2 functions
- Modify all cases that parse addresses to provide the now required
current network params
- Include address params with the wsClientFilter
- Replace removed v1 chaincfg constants with local constants
- Create subsidy cache during server init and pass it to the relevant
subsystems
- blockManagerConfig
- BlkTmplGenerator
- rpcServer
- VotingWallet
- Update mining code that creates the block one coinbase transaction to
create the output scripts as defined in the v2 params
- Replace old v2 dcrjson constant references with new types module
- Fix various comment typos
- Update fees module to use the latest major module versions and bump it v2
2019-08-13 15:50:53 +00:00
"github.com/decred/dcrd/mempool/v3"
2019-09-05 12:11:00 +00:00
"github.com/decred/dcrd/rpc/jsonrpc/types/v2"
2017-08-25 15:32:26 +00:00
"github.com/decred/dcrd/sampleconfig"
2019-07-21 02:05:48 +00:00
"github.com/decred/go-socks/socks"
2018-05-23 19:18:18 +00:00
"github.com/decred/slog"
2017-08-24 22:56:58 +00:00
flags "github.com/jessevdk/go-flags"
2013-08-06 21:55:22 +00:00
)
const (
2016-06-01 19:58:23 +00:00
defaultConfigFilename = "dcrd.conf"
2016-04-11 21:37:52 +00:00
defaultDataDirname = "data"
defaultLogLevel = "info"
defaultLogDirname = "logs"
2016-06-01 19:58:23 +00:00
defaultLogFilename = "dcrd.log"
2018-11-07 00:05:28 +00:00
defaultMaxSameIP = 5
2016-04-11 21:37:52 +00:00
defaultMaxPeers = 125
defaultBanDuration = time . Hour * 24
defaultBanThreshold = 100
defaultMaxRPCClients = 10
defaultMaxRPCWebsockets = 25
2016-04-25 22:51:42 +00:00
defaultMaxRPCConcurrentReqs = 20
2015-08-26 04:03:18 +00:00
defaultDbType = "ffldb"
2016-04-11 21:37:52 +00:00
defaultFreeTxRelayLimit = 15.0
defaultBlockMinSize = 0
2016-06-01 19:58:23 +00:00
defaultBlockMaxSize = 375000
2016-04-11 21:37:52 +00:00
blockMaxSizeMin = 1000
defaultAddrIndex = false
2015-08-26 04:03:18 +00:00
defaultGenerate = false
2016-06-01 19:58:23 +00:00
defaultNoMiningStateSync = false
defaultAllowOldVotes = false
2016-04-11 21:37:52 +00:00
defaultMaxOrphanTransactions = 1000
defaultMaxOrphanTxSize = 5000
2016-04-14 02:56:10 +00:00
defaultSigCacheMaxSize = 100000
2016-02-19 04:51:18 +00:00
defaultTxIndex = false
defaultNoExistsAddrIndex = false
2017-11-08 21:48:44 +00:00
defaultNoCFilters = false
2013-08-06 21:55:22 +00:00
)
var (
2016-09-26 16:59:04 +00:00
defaultHomeDir = dcrutil . AppDataDir ( "dcrd" , false )
defaultConfigFile = filepath . Join ( defaultHomeDir , defaultConfigFilename )
defaultDataDir = filepath . Join ( defaultHomeDir , defaultDataDirname )
2015-08-26 04:03:18 +00:00
knownDbTypes = database . SupportedDrivers ( )
2016-09-26 16:59:04 +00:00
defaultRPCKeyFile = filepath . Join ( defaultHomeDir , "rpc.key" )
defaultRPCCertFile = filepath . Join ( defaultHomeDir , "rpc.cert" )
defaultLogDir = filepath . Join ( defaultHomeDir , defaultLogDirname )
2018-10-11 05:45:24 +00:00
defaultAltDNSNames = [ ] string ( nil )
2013-08-06 21:55:22 +00:00
)
2013-11-26 02:58:18 +00:00
// 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
peer: Refactor peer code into its own package.
This commit introduces package peer which contains peer related features
refactored from peer.go.
The following is an overview of the features the package provides:
- Provides a basic concurrent safe bitcoin peer for handling bitcoin
communications via the peer-to-peer protocol
- Full duplex reading and writing of bitcoin protocol messages
- Automatic handling of the initial handshake process including protocol
version negotiation
- Automatic periodic keep-alive pinging and pong responses
- Asynchronous message queueing of outbound messages with optional
channel for notification when the message is actually sent
- Inventory message batching and send trickling with known inventory
detection and avoidance
- Ability to wait for shutdown/disconnect
- Flexible peer configuration
- Caller is responsible for creating outgoing connections and listening
for incoming connections so they have flexibility to establish
connections as they see fit (proxies, etc.)
- User agent name and version
- Bitcoin network
- Service support signalling (full nodes, bloom filters, etc.)
- Maximum supported protocol version
- Ability to register callbacks for handling bitcoin protocol messages
- Proper handling of bloom filter related commands when the caller does
not specify the related flag to signal support
- Disconnects the peer when the protocol version is high enough
- Does not invoke the related callbacks for older protocol versions
- Snapshottable peer statistics such as the total number of bytes read
and written, the remote address, user agent, and negotiated protocol
version
- Helper functions for pushing addresses, getblocks, getheaders, and
reject messages
- These could all be sent manually via the standard message output
function, but the helpers provide additional nice functionality such
as duplicate filtering and address randomization
- Full documentation with example usage
- Test coverage
In addition to the addition of the new package, btcd has been refactored
to make use of the new package by extending the basic peer it provides to
work with the blockmanager and server to act as a full node. The
following is a broad overview of the changes to integrate the package:
- The server is responsible for all connection management including
persistent peers and banning
- Callbacks for all messages that are required to implement a full node
are registered
- Logic necessary to serve data and behave as a full node is now in the
callback registered with the peer
Finally, the following peer-related things have been improved as a part
of this refactor:
- Don't log or send reject message due to peer disconnects
- Remove trace logs that aren't particularly helpful
- Finish an old TODO to switch the queue WaitGroup over to a channel
- Improve various comments and fix some code consistency cases
- Improve a few logging bits
- Implement a most-recently-used nonce tracking for detecting self
connections and generate a unique nonce for each peer
2015-10-02 06:03:20 +00:00
// minUint32 is a helper function to return the minimum of two uint32s.
// This avoids a math import and the need to cast to floats.
func minUint32 ( a , b uint32 ) uint32 {
if a < b {
return a
}
return b
}
2016-01-20 21:46:42 +00:00
// config defines the configuration options for dcrd.
2013-08-06 21:55:22 +00:00
//
// See loadConfig for details on the configuration load process.
type config struct {
2016-04-25 22:51:42 +00:00
HomeDir string ` short:"A" long:"appdata" description:"Path to application home directory" `
ShowVersion bool ` short:"V" long:"version" description:"Display version information and exit" `
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." `
2017-09-30 13:10:14 +00:00
NoFileLogging bool ` long:"nofilelogging" description:"Disable file logging." `
2016-04-25 22:51:42 +00:00
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)" `
2018-11-07 00:05:28 +00:00
MaxSameIP int ` long:"maxsameip" description:"Max number of connections with the same IP -- 0 to disable" `
2016-04-25 22:51:42 +00:00
MaxPeers int ` long:"maxpeers" description:"Max number of inbound and outbound peers" `
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." `
2017-07-24 19:39:23 +00:00
Whitelists [ ] string ` long:"whitelist" description:"Add an IP network or IP that will not be banned. (eg. 192.168.1.0/24 or ::1)" `
2016-04-25 22:51:42 +00:00
RPCUser string ` short:"u" long:"rpcuser" description:"Username for RPC connections" `
RPCPass string ` short:"P" long:"rpcpass" default-mask:"-" description:"Password for RPC connections" `
RPCLimitUser string ` long:"rpclimituser" description:"Username for limited RPC connections" `
RPCLimitPass string ` long:"rpclimitpass" default-mask:"-" description:"Password for limited RPC connections" `
RPCListeners [ ] string ` long:"rpclisten" description:"Add an interface/port to listen for RPC connections (default port: 9109, testnet: 19109)" `
RPCCert string ` long:"rpccert" description:"File containing the certificate file" `
RPCKey string ` long:"rpckey" description:"File containing the certificate key" `
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" `
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" `
DisableTLS bool ` long:"notls" description:"Disable TLS for the RPC server -- NOTE: This is only allowed if the RPC server is bound to localhost" `
DisableDNSSeed bool ` long:"nodnsseed" description:"Disable DNS seeding for peers" `
ExternalIPs [ ] string ` long:"externalip" description:"Add an ip to the list of local addresses we claim to listen on to peers" `
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" `
2019-08-14 11:43:31 +00:00
NoDiscoverIP bool ` long:"nodiscoverip" description:"Disable automatic network address discovery" `
2016-04-25 22:51:42 +00:00
TorIsolation bool ` long:"torisolation" description:"Enable Tor stream isolation by randomizing user credentials for each connection." `
TestNet bool ` long:"testnet" description:"Use the test network" `
SimNet bool ` long:"simnet" description:"Use the simulation test network" `
multi: Resurrect regression network.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
2018-10-05 04:46:56 +00:00
RegNet bool ` long:"regnet" description:"Use the regression test network" `
2016-04-25 22:51:42 +00:00
DisableCheckpoints bool ` long:"nocheckpoints" description:"Disable built-in checkpoints. Don't do this unless you know what you're doing." `
DbType string ` long:"dbtype" description:"Database backend to use for the Block Chain" `
2017-09-05 04:59:38 +00:00
Profile string ` long:"profile" description:"Enable HTTP profiling on given [addr:]port -- NOTE port must be between 1024 and 65536" `
2016-04-25 22:51:42 +00:00
CPUProfile string ` long:"cpuprofile" description:"Write CPU profile to the specified file" `
MemProfile string ` long:"memprofile" description:"Write mem profile to the specified file" `
DumpBlockchain string ` long:"dumpblockchain" description:"Write blockchain as a flat file of blocks for use with addblock, to the specified filename" `
MiningTimeOffset int ` long:"miningtimeoffset" description:"Offset the mining timestamp of a block by this many seconds (positive values are in the past)" `
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" `
Upnp bool ` long:"upnp" description:"Use UPnP to map our listening port outside of NAT" `
MinRelayTxFee float64 ` long:"minrelaytxfee" description:"The minimum transaction fee in DCR/kB to be considered a non-zero fee." `
FreeTxRelayLimit float64 ` long:"limitfreerelay" description:"Limit relay of transactions with no transaction fee to the given amount in thousands of bytes per minute" `
NoRelayPriority bool ` long:"norelaypriority" description:"Do not require free or low-fee transactions to have high priority for relaying" `
MaxOrphanTxs int ` long:"maxorphantx" description:"Max number of orphan transactions to keep in memory" `
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" `
2019-08-16 22:37:58 +00:00
BlockMinSize uint32 ` long:"blockminsize" description:"Minimum block size in bytes to be used when creating a block" `
2016-04-25 22:51:42 +00:00
BlockMaxSize uint32 ` long:"blockmaxsize" description:"Maximum block size in bytes to be used when creating a block" `
BlockPrioritySize uint32 ` long:"blockprioritysize" description:"Size in bytes for high-priority/low-fee transactions when creating a block" `
SigCacheMaxSize uint ` long:"sigcachemaxsize" description:"The maximum number of entries in the signature verification cache" `
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" `
AllowOldVotes bool ` long:"allowoldvotes" description:"Enable the addition of very old votes to the mempool" `
BlocksOnly bool ` long:"blocksonly" description:"Do not accept transactions from remote peers." `
2018-02-05 22:01:55 +00:00
AcceptNonStd bool ` long:"acceptnonstd" description:"Accept and relay non-standard transactions to the network regardless of the default settings for the active network." `
2017-07-21 18:50:02 +00:00
RejectNonStd bool ` long:"rejectnonstd" description:"Reject non-standard transactions regardless of the default settings for the active network." `
2016-04-25 22:51:42 +00:00
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." `
AddrIndex bool ` long:"addrindex" description:"Maintain a full address-based transaction index which makes the searchrawtransactions RPC available" `
DropAddrIndex bool ` long:"dropaddrindex" description:"Deletes the address-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." `
2017-11-08 21:48:44 +00:00
NoCFilters bool ` long:"nocfilters" description:"Disable compact filtering (CF) support" `
DropCFIndex bool ` long:"dropcfindex" description:"Deletes the index used for compact filtering (CF) support from the database on start up and then exits." `
2016-04-25 22:51:42 +00:00
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" `
2018-10-11 04:40:40 +00:00
AltDNSNames [ ] string ` long:"altdnsnames" description:"Specify additional dns names to use when generating the rpc server certificate" env:"DCRD_ALT_DNSNAMES" env-delim:"," `
2016-04-25 22:51:42 +00:00
onionlookup func ( string ) ( [ ] net . IP , error )
lookup func ( string ) ( [ ] net . IP , error )
oniondial func ( string , string ) ( net . Conn , error )
dial func ( string , string ) ( net . Conn , error )
miningAddrs [ ] dcrutil . Address
minRelayTxFee dcrutil . Amount
2017-07-24 19:39:23 +00:00
whitelists [ ] * net . IPNet
2019-07-19 13:49:49 +00:00
ipv4NetInfo types . NetworksResult
ipv6NetInfo types . NetworksResult
onionNetInfo types . NetworksResult
2013-08-06 21:55:22 +00:00
}
2016-01-20 21:46:42 +00:00
// serviceOptions defines the configuration options for the daemon as a service on
2013-11-20 15:35:14 +00:00
// Windows.
type serviceOptions struct {
ServiceCommand string ` short:"s" long:"service" description:"Service command { install, remove, start, stop}" `
}
2014-09-08 19:19:47 +00:00
// cleanAndExpandPath expands environment variables and leading ~ in the
2013-09-18 05:13:36 +00:00
// passed path, cleans the result, and returns it.
func cleanAndExpandPath ( path string ) string {
2018-05-03 21:20:10 +00:00
// Nothing to do when no path is given.
if path == "" {
return path
}
2018-02-16 16:39:31 +00:00
// 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 = "."
2013-09-18 05:13:36 +00:00
}
2018-02-16 16:39:31 +00:00
return filepath . Join ( homeDir , path )
2013-09-18 05:13:36 +00:00
}
2013-08-06 21:55:22 +00:00
// validLogLevel returns whether or not logLevel is a valid debug log level.
func validLogLevel ( logLevel string ) bool {
2018-05-23 19:18:18 +00:00
_ , ok := slog . LevelFromString ( logLevel )
2017-07-13 13:46:03 +00:00
return ok
2013-08-06 21:55:22 +00:00
}
2013-11-21 23:03:01 +00:00
// 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 )
}
2016-02-25 17:17:12 +00:00
// Sort the subsystems for stable display.
2013-11-21 23:03:01 +00:00
sort . Strings ( subsystems )
return subsystems
}
2013-11-22 16:46:56 +00:00
// 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 {
2019-08-16 22:37:58 +00:00
// When the specified string doesn't have any delimiters, treat it as
2013-11-21 23:03:01 +00:00
// the log level for all subsystems.
if ! strings . Contains ( debugLevel , "," ) && ! strings . Contains ( debugLevel , "=" ) {
// Validate debug log level.
if ! validLogLevel ( debugLevel ) {
2017-08-15 19:36:51 +00:00
str := "the specified debug level [%v] is invalid"
2013-11-21 23:03:01 +00:00
return fmt . Errorf ( str , debugLevel )
}
2013-11-22 18:44:49 +00:00
// Change the logging level for all subsystems.
setLogLevels ( debugLevel )
2013-11-21 23:03:01 +00:00
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 , "=" ) {
2017-08-15 19:36:51 +00:00
str := "the specified debug level contains an invalid " +
2013-11-21 23:03:01 +00:00
"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 {
2017-08-15 19:36:51 +00:00
str := "the specified subsystem [%v] is invalid -- " +
2019-08-16 22:37:58 +00:00
"supported subsystems %v"
2013-11-22 16:46:56 +00:00
return fmt . Errorf ( str , subsysID , supportedSubsystems ( ) )
2013-11-21 23:03:01 +00:00
}
// Validate log level.
if ! validLogLevel ( logLevel ) {
2017-08-15 19:36:51 +00:00
str := "the specified debug level [%v] is invalid"
2013-11-21 23:03:01 +00:00
return fmt . Errorf ( str , logLevel )
}
setLogLevel ( subsysID , logLevel )
}
return nil
}
2013-09-15 17:08:42 +00:00
// 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
}
2013-08-06 21:55:22 +00:00
// removeDuplicateAddresses returns a new slice with all duplicate entries in
// addrs removed.
func removeDuplicateAddresses ( addrs [ ] string ) [ ] string {
2014-07-02 15:14:36 +00:00
result := make ( [ ] string , 0 , len ( addrs ) )
2014-07-02 14:45:17 +00:00
seen := map [ string ] struct { } { }
2013-08-06 21:55:22 +00:00
for _ , val := range addrs {
if _ , ok := seen [ val ] ; ! ok {
result = append ( result , val )
2014-07-02 14:45:17 +00:00
seen [ val ] = struct { } { }
2013-08-06 21:55:22 +00:00
}
}
return result
}
2013-09-19 15:46:33 +00:00
// normalizeAddress returns addr with the passed default port appended if
// there is not already a port specified.
func normalizeAddress ( addr , 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 {
2013-08-06 21:55:22 +00:00
for i , addr := range addrs {
2013-09-19 15:46:33 +00:00
addrs [ i ] = normalizeAddress ( addr , defaultPort )
2013-08-06 21:55:22 +00:00
}
2013-09-19 15:46:33 +00:00
return removeDuplicateAddresses ( addrs )
}
2019-08-22 13:23:36 +00:00
// fileExists reports whether the named file or directory exists.
2013-08-06 21:55:22 +00:00
func fileExists ( name string ) bool {
if _ , err := os . Stat ( name ) ; err != nil {
if os . IsNotExist ( err ) {
return false
}
}
return true
}
2013-11-20 15:35:14 +00:00
// 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
}
2017-08-07 02:44:24 +00:00
// 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 ) error {
// Create the destination directory if it does not exist.
err := os . MkdirAll ( filepath . Dir ( destPath ) , 0700 )
if err != nil {
return err
}
// 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]*$ ` )
2017-08-25 15:32:26 +00:00
s := rpcUserRE . ReplaceAllString ( sampleconfig . FileContents , rpcUserLine )
2017-08-07 02:44:24 +00:00
s = rpcPassRE . ReplaceAllString ( s , rpcPassLine )
// 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 ( s )
return err
}
2019-03-29 03:54:43 +00:00
// generateNetworkInfo is a convenience function that creates a slice from the
// available networks.
2019-07-19 13:49:49 +00:00
func ( cfg * config ) generateNetworkInfo ( ) [ ] types . NetworksResult {
return [ ] types . NetworksResult { cfg . ipv4NetInfo , cfg . ipv6NetInfo ,
2019-03-29 03:54:43 +00:00
cfg . onionNetInfo }
2018-11-27 10:30:22 +00:00
}
// parseNetworkInterfaces updates all network interface states based on the
// provided configuration.
2019-03-29 03:54:43 +00:00
func parseNetworkInterfaces ( cfg * config ) error {
2018-11-27 10:30:22 +00:00
v4Addrs , v6Addrs , _ , err := parseListeners ( cfg . Listeners )
if err != nil {
2019-03-29 03:54:43 +00:00
return err
2018-11-27 10:30:22 +00:00
}
2019-03-29 03:54:43 +00:00
// Set IPV4 interface state.
2018-11-27 10:30:22 +00:00
if len ( v4Addrs ) > 0 {
2019-03-29 03:54:43 +00:00
ipv4 := & cfg . ipv4NetInfo
ipv4 . Reachable = ! cfg . DisableListen
ipv4 . Limited = len ( v6Addrs ) == 0
ipv4 . Proxy = cfg . Proxy
2018-11-27 10:30:22 +00:00
}
2019-03-29 03:54:43 +00:00
// Set IPV6 interface state.
2018-11-27 10:30:22 +00:00
if len ( v6Addrs ) > 0 {
2019-03-29 03:54:43 +00:00
ipv6 := & cfg . ipv6NetInfo
ipv6 . Reachable = ! cfg . DisableListen
ipv6 . Limited = len ( v4Addrs ) == 0
ipv6 . Proxy = cfg . Proxy
2018-11-27 10:30:22 +00:00
}
2019-03-29 03:54:43 +00:00
// Set Onion interface state.
2018-11-27 10:30:22 +00:00
if len ( v6Addrs ) > 0 && ( cfg . Proxy != "" || cfg . OnionProxy != "" ) {
2019-03-29 03:54:43 +00:00
onion := & cfg . onionNetInfo
onion . Reachable = ! cfg . DisableListen && ! cfg . NoOnion
onion . Limited = len ( v4Addrs ) == 0
onion . Proxy = cfg . Proxy
2018-11-27 10:30:22 +00:00
if cfg . OnionProxy != "" {
2019-03-29 03:54:43 +00:00
onion . Proxy = cfg . OnionProxy
2018-11-27 10:30:22 +00:00
}
2019-03-29 03:54:43 +00:00
onion . ProxyRandomizeCredentials = cfg . TorIsolation
2018-11-27 10:30:22 +00:00
}
2019-03-29 03:54:43 +00:00
return nil
2018-11-27 10:30:22 +00:00
}
2013-08-06 21:55:22 +00:00
// 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
//
2016-09-26 16:59:04 +00:00
// The above results in dcrd functioning properly without any config settings
2013-08-06 21:55:22 +00:00
// 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 {
2016-04-25 22:51:42 +00:00
HomeDir : defaultHomeDir ,
ConfigFile : defaultConfigFile ,
DebugLevel : defaultLogLevel ,
2018-11-07 00:05:28 +00:00
MaxSameIP : defaultMaxSameIP ,
2016-04-25 22:51:42 +00:00
MaxPeers : defaultMaxPeers ,
BanDuration : defaultBanDuration ,
BanThreshold : defaultBanThreshold ,
RPCMaxClients : defaultMaxRPCClients ,
RPCMaxWebsockets : defaultMaxRPCWebsockets ,
RPCMaxConcurrentReqs : defaultMaxRPCConcurrentReqs ,
DataDir : defaultDataDir ,
LogDir : defaultLogDir ,
DbType : defaultDbType ,
RPCKey : defaultRPCKeyFile ,
RPCCert : defaultRPCCertFile ,
MinRelayTxFee : mempool . DefaultMinRelayTxFee . ToCoin ( ) ,
FreeTxRelayLimit : defaultFreeTxRelayLimit ,
BlockMinSize : defaultBlockMinSize ,
BlockMaxSize : defaultBlockMaxSize ,
BlockPrioritySize : mempool . DefaultBlockPrioritySize ,
MaxOrphanTxs : defaultMaxOrphanTransactions ,
SigCacheMaxSize : defaultSigCacheMaxSize ,
Generate : defaultGenerate ,
NoMiningStateSync : defaultNoMiningStateSync ,
TxIndex : defaultTxIndex ,
AddrIndex : defaultAddrIndex ,
AllowOldVotes : defaultAllowOldVotes ,
NoExistsAddrIndex : defaultNoExistsAddrIndex ,
2017-11-08 21:48:44 +00:00
NoCFilters : defaultNoCFilters ,
2018-10-11 04:40:40 +00:00
AltDNSNames : defaultAltDNSNames ,
2019-07-19 13:49:49 +00:00
ipv4NetInfo : types . NetworksResult { Name : "IPV4" } ,
ipv6NetInfo : types . NetworksResult { Name : "IPV6" } ,
onionNetInfo : types . NetworksResult { Name : "Onion" } ,
2013-08-06 21:55:22 +00:00
}
2013-11-20 15:35:14 +00:00
// Service options which are only added on Windows.
serviceOpts := serviceOptions { }
2013-08-06 21:55:22 +00:00
// Pre-parse the command line options to see if an alternative config
2014-08-20 01:06:03 +00:00
// file or the version flag was specified. Any errors aside from the
// help message error can be ignored here since they will be caught by
// the final parse below.
2013-08-06 21:55:22 +00:00
preCfg := cfg
2014-08-20 01:06:03 +00:00
preParser := newConfigParser ( & preCfg , & serviceOpts , flags . HelpFlag )
2014-12-21 21:53:33 +00:00
_ , err := preParser . Parse ( )
2014-08-20 01:06:03 +00:00
if err != nil {
2016-11-03 17:42:04 +00:00
if e , ok := err . ( * flags . Error ) ; ok && e . Type != flags . ErrHelp {
2014-08-20 01:06:03 +00:00
fmt . Fprintln ( os . Stderr , err )
2016-11-03 17:42:04 +00:00
os . Exit ( 1 )
} else if ok && e . Type == flags . ErrHelp {
fmt . Fprintln ( os . Stdout , err )
os . Exit ( 0 )
2014-08-20 01:06:03 +00:00
}
}
2013-08-06 21:55:22 +00:00
2013-08-07 23:53:01 +00:00
// Show the version and exit if the version flag was specified.
2014-07-15 01:27:22 +00:00
appName := filepath . Base ( os . Args [ 0 ] )
appName = strings . TrimSuffix ( appName , filepath . Ext ( appName ) )
usageMessage := fmt . Sprintf ( "Use %s -h to show usage" , appName )
2013-08-07 23:53:01 +00:00
if preCfg . ShowVersion {
2018-09-04 20:51:07 +00:00
fmt . Printf ( "%s version %s (Go version %s %s/%s)\n" , appName ,
version . String ( ) , runtime . Version ( ) , runtime . GOOS , runtime . GOARCH )
2013-08-07 23:53:01 +00:00
os . Exit ( 0 )
}
2013-11-20 15:35:14 +00:00
// 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 )
}
2016-04-13 19:29:26 +00:00
// 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.
2016-09-26 16:59:04 +00:00
if preCfg . HomeDir != "" {
cfg . HomeDir , _ = filepath . Abs ( preCfg . HomeDir )
if preCfg . ConfigFile == defaultConfigFile {
2017-08-07 02:44:24 +00:00
defaultConfigFile = filepath . Join ( cfg . HomeDir ,
defaultConfigFilename )
preCfg . ConfigFile = defaultConfigFile
cfg . ConfigFile = defaultConfigFile
2016-09-26 16:59:04 +00:00
} 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 . LogDir == defaultLogDir {
cfg . LogDir = filepath . Join ( cfg . HomeDir , defaultLogDirname )
} else {
cfg . LogDir = preCfg . LogDir
}
2016-04-13 19:29:26 +00:00
}
2017-08-07 02:44:24 +00:00
// Create a default config file when one does not exist and the user did
// not specify an override.
multi: Resurrect regression network.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
2018-10-05 04:46:56 +00:00
if ! ( preCfg . SimNet || preCfg . RegNet ) && preCfg . ConfigFile ==
defaultConfigFile && ! fileExists ( preCfg . ConfigFile ) {
2014-05-28 20:19:38 +00:00
2017-08-07 02:44:24 +00:00
err := createDefaultConfigFile ( preCfg . ConfigFile )
if err != nil {
fmt . Fprintf ( os . Stderr , "Error creating a default " +
"config file: %v\n" , err )
2016-07-15 18:09:42 +00:00
}
2017-08-07 02:44:24 +00:00
}
2016-07-15 18:09:42 +00:00
2017-08-07 02:44:24 +00:00
// Load additional config from file.
var configFileError error
parser := newConfigParser ( & cfg , & serviceOpts , flags . Default )
multi: Resurrect regression network.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
2018-10-05 04:46:56 +00:00
if ! ( cfg . SimNet || cfg . RegNet ) || preCfg . ConfigFile != defaultConfigFile {
2017-08-07 02:44:24 +00:00
err := flags . NewIniParser ( parser ) . ParseFile ( preCfg . ConfigFile )
2013-11-15 20:42:53 +00:00
if err != nil {
2016-09-26 16:59:04 +00:00
if _ , ok := err . ( * os . PathError ) ; ! ok {
fmt . Fprintf ( os . Stderr , "Error parsing config " +
"file: %v\n" , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-11-15 20:42:53 +00:00
return nil , nil , err
}
2016-09-26 16:59:04 +00:00
configFileError = err
2013-08-06 21:55:22 +00:00
}
}
multi: Resurrect regression network.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
2018-10-05 04:46:56 +00:00
// Don't add peers from the config file when in regression test mode.
if preCfg . RegNet && len ( cfg . AddPeers ) > 0 {
cfg . AddPeers = nil
}
2013-08-06 21:55:22 +00:00
// Parse command line options again to ensure they take precedence.
remainingArgs , err := parser . Parse ( )
if err != nil {
if e , ok := err . ( * flags . Error ) ; ! ok || e . Type != flags . ErrHelp {
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-08-06 21:55:22 +00:00
}
return nil , nil , err
}
2014-12-21 21:53:33 +00:00
// Create the home directory if it doesn't already exist.
2014-06-07 19:42:54 +00:00
funcName := "loadConfig"
2016-09-26 16:59:04 +00:00
err = os . MkdirAll ( cfg . HomeDir , 0700 )
2014-12-21 21:53:33 +00:00
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).
if e , ok := err . ( * os . PathError ) ; ok && 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 )
}
}
2017-08-15 19:36:51 +00:00
str := "%s: failed to create home directory: %v"
2014-12-21 21:53:33 +00:00
err := fmt . Errorf ( str , funcName , err )
fmt . Fprintln ( os . Stderr , err )
return nil , nil , err
}
multi: Resurrect regression network.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
2018-10-05 04:46:56 +00:00
// Multiple networks can't be selected simultaneously. Count number of
// network flags passed and assign active network params.
2014-05-28 20:19:38 +00:00
numNets := 0
2016-01-20 21:46:42 +00:00
if cfg . TestNet {
2014-05-28 20:19:38 +00:00
numNets ++
2018-08-08 11:23:15 +00:00
activeNetParams = & testNet3Params
2014-05-28 20:19:38 +00:00
}
if cfg . SimNet {
numNets ++
2014-07-21 05:42:41 +00:00
// Also disable dns seeding on the simulation test network.
activeNetParams = & simNetParams
cfg . DisableDNSSeed = true
2014-05-28 20:19:38 +00:00
}
multi: Resurrect regression network.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
2018-10-05 04:46:56 +00:00
if cfg . RegNet {
numNets ++
activeNetParams = & regNetParams
}
2014-05-28 20:19:38 +00:00
if numNets > 1 {
multi: Resurrect regression network.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
2018-10-05 04:46:56 +00:00
str := "%s: the testnet, regnet, and simnet params can't be " +
2014-05-28 20:19:38 +00:00
"used together -- choose one of the three"
2014-06-07 19:42:54 +00:00
err := fmt . Errorf ( str , funcName )
2013-08-06 21:55:22 +00:00
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-08-06 21:55:22 +00:00
return nil , nil , err
}
2016-08-23 01:02:53 +00:00
// 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.
2018-02-05 22:01:55 +00:00
acceptNonStd := activeNetParams . AcceptNonStdTxs
2016-08-23 01:02:53 +00:00
switch {
2018-02-05 22:01:55 +00:00
case cfg . AcceptNonStd && cfg . RejectNonStd :
str := "%s: rejectnonstd and acceptnonstd cannot be used " +
2016-08-23 01:02:53 +00:00
"together -- choose only one"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
case cfg . RejectNonStd :
2018-02-05 22:01:55 +00:00
acceptNonStd = false
case cfg . AcceptNonStd :
acceptNonStd = true
2016-08-23 01:02:53 +00:00
}
2018-02-05 22:01:55 +00:00
cfg . AcceptNonStd = acceptNonStd
2016-08-23 01:02:53 +00:00
2014-02-12 21:43:27 +00:00
// 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.
2017-03-22 15:26:17 +00:00
//
// Make list of old versions of testnet directories here since the
// network specific DataDir will be used after this.
2014-02-12 21:43:27 +00:00
cfg . DataDir = cleanAndExpandPath ( cfg . DataDir )
2017-03-22 15:26:17 +00:00
var oldTestNets [ ] string
oldTestNets = append ( oldTestNets , filepath . Join ( cfg . DataDir , "testnet" ) )
2018-08-08 15:36:11 +00:00
oldTestNets = append ( oldTestNets , filepath . Join ( cfg . DataDir , "testnet2" ) )
2018-08-08 11:22:06 +00:00
cfg . DataDir = filepath . Join ( cfg . DataDir , activeNetParams . Name )
2017-09-30 13:10:14 +00:00
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 )
2018-08-08 11:22:06 +00:00
cfg . LogDir = filepath . Join ( cfg . LogDir , activeNetParams . Name )
2017-09-30 13:10:14 +00:00
// Initialize log rotation. After log rotation has been initialized, the
// logger variables may be used.
initLogRotator ( filepath . Join ( cfg . LogDir , defaultLogFilename ) )
}
2014-02-12 21:43:27 +00:00
2013-11-22 16:46:56 +00:00
// Special show command to list supported subsystems and exit.
if cfg . DebugLevel == "show" {
fmt . Println ( "Supported subsystems" , supportedSubsystems ( ) )
os . Exit ( 0 )
}
2013-11-21 23:03:01 +00:00
// Parse, validate, and set debug log level(s).
2013-11-22 16:46:56 +00:00
if err := parseAndSetDebugLevels ( cfg . DebugLevel ) ; err != nil {
2014-06-07 19:42:54 +00:00
err := fmt . Errorf ( "%s: %v" , funcName , err . Error ( ) )
2013-08-06 21:55:22 +00:00
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-08-06 21:55:22 +00:00
return nil , nil , err
}
2013-09-15 17:08:42 +00:00
// Validate database type.
if ! validDbType ( cfg . DbType ) {
2017-08-15 19:36:51 +00:00
str := "%s: the specified database type [%v] is invalid -- " +
2013-09-15 17:08:42 +00:00
"supported types %v"
2014-06-07 19:42:54 +00:00
err := fmt . Errorf ( str , funcName , cfg . DbType , knownDbTypes )
2013-09-15 17:08:42 +00:00
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-09-15 17:08:42 +00:00
return nil , nil , err
}
2017-09-05 04:59:38 +00:00
// Validate format of profile, can be an address:port, or just a port.
2013-09-17 21:46:03 +00:00
if cfg . Profile != "" {
2017-09-05 04:59:38 +00:00
// if profile is just a number, then add a default host of "127.0.0.1" such that Profile is a valid tcp address
if _ , err := strconv . Atoi ( cfg . Profile ) ; err == nil {
cfg . Profile = net . JoinHostPort ( "127.0.0.1" , cfg . Profile )
}
// check the Profile is a valid address
_ , portStr , err := net . SplitHostPort ( cfg . Profile )
if err != nil {
str := "%s: profile: %s"
err := fmt . Errorf ( str , funcName , err )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
// finally, check the port is in range
if port , _ := strconv . Atoi ( portStr ) ; port < 1024 || port > 65535 {
str := "%s: profile: address %s: port must be between 1024 and 65535"
err := fmt . Errorf ( str , funcName , cfg . Profile )
2013-09-17 22:04:40 +00:00
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-09-17 22:04:40 +00:00
return nil , nil , err
}
2013-09-17 21:40:27 +00:00
}
2013-08-06 21:55:22 +00:00
// Don't allow ban durations that are too short.
2017-03-08 20:44:15 +00:00
if cfg . BanDuration < time . Second {
2017-08-15 19:36:51 +00:00
str := "%s: the banduration option may not be less than 1s -- parsed [%v]"
2014-06-07 19:42:54 +00:00
err := fmt . Errorf ( str , funcName , cfg . BanDuration )
2013-08-06 21:55:22 +00:00
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-08-06 21:55:22 +00:00
return nil , nil , err
}
2017-07-24 19:39:23 +00:00
// 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 {
2017-08-15 19:36:51 +00:00
str := "%s: the whitelist value of '%s' is invalid"
2017-07-24 19:39:23 +00:00
err = fmt . Errorf ( str , funcName , addr )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
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 )
}
}
2013-08-06 21:55:22 +00:00
// --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"
2014-06-07 19:42:54 +00:00
err := fmt . Errorf ( str , funcName )
2013-08-06 21:55:22 +00:00
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2013-08-06 21:55:22 +00:00
return nil , nil , err
}
2013-09-19 15:46:33 +00:00
// --proxy or --connect without --listen disables listening.
if ( cfg . Proxy != "" || len ( cfg . ConnectPeers ) > 0 ) &&
len ( cfg . Listeners ) == 0 {
2013-08-08 16:11:39 +00:00
cfg . DisableListen = true
}
2013-09-19 15:46:33 +00:00
// Connect means no DNS seeding.
2013-08-06 21:55:22 +00:00
if len ( cfg . ConnectPeers ) > 0 {
cfg . DisableDNSSeed = true
2013-09-19 15:46:33 +00:00
}
// Add the default listener if none were specified. The default
// listener is all addresses on the listen port for the network
// we are to connect to.
if len ( cfg . Listeners ) == 0 {
cfg . Listeners = [ ] string {
2014-05-29 17:35:09 +00:00
net . JoinHostPort ( "" , activeNetParams . DefaultPort ) ,
2013-09-19 15:46:33 +00:00
}
2013-08-06 21:55:22 +00:00
}
2015-03-30 17:45:31 +00:00
// Check to make sure limited and admin users don't have the same username
if cfg . RPCUser == cfg . RPCLimitUser && cfg . RPCUser != "" {
str := "%s: --rpcuser and --rpclimituser must not specify the " +
"same username"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
// Check to make sure limited and admin users don't have the same password
if cfg . RPCPass == cfg . RPCLimitPass && cfg . RPCPass != "" {
str := "%s: --rpcpass and --rpclimitpass must not specify the " +
"same password"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
2013-08-07 16:02:31 +00:00
// The RPC server is disabled if no username or password is provided.
2015-03-30 17:45:31 +00:00
if ( cfg . RPCUser == "" || cfg . RPCPass == "" ) &&
( cfg . RPCLimitUser == "" || cfg . RPCLimitPass == "" ) {
2013-09-18 05:36:40 +00:00
cfg . DisableRPC = true
2013-08-07 16:02:31 +00:00
}
2013-11-19 23:33:07 +00:00
// Default RPC to listen on localhost only.
if ! cfg . DisableRPC && len ( cfg . RPCListeners ) == 0 {
addrs , err := net . LookupHost ( "localhost" )
if err != nil {
return nil , nil , err
2013-11-14 01:51:37 +00:00
}
2013-11-19 23:33:07 +00:00
cfg . RPCListeners = make ( [ ] string , 0 , len ( addrs ) )
for _ , addr := range addrs {
addr = net . JoinHostPort ( addr , activeNetParams . rpcPort )
cfg . RPCListeners = append ( cfg . RPCListeners , addr )
}
2013-11-14 01:51:37 +00:00
}
2016-04-25 22:51:42 +00:00
if cfg . RPCMaxConcurrentReqs < 0 {
2017-08-15 19:36:51 +00:00
str := "%s: the rpcmaxwebsocketconcurrentrequests option may " +
2016-04-25 22:51:42 +00:00
"not be less than 0 -- parsed [%d]"
err := fmt . Errorf ( str , funcName , cfg . RPCMaxConcurrentReqs )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
2019-08-16 22:37:58 +00:00
// Validate the minrelaytxfee.
2016-05-19 16:44:08 +00:00
cfg . minRelayTxFee , err = dcrutil . NewAmount ( cfg . MinRelayTxFee )
2015-10-19 20:21:31 +00:00
if err != nil {
str := "%s: invalid minrelaytxfee: %v"
err := fmt . Errorf ( str , funcName , err )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
2017-08-11 16:23:30 +00:00
// Ensure the specified max block size is not larger than the network will
// allow. 1000 bytes is subtracted from the max to account for overhead.
blockMaxSizeMax := uint32 ( activeNetParams . MaximumBlockSizes [ 0 ] ) - 1000
2014-03-02 10:33:56 +00:00
if cfg . BlockMaxSize < blockMaxSizeMin || cfg . BlockMaxSize >
blockMaxSizeMax {
2017-08-15 19:36:51 +00:00
str := "%s: the blockmaxsize option must be in between %d " +
2014-03-02 10:33:56 +00:00
"and %d -- parsed [%d]"
2014-06-07 19:42:54 +00:00
err := fmt . Errorf ( str , funcName , blockMaxSizeMin ,
2014-03-02 10:33:56 +00:00
blockMaxSizeMax , cfg . BlockMaxSize )
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2015-05-05 14:53:15 +00:00
return nil , nil , err
}
2019-08-16 22:37:58 +00:00
// Limit the max orphan count to a sane value.
2015-05-05 14:53:15 +00:00
if cfg . MaxOrphanTxs < 0 {
2017-08-15 19:36:51 +00:00
str := "%s: the maxorphantx option may not be less than 0 " +
2015-05-05 14:53:15 +00:00
"-- parsed [%d]"
err := fmt . Errorf ( str , funcName , cfg . MaxOrphanTxs )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
2014-03-02 10:33:56 +00:00
return nil , nil , err
}
// Limit the block priority and minimum block sizes to max block size.
cfg . BlockPrioritySize = minUint32 ( cfg . BlockPrioritySize , cfg . BlockMaxSize )
cfg . BlockMinSize = minUint32 ( cfg . BlockMinSize , cfg . BlockMaxSize )
2016-02-19 04:51:18 +00:00
// --txindex and --droptxindex do not mix.
if cfg . TxIndex && cfg . DropTxIndex {
err := fmt . Errorf ( "%s: the --txindex and --droptxindex " +
"options may not be activated at the same time" ,
funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
// --addrindex and --dropaddrindex do not mix.
if cfg . AddrIndex && cfg . DropAddrIndex {
err := fmt . Errorf ( "%s: the --addrindex and --dropaddrindex " +
"options may not be activated at the same time" ,
funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
// --addrindex and --droptxindex do not mix.
if cfg . AddrIndex && cfg . DropTxIndex {
err := fmt . Errorf ( "%s: the --addrindex and --droptxindex " +
"options may not be activated at the same time " +
"because the address index relies on the transaction " +
"index" ,
funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
// !--noexistsaddrindex and --dropexistsaddrindex do not mix.
if ! cfg . NoExistsAddrIndex && cfg . DropExistsAddrIndex {
err := fmt . Errorf ( "dropexistsaddrindex cannot be activated when " +
"existsaddressindex is on (try setting --noexistsaddrindex)" )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
2017-11-08 21:48:44 +00:00
// !--nocfilters and --dropcfindex do not mix.
if ! cfg . NoCFilters && cfg . DropCFIndex {
2019-08-16 22:37:58 +00:00
err := errors . New ( "dropcfindex cannot be activated without nocfilters" )
2017-11-08 21:48:44 +00:00
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
2014-06-12 01:09:38 +00:00
// Check mining addresses are valid and saved parsed versions.
2019-02-03 16:26:15 +00:00
cfg . miningAddrs = make ( [ ] dcrutil . Address , 0 , len ( cfg . MiningAddrs ) )
2014-06-12 01:09:38 +00:00
for _ , strAddr := range cfg . MiningAddrs {
main: Update to use all new major module versions.
This updates all code in the main module to use the latest major modules
versions to pull in the latest updates.
A more general high level overview of the changes is provided below,
however, there is one semantic change worth calling out independently.
The verifymessage RPC will now return an error when provided with
an address that is not for the current active network and the RPC server
version has been bumped accordingly.
Previously, it would return false which indicated the signature is
invalid, even when the provided signature was actually valid for the
other network. Said behavior was not really incorrect since the
address, signature, and message combination is in fact invalid for the
current active network, however, that result could be somewhat
misleading since a false result could easily be interpreted to mean the
signature is actually invalid altogether which is distinct from the case
of the address being for a different network. Therefore, it is
preferable to explicitly return an error in the case of an address on
the wrong network to cleanly separate these cases.
The following is a high level overview of the changes:
- Replace all calls to removed blockchain merkle root, pow, subsidy, and
coinbase funcs with their standalone module equivalents
- Introduce a new local func named calcTxTreeMerkleRoot that accepts
dcrutil.Tx as before and defers to the new standalone func
- Update block locator handling to match the new signature required by
the peer/v2 module
- Introduce a new local func named chainBlockLocatorToHashes which
performs the necessary conversion
- Update all references to old v1 chaincfg params global instances to
use the new v2 functions
- Modify all cases that parse addresses to provide the now required
current network params
- Include address params with the wsClientFilter
- Replace removed v1 chaincfg constants with local constants
- Create subsidy cache during server init and pass it to the relevant
subsystems
- blockManagerConfig
- BlkTmplGenerator
- rpcServer
- VotingWallet
- Update mining code that creates the block one coinbase transaction to
create the output scripts as defined in the v2 params
- Replace old v2 dcrjson constant references with new types module
- Fix various comment typos
- Update fees module to use the latest major module versions and bump it v2
2019-08-13 15:50:53 +00:00
addr , err := dcrutil . DecodeAddress ( strAddr , activeNetParams . Params )
2014-03-20 07:06:10 +00:00
if err != nil {
2014-06-12 01:09:38 +00:00
str := "%s: mining address '%s' failed to decode: %v"
2014-06-07 19:42:54 +00:00
err := fmt . Errorf ( str , funcName , strAddr , err )
2014-03-20 07:06:10 +00:00
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2014-03-20 07:06:10 +00:00
return nil , nil , err
}
2014-06-12 01:09:38 +00:00
cfg . miningAddrs = append ( cfg . miningAddrs , addr )
}
// Ensure there is at least one mining address when the generate flag is
// set.
if cfg . Generate && len ( cfg . MiningAddrs ) == 0 {
str := "%s: the generate flag is set, but there are no mining " +
"addresses specified "
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
2014-07-15 01:27:22 +00:00
fmt . Fprintln ( os . Stderr , usageMessage )
2014-06-12 01:09:38 +00:00
return nil , nil , err
2014-03-20 07:06:10 +00:00
}
2013-11-14 01:51:37 +00:00
// Add default port to all listener addresses if needed and remove
// duplicate addresses.
cfg . Listeners = normalizeAddresses ( cfg . Listeners ,
2014-05-29 17:35:09 +00:00
activeNetParams . DefaultPort )
2013-11-14 01:51:37 +00:00
// Add default port to all rpc listener addresses if needed and remove
2013-09-19 15:46:33 +00:00
// duplicate addresses.
2013-11-14 01:51:37 +00:00
cfg . RPCListeners = normalizeAddresses ( cfg . RPCListeners ,
activeNetParams . rpcPort )
2013-09-19 15:46:33 +00:00
2014-12-21 00:04:07 +00:00
// Only allow TLS to be disabled if the RPC is bound to localhost
// addresses.
if ! cfg . DisableRPC && cfg . DisableTLS {
allowedTLSListeners := map [ string ] struct { } {
2016-02-25 16:47:46 +00:00
"localhost" : { } ,
"127.0.0.1" : { } ,
"::1" : { } ,
2014-12-21 00:04:07 +00:00
}
for _ , addr := range cfg . RPCListeners {
host , _ , err := net . SplitHostPort ( addr )
if err != nil {
str := "%s: RPC listen interface '%s' is " +
"invalid: %v"
err := fmt . Errorf ( str , funcName , addr , err )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
if _ , ok := allowedTLSListeners [ host ] ; ! ok {
str := "%s: the --notls option may not be used " +
"when binding RPC to non localhost " +
"addresses: %s"
err := fmt . Errorf ( str , funcName , addr )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
}
}
2013-08-06 21:55:22 +00:00
// Add default port to all added peer addresses if needed and remove
// duplicate addresses.
2013-11-14 01:51:37 +00:00
cfg . AddPeers = normalizeAddresses ( cfg . AddPeers ,
2014-05-29 17:35:09 +00:00
activeNetParams . DefaultPort )
2013-11-14 01:51:37 +00:00
cfg . ConnectPeers = normalizeAddresses ( cfg . ConnectPeers ,
2014-05-29 17:35:09 +00:00
activeNetParams . DefaultPort )
2013-08-06 21:55:22 +00:00
2015-05-13 20:34:33 +00:00
// Tor stream isolation requires either proxy or onion proxy to be set.
if cfg . TorIsolation && cfg . Proxy == "" && cfg . OnionProxy == "" {
str := "%s: Tor stream isolation requires either proxy or " +
"onionproxy to be set"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
2014-01-10 07:52:15 +00:00
// Setup dial and DNS resolution (lookup) functions depending on the
// specified options. The default is to use the standard net.Dial
// function as well as the system DNS resolver. When a proxy is
// specified, the dial function is set to the proxy specific dial
// function and the lookup is set to use tor (unless --noonion is
// specified in which case the system DNS resolver is used).
2013-12-17 15:10:59 +00:00
cfg . dial = net . Dial
cfg . lookup = net . LookupIP
if cfg . Proxy != "" {
2015-05-13 20:34:33 +00:00
_ , _ , err := net . SplitHostPort ( cfg . Proxy )
if err != nil {
2017-09-08 16:03:59 +00:00
str := "%s: proxy address '%s' is invalid: %v"
2015-05-13 20:34:33 +00:00
err := fmt . Errorf ( str , funcName , cfg . Proxy , err )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
if cfg . TorIsolation &&
( cfg . ProxyUser != "" || cfg . ProxyPass != "" ) {
2016-09-26 16:59:04 +00:00
fmt . Fprintln ( os . Stderr , "Tor isolation set -- " +
"overriding specified proxy user credentials" )
2015-05-13 20:34:33 +00:00
}
2013-12-17 15:10:59 +00:00
proxy := & socks . Proxy {
2015-05-13 20:34:33 +00:00
Addr : cfg . Proxy ,
Username : cfg . ProxyUser ,
Password : cfg . ProxyPass ,
TorIsolation : cfg . TorIsolation ,
2013-12-17 15:10:59 +00:00
}
cfg . dial = proxy . Dial
if ! cfg . NoOnion {
cfg . lookup = func ( host string ) ( [ ] net . IP , error ) {
2016-05-12 09:06:07 +00:00
return connmgr . TorLookupIP ( host , cfg . Proxy )
2013-12-17 15:10:59 +00:00
}
}
}
2014-01-10 07:52:15 +00:00
// Setup onion address dial and DNS resolution (lookup) functions
// depending on the specified options. The default is to use the
// same dial and lookup functions selected above. However, when an
// onion-specific proxy is specified, the onion address dial and
// lookup functions are set to use the onion-specific proxy while
// leaving the normal dial and lookup functions as selected above.
// This allows .onion address traffic to be routed through a different
// proxy than normal traffic.
2013-12-17 15:10:59 +00:00
if cfg . OnionProxy != "" {
2015-05-13 20:34:33 +00:00
_ , _ , err := net . SplitHostPort ( cfg . OnionProxy )
if err != nil {
str := "%s: Onion proxy address '%s' is invalid: %v"
err := fmt . Errorf ( str , funcName , cfg . OnionProxy , err )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , nil , err
}
if cfg . TorIsolation &&
( cfg . OnionProxyUser != "" || cfg . OnionProxyPass != "" ) {
2016-09-26 16:59:04 +00:00
fmt . Fprintln ( os . Stderr , "Tor isolation set -- " +
"overriding specified onionproxy user " +
"credentials " )
2015-05-13 20:34:33 +00:00
}
2013-12-17 15:10:59 +00:00
cfg . oniondial = func ( a , b string ) ( net . Conn , error ) {
proxy := & socks . Proxy {
2015-05-13 20:34:33 +00:00
Addr : cfg . OnionProxy ,
Username : cfg . OnionProxyUser ,
Password : cfg . OnionProxyPass ,
TorIsolation : cfg . TorIsolation ,
2013-12-17 15:10:59 +00:00
}
return proxy . Dial ( a , b )
}
cfg . onionlookup = func ( host string ) ( [ ] net . IP , error ) {
2016-05-12 09:06:07 +00:00
return connmgr . TorLookupIP ( host , cfg . OnionProxy )
2013-12-17 15:10:59 +00:00
}
} else {
cfg . oniondial = cfg . dial
cfg . onionlookup = cfg . lookup
}
2014-01-10 07:52:15 +00:00
// Specifying --noonion means the onion address dial and DNS resolution
// (lookup) functions result in an error.
2013-12-17 15:10:59 +00:00
if cfg . NoOnion {
cfg . oniondial = func ( a , b string ) ( net . Conn , error ) {
return nil , errors . New ( "tor has been disabled" )
}
cfg . onionlookup = func ( a string ) ( [ ] net . IP , error ) {
return nil , errors . New ( "tor has been disabled" )
}
}
2017-03-22 15:26:17 +00:00
// Warn if old testnet directory is present.
for _ , oldDir := range oldTestNets {
if fileExists ( oldDir ) {
dcrdLog . Warnf ( "Block chain data from previous testnet" +
" found (%v) and can probably be removed." ,
oldDir )
}
}
2019-03-29 03:54:43 +00:00
// Parse information regarding the state of the supported network
// interfaces.
if err := parseNetworkInterfaces ( & cfg ) ; err != nil {
2018-11-27 10:30:22 +00:00
return nil , nil , err
}
2016-09-26 16:59:04 +00:00
// 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 {
dcrdLog . Warnf ( "%v" , configFileError )
2016-07-20 18:17:20 +00:00
}
2016-09-26 16:59:04 +00:00
return & cfg , remainingArgs , nil
2016-07-20 18:17:20 +00:00
}
2016-07-15 18:09:42 +00:00
2016-01-20 21:46:42 +00:00
// dcrdDial connects to the address on the named network using the appropriate
2014-01-10 07:31:20 +00:00
// dial function depending on the address and configuration options. For
// example, .onion addresses will be dialed using the onion specific proxy if
// one was specified, but will otherwise use the normal dial function (which
// could itself use a proxy or not).
2018-03-02 19:17:20 +00:00
func dcrdDial ( network , addr string ) ( net . Conn , error ) {
if strings . Contains ( addr , ".onion:" ) {
return cfg . oniondial ( network , addr )
2013-12-17 15:10:59 +00:00
}
2018-03-02 19:17:20 +00:00
return cfg . dial ( network , addr )
2013-12-17 15:10:59 +00:00
}
2016-01-20 21:46:42 +00:00
// dcrdLookup returns the correct DNS lookup function to use depending on the
2014-01-10 07:31:20 +00:00
// passed host and configuration options. For example, .onion addresses will be
// resolved using the onion specific proxy if one was specified, but will
// otherwise treat the normal proxy as tor unless --noonion was specified in
// which case the lookup will fail. Meanwhile, normal IP addresses will be
// resolved using tor if a proxy was specified unless --noonion was also
// specified in which case the normal system DNS resolver will be used.
2016-01-20 21:46:42 +00:00
func dcrdLookup ( host string ) ( [ ] net . IP , error ) {
2013-12-17 15:10:59 +00:00
if strings . HasSuffix ( host , ".onion" ) {
return cfg . onionlookup ( host )
}
return cfg . lookup ( host )
}