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
2015-12-26 09:09:17 +03:00
package main
2016-02-23 05:24:56 +03:00
import (
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
2017-12-22 08:23:24 +03:00
flags "github.com/jessevdk/go-flags"
2016-12-15 05:11:31 +03:00
"github.com/lightningnetwork/lnd/brontide"
"github.com/lightningnetwork/lnd/lnwire"
2017-10-25 22:06:26 +03:00
"github.com/lightningnetwork/lnd/torsvc"
2016-12-15 05:11:31 +03:00
"github.com/roasbeef/btcd/btcec"
2016-05-15 17:17:44 +03:00
"github.com/roasbeef/btcutil"
2016-02-23 05:24:56 +03:00
)
const (
2016-10-15 16:45:51 +03:00
defaultConfigFilename = "lnd.conf"
defaultDataDirname = "data"
2018-01-06 00:42:13 +03:00
defaultChainSubDirname = "chain"
defaultGraphSubDirname = "graph"
2017-07-26 02:22:06 +03:00
defaultTLSCertFilename = "tls.cert"
defaultTLSKeyFilename = "tls.key"
2017-08-18 04:50:57 +03:00
defaultAdminMacFilename = "admin.macaroon"
defaultReadMacFilename = "readonly.macaroon"
2018-03-21 02:50:08 +03:00
defaultInvoiceMacFilename = "invoice.macaroon"
2016-10-15 16:45:51 +03:00
defaultLogLevel = "info"
defaultLogDirname = "logs"
defaultLogFilename = "lnd.log"
defaultRPCPort = 10009
2017-06-10 04:19:14 +03:00
defaultRESTPort = 8080
2017-08-22 10:40:40 +03:00
defaultPeerPort = 9735
2016-10-15 16:45:51 +03:00
defaultRPCHost = "localhost"
defaultMaxPendingChannels = 1
2017-10-12 12:19:51 +03:00
defaultNoEncryptWallet = false
2017-09-14 02:33:46 +03:00
defaultTrickleDelay = 30 * 1000
2017-12-17 16:31:38 +03:00
2018-01-23 05:59:44 +03:00
defaultBroadcastDelta = 10
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 )
defaultAdminMacPath = filepath . Join ( defaultLndDir , defaultAdminMacFilename )
defaultReadMacPath = filepath . Join ( defaultLndDir , defaultReadMacFilename )
defaultInvoiceMacPath = filepath . Join ( defaultLndDir , defaultInvoiceMacFilename )
2016-03-23 04:44:17 +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 )
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 {
2017-05-18 21:48:59 +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." `
}
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-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" `
ZMQPath string ` long:"zmqpath" description:"The path to the ZMQ socket providing at least raw blocks. Raw transactions can be handled as well." `
}
2017-08-11 07:26:48 +03:00
type autoPilotConfig struct {
2018-03-19 03:10:01 +03:00
Active bool ` long:"active" description:"If the autopilot agent should be active or not." `
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" `
2018-03-22 23:45:37 +03:00
MaxChannelSize int64 ` long:"maxchansize" description:"The largest channel that the autopilot agent should create" `
2017-08-11 07:26:48 +03:00
}
2018-01-22 14:48:59 +03:00
type torConfig struct {
2018-02-06 05:33:43 +03:00
Socks string ` long:"socks" description:"The port that Tor's exposed SOCKS5 proxy is listening on. Using Tor allows outbound-only connections (listening will be disabled) -- NOTE port must be between 1024 and 65535" `
DNS string ` long:"dns" description:"The DNS server as IP: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." `
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" `
2018-03-21 01:57:14 +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" `
TLSExtraIP string ` long:"tlsextraip" description:"Adds an extra ip to the generated certificate" `
TLSExtraDomain 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" `
2018-03-21 02:50:08 +03:00
InvoiceMacPath string ` long:"invoicemacaroonpath" description:"Path to the invoice-only macaroon for lnd's RPC and REST services if it doesn't exist" `
2018-03-21 01:57:14 +03:00
LogDir string ` long:"logdir" description:"Directory to log output." `
2016-03-23 04:44:17 +03:00
2017-12-17 20:28:38 +03:00
RPCListeners [ ] string ` long:"rpclisten" description:"Add an interface/port to listen for RPC connections" `
RESTListeners [ ] string ` long:"restlisten" description:"Add an interface/port to listen for REST connections" `
Listeners [ ] string ` long:"listen" description:"Add an interface/port to listen for peer connections" `
DisableListen bool ` long:"nolisten" description:"Disable listening for incoming peer connections" `
2018-01-30 02:17:04 +03:00
ExternalIPs [ ] 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" `
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" `
2017-05-03 05:23:24 +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." `
2017-09-01 04:30:11 +03:00
HodlHTLC bool ` long:"hodlhtlc" description:"Activate the hodl HTLC mode. With hodl HTLC mode, all incoming HTLCs will be accepted by the receiving node, but no attempt will be made to settle the payment with the sender." `
2018-02-22 23:55:17 +03:00
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." `
2017-05-03 05:23:24 +03:00
MaxPendingChannels int ` long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer." `
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
2017-08-11 07:26:48 +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" `
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
NoEncryptWallet bool ` long:"noencryptwallet" description:"If set, wallet will be encrypted using the default passphrase." `
2017-09-14 02:33:46 +03:00
TrickleDelay int ` long:"trickledelay" description:"Time in milliseconds between each release of announcements to the network" `
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
2018-01-23 06:59:15 +03:00
net torsvc . Net
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 ,
AdminMacPath : defaultAdminMacPath ,
InvoiceMacPath : defaultInvoiceMacPath ,
ReadMacPath : defaultReadMacPath ,
LogDir : defaultLogDir ,
2017-05-03 05:23:24 +03:00
Bitcoin : & chainConfig {
2017-12-17 16:31:38 +03:00
MinHTLC : defaultBitcoinMinHTLCMSat ,
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 ,
} ,
2017-12-22 08:23:24 +03:00
MaxPendingChannels : defaultMaxPendingChannels ,
NoEncryptWallet : defaultNoEncryptWallet ,
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 ) ,
MaxChannelSize : int64 ( maxFundingAmount ) ,
2017-08-11 07:26:48 +03:00
} ,
2017-09-14 02:33:46 +03:00
TrickleDelay : defaultTrickleDelay ,
2017-12-16 02:03:38 +03:00
Alias : defaultAlias ,
Color : defaultColor ,
2018-04-03 02:17:50 +03:00
MinChanSize : int64 ( minChanFundingSize ) ,
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 {
fmt . Println ( appName , "version" , version ( ) )
os . Exit ( 0 )
}
2018-02-24 23:59:22 +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.
lndDir := cleanAndExpandPath ( preCfg . LndDir )
if lndDir != defaultLndDir {
defaultCfg . ConfigFile = filepath . Join ( lndDir , defaultConfigFilename )
defaultCfg . DataDir = filepath . Join ( lndDir , defaultDataDirname )
defaultCfg . TLSCertPath = filepath . Join ( lndDir , defaultTLSCertFilename )
defaultCfg . TLSKeyPath = filepath . Join ( lndDir , defaultTLSKeyFilename )
defaultCfg . AdminMacPath = filepath . Join ( lndDir , defaultAdminMacFilename )
2018-03-21 02:50:08 +03:00
defaultCfg . InvoiceMacPath = filepath . Join ( lndDir , defaultInvoiceMacFilename )
2018-02-24 23:59:22 +03:00
defaultCfg . ReadMacPath = filepath . Join ( lndDir , defaultReadMacFilename )
defaultCfg . LogDir = filepath . Join ( lndDir , defaultLogDirname )
}
// 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
}
// Next, load any additional configuration options from the file.
2017-06-19 17:44:26 +03:00
var configFileError error
2016-02-23 05:24:56 +03:00
cfg := defaultCfg
2018-02-24 23:59:22 +03:00
configFile := cleanAndExpandPath ( preCfg . ConfigFile )
if err := flags . IniParse ( configFile , & cfg ) ; err != nil {
2017-06-19 17:44:26 +03:00
configFileError = err
2016-03-23 04:44:17 +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
}
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-02-26 07:10:44 +03:00
2018-03-19 03:10:01 +03:00
// Ensure that the user didn't attempt to specify negative values for
// any of the autopilot params.
2018-03-22 23:45:37 +03:00
if cfg . Autopilot . MaxChannels < 0 {
str := "%s: autopilot.maxchannels must be non-negative"
err := fmt . Errorf ( str , funcName )
2018-03-19 03:10:01 +03:00
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . Allocation < 0 {
2018-03-22 23:45:37 +03:00
str := "%s: autopilot.allocation must be non-negative"
err := fmt . Errorf ( str , funcName )
2018-03-19 03:10:01 +03:00
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . MinChannelSize < 0 {
2018-03-22 23:45:37 +03:00
str := "%s: autopilot.minchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
2018-03-19 03:10:01 +03:00
fmt . Fprintln ( os . Stderr , err )
return nil , err
}
if cfg . Autopilot . MaxChannelSize < 0 {
2018-03-22 23:45:37 +03:00
str := "%s: autopilot.maxchansize must be non-negative"
err := fmt . Errorf ( str , funcName )
2018-03-19 03:10:01 +03:00
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 )
}
if cfg . Autopilot . MaxChannelSize > int64 ( maxFundingAmount ) {
cfg . Autopilot . MaxChannelSize = int64 ( maxFundingAmount )
}
2017-10-25 05:02:29 +03:00
// Setup dial and DNS resolution functions depending on the specified
// options. The default is to use the standard golang "net" package
// functions. When Tor's proxy is specified, the dial function is set to
// the proxy specific dial function and the DNS resolution functions use
// Tor.
2018-01-23 06:59:15 +03:00
cfg . net = & torsvc . RegularNet { }
2018-01-22 14:48:59 +03:00
if cfg . Tor . Socks != "" && cfg . Tor . DNS != "" {
2017-10-21 00:45:23 +03:00
// Validate Tor port number
2018-01-22 14:48:59 +03:00
torport , err := strconv . Atoi ( cfg . Tor . Socks )
2017-10-21 00:45:23 +03:00
if err != nil || torport < 1024 || torport > 65535 {
str := "%s: The tor socks5 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
}
// If ExternalIPs is set, throw an error since we cannot
// listen for incoming connections via Tor's SOCKS5 proxy.
if len ( cfg . ExternalIPs ) != 0 {
str := "%s: Cannot set externalip flag with proxy flag - " +
"cannot listen for incoming connections via Tor's " +
"socks5 proxy"
err := fmt . Errorf ( str , funcName )
return nil , err
}
2018-01-23 06:59:15 +03:00
cfg . net = & torsvc . TorProxyNet {
2018-02-06 05:33:43 +03:00
TorDNS : cfg . Tor . DNS ,
TorSocks : cfg . Tor . Socks ,
StreamIsolation : cfg . Tor . StreamIsolation ,
2018-01-23 06:59:15 +03:00
}
2017-10-25 22:06:26 +03:00
2017-10-21 00:45:23 +03:00
// If we are using Tor, since we only want connections routed
// through Tor, listening is disabled.
cfg . DisableListen = true
2018-01-22 14:48:59 +03:00
} else if cfg . Tor . Socks != "" || cfg . Tor . DNS != "" {
2017-10-25 22:06:26 +03:00
// Both TorSocks and TorDNS must be set.
2018-01-22 14:48:59 +03:00
str := "%s: Both the tor.socks and the tor.dns flags must be set" +
2017-10-25 22:06:26 +03:00
"to properly route connections and avoid DNS leaks while" +
"using Tor"
err := fmt . Errorf ( str , funcName )
return nil , err
2017-10-21 00:45:23 +03:00
}
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-05-03 05:23:24 +03:00
if cfg . Litecoin . SimNet {
str := "%s: simnet mode for litecoin not currently supported"
return nil , fmt . Errorf ( str , funcName )
}
2018-03-14 07:14:42 +03:00
if cfg . Litecoin . RegTest {
str := "%s: regnet mode for litecoin not currently supported"
return nil , fmt . Errorf ( str , funcName )
}
2017-05-03 05:23:24 +03:00
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
}
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.
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 )
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 ++
activeNetParams = regTestNetParams
}
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
}
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-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 )
}
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
}
}
2017-08-22 10:03:03 +03:00
// At this point, we'll save the base data directory in order to ensure
// we don't store the macaroon database within any of the chain
// namespaced directories.
macaroonDatabaseDir = cfg . DataDir
// 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.
if cfg . DataDir != defaultDataDir && cfg . AdminMacPath == defaultAdminMacPath {
2018-03-21 02:50:08 +03:00
cfg . AdminMacPath = filepath . Join (
cfg . DataDir , defaultAdminMacFilename ,
)
2017-08-22 10:03:03 +03:00
}
if cfg . DataDir != defaultDataDir && cfg . ReadMacPath == defaultReadMacPath {
2018-03-21 02:50:08 +03:00
cfg . ReadMacPath = filepath . Join (
cfg . DataDir , defaultReadMacFilename ,
)
}
if cfg . DataDir != defaultDataDir && cfg . InvoiceMacPath == defaultInvoiceMacPath {
cfg . InvoiceMacPath = filepath . Join (
2018-03-26 05:28:47 +03:00
cfg . DataDir , defaultInvoiceMacFilename ,
2018-03-21 02:50:08 +03:00
)
2017-08-22 10:03:03 +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 ,
2018-01-06 00:42:13 +03:00
registeredChains . PrimaryChain ( ) . String ( ) ,
normalizeNetwork ( activeNetParams . Name ) )
2016-03-23 04:44:17 +03:00
// Initialize logging at the default logging level.
2017-06-21 18:07:44 +03:00
initLogRotator ( filepath . Join ( cfg . LogDir , defaultLogFilename ) )
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
}
2017-12-17 20:28:38 +03:00
// At least one RPCListener is required.
if len ( cfg . RPCListeners ) == 0 {
addr := fmt . Sprintf ( "localhost:%d" , defaultRPCPort )
cfg . RPCListeners = append ( cfg . RPCListeners , addr )
}
2018-01-29 02:03:12 +03:00
// Listen on the default interface/port if no REST listeners were
// specified.
2017-12-17 20:28:38 +03:00
if len ( cfg . RESTListeners ) == 0 {
addr := fmt . Sprintf ( "localhost:%d" , defaultRESTPort )
cfg . RESTListeners = append ( cfg . RESTListeners , addr )
}
// Listen on the default interface/port if no listeners were specified.
if len ( cfg . Listeners ) == 0 {
addr := fmt . Sprintf ( ":%d" , defaultPeerPort )
cfg . Listeners = append ( cfg . Listeners , addr )
}
2018-01-29 02:03:12 +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 := enforceSafeAuthentication ( cfg . RPCListeners , ! cfg . NoMacaroons )
if err != nil {
return nil , err
}
err = enforceSafeAuthentication ( cfg . RESTListeners , ! cfg . NoMacaroons )
if err != nil {
return nil , err
}
2017-12-17 20:28:38 +03:00
// Remove all Listeners if listening is disabled.
if cfg . DisableListen {
cfg . Listeners = nil
}
// Add default port to all RPC listener addresses if needed and remove
// duplicate addresses.
cfg . RPCListeners = normalizeAddresses ( cfg . RPCListeners ,
strconv . Itoa ( defaultRPCPort ) )
// Add default port to all REST listener addresses if needed and remove
// duplicate addresses.
cfg . RESTListeners = normalizeAddresses ( cfg . RESTListeners ,
strconv . Itoa ( defaultRESTPort ) )
// Add default port to all listener addresses if needed and remove
// duplicate addresses.
cfg . Listeners = normalizeAddresses ( cfg . Listeners ,
strconv . Itoa ( defaultPeerPort ) )
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 {
// 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" :
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
// noiseDial is a factory function which creates a connmgr compliant dialing
// function by returning a closure which includes the server's identity key.
func noiseDial ( idPriv * btcec . PrivateKey ) func ( net . Addr ) ( net . Conn , error ) {
return func ( a net . Addr ) ( net . Conn , error ) {
lnAddr := a . ( * lnwire . NetAddress )
2017-10-25 05:59:32 +03:00
return brontide . Dial ( idPriv , lnAddr , cfg . net . Dial )
2016-12-15 05:11:31 +03:00
}
}
2017-04-01 17:02:50 +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"
case litecoinChain :
daemonName = "ltcd"
}
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
switch net {
case bitcoinChain :
confDir = conf . Dir
confFile = "btcd"
case litecoinChain :
confDir = conf . Dir
confFile = "ltcd"
}
2017-12-22 08:23:24 +03:00
case * bitcoindConfig :
2018-01-18 23:54:41 +03:00
// If all of RPCUser, RPCPass, and ZMQPath are set, we assume
// those parameters are good to use.
if conf . RPCUser != "" && conf . RPCPass != "" && conf . ZMQPath != "" {
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"
case litecoinChain :
daemonName = "litecoind"
}
2018-01-18 23:54:41 +03:00
// If only one or two of the parameters are set, we assume the
// user did that unintentionally.
if conf . RPCUser != "" || conf . RPCPass != "" || conf . ZMQPath != "" {
2018-03-24 05:26:43 +03:00
return fmt . Errorf ( "please set all or none of " +
"%[1]v.rpcuser, %[1]v.rpcpass, " +
2018-03-22 00:53:35 +03:00
"and %[1]v.zmqpath" , daemonName )
2018-01-18 23:54:41 +03:00
}
2018-02-25 01:18:59 +03:00
2018-03-14 07:14:42 +03:00
switch net {
case bitcoinChain :
confDir = conf . Dir
confFile = "bitcoin"
case litecoinChain :
confDir = conf . Dir
confFile = "litecoin"
}
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 )
rpcUser , rpcPass , zmqPath , err := extractBitcoindRPCParams ( confFile )
if err != nil {
return fmt . Errorf ( "unable to extract RPC credentials:" +
" %v, cannot start w/o RPC connection" ,
err )
}
nConf . RPCUser , nConf . RPCPass , nConf . ZMQPath = rpcUser , rpcPass , zmqPath
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.
func extractBitcoindRPCParams ( bitcoindConfigPath string ) ( string , string , string , error ) {
// First, we'll open up the bitcoind configuration file found at the
// target destination.
bitcoindConfigFile , err := os . Open ( bitcoindConfigPath )
if err != nil {
return "" , "" , "" , err
}
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 {
return "" , "" , "" , err
}
// First, we look for the ZMQ path for raw blocks. If raw transactions
// are sent over this interface, we can also get unconfirmed txs.
2018-04-01 02:06:00 +03:00
zmqPathRE , err := regexp . Compile ( ` (?m)^\s*zmqpubrawblock\s*=\s*([^\s]+) ` )
2017-12-22 08:23:24 +03:00
if err != nil {
return "" , "" , "" , err
}
zmqPathSubmatches := zmqPathRE . FindSubmatch ( configContents )
if len ( zmqPathSubmatches ) < 2 {
return "" , "" , "" , fmt . Errorf ( "unable to find zmqpubrawblock in config" )
}
// 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 {
return "" , "" , "" , err
}
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 {
return splitCookie [ 0 ] , splitCookie [ 1 ] ,
string ( zmqPathSubmatches [ 1 ] ) , nil
}
}
// 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 {
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*rpcpassword\s*=\s*([^\s]+) ` )
2017-12-22 08:23:24 +03:00
if err != nil {
return "" , "" , "" , err
}
passSubmatches := rpcPassRegexp . FindSubmatch ( configContents )
if passSubmatches == nil {
return "" , "" , "" , fmt . Errorf ( "unable to find rpcpassword in config" )
}
return string ( userSubmatches [ 1 ] ) , string ( passSubmatches [ 1 ] ) ,
string ( zmqPathSubmatches [ 1 ] ) , nil
}
2017-12-17 20:28:38 +03:00
// normalizeAddresses returns a new slice with all the passed addresses
// normalized with the given default port and all duplicates removed.
func normalizeAddresses ( addrs [ ] string , defaultPort string ) [ ] string {
result := make ( [ ] string , 0 , len ( addrs ) )
seen := map [ string ] struct { } { }
for _ , addr := range addrs {
if _ , _ , err := net . SplitHostPort ( addr ) ; err != nil {
2018-03-18 05:49:10 +03:00
// If the address is an integer, then we assume it is *only* a
// port and default to binding to that port on localhost
if _ , err := strconv . Atoi ( addr ) ; err == nil {
addr = net . JoinHostPort ( "localhost" , addr )
} else {
addr = net . JoinHostPort ( addr , defaultPort )
}
2017-12-17 20:28:38 +03:00
}
if _ , ok := seen [ addr ] ; ! ok {
result = append ( result , addr )
seen [ addr ] = struct { } { }
}
}
return result
}
2018-01-29 02:03:12 +03:00
// enforceSafeAuthentication enforces "safe" authentication taking into account
// the interfaces that the RPC servers are listening on, and if macaroons are
// activated or not. To project users from using dangerous config combinations,
// we'll prevent disabling authentication if the sever is listening on a public
// interface.
func enforceSafeAuthentication ( addrs [ ] string , macaroonsActive bool ) error {
isLoopback := func ( addr string ) bool {
2018-03-15 12:04:17 +03:00
loopBackAddrs := [ ] string { "localhost" , "127.0.0.1" , "[::1]" }
2018-01-29 02:03:12 +03:00
for _ , loopback := range loopBackAddrs {
if strings . Contains ( addr , loopback ) {
return true
}
}
return false
}
// We'll now examine all addresses that this RPC server is listening
// on. If it's a localhost address, we'll skip it, otherwise, we'll
// return an error if macaroons are inactive.
for _ , addr := range addrs {
if isLoopback ( addr ) {
continue
}
if ! macaroonsActive {
return fmt . Errorf ( "Detected RPC server listening on " +
"publicly reachable interface %v with " +
"authentication disabled! Refusing to start with " +
"--no-macaroons specified." , addr )
}
}
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
}