2017-11-28 03:12:09 +03:00
// Copyright (c) 2013-2017 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
2020-05-13 16:08:27 +03:00
// Copyright (C) 2015-2020 The Lightning Network Developers
2017-11-28 03:12:09 +03:00
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-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"
2020-09-18 15:07:40 +03:00
"github.com/lightninglabs/neutrino"
2019-06-08 18:29:33 +03:00
"github.com/lightningnetwork/lnd/autopilot"
2018-09-20 13:26:58 +03:00
"github.com/lightningnetwork/lnd/build"
2020-09-29 18:56:18 +03:00
"github.com/lightningnetwork/lnd/chainreg"
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"
2020-11-17 02:28:56 +03:00
"github.com/lightningnetwork/lnd/funding"
2019-07-27 04:05:58 +03:00
"github.com/lightningnetwork/lnd/htlcswitch"
2018-04-27 00:07:45 +03:00
"github.com/lightningnetwork/lnd/htlcswitch/hodl"
2020-08-13 01:45:57 +03:00
"github.com/lightningnetwork/lnd/input"
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"
2020-12-10 16:16:53 +03:00
"github.com/lightningnetwork/lnd/lnwallet"
2018-08-30 05:05:38 +03:00
"github.com/lightningnetwork/lnd/routing"
2020-08-28 12:18:15 +03:00
"github.com/lightningnetwork/lnd/signal"
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
defaultDataDirname = "data"
defaultChainSubDirname = "chain"
defaultGraphSubDirname = "graph"
2019-06-14 03:31:35 +03:00
defaultTowerSubDirname = "watchtower"
2019-05-15 10:02:53 +03:00
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"
2020-02-03 13:52:22 +03:00
defaultNoSeedBackup = false
defaultPaymentsExpirationGracePeriod = time . Duration ( 0 )
defaultTrickleDelay = 90 * 1000
defaultChanStatusSampleInterval = time . Minute
defaultChanEnableTimeout = 19 * time . Minute
defaultChanDisableTimeout = 20 * time . Minute
2020-06-27 04:40:00 +03:00
defaultHeightHintCacheQueryDisable = false
2020-02-03 13:52:22 +03:00
defaultMaxLogFiles = 3
defaultMaxLogFileSize = 10
defaultMinBackoff = time . Second
defaultMaxBackoff = time . Hour
2019-01-07 20:48:02 +03:00
defaultLetsEncryptDirname = "letsencrypt"
2020-09-17 10:54:23 +03:00
defaultLetsEncryptListen = ":80"
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
2017-12-17 16:31:38 +03:00
// minTimeLockDelta is the minimum timelock we require for incoming
// HTLCs on our channels.
2020-07-24 23:13:56 +03:00
minTimeLockDelta = routing . MinCLTVDelta
2017-12-17 16:31:38 +03:00
2020-03-17 22:43:14 +03:00
// defaultAcceptorTimeout is the time after which an RPCAcceptor will time
// out and return false if it hasn't yet received a response.
defaultAcceptorTimeout = 15 * time . Second
2017-12-16 02:03:38 +03:00
defaultAlias = ""
defaultColor = "#3399FF"
2020-05-13 03:05:18 +03:00
2021-03-02 15:11:10 +03:00
// defaultCoopCloseTargetConfs is the default confirmation target
// that will be used to estimate a fee rate to use during a
// cooperative channel closure initiated by a remote peer. By default
// we'll set this to a lax value since we weren't the ones that
// initiated the channel closure.
defaultCoopCloseTargetConfs = 6
2020-05-13 03:05:18 +03:00
// defaultHostSampleInterval is the default amount of time that the
// HostAnnouncer will wait between DNS resolutions to check if the
// backing IP of a host has changed.
defaultHostSampleInterval = time . Minute * 5
2020-08-24 09:54:38 +03:00
defaultChainInterval = time . Minute
2021-01-14 23:07:31 +03:00
defaultChainTimeout = time . Second * 30
defaultChainBackoff = time . Minute * 2
2020-08-24 09:54:38 +03:00
defaultChainAttempts = 3
2020-08-24 09:54:39 +03:00
2020-09-15 10:27:02 +03:00
// Set defaults for a health check which ensures that we have space
// available on disk. Although this check is off by default so that we
// avoid breaking any existing setups (particularly on mobile), we still
// set the other default values so that the health check can be easily
// enabled with sane defaults.
2020-08-24 09:54:39 +03:00
defaultRequiredDisk = 0.1
defaultDiskInterval = time . Hour * 12
defaultDiskTimeout = time . Second * 5
defaultDiskBackoff = time . Minute
2020-09-15 10:27:02 +03:00
defaultDiskAttempts = 0
2020-08-13 01:45:57 +03:00
2020-12-02 05:34:19 +03:00
// Set defaults for a health check which ensures that the TLS certificate
// is not expired. Although this check is off by default (not all setups
// require it), we still set the other default values so that the health
// check can be easily enabled with sane defaults.
defaultTLSInterval = time . Minute
defaultTLSTimeout = time . Second * 5
defaultTLSBackoff = time . Minute
defaultTLSAttempts = 0
2020-08-13 01:45:57 +03:00
// defaultRemoteMaxHtlcs specifies the default limit for maximum
// concurrent HTLCs the remote party may add to commitment transactions.
// This value can be overridden with --default-remote-max-htlcs.
defaultRemoteMaxHtlcs = 483
2020-10-29 12:29:53 +03:00
// defaultMaxLocalCSVDelay is the maximum delay we accept on our
// commitment output.
// TODO(halseth): find a more scientific choice of value.
defaultMaxLocalCSVDelay = 10000
2016-02-23 05:24:56 +03:00
)
var (
2020-05-13 15:56:19 +03:00
// DefaultLndDir is the default directory where lnd tries to find its
// configuration file and store its data. This is a directory in the
// user's application data, for example:
// C:\Users\<username>\AppData\Local\Lnd on Windows
// ~/.lnd on Linux
// ~/Library/Application Support/Lnd on MacOS
DefaultLndDir = btcutil . AppDataDir ( "lnd" , false )
// DefaultConfigFile is the default full path of lnd's configuration
// file.
2020-05-13 16:47:45 +03:00
DefaultConfigFile = filepath . Join ( DefaultLndDir , lncfg . DefaultConfigFilename )
2020-05-13 15:56:19 +03:00
defaultDataDir = filepath . Join ( DefaultLndDir , defaultDataDirname )
defaultLogDir = filepath . Join ( DefaultLndDir , defaultLogDirname )
2018-03-21 02:50:08 +03:00
2019-06-14 03:31:35 +03:00
defaultTowerDir = filepath . Join ( defaultDataDir , defaultTowerSubDirname )
2019-01-07 20:48:02 +03:00
defaultTLSCertPath = filepath . Join ( DefaultLndDir , defaultTLSCertFilename )
defaultTLSKeyPath = filepath . Join ( DefaultLndDir , defaultTLSKeyFilename )
defaultLetsEncryptDir = filepath . Join ( DefaultLndDir , defaultLetsEncryptDirname )
2018-03-21 02:50:08 +03:00
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 ) )
2020-03-13 11:41:08 +03:00
// bitcoindEsimateModes defines all the legal values for bitcoind's
// estimatesmartfee RPC call.
defaultBitcoindEstimateMode = "CONSERVATIVE"
bitcoindEstimateModes = [ 2 ] string { "ECONOMICAL" , defaultBitcoindEstimateMode }
2020-05-07 06:49:36 +03:00
defaultSphinxDbName = "sphinxreplay.db"
2016-02-23 05:24:56 +03:00
)
2020-04-30 10:34:10 +03:00
// Config defines the configuration options for lnd.
2016-03-23 04:44:17 +03:00
//
2020-04-30 10:34:10 +03:00
// See LoadConfig for further details regarding the configuration
2016-03-23 04:44:17 +03:00
// loading+parsing process.
2020-04-30 10:34:10 +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" `
2020-02-05 15:51:48 +03:00
LndDir string ` long:"lnddir" description:"The base directory that contains lnd's data, logs, configuration file, etc." `
ConfigFile string ` short:"C" long:"configfile" description:"Path to configuration file" `
DataDir string ` short:"b" long:"datadir" description:"The directory to store lnd's data within" `
SyncFreelist bool ` long:"sync-freelist" description:"Whether the databases used within lnd should sync their freelist to disk. This is disabled by default resulting in improved memory performance during operation, but with an increase in startup time." `
2020-06-26 20:53:05 +03:00
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" `
TLSAutoRefresh bool ` long:"tlsautorefresh" description:"Re-generate TLS certificate and key if the IPs or domains are changed" `
TLSDisableAutofill bool ` long:"tlsdisableautofill" description:"Do not include the interface IPs or the system hostname in TLS certificate, use first --tlsextradomain as Common Name instead, if set" `
2020-02-05 15:51:48 +03:00
2020-07-21 13:12:13 +03:00
NoMacaroons bool ` long:"no-macaroons" description:"Disable macaroon authentication, can only be used if server is not listening on a public interface." `
2020-03-17 22:43:14 +03:00
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" `
AcceptorTimeout time . Duration ` long:"acceptortimeout" description:"Time after which an RPCAcceptor will time out and return false if it hasn't yet received a response" `
2018-05-23 16:38:19 +03:00
2019-01-07 20:48:02 +03:00
LetsEncryptDir string ` long:"letsencryptdir" description:"The directory to store Let's Encrypt certificates within" `
2020-09-17 10:54:23 +03:00
LetsEncryptListen string ` long:"letsencryptlisten" description:"The IP:port on which lnd will listen for Let's Encrypt challenges. Let's Encrypt will always try to contact on port 80. Often non-root processes are not allowed to bind to ports lower than 1024. This configuration option allows a different port to be used, but must be used in combination with port forwarding from port 80. This configuration can also be used to specify another IP address to listen on, for example an IPv6 address." `
2019-01-07 20:48:02 +03:00
LetsEncryptDomain string ` long:"letsencryptdomain" description:"Request a Let's Encrypt certificate for this domain. Note that the certicate is only requested and stored when the first rpc connection comes in." `
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!
2020-08-25 07:54:31 +03:00
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" `
ExternalHosts [ ] string ` long:"externalhosts" description:"A set of hosts that should be periodically resolved to announce IPs for" `
RPCListeners [ ] net . Addr
RESTListeners [ ] net . Addr
RestCORS [ ] string ` long:"restcors" description:"Add an ip:port/hostname to allow cross origin access from. To allow all origins, set as \"*\"." `
Listeners [ ] net . Addr
ExternalIPs [ ] net . Addr
DisableListen bool ` long:"nolisten" description:"Disable listening for incoming peer connections" `
DisableRest bool ` long:"norest" description:"Disable REST API" `
2020-09-24 14:34:24 +03:00
DisableRestTLS bool ` long:"no-rest-tls" description:"Disable TLS for REST connections" `
2020-08-25 07:54:31 +03:00
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" `
MinBackoff time . Duration ` long:"minbackoff" description:"Shortest backoff when reconnecting to persistent peers. Valid time units are { s, m, h}." `
MaxBackoff time . Duration ` long:"maxbackoff" description:"Longest backoff when reconnecting to persistent peers. Valid time units are { s, m, h}." `
ConnectionTimeout time . Duration ` long:"connectiontimeout" description:"The timeout value for network connections. Valid time units are { ms, s, m, h}." `
2016-03-23 04:44:17 +03:00
2020-11-16 13:23:26 +03:00
DebugLevel string ` short:"d" long:"debuglevel" description:"Logging level for all subsystems { trace, debug, info, warn, error, critical} -- You may also specify <global-level>,<subsystem>=<level>,<subsystem2>=<level>,... to set the log level for individual subsystems -- Use show to list available subsystems" `
2016-03-23 04:44:17 +03:00
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-11-20 07:13:04 +03:00
UnsafeDisconnect bool ` long:"unsafe-disconnect" description:"DEPRECATED: Allows the rpcserver to intentionally disconnect from peers with open channels. THIS FLAG WILL BE REMOVED IN 0.10.0" `
2019-02-09 06:39:00 +03:00
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
2021-01-11 11:22:38 +03:00
FeeURL string ` long:"feeurl" description:"Optional URL for external fee estimation. If no URL is specified, the method for fee estimation will depend on the chosen backend and network. Must be set for neutrino on mainnet." `
2020-09-10 10:43:35 +03:00
2020-05-13 16:57:30 +03:00
Bitcoin * lncfg . Chain ` group:"Bitcoin" namespace:"bitcoin" `
BtcdMode * lncfg . Btcd ` group:"btcd" namespace:"btcd" `
BitcoindMode * lncfg . Bitcoind ` group:"bitcoind" namespace:"bitcoind" `
NeutrinoMode * lncfg . Neutrino ` group:"neutrino" namespace:"neutrino" `
2017-08-11 07:26:48 +03:00
2020-05-13 16:57:30 +03:00
Litecoin * lncfg . Chain ` group:"Litecoin" namespace:"litecoin" `
LtcdMode * lncfg . Btcd ` group:"ltcd" namespace:"ltcd" `
LitecoindMode * lncfg . Bitcoind ` group:"litecoind" namespace:"litecoind" `
2017-12-22 08:23:24 +03:00
2020-05-13 16:57:30 +03:00
Autopilot * lncfg . AutoPilot ` group:"Autopilot" namespace:"autopilot" `
2017-09-04 03:00:05 +03:00
2020-05-13 16:57:30 +03:00
Tor * lncfg . Tor ` group:"Tor" namespace:"tor" `
2018-01-22 14:48:59 +03:00
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
2020-08-05 08:29:15 +03:00
NoSeedBackup bool ` long:"noseedbackup" description:"If true, NO SEED WILL BE EXPOSED -- EVER, AND THE WALLET WILL BE ENCRYPTED USING THE DEFAULT PASSPHRASE. THIS FLAG IS ONLY FOR TESTING AND SHOULD NEVER BE USED ON MAINNET." `
2017-09-14 02:33:46 +03:00
2020-10-24 17:34:52 +03:00
ResetWalletTransactions bool ` long:"reset-wallet-transactions" description:"Removes all transaction history from the on-chain wallet on startup, forcing a full chain rescan starting at the wallet's birthday. Implements the same functionality as btcwallet's dropwtxmgr command. Should be set to false after successful execution to avoid rescanning on every restart of lnd." `
2020-02-03 13:52:22 +03:00
PaymentsExpirationGracePeriod time . Duration ` long:"payments-expiration-grace-period" description:"A period to wait before force closing channels with outgoing htlcs that have timed-out and are a result of this node initiated payments." `
TrickleDelay int ` long:"trickledelay" description:"Time in milliseconds between each release of announcements to the network" `
2020-03-20 02:07:47 +03:00
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." `
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." `
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." `
2020-06-27 04:40:00 +03:00
HeightHintCacheQueryDisable bool ` long:"height-hint-cache-query-disable" description:"Disable queries from the height-hint cache to try to recover channels stuck in the pending close state. Disabling height hint queries may cause longer chain rescans, resulting in a performance hit. Unset this after channels are unstuck so you can get better performance again." `
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" `
2020-09-15 05:16:32 +03:00
MaxChanSize int64 ` long:"maxchansize" description:"The largest channel size (in satoshis) that we should accept. Incoming channels larger than this will be rejected" `
2021-03-02 15:11:10 +03:00
CoopCloseTargetConfs uint32 ` long:"coop-close-target-confs" description:"The target number of blocks that a cooperative channel close transaction should confirm in. This is used to estimate the fee to use as the lower bound during fee negotiation for the channel closure." `
2017-10-21 00:45:23 +03:00
2020-08-13 01:45:57 +03:00
DefaultRemoteMaxHtlcs uint16 ` long:"default-remote-max-htlcs" description:"The default max_htlc applied when opening or accepting channels. This value limits the number of concurrent HTLCs that the remote party can add to the commitment. The maximum possible value is 483." `
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
2019-07-31 03:26:03 +03:00
IgnoreHistoricalGossipFilters bool ` long:"ignore-historical-gossip-filters" description:"If true, will not reply with historical data that matches the range specified by a remote peer's gossip_timestamp_filter. Doing so will result in lower memory and bandwidth requirements." `
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." `
2018-11-19 20:37:50 +03:00
RejectHTLC bool ` long:"rejecthtlc" description:"If true, lnd will not forward any HTLCs that are meant as onward payments. This option will still allow lnd to send HTLCs and receive HTLCs but lnd won't be used as a hop." `
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" `
2019-07-27 04:05:58 +03:00
MaxOutgoingCltvExpiry uint32 ` long:"max-cltv-expiry" description:"The maximum number of blocks funds could be locked up for when forwarding payments." `
2019-08-24 02:04:59 +03:00
MaxChannelFeeAllocation float64 ` long:"max-channel-fee-allocation" description:"The maximum percentage of total funds that can be allocated to a channel's commitment fee. This only applies for the initiator of the channel. Valid values are within [0.1, 1]." `
2020-12-10 16:16:53 +03:00
MaxCommitFeeRateAnchors uint64 ` long:"max-commit-fee-rate-anchors" description:"The maximum fee rate in sat/vbyte that will be used for commitments of channels of the anchors type. Must be large enough to ensure transaction propagation" `
2020-05-12 01:38:56 +03:00
DryRunMigration bool ` long:"dry-run-migration" description:"If true, lnd will abort committing a migration if it would otherwise have been successful. This leaves the database unmodified, and still compatible with the previously active version of lnd." `
2018-04-27 23:54:35 +03:00
net tor . Net
2018-08-30 05:05:38 +03:00
2019-12-10 21:13:55 +03:00
EnableUpfrontShutdown bool ` long:"enable-upfront-shutdown" description:"If true, option upfront shutdown script will be enabled. If peers that we open channels with support this feature, we will automatically set the script to which cooperative closes should be paid out to on channel open. This offers the partial protection of a channel peer disconnecting from us if cooperative close is attempted with a different script." `
2019-12-03 12:38:29 +03:00
2020-01-16 15:13:59 +03:00
AcceptKeySend bool ` long:"accept-keysend" description:"If true, spontaneous payments through keysend will be accepted. [experimental]" `
2019-12-05 14:55:17 +03:00
2020-04-09 11:42:10 +03:00
KeysendHoldTime time . Duration ` long:"keysend-hold-time" description:"If non-zero, keysend payments are accepted but not immediately settled. If the payment isn't settled manually after the specified time, it is canceled automatically. [experimental]" `
2020-07-29 00:57:51 +03:00
GcCanceledInvoicesOnStartup bool ` long:"gc-canceled-invoices-on-startup" description:"If true, we'll attempt to garbage collect canceled invoices upon start." `
2020-08-04 19:28:15 +03:00
GcCanceledInvoicesOnTheFly bool ` long:"gc-canceled-invoices-on-the-fly" description:"If true, we'll delete newly canceled invoices on the fly." `
2020-10-21 12:22:34 +03:00
Routing * lncfg . Routing ` group:"routing" namespace:"routing" `
2019-03-14 06:32:39 +03:00
2021-01-29 11:14:21 +03:00
Gossip * lncfg . Gossip ` group:"gossip" namespace:"gossip" `
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" `
2019-06-14 03:29:28 +03:00
WtClient * lncfg . WtClient ` group:"wtclient" namespace:"wtclient" `
2019-06-14 03:31:35 +03:00
Watchtower * lncfg . Watchtower ` group:"watchtower" namespace:"watchtower" `
2019-08-06 07:34:46 +03:00
2020-03-06 18:11:48 +03:00
ProtocolOptions * lncfg . ProtocolOptions ` group:"protocol" namespace:"protocol" `
2020-01-30 11:01:18 +03:00
AllowCircularRoute bool ` long:"allow-circular-route" description:"If true, our node will allow htlc forwards that arrive and depart on the same channel." `
2020-05-14 14:37:32 +03:00
2020-08-24 09:54:38 +03:00
HealthChecks * lncfg . HealthCheckConfig ` group:"healthcheck" namespace:"healthcheck" `
2020-03-13 19:05:28 +03:00
DB * lncfg . DB ` group:"db" namespace:"db" `
2020-05-25 19:22:41 +03:00
// LogWriter is the root logger that all of the daemon's subloggers are
// hooked up to.
LogWriter * build . RotatingLogWriter
2020-05-14 14:37:32 +03:00
// registeredChains keeps track of all chains that have been registered
// with the daemon.
2020-10-06 21:56:10 +03:00
registeredChains * chainreg . ChainRegistry
2020-05-14 14:40:18 +03:00
// networkDir is the path to the directory of the currently active
// network. This path will hold the files related to each different
// network.
networkDir string
2020-08-04 21:56:31 +03:00
// ActiveNetParams contains parameters of the target chain.
2020-09-29 20:00:19 +03:00
ActiveNetParams chainreg . BitcoinNetParams
2016-02-23 05:24:56 +03:00
}
2020-04-30 10:55:32 +03:00
// DefaultConfig returns all default values for the Config struct.
func DefaultConfig ( ) Config {
return Config {
2020-09-17 10:54:23 +03:00
LndDir : DefaultLndDir ,
ConfigFile : DefaultConfigFile ,
DataDir : defaultDataDir ,
DebugLevel : defaultLogLevel ,
TLSCertPath : defaultTLSCertPath ,
TLSKeyPath : defaultTLSKeyPath ,
LetsEncryptDir : defaultLetsEncryptDir ,
LetsEncryptListen : defaultLetsEncryptListen ,
LogDir : defaultLogDir ,
MaxLogFiles : defaultMaxLogFiles ,
MaxLogFileSize : defaultMaxLogFileSize ,
AcceptorTimeout : defaultAcceptorTimeout ,
2020-05-13 16:57:30 +03:00
Bitcoin : & lncfg . Chain {
2020-10-06 21:56:10 +03:00
MinHTLCIn : chainreg . DefaultBitcoinMinHTLCInMSat ,
MinHTLCOut : chainreg . DefaultBitcoinMinHTLCOutMSat ,
BaseFee : chainreg . DefaultBitcoinBaseFeeMSat ,
FeeRate : chainreg . DefaultBitcoinFeeRate ,
TimeLockDelta : chainreg . DefaultBitcoinTimeLockDelta ,
2020-10-29 12:29:53 +03:00
MaxLocalDelay : defaultMaxLocalCSVDelay ,
2017-12-22 08:23:24 +03:00
Node : "btcd" ,
} ,
2020-05-13 16:57:30 +03:00
BtcdMode : & lncfg . Btcd {
2018-02-25 01:18:59 +03:00
Dir : defaultBtcdDir ,
2017-12-22 08:23:24 +03:00
RPCHost : defaultRPCHost ,
RPCCert : defaultBtcdRPCCertFile ,
} ,
2020-05-13 16:57:30 +03:00
BitcoindMode : & lncfg . Bitcoind {
2020-03-13 11:41:08 +03:00
Dir : defaultBitcoindDir ,
RPCHost : defaultRPCHost ,
EstimateMode : defaultBitcoindEstimateMode ,
2017-05-03 05:23:24 +03:00
} ,
2020-05-13 16:57:30 +03:00
Litecoin : & lncfg . Chain {
2020-10-06 21:56:10 +03:00
MinHTLCIn : chainreg . DefaultLitecoinMinHTLCInMSat ,
MinHTLCOut : chainreg . DefaultLitecoinMinHTLCOutMSat ,
BaseFee : chainreg . DefaultLitecoinBaseFeeMSat ,
FeeRate : chainreg . DefaultLitecoinFeeRate ,
TimeLockDelta : chainreg . DefaultLitecoinTimeLockDelta ,
2020-10-29 12:29:53 +03:00
MaxLocalDelay : defaultMaxLocalCSVDelay ,
2018-03-14 07:14:42 +03:00
Node : "ltcd" ,
2017-12-22 08:23:24 +03:00
} ,
2020-05-13 16:57:30 +03:00
LtcdMode : & lncfg . Btcd {
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
} ,
2020-05-13 16:57:30 +03:00
LitecoindMode : & lncfg . Bitcoind {
2020-03-13 11:41:08 +03:00
Dir : defaultLitecoindDir ,
RPCHost : defaultRPCHost ,
EstimateMode : defaultBitcoindEstimateMode ,
2018-03-14 07:14:42 +03:00
} ,
2020-09-18 15:07:40 +03:00
NeutrinoMode : & lncfg . Neutrino {
UserAgentName : neutrino . UserAgentName ,
UserAgentVersion : neutrino . UserAgentVersion ,
} ,
2019-11-20 07:13:04 +03:00
UnsafeDisconnect : true ,
2020-05-13 16:47:45 +03:00
MaxPendingChannels : lncfg . 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 ,
2020-08-25 07:54:31 +03:00
ConnectionTimeout : tor . DefaultConnTimeout ,
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
} ,
2020-05-13 16:57:30 +03:00
Autopilot : & lncfg . AutoPilot {
2018-03-19 03:10:01 +03:00
MaxChannels : 5 ,
Allocation : 0.6 ,
2020-11-17 02:28:56 +03:00
MinChannelSize : int64 ( funding . MinChanFundingSize ) ,
2019-05-15 10:02:53 +03:00
MaxChannelSize : int64 ( MaxFundingAmount ) ,
2019-07-24 21:59:28 +03:00
MinConfs : 1 ,
2019-06-08 18:29:33 +03:00
ConfTarget : autopilot . DefaultConfTarget ,
2018-12-19 20:56:43 +03:00
Heuristic : map [ string ] float64 {
2020-10-03 06:13:54 +03:00
"top_centrality" : 1.0 ,
2018-12-19 20:56:43 +03:00
} ,
2017-08-11 07:26:48 +03:00
} ,
2020-02-03 13:52:22 +03:00
PaymentsExpirationGracePeriod : defaultPaymentsExpirationGracePeriod ,
TrickleDelay : defaultTrickleDelay ,
ChanStatusSampleInterval : defaultChanStatusSampleInterval ,
ChanEnableTimeout : defaultChanEnableTimeout ,
ChanDisableTimeout : defaultChanDisableTimeout ,
2020-06-27 04:40:00 +03:00
HeightHintCacheQueryDisable : defaultHeightHintCacheQueryDisable ,
2020-02-03 13:52:22 +03:00
Alias : defaultAlias ,
Color : defaultColor ,
2020-11-17 02:28:56 +03:00
MinChanSize : int64 ( funding . MinChanFundingSize ) ,
2020-09-15 05:16:32 +03:00
MaxChanSize : int64 ( 0 ) ,
2021-03-02 15:11:10 +03:00
CoopCloseTargetConfs : defaultCoopCloseTargetConfs ,
2020-08-13 01:45:57 +03:00
DefaultRemoteMaxHtlcs : defaultRemoteMaxHtlcs ,
2020-02-03 13:52:22 +03:00
NumGraphSyncPeers : defaultMinPeers ,
HistoricalSyncInterval : discovery . DefaultHistoricalSyncInterval ,
2020-05-13 16:57:30 +03:00
Tor : & lncfg . Tor {
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 ( ) ,
2019-06-14 03:31:35 +03:00
Watchtower : & lncfg . Watchtower {
TowerDir : defaultTowerDir ,
} ,
2020-08-24 09:54:38 +03:00
HealthChecks : & lncfg . HealthCheckConfig {
ChainCheck : & lncfg . CheckConfig {
Interval : defaultChainInterval ,
Timeout : defaultChainTimeout ,
Attempts : defaultChainAttempts ,
Backoff : defaultChainBackoff ,
} ,
2020-08-24 09:54:39 +03:00
DiskCheck : & lncfg . DiskCheckConfig {
RequiredRemaining : defaultRequiredDisk ,
CheckConfig : & lncfg . CheckConfig {
Interval : defaultDiskInterval ,
Attempts : defaultDiskAttempts ,
Timeout : defaultDiskTimeout ,
Backoff : defaultDiskBackoff ,
} ,
} ,
2020-12-02 05:34:19 +03:00
TLSCheck : & lncfg . CheckConfig {
Interval : defaultTLSInterval ,
Timeout : defaultTLSTimeout ,
Attempts : defaultTLSAttempts ,
Backoff : defaultTLSBackoff ,
} ,
2020-08-24 09:54:38 +03:00
} ,
2021-03-04 02:12:25 +03:00
Gossip : & lncfg . Gossip {
MaxChannelUpdateBurst : discovery . DefaultMaxChannelUpdateBurst ,
ChannelUpdateInterval : discovery . DefaultChannelUpdateInterval ,
} ,
2019-08-24 02:04:59 +03:00
MaxOutgoingCltvExpiry : htlcswitch . DefaultMaxOutgoingCltvExpiry ,
MaxChannelFeeAllocation : htlcswitch . DefaultMaxLinkFeeAllocation ,
2020-12-10 16:16:53 +03:00
MaxCommitFeeRateAnchors : lnwallet . DefaultAnchorsCommitMaxFeeRateSatPerVByte ,
2020-05-25 19:22:41 +03:00
LogWriter : build . NewRotatingLogWriter ( ) ,
2020-03-13 19:05:28 +03:00
DB : lncfg . DefaultDB ( ) ,
2020-10-06 21:56:10 +03:00
registeredChains : chainreg . NewChainRegistry ( ) ,
2020-09-29 20:00:19 +03:00
ActiveNetParams : chainreg . BitcoinTestNetParams ,
2016-02-23 05:24:56 +03:00
}
2020-04-30 10:55:32 +03:00
}
2016-03-23 04:44:17 +03:00
2020-04-30 10:55:32 +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
2020-08-28 12:18:15 +03:00
func LoadConfig ( interceptor signal . Interceptor ) ( * Config , error ) {
2016-03-23 04:44:17 +03:00
// Pre-parse the command line options to pick up an alternative config
// file.
2020-04-30 10:55:32 +03:00
preCfg := DefaultConfig ( )
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 {
2020-04-14 12:13:11 +03:00
fmt . Println ( appName , "version" , build . Version ( ) ,
"commit=" + build . Commit )
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.
2020-04-30 11:02:56 +03:00
configFileDir := CleanAndExpandPath ( preCfg . LndDir )
configFilePath := CleanAndExpandPath ( preCfg . ConfigFile )
2020-05-13 15:56:19 +03:00
if configFileDir != DefaultLndDir {
if configFilePath == DefaultConfigFile {
2018-08-28 08:21:01 +03:00
configFilePath = filepath . Join (
2020-05-13 16:47:45 +03:00
configFileDir , lncfg . DefaultConfigFilename ,
2018-08-28 08:21:01 +03:00
)
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
}
2020-04-30 11:00:46 +03:00
// Make sure everything we just loaded makes sense.
2020-08-28 12:18:15 +03:00
cleanCfg , err := ValidateConfig ( cfg , usageMessage , interceptor )
2020-04-30 11:00:46 +03:00
if err != nil {
return nil , err
}
// 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 )
}
return cleanCfg , nil
}
// ValidateConfig check the given configuration to be sane. This makes sure no
// illegal values or combination of values are set. All file system paths are
// normalized. The cleaned up config is returned on success.
2020-08-28 12:18:15 +03:00
func ValidateConfig ( cfg Config , usageMessage string ,
interceptor signal . Interceptor ) ( * Config , error ) {
2018-08-28 08:21:01 +03:00
// 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.
2020-04-30 11:02:56 +03:00
lndDir := CleanAndExpandPath ( cfg . LndDir )
2020-05-13 15:56:19 +03:00
if lndDir != DefaultLndDir {
2018-08-28 08:21:01 +03:00
cfg . DataDir = filepath . Join ( lndDir , defaultDataDirname )
2019-01-07 20:48:02 +03:00
cfg . LetsEncryptDir = filepath . Join (
lndDir , defaultLetsEncryptDirname ,
)
2018-08-28 08:21:01 +03:00
cfg . TLSCertPath = filepath . Join ( lndDir , defaultTLSCertFilename )
cfg . TLSKeyPath = filepath . Join ( lndDir , defaultTLSKeyFilename )
cfg . LogDir = filepath . Join ( lndDir , defaultLogDirname )
2019-06-14 03:31:35 +03:00
// If the watchtower's directory is set to the default, i.e. the
// user has not requested a different location, we'll move the
// location to be relative to the specified lnd directory.
if cfg . Watchtower . TowerDir == defaultTowerDir {
cfg . Watchtower . TowerDir =
filepath . Join ( cfg . DataDir , defaultTowerSubDirname )
}
2018-02-24 23:59:22 +03:00
}
2016-03-23 04:44:17 +03:00
funcName := "loadConfig"
2020-09-16 16:07:15 +03:00
makeDirectory := func ( dir string ) error {
err := os . MkdirAll ( dir , 0700 )
if err != nil {
// Show a nicer error message if it's because a symlink
// is linked to a directory that does not exist
// (probably because it's not mounted).
if e , ok := err . ( * os . PathError ) ; ok && os . IsExist ( err ) {
link , lerr := os . Readlink ( e . Path )
if lerr == nil {
str := "is symlink %s -> %s mounted?"
err = fmt . Errorf ( str , e . Path , link )
}
2016-03-23 04:44:17 +03:00
}
2020-09-16 16:07:15 +03:00
str := "%s: Failed to create lnd directory: %v"
err := fmt . Errorf ( str , funcName , err )
_ , _ = fmt . Fprintln ( os . Stderr , err )
return err
2016-03-23 04:44:17 +03:00
}
2020-09-16 16:07:15 +03:00
return nil
2016-03-23 04:44:17 +03:00
}
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.
2020-04-30 11:02:56 +03:00
cfg . DataDir = CleanAndExpandPath ( cfg . DataDir )
cfg . TLSCertPath = CleanAndExpandPath ( cfg . TLSCertPath )
cfg . TLSKeyPath = CleanAndExpandPath ( cfg . TLSKeyPath )
2019-01-07 20:48:02 +03:00
cfg . LetsEncryptDir = CleanAndExpandPath ( cfg . LetsEncryptDir )
2020-04-30 11:02:56 +03:00
cfg . AdminMacPath = CleanAndExpandPath ( cfg . AdminMacPath )
cfg . ReadMacPath = CleanAndExpandPath ( cfg . ReadMacPath )
cfg . InvoiceMacPath = CleanAndExpandPath ( cfg . InvoiceMacPath )
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 )
cfg . LitecoindMode . Dir = CleanAndExpandPath ( cfg . LitecoindMode . Dir )
cfg . Tor . PrivateKeyPath = CleanAndExpandPath ( cfg . Tor . PrivateKeyPath )
cfg . Tor . WatchtowerKeyPath = CleanAndExpandPath ( cfg . Tor . WatchtowerKeyPath )
cfg . Watchtower . TowerDir = CleanAndExpandPath ( cfg . Watchtower . TowerDir )
2021-02-12 13:14:36 +03:00
cfg . BackupFilePath = CleanAndExpandPath ( cfg . BackupFilePath )
2018-02-26 07:10:44 +03:00
2020-09-16 16:07:15 +03:00
// Create the lnd directory and all other sub directories if they don't
// already exist. This makes sure that directory trees are also created
// for files that point to outside of the lnddir.
dirs := [ ] string {
lndDir , cfg . DataDir ,
cfg . LetsEncryptDir , cfg . Watchtower . TowerDir ,
filepath . Dir ( cfg . TLSCertPath ) , filepath . Dir ( cfg . TLSKeyPath ) ,
filepath . Dir ( cfg . AdminMacPath ) , filepath . Dir ( cfg . ReadMacPath ) ,
filepath . Dir ( cfg . InvoiceMacPath ) ,
filepath . Dir ( cfg . Tor . PrivateKeyPath ) ,
filepath . Dir ( cfg . Tor . WatchtowerKeyPath ) ,
}
for _ , dir := range dirs {
if err := makeDirectory ( dir ) ; err != nil {
return nil , err
}
}
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 )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-04-27 23:54:35 +03:00
return nil , err
}
if cfg . Autopilot . Allocation < 0 {
str := "%s: autopilot.allocation must be non-negative"
err := fmt . Errorf ( str , funcName )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-04-27 23:54:35 +03:00
return nil , err
}
if cfg . Autopilot . MinChannelSize < 0 {
str := "%s: autopilot.minchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-04-27 23:54:35 +03:00
return nil , err
}
if cfg . Autopilot . MaxChannelSize < 0 {
str := "%s: autopilot.maxchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-04-27 23:54:35 +03:00
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 )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-08-10 05:03:08 +03:00
return nil , err
}
2019-06-08 18:29:33 +03:00
if cfg . Autopilot . ConfTarget < 1 {
str := "%s: autopilot.conftarget must be positive"
err := fmt . Errorf ( str , funcName )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-08-10 05:03:08 +03:00
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
2020-09-15 05:16:32 +03:00
// are within the bounds of the normal chan size constraints.
2020-11-17 02:28:56 +03:00
if cfg . Autopilot . MinChannelSize < int64 ( funding . MinChanFundingSize ) {
cfg . Autopilot . MinChannelSize = int64 ( funding . MinChanFundingSize )
2018-04-27 23:54:35 +03:00
}
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
}
2020-09-15 05:16:32 +03:00
// Ensure that --maxchansize is properly handled when set by user.
// For non-Wumbo channels this limit remains 16777215 satoshis by default
// as specified in BOLT-02. For wumbo channels this limit is 1,000,000,000.
// satoshis (10 BTC). Always enforce --maxchansize explicitly set by user.
// If unset (marked by 0 value), then enforce proper default.
if cfg . MaxChanSize == 0 {
if cfg . ProtocolOptions . Wumbo ( ) {
2020-11-17 02:28:56 +03:00
cfg . MaxChanSize = int64 ( funding . MaxBtcFundingAmountWumbo )
2020-09-15 05:16:32 +03:00
} else {
2020-11-17 02:28:56 +03:00
cfg . MaxChanSize = int64 ( funding . MaxBtcFundingAmount )
2020-09-15 05:16:32 +03:00
}
}
// Ensure that the user specified values for the min and max channel
// size make sense.
if cfg . MaxChanSize < cfg . MinChanSize {
return nil , fmt . Errorf ( "invalid channel size parameters: " +
"max channel size %v, must be no less than min chan size %v" ,
cfg . MaxChanSize , cfg . MinChanSize ,
)
}
// Don't allow superflous --maxchansize greater than
// BOLT 02 soft-limit for non-wumbo channel
if ! cfg . ProtocolOptions . Wumbo ( ) && cfg . MaxChanSize > int64 ( MaxFundingAmount ) {
return nil , fmt . Errorf ( "invalid channel size parameters: " +
"maximum channel size %v is greater than maximum non-wumbo" +
" channel size %v" ,
cfg . MaxChanSize , MaxFundingAmount ,
)
}
2019-08-24 02:04:59 +03:00
// Ensure a valid max channel fee allocation was set.
if cfg . MaxChannelFeeAllocation <= 0 || cfg . MaxChannelFeeAllocation > 1 {
return nil , fmt . Errorf ( "invalid max channel fee allocation: " +
"%v, must be within (0, 1]" ,
cfg . MaxChannelFeeAllocation )
}
2020-12-10 16:16:53 +03:00
if cfg . MaxCommitFeeRateAnchors < 1 {
return nil , fmt . Errorf ( "invalid max commit fee rate anchors: " +
"%v, must be at least 1 sat/vbyte" ,
cfg . MaxCommitFeeRateAnchors )
}
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
2020-04-18 20:29:14 +03:00
// Ensure that tor socks host:port is not equal to tor control
// host:port. This would lead to lnd not starting up properly.
if cfg . Tor . SOCKS == cfg . Tor . Control {
str := "%s: tor.socks and tor.control can not use " +
"the same host:port"
return nil , fmt . Errorf ( str , funcName )
}
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 ,
)
}
}
2020-03-17 17:53:17 +03:00
if cfg . Tor . WatchtowerKeyPath == "" {
switch {
case cfg . Tor . V2 :
cfg . Tor . WatchtowerKeyPath = filepath . Join (
cfg . Watchtower . TowerDir , defaultTorV2PrivateKeyFilename ,
)
case cfg . Tor . V3 :
cfg . Tor . WatchtowerKeyPath = filepath . Join (
cfg . Watchtower . TowerDir , 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" )
}
2020-05-13 03:05:18 +03:00
if cfg . NAT && len ( cfg . ExternalHosts ) != 0 {
return nil , errors . New ( "NAT support and externalhosts are " +
"mutually exclusive, only one should be selected" )
}
2018-04-18 08:37:34 +03:00
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 :
2020-11-17 02:28:56 +03:00
err := cfg . Litecoin . Validate ( minTimeLockDelta , funding . MinLtcRemoteDelay )
2020-10-29 12:29:53 +03:00
if err != nil {
return nil , err
2017-12-17 16:31:38 +03:00
}
2020-10-29 12:29:53 +03:00
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
2020-09-29 20:00:19 +03:00
var ltcParams chainreg . LitecoinNetParams
2018-03-15 12:04:17 +03:00
if cfg . Litecoin . MainNet {
numNets ++
2020-09-29 20:00:19 +03:00
ltcParams = chainreg . LitecoinMainNetParams
2018-03-15 12:04:17 +03:00
}
if cfg . Litecoin . TestNet3 {
numNets ++
2020-09-29 20:00:19 +03:00
ltcParams = chainreg . LitecoinTestNetParams
2018-03-15 12:04:17 +03:00
}
2018-11-30 00:53:01 +03:00
if cfg . Litecoin . RegTest {
numNets ++
2020-09-29 20:00:19 +03:00
ltcParams = chainreg . LitecoinRegTestNetParams
2018-11-30 00:53:01 +03:00
}
if cfg . Litecoin . SimNet {
numNets ++
2020-09-29 20:00:19 +03:00
ltcParams = chainreg . LitecoinSimNetParams
2018-11-30 00:53:01 +03:00
}
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
}
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.
2020-09-29 20:00:19 +03:00
chainreg . ApplyLitecoinParams ( & cfg . 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 ,
2020-09-29 18:56:18 +03:00
chainreg . LitecoinChain , funcName , cfg . ActiveNetParams )
2018-03-14 07:14:42 +03:00
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 ,
2020-09-29 18:56:18 +03:00
chainreg . LitecoinChain , funcName , cfg . ActiveNetParams )
2018-03-14 07:14:42 +03:00
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 ,
2020-09-29 18:56:18 +03:00
chainreg . LitecoinChain . String ( ) )
2017-05-03 05:23:24 +03:00
// Finally we'll register the litecoin chain as our current
// primary chain.
2020-09-29 18:56:18 +03:00
cfg . registeredChains . RegisterPrimaryChain ( chainreg . LitecoinChain )
2020-11-17 02:28:56 +03:00
MaxFundingAmount = funding . MaxLtcFundingAmount
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 ++
2020-09-29 20:00:19 +03:00
cfg . ActiveNetParams = chainreg . BitcoinMainNetParams
2018-03-15 12:04:17 +03:00
}
2017-05-03 05:23:24 +03:00
if cfg . Bitcoin . TestNet3 {
numNets ++
2020-09-29 20:00:19 +03:00
cfg . ActiveNetParams = chainreg . BitcoinTestNetParams
2017-05-03 05:23:24 +03:00
}
2017-07-12 02:54:43 +03:00
if cfg . Bitcoin . RegTest {
numNets ++
2020-09-29 20:00:19 +03:00
cfg . ActiveNetParams = chainreg . 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 ++
2020-09-29 20:00:19 +03:00
cfg . ActiveNetParams = chainreg . BitcoinSimNetParams
2017-05-03 05:23:24 +03:00
}
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
}
2020-11-17 02:28:56 +03:00
err := cfg . Bitcoin . Validate ( minTimeLockDelta , funding . MinBtcRemoteDelay )
2020-10-29 12:29:53 +03:00
if err != nil {
return nil , err
2017-12-17 16:31:38 +03:00
}
2017-12-22 08:23:24 +03:00
switch cfg . Bitcoin . Node {
case "btcd" :
2018-03-15 12:04:17 +03:00
err := parseRPCParams (
2020-09-29 18:56:18 +03:00
cfg . Bitcoin , cfg . BtcdMode , chainreg . BitcoinChain , funcName ,
2020-08-04 21:56:31 +03:00
cfg . ActiveNetParams ,
2018-03-15 12:04:17 +03:00
)
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 (
2020-09-29 18:56:18 +03:00
cfg . Bitcoin , cfg . BitcoindMode , chainreg . BitcoinChain , funcName ,
2020-08-04 21:56:31 +03:00
cfg . ActiveNetParams ,
2018-03-15 12:04:17 +03:00
)
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 ,
2020-09-29 18:56:18 +03:00
chainreg . BitcoinChain . String ( ) )
2017-05-03 05:23:24 +03:00
// Finally we'll register the bitcoin chain as our current
// primary chain.
2020-09-29 18:56:18 +03:00
cfg . registeredChains . RegisterPrimaryChain ( chainreg . BitcoinChain )
2017-05-03 05:23:24 +03:00
}
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 )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-05-23 22:05:04 +03:00
return nil , err
}
if cfg . Autopilot . Allocation < 0 {
str := "%s: autopilot.allocation must be non-negative"
err := fmt . Errorf ( str , funcName )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-05-23 22:05:04 +03:00
return nil , err
}
if cfg . Autopilot . MinChannelSize < 0 {
str := "%s: autopilot.minchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-05-23 22:05:04 +03:00
return nil , err
}
if cfg . Autopilot . MaxChannelSize < 0 {
str := "%s: autopilot.maxchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2018-05-23 22:05:04 +03:00
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.
2020-11-17 02:28:56 +03:00
if cfg . Autopilot . MinChannelSize < int64 ( funding . MinChanFundingSize ) {
cfg . Autopilot . MinChannelSize = int64 ( funding . MinChanFundingSize )
2018-05-23 22:05:04 +03:00
}
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 )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
_ , _ = fmt . Fprintln ( os . Stderr , usageMessage )
2016-06-21 07:42:07 +03:00
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.
2020-05-14 14:40:18 +03:00
cfg . networkDir = filepath . Join (
2018-08-22 22:27:16 +03:00
cfg . DataDir , defaultChainSubDirname ,
2020-05-14 14:37:32 +03:00
cfg . registeredChains . PrimaryChain ( ) . String ( ) ,
2020-10-06 21:17:14 +03:00
lncfg . NormalizeNetwork ( cfg . ActiveNetParams . Name ) ,
2018-08-22 22:27:16 +03:00
)
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 (
2020-05-14 14:40:18 +03:00
cfg . 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 (
2020-05-14 14:40:18 +03:00
cfg . 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 (
2020-05-14 14:40:18 +03:00
cfg . 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 (
2020-05-14 14:40:18 +03:00
cfg . networkDir , chanbackup . DefaultBackupFileName ,
2019-02-09 06:39:00 +03:00
)
}
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 ,
2020-05-14 14:37:32 +03:00
cfg . registeredChains . PrimaryChain ( ) . String ( ) ,
2020-10-06 21:17:14 +03:00
lncfg . NormalizeNetwork ( cfg . ActiveNetParams . Name ) )
2016-03-23 04:44:17 +03:00
2020-05-25 19:22:41 +03:00
// A log writer must be passed in, otherwise we can't function and would
// run into a panic later on.
if cfg . LogWriter == nil {
return nil , fmt . Errorf ( "log writer missing in config" )
}
2018-08-24 05:48:21 +03:00
// Special show command to list supported subsystems and exit.
if cfg . DebugLevel == "show" {
2019-09-20 17:22:02 +03:00
fmt . Println ( "Supported subsystems" ,
2020-05-25 19:22:41 +03:00
cfg . LogWriter . SupportedSubsystems ( ) )
2018-08-24 05:48:21 +03:00
os . Exit ( 0 )
2019-09-20 17:22:02 +03:00
}
2018-08-24 05:48:21 +03:00
2016-03-23 04:44:17 +03:00
// Initialize logging at the default logging level.
2020-08-28 12:18:15 +03:00
SetupLoggers ( cfg . LogWriter , interceptor )
2020-05-25 19:22:41 +03:00
err = cfg . LogWriter . InitLogRotator (
2018-05-23 16:38:19 +03:00
filepath . Join ( cfg . LogDir , defaultLogFilename ) ,
cfg . MaxLogFileSize , cfg . MaxLogFiles ,
2019-09-20 17:22:02 +03:00
)
if err != nil {
str := "%s: log rotation setup failed: %v"
err = fmt . Errorf ( str , funcName , err . Error ( ) )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
2019-09-20 17:22:02 +03:00
return nil , err
}
2016-03-23 04:44:17 +03:00
// Parse, validate, and set debug log level(s).
2020-05-25 19:22:41 +03:00
err = build . ParseAndSetDebugLevels ( cfg . DebugLevel , cfg . LogWriter )
2019-09-20 17:22:02 +03:00
if err != nil {
err = fmt . Errorf ( "%s: %v" , funcName , err . Error ( ) )
2020-04-30 11:00:46 +03:00
_ , _ = fmt . Fprintln ( os . Stderr , err )
_ , _ = fmt . Fprintln ( os . Stderr , usageMessage )
2016-03-23 04:44:17 +03:00
return nil , err
2019-09-20 17:22:02 +03:00
}
2016-03-23 04:44:17 +03:00
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
2020-09-30 13:07:10 +03:00
// out with an error. Since we don't allow disabling TLS for gRPC
// connections we pass in tlsActive=true.
2019-04-13 04:39:14 +03:00
err = lncfg . EnforceSafeAuthentication (
2020-09-30 13:07:10 +03:00
cfg . RPCListeners , ! cfg . NoMacaroons , true ,
2019-04-13 04:39:14 +03:00
)
if err != nil {
return nil , err
}
2019-09-05 03:12:37 +03:00
if cfg . DisableRest {
ltndLog . Infof ( "REST API is disabled!" )
cfg . RESTListeners = nil
} else {
err = lncfg . EnforceSafeAuthentication (
2020-09-30 13:07:10 +03:00
cfg . RESTListeners , ! cfg . NoMacaroons , ! cfg . DisableRestTLS ,
2019-09-05 03:12:37 +03:00
)
if err != nil {
return nil , err
}
2019-04-13 04:39:14 +03:00
}
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" )
}
2020-08-05 01:34:29 +03:00
// Newer versions of lnd added a new sub-config for bolt-specific
// parameters. However we want to also allow existing users to use the
// value on the top-level config. If the outer config value is set,
// then we'll use that directly.
if cfg . SyncFreelist {
cfg . DB . Bolt . SyncFreelist = cfg . SyncFreelist
}
2020-08-13 01:45:57 +03:00
// Ensure that the user hasn't chosen a remote-max-htlc value greater
// than the protocol maximum.
maxRemoteHtlcs := uint16 ( input . MaxHTLCNumber / 2 )
if cfg . DefaultRemoteMaxHtlcs > maxRemoteHtlcs {
return nil , fmt . Errorf ( "default-remote-max-htlcs (%v) must be " +
"less than %v" , cfg . DefaultRemoteMaxHtlcs ,
maxRemoteHtlcs )
}
2021-01-29 11:14:21 +03:00
if err := cfg . Gossip . Parse ( ) ; err != nil {
return nil , err
}
2019-06-14 03:29:28 +03:00
// Validate the subconfigs for workers, caches, and the tower client.
2019-04-02 02:34:17 +03:00
err = lncfg . Validate (
cfg . Workers ,
cfg . Caches ,
2019-06-14 03:29:28 +03:00
cfg . WtClient ,
2020-03-13 19:05:28 +03:00
cfg . DB ,
2020-08-24 09:54:38 +03:00
cfg . HealthChecks ,
2019-04-02 02:34:17 +03:00
)
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 {
2020-04-14 20:56:05 +03:00
return nil , fmt . Errorf ( "unable to parse node color: %v" , err )
2018-10-25 08:10:18 +03:00
}
2020-04-30 11:00:46 +03:00
// All good, return the sanitized result.
return & cfg , err
2016-03-23 04:44:17 +03:00
}
2020-03-13 19:05:28 +03:00
// localDatabaseDir returns the default directory where the
// local bolt db files are stored.
2020-03-13 19:06:58 +03:00
func ( c * Config ) localDatabaseDir ( ) string {
return filepath . Join ( c . DataDir ,
2020-03-13 19:05:28 +03:00
defaultGraphSubDirname ,
2020-10-06 21:17:14 +03:00
lncfg . NormalizeNetwork ( c . ActiveNetParams . Name ) )
2020-03-13 19:05:28 +03:00
}
2020-05-20 15:04:34 +03:00
func ( c * Config ) networkName ( ) string {
2020-10-06 21:17:14 +03:00
return lncfg . NormalizeNetwork ( c . ActiveNetParams . Name )
2020-05-20 15:04:34 +03:00
}
2020-04-30 11:02:56 +03:00
// CleanAndExpandPath expands environment variables and leading ~ in the
2016-03-23 04:44:17 +03:00
// 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
2020-04-30 11:02:56 +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
2020-05-13 16:08:27 +03:00
u , err := user . Current ( )
2018-02-26 06:41:44 +03:00
if err == nil {
2020-05-13 16:08:27 +03:00
homeDir = u . HomeDir
2018-02-26 06:41:44 +03:00
} 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 ) )
}
2020-09-29 18:56:18 +03:00
func parseRPCParams ( cConfig * lncfg . Chain , nodeConfig interface { } ,
net chainreg . ChainCode , funcName string ,
2020-09-29 20:00:19 +03:00
netParams chainreg . BitcoinNetParams ) error { // nolint:unparam
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 ) {
2020-05-13 16:57:30 +03:00
case * lncfg . Btcd :
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 {
2020-09-29 18:56:18 +03:00
case chainreg . BitcoinChain :
2018-03-22 00:53:35 +03:00
daemonName = "btcd"
2018-07-17 02:48:31 +03:00
confDir = conf . Dir
confFile = "btcd"
2020-09-29 18:56:18 +03:00
case chainreg . LitecoinChain :
2018-03-22 00:53:35 +03:00
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
2020-05-13 16:57:30 +03:00
case * lncfg . Bitcoind :
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
}
}
2020-03-13 11:41:08 +03:00
// Ensure that if the estimate mode is set, that it is a legal
// value.
if conf . EstimateMode != "" {
err := checkEstimateMode ( conf . EstimateMode )
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 {
2020-09-29 18:56:18 +03:00
case chainreg . BitcoinChain :
2018-03-22 00:53:35 +03:00
daemonName = "bitcoind"
2018-07-17 02:48:31 +03:00
confDir = conf . Dir
confFile = "bitcoin"
2020-09-29 18:56:18 +03:00
case chainreg . LitecoinChain :
2018-03-22 00:53:35 +03:00
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" :
2020-05-13 16:57:30 +03:00
nConf := nodeConfig . ( * lncfg . Btcd )
2017-12-22 08:23:24 +03:00
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" :
2020-05-13 16:57:30 +03:00
nConf := nodeConfig . ( * lncfg . Bitcoind )
2018-07-17 02:48:31 +03:00
rpcUser , rpcPass , zmqBlockHost , zmqTxHost , err :=
2020-08-04 21:56:31 +03:00
extractBitcoindRPCParams ( netParams . Params . Name , 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
}
2020-05-13 16:08:27 +03:00
defer func ( ) { _ = btcdConfigFile . Close ( ) } ( )
2017-04-01 17:02:50 +03:00
// 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
2020-08-04 21:56:31 +03:00
// extractBitcoindRPCParams attempts to extract the RPC credentials for an
2017-12-22 08:23:24 +03:00
// 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.
2020-08-04 21:56:31 +03:00
func extractBitcoindRPCParams ( networkName string ,
bitcoindConfigPath string ) ( string , string , string , string , error ) {
2020-05-13 16:08:27 +03:00
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
}
2020-05-13 16:08:27 +03:00
defer func ( ) { _ = bitcoindConfigFile . Close ( ) } ( )
2017-12-22 08:23:24 +03:00
// 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 := "/"
2020-08-04 21:56:31 +03:00
switch networkName {
2018-03-27 15:51:41 +03:00
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 {
2019-09-24 15:49:59 +03:00
return errors . New ( "zmqpubrawblock and zmqpubrawtx must be set " +
2018-08-28 08:20:16 +03:00
"to different addresses" )
}
return nil
}
2020-03-13 11:41:08 +03:00
// checkEstimateMode ensures that the provided estimate mode is legal.
func checkEstimateMode ( estimateMode string ) error {
for _ , mode := range bitcoindEstimateModes {
if estimateMode == mode {
return nil
}
}
return fmt . Errorf ( "estimatemode must be one of the following: %v" ,
bitcoindEstimateModes [ : ] )
}