2017-11-28 03:12:09 +03:00
// Copyright (c) 2013-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Copyright (C) 2015-2017 The Lightning Network Developers
2019-01-24 16:28:25 +03:00
package lnd
2016-02-23 05:24:56 +03:00
import (
2018-04-27 23:54:35 +03:00
"errors"
2016-03-23 04:44:17 +03:00
"fmt"
2017-04-01 17:02:50 +03:00
"io/ioutil"
2016-12-15 05:11:31 +03:00
"net"
2016-03-22 23:30:54 +03:00
"os"
2018-02-26 06:41:44 +03:00
"os/user"
2017-12-22 08:23:24 +03:00
"path"
2016-03-22 23:30:54 +03:00
"path/filepath"
2017-04-01 17:02:50 +03:00
"regexp"
2016-03-23 04:44:17 +03:00
"sort"
2016-06-21 07:42:07 +03:00
"strconv"
2016-03-23 04:44:17 +03:00
"strings"
2017-05-18 21:48:59 +03:00
"time"
2016-03-22 23:30:54 +03:00
2018-06-05 04:34:16 +03:00
"github.com/btcsuite/btcutil"
2017-12-22 08:23:24 +03:00
flags "github.com/jessevdk/go-flags"
2018-09-20 13:26:58 +03:00
"github.com/lightningnetwork/lnd/build"
2019-02-09 06:39:00 +03:00
"github.com/lightningnetwork/lnd/chanbackup"
2019-04-02 02:34:17 +03:00
"github.com/lightningnetwork/lnd/channeldb"
2019-04-11 05:31:05 +03:00
"github.com/lightningnetwork/lnd/discovery"
2018-04-27 00:07:45 +03:00
"github.com/lightningnetwork/lnd/htlcswitch/hodl"
2018-05-23 16:41:16 +03:00
"github.com/lightningnetwork/lnd/lncfg"
2019-05-22 12:56:04 +03:00
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
config+rpc: create new generalized dynamic sub rpc server config framework
In this commit, we add the glue infrastructure to make the sub RPC
server system work properly. Our high level goal is the following: using
only the lnrpc package (with no visibility into the sub RPC servers),
the RPC server is able to find, create, run, and manage the entire set
of present and future sub RPC servers. In order to achieve this, we use
the reflect package and build tags heavily to permit a loosely coupled
configuration parsing system for the sub RPC servers.
We start with a new `subRpcServerConfigs` struct which is _always_
present. This struct has its own group, and will house a series of
sub-configs, one for each sub RPC server. Each sub-config is actually
gated behind a build flag, and can be used to allow users on the command
line or in the config to specify arguments related to the sub-server. If
the config isn't present, then we don't attempt to parse it at all, if
it is, then that means the RPC server has been registered, and we should
parse the contents of its config.
The `subRpcServerConfigs` struct has two main methods:
`PopulateDependancies` and `FetchConfig`. The `PopulateDependancies` is
used to dynamically locate and set the config fields for each new
sub-server. As the config may not actually have any fields (if the build
flag is off), we use the reflect pacakge to determine if things are
compiled in or not, then if so, we dynamically set each of the config
parameters. The `PopulateDependancies` method implements the
`lnrpc.SubServerConfigDispatcher` interface. Our goal is to allow sub
servers to look up their actual config in this main config struct. We
achieve this by using reflect to look up the target field _as if it were
a key in a map_. If the field is found, then we check if it has any
actual attributes (it won't if the build flag is off), if it is, then we
return it as we expect it to be populated already.
2018-10-23 03:58:30 +03:00
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
2016-12-15 05:11:31 +03:00
"github.com/lightningnetwork/lnd/lnwire"
2018-08-30 05:05:38 +03:00
"github.com/lightningnetwork/lnd/routing"
2018-04-27 23:54:35 +03:00
"github.com/lightningnetwork/lnd/tor"
2016-02-23 05:24:56 +03:00
)
const (
2019-05-15 10:02:53 +03:00
defaultConfigFilename = "lnd.conf"
defaultDataDirname = "data"
defaultChainSubDirname = "chain"
defaultGraphSubDirname = "graph"
defaultTLSCertFilename = "tls.cert"
defaultTLSKeyFilename = "tls.key"
defaultAdminMacFilename = "admin.macaroon"
defaultReadMacFilename = "readonly.macaroon"
defaultInvoiceMacFilename = "invoice.macaroon"
defaultLogLevel = "info"
defaultLogDirname = "logs"
defaultLogFilename = "lnd.log"
defaultRPCPort = 10009
defaultRESTPort = 8080
defaultPeerPort = 9735
defaultRPCHost = "localhost"
// DefaultMaxPendingChannels is the default maximum number of incoming
// pending channels permitted per peer.
DefaultMaxPendingChannels = 1
2019-02-15 04:13:11 +03:00
defaultNoSeedBackup = false
defaultTrickleDelay = 90 * 1000
defaultChanStatusSampleInterval = time . Minute
defaultChanEnableTimeout = 19 * time . Minute
defaultChanDisableTimeout = 20 * time . Minute
defaultMaxLogFiles = 3
defaultMaxLogFileSize = 10
defaultMinBackoff = time . Second
defaultMaxBackoff = time . Hour
2017-12-17 16:31:38 +03:00
2018-04-27 23:54:35 +03:00
defaultTorSOCKSPort = 9050
defaultTorDNSHost = "soa.nodes.lightning.directory"
defaultTorDNSPort = 53
defaultTorControlPort = 9051
defaultTorV2PrivateKeyFilename = "v2_onion_private_key"
2018-07-01 05:25:03 +03:00
defaultTorV3PrivateKeyFilename = "v3_onion_private_key"
2018-04-27 23:54:35 +03:00
2019-05-15 10:02:53 +03:00
// DefaultIncomingBroadcastDelta defines the number of blocks before the
2019-04-04 15:48:55 +03:00
// expiry of an incoming htlc at which we force close the channel. We
// only go to chain if we also have the preimage to actually pull in the
// htlc. BOLT #2 suggests 7 blocks. We use a few more for extra safety.
// Within this window we need to get our sweep or 2nd level success tx
// confirmed, because after that the remote party is also able to claim
// the htlc using the timeout path.
2019-05-15 10:02:53 +03:00
DefaultIncomingBroadcastDelta = 10
2019-04-03 13:18:19 +03:00
2019-04-04 15:48:55 +03:00
// defaultFinalCltvRejectDelta defines the number of blocks before the
// expiry of an incoming exit hop htlc at which we cancel it back
// immediately. It is an extra safety measure over the final cltv
// requirement as it is defined in the invoice. It ensures that we
// cancel back htlcs that, when held on to, may cause us to force close
// the channel because we enter the incoming broadcast window. Bolt #11
// suggests 9 blocks here. We use a few more for additional safety.
//
// There is still a small gap that remains between receiving the
// RevokeAndAck and canceling back. If a new block arrives within that
// window, we may still force close the channel. There is currently no
// way to reject an UpdateAddHtlc of which we already know that it will
// push us in the broadcast window.
2019-05-15 10:02:53 +03:00
defaultFinalCltvRejectDelta = DefaultIncomingBroadcastDelta + 3
2019-04-04 15:48:55 +03:00
2019-05-15 10:02:53 +03:00
// DefaultOutgoingBroadcastDelta defines the number of blocks before the
2019-04-04 15:48:55 +03:00
// expiry of an outgoing htlc at which we force close the channel. We
// are not in a hurry to force close, because there is nothing to claim
// for us. We do need to time the htlc out, because there may be an
// incoming htlc that will time out too (albeit later). Bolt #2 suggests
// a value of -1 here, but we allow one block less to prevent potential
// confusion around the negative value. It means we force close the
// channel at exactly the htlc expiry height.
2019-05-15 10:02:53 +03:00
DefaultOutgoingBroadcastDelta = 0
2019-04-04 15:48:55 +03:00
// defaultOutgoingCltvRejectDelta defines the number of blocks before
// the expiry of an outgoing htlc at which we don't want to offer it to
// the next peer anymore. If that happens, we cancel back the incoming
// htlc. This is to prevent the situation where we have an outstanding
// htlc that brings or will soon bring us inside the outgoing broadcast
// window and trigger us to force close the channel. Bolt #2 suggests a
// value of 0. We pad it a bit, to prevent a slow round trip to the next
// peer and a block arriving during that round trip to trigger force
// closure.
2019-05-15 10:02:53 +03:00
defaultOutgoingCltvRejectDelta = DefaultOutgoingBroadcastDelta + 3
2018-01-23 05:59:44 +03:00
2017-12-17 16:31:38 +03:00
// minTimeLockDelta is the minimum timelock we require for incoming
// HTLCs on our channels.
minTimeLockDelta = 4
2017-12-16 02:03:38 +03:00
defaultAlias = ""
defaultColor = "#3399FF"
2016-02-23 05:24:56 +03:00
)
var (
2018-03-21 02:50:08 +03:00
defaultLndDir = btcutil . AppDataDir ( "lnd" , false )
defaultConfigFile = filepath . Join ( defaultLndDir , defaultConfigFilename )
defaultDataDir = filepath . Join ( defaultLndDir , defaultDataDirname )
defaultLogDir = filepath . Join ( defaultLndDir , defaultLogDirname )
defaultTLSCertPath = filepath . Join ( defaultLndDir , defaultTLSCertFilename )
defaultTLSKeyPath = filepath . Join ( defaultLndDir , defaultTLSKeyFilename )
2018-02-25 01:18:59 +03:00
defaultBtcdDir = btcutil . AppDataDir ( "btcd" , false )
defaultBtcdRPCCertFile = filepath . Join ( defaultBtcdDir , "rpc.cert" )
2017-05-03 05:23:24 +03:00
2018-02-25 01:18:59 +03:00
defaultLtcdDir = btcutil . AppDataDir ( "ltcd" , false )
defaultLtcdRPCCertFile = filepath . Join ( defaultLtcdDir , "rpc.cert" )
2017-12-22 08:23:24 +03:00
2018-03-14 07:14:42 +03:00
defaultBitcoindDir = btcutil . AppDataDir ( "bitcoin" , false )
defaultLitecoindDir = btcutil . AppDataDir ( "litecoin" , false )
2018-04-27 23:54:35 +03:00
2018-07-01 05:25:03 +03:00
defaultTorSOCKS = net . JoinHostPort ( "localhost" , strconv . Itoa ( defaultTorSOCKSPort ) )
defaultTorDNS = net . JoinHostPort ( defaultTorDNSHost , strconv . Itoa ( defaultTorDNSPort ) )
defaultTorControl = net . JoinHostPort ( "localhost" , strconv . Itoa ( defaultTorControlPort ) )
2016-02-23 05:24:56 +03:00
)
2017-05-03 05:23:24 +03:00
type chainConfig struct {
2017-08-11 07:26:48 +03:00
Active bool ` long:"active" description:"If the chain should be active or not." `
2017-12-18 05:40:05 +03:00
ChainDir string ` long:"chaindir" description:"The directory to store the chain's data within." `
2017-05-03 05:23:24 +03:00
2018-03-14 07:14:42 +03:00
Node string ` long:"node" description:"The blockchain interface to use." choice:"btcd" choice:"bitcoind" choice:"neutrino" choice:"ltcd" choice:"litecoind" `
2017-05-03 05:23:24 +03:00
2018-03-15 12:04:17 +03:00
MainNet bool ` long:"mainnet" description:"Use the main network" `
2017-05-03 05:23:24 +03:00
TestNet3 bool ` long:"testnet" description:"Use the test network" `
SimNet bool ` long:"simnet" description:"Use the simulation test network" `
2017-07-12 02:54:43 +03:00
RegTest bool ` long:"regtest" description:"Use the regression test network" `
2017-12-17 16:31:38 +03:00
2017-12-17 18:07:32 +03:00
DefaultNumChanConfs int ` long:"defaultchanconfs" description:"The default number of confirmations a channel must have before it's considered open. If this is not set, we will scale the value according to the channel size." `
DefaultRemoteDelay int ` long:"defaultremotedelay" description:"The default number of blocks we will require our channel counterparty to wait before accessing its funds in case of unilateral close. If this is not set, we will scale the value according to the channel size." `
MinHTLC lnwire . MilliSatoshi ` long:"minhtlc" description:"The smallest HTLC we are willing to forward on our channels, in millisatoshi" `
BaseFee lnwire . MilliSatoshi ` long:"basefee" description:"The base fee in millisatoshi we will charge for forwarding payments on our channels" `
FeeRate lnwire . MilliSatoshi ` long:"feerate" description:"The fee rate used when forwarding payments on our channels. The total fee charged is basefee + (amount * feerate / 1000000), where amount is the forwarded amount." `
TimeLockDelta uint32 ` long:"timelockdelta" description:"The CLTV delta we will subtract from a forwarded HTLC's timelock value" `
2017-05-03 05:23:24 +03:00
}
2017-06-06 01:44:18 +03:00
type neutrinoConfig struct {
2019-05-25 04:16:33 +03: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" `
MaxPeers int ` long:"maxpeers" description:"Max number of inbound and outbound 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." `
FeeURL string ` long:"feeurl" description:"Optional URL for fee estimation. If a URL is not specified, static fees will be used for estimation." `
AssertFilterHeader string ` long:"assertfilterheader" description:"Optional filter header in height:hash format to assert the state of neutrino's filter header chain on startup. If the assertion does not hold, then the filter header chain will be re-synced from the genesis block." `
2017-05-18 21:48:59 +03:00
}
2017-12-22 08:23:24 +03:00
type btcdConfig struct {
2018-02-25 01:18:59 +03:00
Dir string ` long:"dir" description:"The base directory that contains the node's data, logs, configuration file, etc." `
2017-12-22 08:23:24 +03:00
RPCHost string ` long:"rpchost" description:"The daemon's rpc listening address. If a port is omitted, then the default port for the selected chain parameters will be used." `
RPCUser string ` long:"rpcuser" description:"Username for RPC connections" `
RPCPass string ` long:"rpcpass" default-mask:"-" description:"Password for RPC connections" `
RPCCert string ` long:"rpccert" description:"File containing the daemon's certificate file" `
RawRPCCert string ` long:"rawrpccert" description:"The raw bytes of the daemon's PEM-encoded certificate chain which will be used to authenticate the RPC connection." `
}
type bitcoindConfig struct {
2018-07-17 02:48:31 +03:00
Dir string ` long:"dir" description:"The base directory that contains the node's data, logs, configuration file, etc." `
RPCHost string ` long:"rpchost" description:"The daemon's rpc listening address. If a port is omitted, then the default port for the selected chain parameters will be used." `
RPCUser string ` long:"rpcuser" description:"Username for RPC connections" `
RPCPass string ` long:"rpcpass" default-mask:"-" description:"Password for RPC connections" `
ZMQPubRawBlock string ` long:"zmqpubrawblock" description:"The address listening for ZMQ connections to deliver raw block notifications" `
ZMQPubRawTx string ` long:"zmqpubrawtx" description:"The address listening for ZMQ connections to deliver raw transaction notifications" `
2017-12-22 08:23:24 +03:00
}
2017-08-11 07:26:48 +03:00
type autoPilotConfig struct {
2018-12-19 20:56:43 +03:00
Active bool ` long:"active" description:"If the autopilot agent should be active or not." `
Heuristic map [ string ] float64 ` long:"heuristic" description:"Heuristic to activate, and the weight to give it during scoring." `
MaxChannels int ` long:"maxchannels" description:"The maximum number of channels that should be created" `
Allocation float64 ` long:"allocation" description:"The percentage of total funds that should be committed to automatic channel establishment" `
MinChannelSize int64 ` long:"minchansize" description:"The smallest channel that the autopilot agent should create" `
MaxChannelSize int64 ` long:"maxchansize" description:"The largest channel that the autopilot agent should create" `
Private bool ` long:"private" description:"Whether the channels created by the autopilot agent should be private or not. Private channels won't be announced to the network." `
MinConfs int32 ` long:"minconfs" description:"The minimum number of confirmations each of your inputs in funding transactions created by the autopilot agent must have." `
2017-08-11 07:26:48 +03:00
}
2018-01-22 14:48:59 +03:00
type torConfig struct {
2018-07-01 05:25:03 +03:00
Active bool ` long:"active" description:"Allow outbound and inbound connections to be routed through Tor" `
SOCKS string ` long:"socks" description:"The host:port that Tor's exposed SOCKS5 proxy is listening on" `
DNS string ` long:"dns" description:"The DNS server as host:port that Tor will use for SRV queries - NOTE must have TCP resolution enabled" `
StreamIsolation bool ` long:"streamisolation" description:"Enable Tor stream isolation by randomizing user credentials for each connection." `
Control string ` long:"control" description:"The host:port that Tor is listening on for Tor control connections" `
V2 bool ` long:"v2" description:"Automatically set up a v2 onion service to listen for inbound connections" `
V3 bool ` long:"v3" description:"Automatically set up a v3 onion service to listen for inbound connections" `
PrivateKeyPath string ` long:"privatekeypath" description:"The path to the private key of the onion service being created" `
2018-01-22 14:48:59 +03:00
}
2016-06-21 07:42:07 +03:00
// config defines the configuration options for lnd.
2016-03-23 04:44:17 +03:00
//
// See loadConfig for further details regarding the configuration
// loading+parsing process.
2016-02-23 05:24:56 +03:00
type config struct {
2016-03-23 04:44:17 +03:00
ShowVersion bool ` short:"V" long:"version" description:"Display version information and exit" `
2019-02-26 07:21:46 +03:00
LndDir string ` long:"lnddir" description:"The base directory that contains lnd's data, logs, configuration file, etc." `
ConfigFile string ` long:"C" long:"configfile" description:"Path to configuration file" `
DataDir string ` short:"b" long:"datadir" description:"The directory to store lnd's data within" `
TLSCertPath string ` long:"tlscertpath" description:"Path to write the TLS certificate for lnd's RPC and REST services" `
TLSKeyPath string ` long:"tlskeypath" description:"Path to write the TLS private key for lnd's RPC and REST services" `
TLSExtraIPs [ ] string ` long:"tlsextraip" description:"Adds an extra ip to the generated certificate" `
TLSExtraDomains [ ] string ` long:"tlsextradomain" description:"Adds an extra domain to the generated certificate" `
NoMacaroons bool ` long:"no-macaroons" description:"Disable macaroon authentication" `
AdminMacPath string ` long:"adminmacaroonpath" description:"Path to write the admin macaroon for lnd's RPC and REST services if it doesn't exist" `
ReadMacPath string ` long:"readonlymacaroonpath" description:"Path to write the read-only macaroon for lnd's RPC and REST services if it doesn't exist" `
InvoiceMacPath string ` long:"invoicemacaroonpath" description:"Path to the invoice-only macaroon for lnd's RPC and REST services if it doesn't exist" `
LogDir string ` long:"logdir" description:"Directory to log output." `
MaxLogFiles int ` long:"maxlogfiles" description:"Maximum logfiles to keep (0 for no rotation)" `
MaxLogFileSize int ` long:"maxlogfilesize" description:"Maximum logfile size in MB" `
2018-05-23 16:38:19 +03:00
// We'll parse these 'raw' string arguments into real net.Addrs in the
// loadConfig function. We need to expose the 'raw' strings so the
// command line library can access them.
// Only the parsed net.Addrs should be used!
RawRPCListeners [ ] string ` long:"rpclisten" description:"Add an interface/port/socket to listen for RPC connections" `
RawRESTListeners [ ] string ` long:"restlisten" description:"Add an interface/port/socket to listen for REST connections" `
RawListeners [ ] string ` long:"listen" description:"Add an interface/port to listen for peer connections" `
RawExternalIPs [ ] string ` long:"externalip" description:"Add an ip:port to the list of local addresses we claim to listen on to peers. If a port is not specified, the default (9735) will be used regardless of other parameters" `
RPCListeners [ ] net . Addr
RESTListeners [ ] net . Addr
Listeners [ ] net . Addr
ExternalIPs [ ] net . Addr
2018-10-04 18:55:37 +03:00
DisableListen bool ` long:"nolisten" description:"Disable listening for incoming peer connections" `
NAT bool ` long:"nat" description:"Toggle NAT traversal support (using either UPnP or NAT-PMP) to automatically advertise your external IP address to the network -- NOTE this does not support devices behind multiple NATs" `
2019-01-04 05:38:35 +03:00
MinBackoff time . Duration ` long:"minbackoff" description:"Shortest backoff when reconnecting to persistent peers. Valid time units are { s, m, h}." `
2018-10-04 18:55:37 +03:00
MaxBackoff time . Duration ` long:"maxbackoff" description:"Longest backoff when reconnecting to persistent peers. Valid time units are { s, m, h}." `
2016-03-23 04:44:17 +03:00
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" `
2017-10-15 03:08:27 +03:00
CPUProfile string ` long:"cpuprofile" description:"Write CPU profile to the specified file" `
2017-10-25 05:02:29 +03:00
Profile string ` long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65535" `
2019-02-09 06:39:00 +03:00
DebugHTLC bool ` long:"debughtlc" description:"Activate the debug htlc mode. With the debug HTLC mode, all payments sent use a pre-determined R-Hash. Additionally, all HTLCs sent to a node with the debug HTLC R-Hash are immediately settled in the next available state transition." `
UnsafeDisconnect bool ` long:"unsafe-disconnect" description:"Allows the rpcserver to intentionally disconnect from peers with open channels. USED FOR TESTING ONLY." `
UnsafeReplay bool ` long:"unsafe-replay" description:"Causes a link to replay the adds on its commitment txn after starting up, this enables testing of the sphinx replay logic." `
MaxPendingChannels int ` long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer." `
BackupFilePath string ` long:"backupfilepath" description:"The target location of the channel backup file" `
2017-05-03 05:23:24 +03:00
2017-12-22 08:23:24 +03:00
Bitcoin * chainConfig ` group:"Bitcoin" namespace:"bitcoin" `
BtcdMode * btcdConfig ` group:"btcd" namespace:"btcd" `
BitcoindMode * bitcoindConfig ` group:"bitcoind" namespace:"bitcoind" `
2017-06-06 01:44:18 +03:00
NeutrinoMode * neutrinoConfig ` group:"neutrino" namespace:"neutrino" `
2017-08-11 07:26:48 +03:00
2018-03-14 07:14:42 +03:00
Litecoin * chainConfig ` group:"Litecoin" namespace:"litecoin" `
LtcdMode * btcdConfig ` group:"ltcd" namespace:"ltcd" `
LitecoindMode * bitcoindConfig ` group:"litecoind" namespace:"litecoind" `
2017-12-22 08:23:24 +03:00
2018-04-27 23:54:35 +03:00
Autopilot * autoPilotConfig ` group:"Autopilot" namespace:"autopilot" `
2017-09-04 03:00:05 +03:00
2018-01-22 14:48:59 +03:00
Tor * torConfig ` group:"Tor" namespace:"tor" `
2018-11-03 01:41:38 +03:00
SubRPCServers * subRPCServerConfigs ` group:"subrpc" `
config+rpc: create new generalized dynamic sub rpc server config framework
In this commit, we add the glue infrastructure to make the sub RPC
server system work properly. Our high level goal is the following: using
only the lnrpc package (with no visibility into the sub RPC servers),
the RPC server is able to find, create, run, and manage the entire set
of present and future sub RPC servers. In order to achieve this, we use
the reflect package and build tags heavily to permit a loosely coupled
configuration parsing system for the sub RPC servers.
We start with a new `subRpcServerConfigs` struct which is _always_
present. This struct has its own group, and will house a series of
sub-configs, one for each sub RPC server. Each sub-config is actually
gated behind a build flag, and can be used to allow users on the command
line or in the config to specify arguments related to the sub-server. If
the config isn't present, then we don't attempt to parse it at all, if
it is, then that means the RPC server has been registered, and we should
parse the contents of its config.
The `subRpcServerConfigs` struct has two main methods:
`PopulateDependancies` and `FetchConfig`. The `PopulateDependancies` is
used to dynamically locate and set the config fields for each new
sub-server. As the config may not actually have any fields (if the build
flag is off), we use the reflect pacakge to determine if things are
compiled in or not, then if so, we dynamically set each of the config
parameters. The `PopulateDependancies` method implements the
`lnrpc.SubServerConfigDispatcher` interface. Our goal is to allow sub
servers to look up their actual config in this main config struct. We
achieve this by using reflect to look up the target field _as if it were
a key in a map_. If the field is found, then we check if it has any
actual attributes (it won't if the build flag is off), if it is, then we
return it as we expect it to be populated already.
2018-10-23 03:58:30 +03:00
2018-04-27 00:07:45 +03:00
Hodl * hodl . Config ` group:"hodl" namespace:"hodl" `
2017-09-04 03:00:05 +03:00
NoNetBootstrap bool ` long:"nobootstrap" description:"If true, then automatic network bootstrapping will not be attempted." `
2017-10-12 12:19:51 +03:00
2018-09-05 04:42:40 +03:00
NoSeedBackup bool ` long:"noseedbackup" description:"If true, NO SEED WILL BE EXPOSED AND THE WALLET WILL BE ENCRYPTED USING THE DEFAULT PASSPHRASE -- EVER. THIS FLAG IS ONLY FOR TESTING AND IS BEING DEPRECATED." `
2017-09-14 02:33:46 +03:00
2019-02-15 04:13:11 +03:00
TrickleDelay int ` long:"trickledelay" description:"Time in milliseconds between each release of announcements to the network" `
ChanEnableTimeout time . Duration ` long:"chan-enable-timeout" description:"The duration that a peer connection must be stable before attempting to send a channel update to reenable or cancel a pending disables of the peer's channels on the network (default: 19m)." `
ChanDisableTimeout time . Duration ` long:"chan-disable-timeout" description:"The duration that must elapse after first detecting that an already active channel is actually inactive and sending channel update disabling it to the network. The pending disable can be canceled if the peer reconnects and becomes stable for chan-enable-timeout before the disable update is sent. (default: 20m)" `
ChanStatusSampleInterval time . Duration ` long:"chan-status-sample-interval" description:"The polling interval between attempts to detect if an active channel has become inactive due to its peer going offline. (default: 1m)" `
2017-12-16 02:03:38 +03:00
2018-04-03 02:17:50 +03:00
Alias string ` long:"alias" description:"The node alias. Used as a moniker by peers and intelligence services" `
Color string ` long:"color" description:"The color of the node in hex format (i.e. '#3399FF'). Used to customize node appearance in intelligence services" `
MinChanSize int64 ` long:"minchansize" description:"The smallest channel size (in satoshis) that we should accept. Incoming channels smaller than this will be rejected" `
2017-10-21 00:45:23 +03:00
2019-04-11 05:31:05 +03:00
NumGraphSyncPeers int ` long:"numgraphsyncpeers" description:"The number of peers that we should receive new graph updates from. This option can be tuned to save bandwidth for light clients or routing nodes." `
HistoricalSyncInterval time . Duration ` long:"historicalsyncinterval" description:"The polling interval between historical graph sync attempts. Each historical graph sync attempt ensures we reconcile with the remote peer's graph from the genesis block." `
2018-04-17 05:15:31 +03:00
2018-10-10 11:28:39 +03:00
RejectPush bool ` long:"rejectpush" description:"If true, lnd will not accept channel opening requests with non-zero push amounts. This should prevent accidental pushes to merchant nodes." `
2019-04-04 12:25:31 +03:00
StaggerInitialReconnect bool ` long:"stagger-initial-reconnect" description:"If true, will apply a randomized staggering between 0s and 30s when reconnecting to persistent peers on startup. The first 10 reconnections will be attempted instantly, regardless of the flag's value" `
2018-04-27 23:54:35 +03:00
net tor . Net
2018-08-30 05:05:38 +03:00
Routing * routing . Conf ` group:"routing" namespace:"routing" `
2019-03-14 06:32:39 +03:00
Workers * lncfg . Workers ` group:"workers" namespace:"workers" `
2019-04-02 02:34:17 +03:00
Caches * lncfg . Caches ` group:"caches" namespace:"caches" `
2019-05-31 10:59:27 +03:00
Prometheus lncfg . Prometheus ` group:"prometheus" namespace:"prometheus" `
2016-02-23 05:24:56 +03: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
func loadConfig ( ) ( * config , error ) {
defaultCfg := config {
2018-03-21 02:50:08 +03:00
LndDir : defaultLndDir ,
ConfigFile : defaultConfigFile ,
DataDir : defaultDataDir ,
DebugLevel : defaultLogLevel ,
TLSCertPath : defaultTLSCertPath ,
TLSKeyPath : defaultTLSKeyPath ,
LogDir : defaultLogDir ,
2018-04-07 01:11:42 +03:00
MaxLogFiles : defaultMaxLogFiles ,
MaxLogFileSize : defaultMaxLogFileSize ,
2017-05-03 05:23:24 +03:00
Bitcoin : & chainConfig {
2017-12-17 16:31:38 +03:00
MinHTLC : defaultBitcoinMinHTLCMSat ,
2019-05-15 10:02:53 +03:00
BaseFee : DefaultBitcoinBaseFeeMSat ,
FeeRate : DefaultBitcoinFeeRate ,
TimeLockDelta : DefaultBitcoinTimeLockDelta ,
2017-12-22 08:23:24 +03:00
Node : "btcd" ,
} ,
BtcdMode : & btcdConfig {
2018-02-25 01:18:59 +03:00
Dir : defaultBtcdDir ,
2017-12-22 08:23:24 +03:00
RPCHost : defaultRPCHost ,
RPCCert : defaultBtcdRPCCertFile ,
} ,
BitcoindMode : & bitcoindConfig {
2018-02-25 01:18:59 +03:00
Dir : defaultBitcoindDir ,
2017-12-22 08:23:24 +03:00
RPCHost : defaultRPCHost ,
2017-05-03 05:23:24 +03:00
} ,
Litecoin : & chainConfig {
2017-12-17 16:31:38 +03:00
MinHTLC : defaultLitecoinMinHTLCMSat ,
BaseFee : defaultLitecoinBaseFeeMSat ,
FeeRate : defaultLitecoinFeeRate ,
TimeLockDelta : defaultLitecoinTimeLockDelta ,
2018-03-14 07:14:42 +03:00
Node : "ltcd" ,
2017-12-22 08:23:24 +03:00
} ,
LtcdMode : & btcdConfig {
2018-02-25 01:18:59 +03:00
Dir : defaultLtcdDir ,
2017-12-22 08:23:24 +03:00
RPCHost : defaultRPCHost ,
RPCCert : defaultLtcdRPCCertFile ,
2017-05-03 05:23:24 +03:00
} ,
2018-03-14 07:14:42 +03:00
LitecoindMode : & bitcoindConfig {
Dir : defaultLitecoindDir ,
RPCHost : defaultRPCHost ,
} ,
2019-05-15 10:02:53 +03:00
MaxPendingChannels : DefaultMaxPendingChannels ,
2018-09-05 04:42:40 +03:00
NoSeedBackup : defaultNoSeedBackup ,
2019-01-04 05:38:35 +03:00
MinBackoff : defaultMinBackoff ,
2018-10-04 18:55:37 +03:00
MaxBackoff : defaultMaxBackoff ,
2018-11-03 01:41:38 +03:00
SubRPCServers : & subRPCServerConfigs {
2019-05-22 12:56:04 +03:00
SignRPC : & signrpc . Config { } ,
RouterRPC : routerrpc . DefaultConfig ( ) ,
config+rpc: create new generalized dynamic sub rpc server config framework
In this commit, we add the glue infrastructure to make the sub RPC
server system work properly. Our high level goal is the following: using
only the lnrpc package (with no visibility into the sub RPC servers),
the RPC server is able to find, create, run, and manage the entire set
of present and future sub RPC servers. In order to achieve this, we use
the reflect package and build tags heavily to permit a loosely coupled
configuration parsing system for the sub RPC servers.
We start with a new `subRpcServerConfigs` struct which is _always_
present. This struct has its own group, and will house a series of
sub-configs, one for each sub RPC server. Each sub-config is actually
gated behind a build flag, and can be used to allow users on the command
line or in the config to specify arguments related to the sub-server. If
the config isn't present, then we don't attempt to parse it at all, if
it is, then that means the RPC server has been registered, and we should
parse the contents of its config.
The `subRpcServerConfigs` struct has two main methods:
`PopulateDependancies` and `FetchConfig`. The `PopulateDependancies` is
used to dynamically locate and set the config fields for each new
sub-server. As the config may not actually have any fields (if the build
flag is off), we use the reflect pacakge to determine if things are
compiled in or not, then if so, we dynamically set each of the config
parameters. The `PopulateDependancies` method implements the
`lnrpc.SubServerConfigDispatcher` interface. Our goal is to allow sub
servers to look up their actual config in this main config struct. We
achieve this by using reflect to look up the target field _as if it were
a key in a map_. If the field is found, then we check if it has any
actual attributes (it won't if the build flag is off), if it is, then we
return it as we expect it to be populated already.
2018-10-23 03:58:30 +03:00
} ,
2017-08-11 07:26:48 +03:00
Autopilot : & autoPilotConfig {
2018-03-19 03:10:01 +03:00
MaxChannels : 5 ,
Allocation : 0.6 ,
MinChannelSize : int64 ( minChanFundingSize ) ,
2019-05-15 10:02:53 +03:00
MaxChannelSize : int64 ( MaxFundingAmount ) ,
2018-12-19 20:56:43 +03:00
Heuristic : map [ string ] float64 {
"preferential" : 1.0 ,
} ,
2017-08-11 07:26:48 +03:00
} ,
2019-02-15 04:13:11 +03:00
TrickleDelay : defaultTrickleDelay ,
ChanStatusSampleInterval : defaultChanStatusSampleInterval ,
ChanEnableTimeout : defaultChanEnableTimeout ,
ChanDisableTimeout : defaultChanDisableTimeout ,
Alias : defaultAlias ,
Color : defaultColor ,
MinChanSize : int64 ( minChanFundingSize ) ,
2019-03-23 05:56:18 +03:00
NumGraphSyncPeers : defaultMinPeers ,
2019-04-11 05:31:05 +03:00
HistoricalSyncInterval : discovery . DefaultHistoricalSyncInterval ,
2018-04-27 23:54:35 +03:00
Tor : & torConfig {
2018-07-01 05:25:03 +03:00
SOCKS : defaultTorSOCKS ,
DNS : defaultTorDNS ,
Control : defaultTorControl ,
2018-04-27 23:54:35 +03:00
} ,
net : & tor . ClearNet { } ,
2019-03-14 06:32:39 +03:00
Workers : & lncfg . Workers {
Read : lncfg . DefaultReadWorkers ,
Write : lncfg . DefaultWriteWorkers ,
Sig : lncfg . DefaultSigWorkers ,
} ,
2019-04-02 02:34:17 +03:00
Caches : & lncfg . Caches {
RejectCacheSize : channeldb . DefaultRejectCacheSize ,
ChannelCacheSize : channeldb . DefaultChannelCacheSize ,
} ,
2019-05-31 10:59:27 +03:00
Prometheus : lncfg . DefaultPrometheus ( ) ,
2016-02-23 05:24:56 +03:00
}
2016-03-23 04:44:17 +03:00
// Pre-parse the command line options to pick up an alternative config
// file.
2016-02-23 05:24:56 +03:00
preCfg := defaultCfg
2016-03-23 04:44:17 +03:00
if _ , err := flags . Parse ( & preCfg ) ; err != nil {
2016-02-23 05:24:56 +03:00
return nil , err
}
2016-03-23 04:44:17 +03:00
// Show the version and exit if the version flag was specified.
appName := filepath . Base ( os . Args [ 0 ] )
appName = strings . TrimSuffix ( appName , filepath . Ext ( appName ) )
usageMessage := fmt . Sprintf ( "Use %s -h to show usage" , appName )
if preCfg . ShowVersion {
2018-09-20 13:26:58 +03:00
fmt . Println ( appName , "version" , build . Version ( ) )
2016-03-23 04:44:17 +03:00
os . Exit ( 0 )
}
2018-08-28 08:21:01 +03:00
// If the config file path has not been modified by the user, then we'll
// use the default config file path. However, if the user has modified
// their lnddir, then we should assume they intend to use the config
// file within it.
configFileDir := cleanAndExpandPath ( preCfg . LndDir )
2018-07-06 22:44:36 +03:00
configFilePath := cleanAndExpandPath ( preCfg . ConfigFile )
2018-08-28 08:21:01 +03:00
if configFileDir != defaultLndDir {
2018-07-06 22:44:36 +03:00
if configFilePath == defaultConfigFile {
2018-08-28 08:21:01 +03:00
configFilePath = filepath . Join (
configFileDir , defaultConfigFilename ,
)
2018-07-06 22:44:36 +03:00
}
2018-08-28 08:21:01 +03:00
}
// Next, load any additional configuration options from the file.
var configFileError error
cfg := preCfg
if err := flags . IniParse ( configFilePath , & cfg ) ; err != nil {
2018-09-13 07:35:27 +03:00
// If it's a parsing related error, then we'll return
// immediately, otherwise we can proceed as possibly the config
// file doesn't exist which is OK.
if _ , ok := err . ( * flags . IniError ) ; ok {
return nil , err
}
2018-09-13 08:10:14 +03:00
configFileError = err
2018-08-28 08:21:01 +03:00
}
// Finally, parse the remaining command line options again to ensure
// they take precedence.
if _ , err := flags . Parse ( & cfg ) ; err != nil {
return nil , err
}
// If the provided lnd directory is not the default, we'll modify the
// path to all of the files and directories that will live within it.
lndDir := cleanAndExpandPath ( cfg . LndDir )
if lndDir != defaultLndDir {
cfg . DataDir = filepath . Join ( lndDir , defaultDataDirname )
cfg . TLSCertPath = filepath . Join ( lndDir , defaultTLSCertFilename )
cfg . TLSKeyPath = filepath . Join ( lndDir , defaultTLSKeyFilename )
cfg . LogDir = filepath . Join ( lndDir , defaultLogDirname )
2018-02-24 23:59:22 +03:00
}
// Create the lnd directory if it doesn't already exist.
2016-03-23 04:44:17 +03:00
funcName := "loadConfig"
2018-02-24 23:59:22 +03:00
if err := os . MkdirAll ( lndDir , 0700 ) ; err != nil {
2016-03-23 04:44:17 +03:00
// 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 )
}
}
2018-02-24 23:59:22 +03:00
str := "%s: Failed to create lnd directory: %v"
2016-03-23 04:44:17 +03:00
err := fmt . Errorf ( str , funcName , err )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
2018-02-26 07:10:44 +03:00
// As soon as we're done parsing configuration options, ensure all paths
// to directories and files are cleaned and expanded before attempting
// to use them later on.
cfg . DataDir = cleanAndExpandPath ( cfg . DataDir )
cfg . TLSCertPath = cleanAndExpandPath ( cfg . TLSCertPath )
cfg . TLSKeyPath = cleanAndExpandPath ( cfg . TLSKeyPath )
cfg . AdminMacPath = cleanAndExpandPath ( cfg . AdminMacPath )
cfg . ReadMacPath = cleanAndExpandPath ( cfg . ReadMacPath )
2018-03-21 02:50:08 +03:00
cfg . InvoiceMacPath = cleanAndExpandPath ( cfg . InvoiceMacPath )
2018-02-26 07:10:44 +03:00
cfg . LogDir = cleanAndExpandPath ( cfg . LogDir )
cfg . BtcdMode . Dir = cleanAndExpandPath ( cfg . BtcdMode . Dir )
cfg . LtcdMode . Dir = cleanAndExpandPath ( cfg . LtcdMode . Dir )
cfg . BitcoindMode . Dir = cleanAndExpandPath ( cfg . BitcoindMode . Dir )
2018-03-14 07:14:42 +03:00
cfg . LitecoindMode . Dir = cleanAndExpandPath ( cfg . LitecoindMode . Dir )
2018-07-01 05:25:03 +03:00
cfg . Tor . PrivateKeyPath = cleanAndExpandPath ( cfg . Tor . PrivateKeyPath )
2018-02-26 07:10:44 +03:00
2018-04-27 23:54:35 +03:00
// Ensure that the user didn't attempt to specify negative values for
// any of the autopilot params.
if cfg . Autopilot . MaxChannels < 0 {
str := "%s: autopilot.maxchannels must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . Allocation < 0 {
str := "%s: autopilot.allocation must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . MinChannelSize < 0 {
str := "%s: autopilot.minchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . MaxChannelSize < 0 {
str := "%s: autopilot.maxchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
2018-08-10 05:03:08 +03:00
if cfg . Autopilot . MinConfs < 0 {
str := "%s: autopilot.minconfs must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
2017-10-21 00:45:23 +03:00
2018-04-27 23:54:35 +03:00
// Ensure that the specified values for the min and max channel size
// don't are within the bounds of the normal chan size constraints.
if cfg . Autopilot . MinChannelSize < int64 ( minChanFundingSize ) {
cfg . Autopilot . MinChannelSize = int64 ( minChanFundingSize )
}
2019-05-15 10:02:53 +03:00
if cfg . Autopilot . MaxChannelSize > int64 ( MaxFundingAmount ) {
cfg . Autopilot . MaxChannelSize = int64 ( MaxFundingAmount )
2018-04-27 23:54:35 +03:00
}
2017-10-25 22:06:26 +03:00
2018-12-19 20:56:43 +03:00
if _ , err := validateAtplCfg ( cfg . Autopilot ) ; err != nil {
return nil , err
}
2018-04-27 23:54:35 +03:00
// Validate the Tor config parameters.
2018-05-23 16:41:16 +03:00
socks , err := lncfg . ParseAddressString (
2018-04-27 23:54:35 +03:00
cfg . Tor . SOCKS , strconv . Itoa ( defaultTorSOCKSPort ) ,
2018-06-28 01:05:11 +03:00
cfg . net . ResolveTCPAddr ,
2018-04-27 23:54:35 +03:00
)
2018-05-23 16:41:16 +03:00
if err != nil {
return nil , err
}
cfg . Tor . SOCKS = socks . String ( )
2018-06-28 01:05:11 +03:00
2018-06-30 02:24:53 +03:00
// We'll only attempt to normalize and resolve the DNS host if it hasn't
// changed, as it doesn't need to be done for the default.
if cfg . Tor . DNS != defaultTorDNS {
dns , err := lncfg . ParseAddressString (
cfg . Tor . DNS , strconv . Itoa ( defaultTorDNSPort ) ,
cfg . net . ResolveTCPAddr ,
)
if err != nil {
return nil , err
}
cfg . Tor . DNS = dns . String ( )
2018-05-23 16:41:16 +03:00
}
2018-06-28 01:05:11 +03:00
2018-05-23 16:41:16 +03:00
control , err := lncfg . ParseAddressString (
2018-04-27 23:54:35 +03:00
cfg . Tor . Control , strconv . Itoa ( defaultTorControlPort ) ,
2018-06-28 01:05:11 +03:00
cfg . net . ResolveTCPAddr ,
2018-04-27 23:54:35 +03:00
)
2018-05-23 16:41:16 +03:00
if err != nil {
return nil , err
}
cfg . Tor . Control = control . String ( )
2018-06-28 01:05:11 +03:00
2018-04-27 23:54:35 +03:00
switch {
case cfg . Tor . V2 && cfg . Tor . V3 :
return nil , errors . New ( "either tor.v2 or tor.v3 can be set, " +
"but not both" )
case cfg . DisableListen && ( cfg . Tor . V2 || cfg . Tor . V3 ) :
return nil , errors . New ( "listening must be enabled when " +
"enabling inbound connections over Tor" )
}
2017-10-21 00:45:23 +03:00
2018-07-01 05:25:03 +03:00
if cfg . Tor . PrivateKeyPath == "" {
switch {
case cfg . Tor . V2 :
cfg . Tor . PrivateKeyPath = filepath . Join (
lndDir , defaultTorV2PrivateKeyFilename ,
)
case cfg . Tor . V3 :
cfg . Tor . PrivateKeyPath = filepath . Join (
lndDir , defaultTorV3PrivateKeyFilename ,
)
}
}
2018-04-27 23:54:35 +03:00
// Set up the network-related functions that will be used throughout
// the daemon. We use the standard Go "net" package functions by
// default. If we should be proxying all traffic through Tor, then
// we'll use the Tor proxy specific functions in order to avoid leaking
// our real information.
if cfg . Tor . Active {
cfg . net = & tor . ProxyNet {
SOCKS : cfg . Tor . SOCKS ,
DNS : cfg . Tor . DNS ,
StreamIsolation : cfg . Tor . StreamIsolation ,
}
2017-10-21 00:45:23 +03:00
}
2018-04-18 08:37:34 +03:00
if cfg . DisableListen && cfg . NAT {
return nil , errors . New ( "NAT traversal cannot be used when " +
"listening is disabled" )
}
2018-04-27 23:54:35 +03:00
// Determine the active chain configuration and its parameters.
2017-12-22 08:23:24 +03:00
switch {
2017-05-03 05:23:24 +03:00
// At this moment, multiple active chains are not supported.
2017-12-22 08:23:24 +03:00
case cfg . Litecoin . Active && cfg . Bitcoin . Active :
2017-05-03 05:23:24 +03:00
str := "%s: Currently both Bitcoin and Litecoin cannot be " +
"active together"
2017-12-22 08:23:24 +03:00
return nil , fmt . Errorf ( str , funcName )
2017-05-18 21:48:59 +03:00
2017-10-18 05:36:04 +03:00
// Either Bitcoin must be active, or Litecoin must be active.
// Otherwise, we don't know which chain we're on.
case ! cfg . Bitcoin . Active && ! cfg . Litecoin . Active :
2017-12-22 08:23:24 +03:00
return nil , fmt . Errorf ( "%s: either bitcoin.active or " +
"litecoin.active must be set to 1 (true)" , funcName )
2017-10-18 05:36:04 +03:00
case cfg . Litecoin . Active :
2017-12-17 16:31:38 +03:00
if cfg . Litecoin . TimeLockDelta < minTimeLockDelta {
return nil , fmt . Errorf ( "timelockdelta must be at least %v" ,
minTimeLockDelta )
}
2018-03-15 12:04:17 +03:00
// Multiple networks can't be selected simultaneously. Count
// number of network flags passed; assign active network params
// while we're at it.
numNets := 0
var ltcParams litecoinNetParams
if cfg . Litecoin . MainNet {
numNets ++
ltcParams = litecoinMainNetParams
}
if cfg . Litecoin . TestNet3 {
numNets ++
ltcParams = litecoinTestNetParams
}
2018-11-30 00:53:01 +03:00
if cfg . Litecoin . RegTest {
numNets ++
ltcParams = litecoinRegTestNetParams
}
if cfg . Litecoin . SimNet {
numNets ++
ltcParams = litecoinSimNetParams
}
2018-03-15 12:04:17 +03:00
if numNets > 1 {
str := "%s: The mainnet, testnet, and simnet params " +
"can't be used together -- choose one of the " +
"three"
err := fmt . Errorf ( str , funcName )
return nil , err
}
// The target network must be provided, otherwise, we won't
// know how to initialize the daemon.
if numNets == 0 {
str := "%s: either --litecoin.mainnet, or " +
"litecoin.testnet must be specified"
err := fmt . Errorf ( str , funcName )
return nil , err
}
2018-06-30 00:04:42 +03:00
if cfg . Litecoin . MainNet && cfg . DebugHTLC {
str := "%s: debug-htlc mode cannot be used " +
"on litecoin mainnet"
err := fmt . Errorf ( str , funcName )
return nil , err
}
2017-05-03 05:23:24 +03:00
// The litecoin chain is the current active chain. However
2017-12-22 08:23:24 +03:00
// throughout the codebase we required chaincfg.Params. So as a
2017-05-03 05:23:24 +03:00
// temporary hack, we'll mutate the default net params for
2017-10-18 05:36:04 +03:00
// bitcoin with the litecoin specific information.
2018-03-15 12:04:17 +03:00
applyLitecoinParams ( & activeNetParams , & ltcParams )
2017-05-03 05:23:24 +03:00
2018-03-14 07:14:42 +03:00
switch cfg . Litecoin . Node {
case "ltcd" :
err := parseRPCParams ( cfg . Litecoin , cfg . LtcdMode ,
litecoinChain , funcName )
if err != nil {
err := fmt . Errorf ( "unable to load RPC " +
"credentials for ltcd: %v" , err )
return nil , err
}
case "litecoind" :
if cfg . Litecoin . SimNet {
return nil , fmt . Errorf ( "%s: litecoind does not " +
"support simnet" , funcName )
}
err := parseRPCParams ( cfg . Litecoin , cfg . LitecoindMode ,
litecoinChain , funcName )
if err != nil {
err := fmt . Errorf ( "unable to load RPC " +
"credentials for litecoind: %v" , err )
return nil , err
}
default :
str := "%s: only ltcd and litecoind mode supported for " +
"litecoin at this time"
return nil , fmt . Errorf ( str , funcName )
2017-05-03 05:23:24 +03:00
}
2018-01-06 00:42:13 +03:00
cfg . Litecoin . ChainDir = filepath . Join ( cfg . DataDir ,
defaultChainSubDirname ,
litecoinChain . String ( ) )
2017-05-03 05:23:24 +03:00
// Finally we'll register the litecoin chain as our current
// primary chain.
registeredChains . RegisterPrimaryChain ( litecoinChain )
2019-05-15 10:02:53 +03:00
MaxFundingAmount = maxLtcFundingAmount
MaxPaymentMSat = maxLtcPaymentMSat
2017-10-18 05:36:04 +03:00
case cfg . Bitcoin . Active :
2017-05-03 05:23:24 +03:00
// Multiple networks can't be selected simultaneously. Count
// number of network flags passed; assign active network params
// while we're at it.
numNets := 0
2018-03-15 12:04:17 +03:00
if cfg . Bitcoin . MainNet {
numNets ++
activeNetParams = bitcoinMainNetParams
}
2017-05-03 05:23:24 +03:00
if cfg . Bitcoin . TestNet3 {
numNets ++
activeNetParams = bitcoinTestNetParams
}
2017-07-12 02:54:43 +03:00
if cfg . Bitcoin . RegTest {
numNets ++
2018-11-30 00:53:01 +03:00
activeNetParams = bitcoinRegTestNetParams
2017-07-12 02:54:43 +03:00
}
2017-05-03 05:23:24 +03:00
if cfg . Bitcoin . SimNet {
2017-09-04 03:00:05 +03:00
numNets ++
2017-05-03 05:23:24 +03:00
activeNetParams = bitcoinSimNetParams
}
if numNets > 1 {
2018-03-15 12:04:17 +03:00
str := "%s: The mainnet, testnet, regtest, and " +
"simnet params can't be used together -- " +
"choose one of the four"
err := fmt . Errorf ( str , funcName )
return nil , err
}
// The target network must be provided, otherwise, we won't
// know how to initialize the daemon.
if numNets == 0 {
str := "%s: either --bitcoin.mainnet, or " +
"bitcoin.testnet, bitcoin.simnet, or bitcoin.regtest " +
"must be specified"
err := fmt . Errorf ( str , funcName )
return nil , err
}
2018-06-30 00:04:42 +03:00
if cfg . Bitcoin . MainNet && cfg . DebugHTLC {
str := "%s: debug-htlc mode cannot be used " +
"on bitcoin mainnet"
err := fmt . Errorf ( str , funcName )
return nil , err
}
2018-03-15 12:04:17 +03:00
if cfg . Bitcoin . Node == "neutrino" && cfg . Bitcoin . MainNet {
str := "%s: neutrino isn't yet supported for " +
"bitcoin's mainnet"
2017-05-03 05:23:24 +03:00
err := fmt . Errorf ( str , funcName )
return nil , err
}
2017-12-17 16:31:38 +03:00
if cfg . Bitcoin . TimeLockDelta < minTimeLockDelta {
return nil , fmt . Errorf ( "timelockdelta must be at least %v" ,
minTimeLockDelta )
}
2017-12-22 08:23:24 +03:00
switch cfg . Bitcoin . Node {
case "btcd" :
2018-03-15 12:04:17 +03:00
err := parseRPCParams (
cfg . Bitcoin , cfg . BtcdMode , bitcoinChain , funcName ,
)
2017-12-22 08:23:24 +03:00
if err != nil {
err := fmt . Errorf ( "unable to load RPC " +
"credentials for btcd: %v" , err )
return nil , err
}
case "bitcoind" :
if cfg . Bitcoin . SimNet {
return nil , fmt . Errorf ( "%s: bitcoind does not " +
"support simnet" , funcName )
}
2018-03-15 12:04:17 +03:00
err := parseRPCParams (
cfg . Bitcoin , cfg . BitcoindMode , bitcoinChain , funcName ,
)
2017-05-18 21:48:59 +03:00
if err != nil {
2017-12-22 08:23:24 +03:00
err := fmt . Errorf ( "unable to load RPC " +
"credentials for bitcoind: %v" , err )
2017-05-18 21:48:59 +03:00
return nil , err
}
2017-12-22 08:23:24 +03:00
case "neutrino" :
// No need to get RPC parameters.
2018-08-30 05:05:38 +03:00
2018-03-14 07:14:42 +03:00
default :
str := "%s: only btcd, bitcoind, and neutrino mode " +
"supported for bitcoin at this time"
return nil , fmt . Errorf ( str , funcName )
2017-05-03 05:23:24 +03:00
}
2017-05-18 21:48:59 +03:00
2018-01-06 00:42:13 +03:00
cfg . Bitcoin . ChainDir = filepath . Join ( cfg . DataDir ,
defaultChainSubDirname ,
bitcoinChain . String ( ) )
2017-05-03 05:23:24 +03:00
// Finally we'll register the bitcoin chain as our current
// primary chain.
registeredChains . RegisterPrimaryChain ( bitcoinChain )
}
2018-05-23 22:05:04 +03:00
// Ensure that the user didn't attempt to specify negative values for
// any of the autopilot params.
if cfg . Autopilot . MaxChannels < 0 {
str := "%s: autopilot.maxchannels must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . Allocation < 0 {
str := "%s: autopilot.allocation must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . MinChannelSize < 0 {
str := "%s: autopilot.minchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . MaxChannelSize < 0 {
str := "%s: autopilot.maxchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
// Ensure that the specified values for the min and max channel size
// don't are within the bounds of the normal chan size constraints.
if cfg . Autopilot . MinChannelSize < int64 ( minChanFundingSize ) {
cfg . Autopilot . MinChannelSize = int64 ( minChanFundingSize )
}
2019-05-15 10:02:53 +03:00
if cfg . Autopilot . MaxChannelSize > int64 ( MaxFundingAmount ) {
cfg . Autopilot . MaxChannelSize = int64 ( MaxFundingAmount )
2018-05-23 22:05:04 +03:00
}
2017-01-13 08:01:50 +03:00
// Validate profile port number.
2016-06-21 07:42:07 +03:00
if cfg . Profile != "" {
profilePort , err := strconv . Atoi ( cfg . Profile )
if err != nil || profilePort < 1024 || profilePort > 65535 {
str := "%s: The profile port must be between 1024 and 65535"
err := fmt . Errorf ( str , funcName )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , err
}
}
2018-08-24 03:44:14 +03:00
// We'll now construct the network directory which will be where we
2019-02-09 06:39:00 +03:00
// store all the data specific to this chain/network.
2018-08-22 22:27:16 +03:00
networkDir = filepath . Join (
cfg . DataDir , defaultChainSubDirname ,
registeredChains . PrimaryChain ( ) . String ( ) ,
normalizeNetwork ( activeNetParams . Name ) ,
)
2017-08-22 10:03:03 +03:00
// If a custom macaroon directory wasn't specified and the data
// directory has changed from the default path, then we'll also update
// the path for the macaroons to be generated.
2018-08-22 22:30:14 +03:00
if cfg . AdminMacPath == "" {
2018-03-21 02:50:08 +03:00
cfg . AdminMacPath = filepath . Join (
2018-08-22 22:27:16 +03:00
networkDir , defaultAdminMacFilename ,
2018-03-21 02:50:08 +03:00
)
2017-08-22 10:03:03 +03:00
}
2018-08-22 22:30:14 +03:00
if cfg . ReadMacPath == "" {
2018-03-21 02:50:08 +03:00
cfg . ReadMacPath = filepath . Join (
2018-08-22 22:27:16 +03:00
networkDir , defaultReadMacFilename ,
2018-03-21 02:50:08 +03:00
)
}
2018-08-22 22:30:14 +03:00
if cfg . InvoiceMacPath == "" {
2018-03-21 02:50:08 +03:00
cfg . InvoiceMacPath = filepath . Join (
2018-08-22 22:27:16 +03:00
networkDir , defaultInvoiceMacFilename ,
2018-03-21 02:50:08 +03:00
)
2017-08-22 10:03:03 +03:00
}
2019-02-09 06:39:00 +03:00
// Similarly, if a custom back up file path wasn't specified, then
// we'll update the file location to match our set network directory.
if cfg . BackupFilePath == "" {
cfg . BackupFilePath = filepath . Join (
networkDir , chanbackup . DefaultBackupFileName ,
)
}
2016-03-23 04:44:17 +03:00
// Append the network type to the log directory so it is "namespaced"
// per network in the same fashion as the data directory.
2017-05-03 05:23:24 +03:00
cfg . LogDir = filepath . Join ( cfg . LogDir ,
2018-01-06 00:42:13 +03:00
registeredChains . PrimaryChain ( ) . String ( ) ,
normalizeNetwork ( activeNetParams . Name ) )
2016-03-23 04:44:17 +03:00
2018-08-24 05:48:21 +03:00
// Special show command to list supported subsystems and exit.
if cfg . DebugLevel == "show" {
fmt . Println ( "Supported subsystems" , supportedSubsystems ( ) )
os . Exit ( 0 )
}
2016-03-23 04:44:17 +03:00
// Initialize logging at the default logging level.
2018-06-06 03:40:40 +03:00
initLogRotator (
2018-05-23 16:38:19 +03:00
filepath . Join ( cfg . LogDir , defaultLogFilename ) ,
cfg . MaxLogFileSize , cfg . MaxLogFiles ,
2018-06-06 03:40:40 +03:00
)
2016-03-23 04:44:17 +03:00
// Parse, validate, and set debug log level(s).
if err := parseAndSetDebugLevels ( cfg . DebugLevel ) ; err != nil {
err := fmt . Errorf ( "%s: %v" , funcName , err . Error ( ) )
fmt . Fprintln ( os . Stderr , err )
fmt . Fprintln ( os . Stderr , usageMessage )
return nil , err
}
2018-05-23 16:38:19 +03:00
// At least one RPCListener is required. So listen on localhost per
// default.
if len ( cfg . RawRPCListeners ) == 0 {
2017-12-17 20:28:38 +03:00
addr := fmt . Sprintf ( "localhost:%d" , defaultRPCPort )
2018-05-23 16:38:19 +03:00
cfg . RawRPCListeners = append ( cfg . RawRPCListeners , addr )
2017-12-17 20:28:38 +03:00
}
2018-05-23 16:38:19 +03:00
// Listen on localhost if no REST listeners were specified.
if len ( cfg . RawRESTListeners ) == 0 {
2017-12-17 20:28:38 +03:00
addr := fmt . Sprintf ( "localhost:%d" , defaultRESTPort )
2018-05-23 16:38:19 +03:00
cfg . RawRESTListeners = append ( cfg . RawRESTListeners , addr )
2017-12-17 20:28:38 +03:00
}
// Listen on the default interface/port if no listeners were specified.
2018-05-23 16:38:19 +03:00
// An empty address string means default interface/address, which on
2019-01-17 08:11:27 +03:00
// most unix systems is the same as 0.0.0.0. If Tor is active, we
// default to only listening on localhost for hidden service
// connections.
2018-05-23 16:38:19 +03:00
if len ( cfg . RawListeners ) == 0 {
2017-12-17 20:28:38 +03:00
addr := fmt . Sprintf ( ":%d" , defaultPeerPort )
2019-01-17 08:11:27 +03:00
if cfg . Tor . Active {
addr = fmt . Sprintf ( "localhost:%d" , defaultPeerPort )
}
2018-05-23 16:38:19 +03:00
cfg . RawListeners = append ( cfg . RawListeners , addr )
2017-12-17 20:28:38 +03:00
}
// Add default port to all RPC listener addresses if needed and remove
// duplicate addresses.
2018-05-23 16:41:16 +03:00
cfg . RPCListeners , err = lncfg . NormalizeAddresses (
2018-05-23 16:38:19 +03:00
cfg . RawRPCListeners , strconv . Itoa ( defaultRPCPort ) ,
2018-06-28 01:05:11 +03:00
cfg . net . ResolveTCPAddr ,
2018-04-23 19:42:17 +03:00
)
2018-05-23 16:38:19 +03:00
if err != nil {
return nil , err
}
2017-12-17 20:28:38 +03:00
// Add default port to all REST listener addresses if needed and remove
// duplicate addresses.
2018-05-23 16:41:16 +03:00
cfg . RESTListeners , err = lncfg . NormalizeAddresses (
2018-05-23 16:38:19 +03:00
cfg . RawRESTListeners , strconv . Itoa ( defaultRESTPort ) ,
2018-06-28 01:05:11 +03:00
cfg . net . ResolveTCPAddr ,
2018-04-23 19:42:17 +03:00
)
2018-05-23 16:38:19 +03:00
if err != nil {
return nil , err
}
2017-12-17 20:28:38 +03:00
2019-04-13 04:39:14 +03:00
// For each of the RPC listeners (REST+gRPC), we'll ensure that users
// have specified a safe combo for authentication. If not, we'll bail
// out with an error.
err = lncfg . EnforceSafeAuthentication (
cfg . RPCListeners , ! cfg . NoMacaroons ,
)
if err != nil {
return nil , err
}
err = lncfg . EnforceSafeAuthentication (
cfg . RESTListeners , ! cfg . NoMacaroons ,
)
if err != nil {
return nil , err
}
2018-07-03 07:54:17 +03:00
// Remove the listening addresses specified if listening is disabled.
if cfg . DisableListen {
ltndLog . Infof ( "Listening on the p2p interface is disabled!" )
cfg . Listeners = nil
cfg . ExternalIPs = nil
} else {
2018-04-23 19:42:17 +03:00
2018-07-03 07:54:17 +03:00
// Add default port to all listener addresses if needed and remove
// duplicate addresses.
cfg . Listeners , err = lncfg . NormalizeAddresses (
cfg . RawListeners , strconv . Itoa ( defaultPeerPort ) ,
cfg . net . ResolveTCPAddr ,
)
if err != nil {
return nil , err
}
2018-05-23 16:38:19 +03:00
2018-07-03 07:54:17 +03:00
// Add default port to all external IP addresses if needed and remove
// duplicate addresses.
cfg . ExternalIPs , err = lncfg . NormalizeAddresses (
cfg . RawExternalIPs , strconv . Itoa ( defaultPeerPort ) ,
cfg . net . ResolveTCPAddr ,
)
if err != nil {
2018-05-23 16:38:19 +03:00
return nil , err
}
2018-07-03 07:54:17 +03:00
// For the p2p port it makes no sense to listen to an Unix socket.
// Also, we would need to refactor the brontide listener to support
// that.
for _ , p2pListener := range cfg . Listeners {
if lncfg . IsUnix ( p2pListener ) {
err := fmt . Errorf ( "unix socket addresses cannot be " +
"used for the p2p connection listener: %s" ,
p2pListener )
return nil , err
}
}
2018-05-23 16:38:19 +03:00
}
2017-12-17 20:28:38 +03:00
2019-01-04 05:38:35 +03:00
// Ensure that the specified minimum backoff is below or equal to the
// maximum backoff.
if cfg . MinBackoff > cfg . MaxBackoff {
return nil , fmt . Errorf ( "maxbackoff must be greater than " +
"minbackoff" )
}
2019-04-02 02:34:17 +03:00
// Validate the subconfigs for workers and caches.
err = lncfg . Validate (
cfg . Workers ,
cfg . Caches ,
)
if err != nil {
2019-03-14 06:32:52 +03:00
return nil , err
}
2018-10-25 08:10:18 +03:00
// Finally, ensure that the user's color is correctly formatted,
// otherwise the server will not be able to start after the unlocking
// the wallet.
_ , err = parseHexColor ( cfg . Color )
if err != nil {
return nil , fmt . Errorf ( "Unable to parse node color: %v" , err )
}
2017-06-19 17:44:26 +03: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 {
ltndLog . Warnf ( "%v" , configFileError )
}
2016-03-23 04:44:17 +03:00
return & cfg , nil
}
// cleanAndExpandPath expands environment variables and leading ~ in the
// passed path, cleans the result, and returns it.
2017-07-26 02:22:06 +03:00
// This function is taken from https://github.com/btcsuite/btcd
2016-03-23 04:44:17 +03:00
func cleanAndExpandPath ( path string ) string {
2018-08-22 22:25:55 +03:00
if path == "" {
return ""
}
2016-03-23 04:44:17 +03:00
// Expand initial ~ to OS specific home directory.
if strings . HasPrefix ( path , "~" ) {
2018-02-26 06:41:44 +03:00
var homeDir string
user , err := user . Current ( )
if err == nil {
homeDir = user . HomeDir
} else {
homeDir = os . Getenv ( "HOME" )
}
2016-03-23 04:44:17 +03:00
path = strings . Replace ( path , "~" , homeDir , 1 )
}
// NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
2017-01-13 08:01:50 +03:00
// but the variables can still be expanded via POSIX-style $VARIABLE.
2016-03-23 04:44:17 +03:00
return filepath . Clean ( os . ExpandEnv ( path ) )
}
// parseAndSetDebugLevels attempts to parse the specified debug level and set
2016-06-21 07:42:07 +03:00
// the levels accordingly. An appropriate error is returned if anything is
2016-03-23 04:44:17 +03:00
// invalid.
func parseAndSetDebugLevels ( debugLevel string ) error {
2017-12-18 05:40:05 +03:00
// When the specified string doesn't have any delimiters, treat it as
2016-03-23 04:44:17 +03:00
// 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 )
2016-02-23 05:24:56 +03:00
}
2016-03-23 04:44:17 +03:00
// 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 -- " +
2018-02-07 06:11:11 +03:00
"supported subsystems %v"
2016-03-23 04:44:17 +03:00
return fmt . Errorf ( str , subsysID , supportedSubsystems ( ) )
2016-02-23 05:24:56 +03:00
}
2016-03-23 04:44:17 +03:00
// Validate log level.
if ! validLogLevel ( logLevel ) {
str := "The specified debug level [%v] is invalid"
return fmt . Errorf ( str , logLevel )
}
setLogLevel ( subsysID , logLevel )
2016-02-23 05:24:56 +03:00
}
2016-03-23 04:44:17 +03:00
return nil
}
// validLogLevel returns whether or not logLevel is a valid debug log level.
func validLogLevel ( logLevel string ) bool {
switch logLevel {
case "trace" :
fallthrough
case "debug" :
fallthrough
case "info" :
fallthrough
case "warn" :
fallthrough
case "error" :
fallthrough
case "critical" :
2018-04-17 05:17:58 +03:00
fallthrough
case "off" :
2016-03-23 04:44:17 +03:00
return true
}
return false
}
// 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
2016-02-23 05:24:56 +03:00
}
2016-12-15 05:11:31 +03:00
2017-12-22 08:23:24 +03:00
func parseRPCParams ( cConfig * chainConfig , nodeConfig interface { } , net chainCode ,
funcName string ) error {
2018-02-25 01:18:59 +03:00
// First, we'll check our node config to make sure the RPC parameters
// were set correctly. We'll also determine the path to the conf file
// depending on the backend node.
var daemonName , confDir , confFile string
2017-12-22 08:23:24 +03:00
switch conf := nodeConfig . ( type ) {
case * btcdConfig :
2018-01-18 23:54:41 +03:00
// If both RPCUser and RPCPass are set, we assume those
// credentials are good to use.
if conf . RPCUser != "" && conf . RPCPass != "" {
2017-12-22 08:23:24 +03:00
return nil
}
2018-03-22 00:53:35 +03:00
// Get the daemon name for displaying proper errors.
switch net {
case bitcoinChain :
daemonName = "btcd"
2018-07-17 02:48:31 +03:00
confDir = conf . Dir
confFile = "btcd"
2018-03-22 00:53:35 +03:00
case litecoinChain :
daemonName = "ltcd"
2018-07-17 02:48:31 +03:00
confDir = conf . Dir
confFile = "ltcd"
2018-03-22 00:53:35 +03:00
}
2018-01-18 23:54:41 +03:00
// If only ONE of RPCUser or RPCPass is set, we assume the
// user did that unintentionally.
if conf . RPCUser != "" || conf . RPCPass != "" {
2018-03-24 05:26:43 +03:00
return fmt . Errorf ( "please set both or neither of " +
2018-03-22 00:53:35 +03:00
"%[1]v.rpcuser, %[1]v.rpcpass" , daemonName )
2018-01-18 23:54:41 +03:00
}
2018-02-25 01:18:59 +03:00
2017-12-22 08:23:24 +03:00
case * bitcoindConfig :
2018-08-28 08:20:16 +03:00
// Ensure that if the ZMQ options are set, that they are not
// equal.
if conf . ZMQPubRawBlock != "" && conf . ZMQPubRawTx != "" {
err := checkZMQOptions (
conf . ZMQPubRawBlock , conf . ZMQPubRawTx ,
)
if err != nil {
return err
}
}
2018-07-17 02:48:31 +03:00
// If all of RPCUser, RPCPass, ZMQBlockHost, and ZMQTxHost are
// set, we assume those parameters are good to use.
if conf . RPCUser != "" && conf . RPCPass != "" &&
conf . ZMQPubRawBlock != "" && conf . ZMQPubRawTx != "" {
2017-12-22 08:23:24 +03:00
return nil
}
2018-03-22 00:53:35 +03:00
// Get the daemon name for displaying proper errors.
switch net {
case bitcoinChain :
daemonName = "bitcoind"
2018-07-17 02:48:31 +03:00
confDir = conf . Dir
confFile = "bitcoin"
2018-03-22 00:53:35 +03:00
case litecoinChain :
daemonName = "litecoind"
2018-07-17 02:48:31 +03:00
confDir = conf . Dir
confFile = "litecoin"
2018-03-22 00:53:35 +03:00
}
2018-07-17 02:48:31 +03:00
2018-08-28 08:20:16 +03:00
// If not all of the parameters are set, we'll assume the user
// did this unintentionally.
2018-07-17 02:48:31 +03:00
if conf . RPCUser != "" || conf . RPCPass != "" ||
conf . ZMQPubRawBlock != "" || conf . ZMQPubRawTx != "" {
2018-03-24 05:26:43 +03:00
return fmt . Errorf ( "please set all or none of " +
"%[1]v.rpcuser, %[1]v.rpcpass, " +
2018-07-17 02:48:31 +03:00
"%[1]v.zmqpubrawblock, %[1]v.zmqpubrawtx" ,
daemonName )
2018-03-14 07:14:42 +03:00
}
2017-05-03 05:23:24 +03:00
}
// If we're in simnet mode, then the running btcd instance won't read
// the RPC credentials from the configuration. So if lnd wasn't
2017-08-25 04:54:17 +03:00
// specified the parameters, then we won't be able to start.
2017-05-03 05:23:24 +03:00
if cConfig . SimNet {
str := "%v: rpcuser and rpcpass must be set to your btcd " +
2017-08-25 04:54:17 +03:00
"node's RPC parameters for simnet mode"
2017-05-03 05:23:24 +03:00
return fmt . Errorf ( str , funcName )
}
fmt . Println ( "Attempting automatic RPC configuration to " + daemonName )
2018-02-25 01:18:59 +03:00
confFile = filepath . Join ( confDir , fmt . Sprintf ( "%v.conf" , confFile ) )
2017-12-22 08:23:24 +03:00
switch cConfig . Node {
2018-03-14 07:14:42 +03:00
case "btcd" , "ltcd" :
2017-12-22 08:23:24 +03:00
nConf := nodeConfig . ( * btcdConfig )
rpcUser , rpcPass , err := extractBtcdRPCParams ( confFile )
if err != nil {
return fmt . Errorf ( "unable to extract RPC credentials:" +
" %v, cannot start w/o RPC connection" ,
err )
}
nConf . RPCUser , nConf . RPCPass = rpcUser , rpcPass
2018-03-14 07:14:42 +03:00
case "bitcoind" , "litecoind" :
2017-12-22 08:23:24 +03:00
nConf := nodeConfig . ( * bitcoindConfig )
2018-07-17 02:48:31 +03:00
rpcUser , rpcPass , zmqBlockHost , zmqTxHost , err :=
extractBitcoindRPCParams ( confFile )
2017-12-22 08:23:24 +03:00
if err != nil {
return fmt . Errorf ( "unable to extract RPC credentials:" +
" %v, cannot start w/o RPC connection" ,
err )
}
2018-07-17 02:48:31 +03:00
nConf . RPCUser , nConf . RPCPass = rpcUser , rpcPass
nConf . ZMQPubRawBlock , nConf . ZMQPubRawTx = zmqBlockHost , zmqTxHost
2017-05-03 05:23:24 +03:00
}
fmt . Printf ( "Automatically obtained %v's RPC credentials\n" , daemonName )
return nil
}
2017-12-22 08:23:24 +03:00
// extractBtcdRPCParams attempts to extract the RPC credentials for an existing
2017-04-01 17:02:50 +03:00
// btcd instance. The passed path is expected to be the location of btcd's
// application data directory on the target system.
2017-12-22 08:23:24 +03:00
func extractBtcdRPCParams ( btcdConfigPath string ) ( string , string , error ) {
2017-04-01 17:02:50 +03:00
// First, we'll open up the btcd configuration file found at the target
// destination.
btcdConfigFile , err := os . Open ( btcdConfigPath )
if err != nil {
return "" , "" , err
}
defer btcdConfigFile . Close ( )
// With the file open extract the contents of the configuration file so
2017-12-22 08:23:24 +03:00
// we can attempt to locate the RPC credentials.
2017-04-01 17:02:50 +03:00
configContents , err := ioutil . ReadAll ( btcdConfigFile )
if err != nil {
return "" , "" , err
}
// Attempt to locate the RPC user using a regular expression. If we
// don't have a match for our regular expression then we'll exit with
// an error.
2018-04-01 02:06:00 +03:00
rpcUserRegexp , err := regexp . Compile ( ` (?m)^\s*rpcuser\s*=\s*([^\s]+) ` )
2017-04-01 17:02:50 +03:00
if err != nil {
return "" , "" , err
}
userSubmatches := rpcUserRegexp . FindSubmatch ( configContents )
if userSubmatches == nil {
return "" , "" , fmt . Errorf ( "unable to find rpcuser in config" )
}
// Similarly, we'll use another regular expression to find the set
// rpcpass (if any). If we can't find the pass, then we'll exit with an
// error.
2018-04-01 02:06:00 +03:00
rpcPassRegexp , err := regexp . Compile ( ` (?m)^\s*rpcpass\s*=\s*([^\s]+) ` )
2017-04-01 17:02:50 +03:00
if err != nil {
return "" , "" , err
}
passSubmatches := rpcPassRegexp . FindSubmatch ( configContents )
if passSubmatches == nil {
return "" , "" , fmt . Errorf ( "unable to find rpcuser in config" )
}
return string ( userSubmatches [ 1 ] ) , string ( passSubmatches [ 1 ] ) , nil
}
2017-12-22 08:23:24 +03:00
// extractBitcoindParams attempts to extract the RPC credentials for an
// existing bitcoind node instance. The passed path is expected to be the
// location of bitcoind's bitcoin.conf on the target system. The routine looks
// for a cookie first, optionally following the datadir configuration option in
// the bitcoin.conf. If it doesn't find one, it looks for rpcuser/rpcpassword.
2018-07-17 02:48:31 +03:00
func extractBitcoindRPCParams ( bitcoindConfigPath string ) ( string , string , string , string , error ) {
2017-12-22 08:23:24 +03:00
// First, we'll open up the bitcoind configuration file found at the
// target destination.
bitcoindConfigFile , err := os . Open ( bitcoindConfigPath )
if err != nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , err
2017-12-22 08:23:24 +03:00
}
defer bitcoindConfigFile . Close ( )
// With the file open extract the contents of the configuration file so
// we can attempt to locate the RPC credentials.
configContents , err := ioutil . ReadAll ( bitcoindConfigFile )
if err != nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , err
2017-12-22 08:23:24 +03:00
}
2018-07-17 02:48:31 +03:00
// First, we'll look for the ZMQ hosts providing raw block and raw
// transaction notifications.
zmqBlockHostRE , err := regexp . Compile (
` (?m)^\s*zmqpubrawblock\s*=\s*([^\s]+) ` ,
)
2017-12-22 08:23:24 +03:00
if err != nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , err
}
zmqBlockHostSubmatches := zmqBlockHostRE . FindSubmatch ( configContents )
if len ( zmqBlockHostSubmatches ) < 2 {
return "" , "" , "" , "" , fmt . Errorf ( "unable to find " +
"zmqpubrawblock in config" )
}
zmqTxHostRE , err := regexp . Compile ( ` (?m)^\s*zmqpubrawtx\s*=\s*([^\s]+) ` )
if err != nil {
return "" , "" , "" , "" , err
}
zmqTxHostSubmatches := zmqTxHostRE . FindSubmatch ( configContents )
if len ( zmqTxHostSubmatches ) < 2 {
return "" , "" , "" , "" , errors . New ( "unable to find zmqpubrawtx " +
"in config" )
2017-12-22 08:23:24 +03:00
}
2018-07-17 02:48:31 +03:00
zmqBlockHost := string ( zmqBlockHostSubmatches [ 1 ] )
zmqTxHost := string ( zmqTxHostSubmatches [ 1 ] )
2018-08-28 08:20:16 +03:00
if err := checkZMQOptions ( zmqBlockHost , zmqTxHost ) ; err != nil {
return "" , "" , "" , "" , err
2017-12-22 08:23:24 +03:00
}
// Next, we'll try to find an auth cookie. We need to detect the chain
// by seeing if one is specified in the configuration file.
dataDir := path . Dir ( bitcoindConfigPath )
2018-04-01 02:06:00 +03:00
dataDirRE , err := regexp . Compile ( ` (?m)^\s*datadir\s*=\s*([^\s]+) ` )
2017-12-22 08:23:24 +03:00
if err != nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , err
2017-12-22 08:23:24 +03:00
}
dataDirSubmatches := dataDirRE . FindSubmatch ( configContents )
if dataDirSubmatches != nil {
dataDir = string ( dataDirSubmatches [ 1 ] )
}
chainDir := "/"
2018-03-27 15:51:41 +03:00
switch activeNetParams . Params . Name {
case "testnet3" :
chainDir = "/testnet3/"
case "testnet4" :
chainDir = "/testnet4/"
case "regtest" :
chainDir = "/regtest/"
2017-12-22 08:23:24 +03:00
}
cookie , err := ioutil . ReadFile ( dataDir + chainDir + ".cookie" )
if err == nil {
splitCookie := strings . Split ( string ( cookie ) , ":" )
if len ( splitCookie ) == 2 {
2018-07-17 02:48:31 +03:00
return splitCookie [ 0 ] , splitCookie [ 1 ] , zmqBlockHost ,
zmqTxHost , nil
2017-12-22 08:23:24 +03:00
}
}
// We didn't find a cookie, so we attempt to locate the RPC user using
// a regular expression. If we don't have a match for our regular
// expression then we'll exit with an error.
2018-04-01 02:06:00 +03:00
rpcUserRegexp , err := regexp . Compile ( ` (?m)^\s*rpcuser\s*=\s*([^\s]+) ` )
2017-12-22 08:23:24 +03:00
if err != nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , err
2017-12-22 08:23:24 +03:00
}
userSubmatches := rpcUserRegexp . FindSubmatch ( configContents )
if userSubmatches == nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , fmt . Errorf ( "unable to find rpcuser in " +
"config" )
2017-12-22 08:23:24 +03:00
}
// Similarly, we'll use another regular expression to find the set
// rpcpass (if any). If we can't find the pass, then we'll exit with an
// error.
2018-04-01 02:06:00 +03:00
rpcPassRegexp , err := regexp . Compile ( ` (?m)^\s*rpcpassword\s*=\s*([^\s]+) ` )
2017-12-22 08:23:24 +03:00
if err != nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , err
2017-12-22 08:23:24 +03:00
}
passSubmatches := rpcPassRegexp . FindSubmatch ( configContents )
if passSubmatches == nil {
2018-07-17 02:48:31 +03:00
return "" , "" , "" , "" , fmt . Errorf ( "unable to find rpcpassword " +
"in config" )
2017-12-22 08:23:24 +03:00
}
return string ( userSubmatches [ 1 ] ) , string ( passSubmatches [ 1 ] ) ,
2018-07-17 02:48:31 +03:00
zmqBlockHost , zmqTxHost , nil
2017-12-22 08:23:24 +03:00
}
2017-12-17 20:28:38 +03:00
2018-08-28 08:20:16 +03:00
// checkZMQOptions ensures that the provided addresses to use as the hosts for
// ZMQ rawblock and rawtx notifications are different.
func checkZMQOptions ( zmqBlockHost , zmqTxHost string ) error {
if zmqBlockHost == zmqTxHost {
return errors . New ( "zmqpubrawblock and zmqpubrawtx must be set" +
"to different addresses" )
}
return nil
}
2018-01-06 00:42:13 +03:00
// normalizeNetwork returns the common name of a network type used to create
// file paths. This allows differently versioned networks to use the same path.
func normalizeNetwork ( network string ) string {
if strings . HasPrefix ( network , "testnet" ) {
return "testnet"
}
return network
}