config.go 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. // Copyright (c) 2013-2017 The btcsuite developers
  2. // Copyright (c) 2015-2016 The Decred developers
  3. // Copyright (C) 2015-2022 The Lightning Network Developers
  4. package lnd
  5. import (
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "os"
  12. "os/user"
  13. "path/filepath"
  14. "reflect"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/btcsuite/btcd/btcutil"
  20. "github.com/btcsuite/btcd/chaincfg"
  21. flags "github.com/jessevdk/go-flags"
  22. "github.com/lightninglabs/neutrino"
  23. "github.com/lightningnetwork/lnd/autopilot"
  24. "github.com/lightningnetwork/lnd/build"
  25. "github.com/lightningnetwork/lnd/chainreg"
  26. "github.com/lightningnetwork/lnd/chanbackup"
  27. "github.com/lightningnetwork/lnd/channeldb"
  28. "github.com/lightningnetwork/lnd/discovery"
  29. "github.com/lightningnetwork/lnd/funding"
  30. "github.com/lightningnetwork/lnd/htlcswitch"
  31. "github.com/lightningnetwork/lnd/htlcswitch/hodl"
  32. "github.com/lightningnetwork/lnd/input"
  33. "github.com/lightningnetwork/lnd/lncfg"
  34. "github.com/lightningnetwork/lnd/lnrpc"
  35. "github.com/lightningnetwork/lnd/lnrpc/peersrpc"
  36. "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
  37. "github.com/lightningnetwork/lnd/lnrpc/signrpc"
  38. "github.com/lightningnetwork/lnd/lnwallet"
  39. "github.com/lightningnetwork/lnd/lnwire"
  40. "github.com/lightningnetwork/lnd/routing"
  41. "github.com/lightningnetwork/lnd/signal"
  42. "github.com/lightningnetwork/lnd/tor"
  43. )
  44. const (
  45. defaultDataDirname = "data"
  46. defaultChainSubDirname = "chain"
  47. defaultGraphSubDirname = "graph"
  48. defaultTowerSubDirname = "watchtower"
  49. defaultTLSCertFilename = "tls.cert"
  50. defaultTLSKeyFilename = "tls.key"
  51. defaultAdminMacFilename = "admin.macaroon"
  52. defaultReadMacFilename = "readonly.macaroon"
  53. defaultInvoiceMacFilename = "invoice.macaroon"
  54. defaultLogLevel = "info"
  55. defaultLogDirname = "logs"
  56. defaultLogFilename = "lnd.log"
  57. defaultRPCPort = 10009
  58. defaultRESTPort = 8080
  59. defaultPeerPort = 9735
  60. defaultRPCHost = "localhost"
  61. defaultNoSeedBackup = false
  62. defaultPaymentsExpirationGracePeriod = time.Duration(0)
  63. defaultTrickleDelay = 90 * 1000
  64. defaultChanStatusSampleInterval = time.Minute
  65. defaultChanEnableTimeout = 19 * time.Minute
  66. defaultChanDisableTimeout = 20 * time.Minute
  67. defaultHeightHintCacheQueryDisable = false
  68. defaultMaxLogFiles = 3
  69. defaultMaxLogFileSize = 10
  70. defaultMinBackoff = time.Second
  71. defaultMaxBackoff = time.Hour
  72. defaultLetsEncryptDirname = "letsencrypt"
  73. defaultLetsEncryptListen = ":80"
  74. defaultTorSOCKSPort = 9050
  75. defaultTorDNSHost = "soa.nodes.lightning.directory"
  76. defaultTorDNSPort = 53
  77. defaultTorControlPort = 9051
  78. defaultTorV2PrivateKeyFilename = "v2_onion_private_key"
  79. defaultTorV3PrivateKeyFilename = "v3_onion_private_key"
  80. // defaultZMQReadDeadline is the default read deadline to be used for
  81. // both the block and tx ZMQ subscriptions.
  82. defaultZMQReadDeadline = 5 * time.Second
  83. // DefaultAutogenValidity is the default validity of a self-signed
  84. // certificate. The value corresponds to 14 months
  85. // (14 months * 30 days * 24 hours).
  86. defaultTLSCertDuration = 14 * 30 * 24 * time.Hour
  87. // minTimeLockDelta is the minimum timelock we require for incoming
  88. // HTLCs on our channels.
  89. minTimeLockDelta = routing.MinCLTVDelta
  90. // MaxTimeLockDelta is the maximum CLTV delta that can be applied to
  91. // forwarded HTLCs.
  92. MaxTimeLockDelta = routing.MaxCLTVDelta
  93. // defaultAcceptorTimeout is the time after which an RPCAcceptor will time
  94. // out and return false if it hasn't yet received a response.
  95. defaultAcceptorTimeout = 15 * time.Second
  96. defaultAlias = ""
  97. defaultColor = "#3399FF"
  98. // defaultCoopCloseTargetConfs is the default confirmation target
  99. // that will be used to estimate a fee rate to use during a
  100. // cooperative channel closure initiated by a remote peer. By default
  101. // we'll set this to a lax value since we weren't the ones that
  102. // initiated the channel closure.
  103. defaultCoopCloseTargetConfs = 6
  104. // defaultBlockCacheSize is the size (in bytes) of blocks that will be
  105. // keep in memory if no size is specified.
  106. defaultBlockCacheSize uint64 = 20 * 1024 * 1024 // 20 MB
  107. // defaultHostSampleInterval is the default amount of time that the
  108. // HostAnnouncer will wait between DNS resolutions to check if the
  109. // backing IP of a host has changed.
  110. defaultHostSampleInterval = time.Minute * 5
  111. defaultChainInterval = time.Minute
  112. defaultChainTimeout = time.Second * 30
  113. defaultChainBackoff = time.Minute * 2
  114. defaultChainAttempts = 3
  115. // Set defaults for a health check which ensures that we have space
  116. // available on disk. Although this check is off by default so that we
  117. // avoid breaking any existing setups (particularly on mobile), we still
  118. // set the other default values so that the health check can be easily
  119. // enabled with sane defaults.
  120. defaultRequiredDisk = 0.1
  121. defaultDiskInterval = time.Hour * 12
  122. defaultDiskTimeout = time.Second * 5
  123. defaultDiskBackoff = time.Minute
  124. defaultDiskAttempts = 0
  125. // Set defaults for a health check which ensures that the TLS certificate
  126. // is not expired. Although this check is off by default (not all setups
  127. // require it), we still set the other default values so that the health
  128. // check can be easily enabled with sane defaults.
  129. defaultTLSInterval = time.Minute
  130. defaultTLSTimeout = time.Second * 5
  131. defaultTLSBackoff = time.Minute
  132. defaultTLSAttempts = 0
  133. // Set defaults for a health check which ensures that the tor
  134. // connection is alive. Although this check is off by default (not all
  135. // setups require it), we still set the other default values so that
  136. // the health check can be easily enabled with sane defaults.
  137. defaultTCInterval = time.Minute
  138. defaultTCTimeout = time.Second * 5
  139. defaultTCBackoff = time.Minute
  140. defaultTCAttempts = 0
  141. // Set defaults for a health check which ensures that the remote signer
  142. // RPC connection is alive. Although this check is off by default (only
  143. // active when remote signing is turned on), we still set the other
  144. // default values so that the health check can be easily enabled with
  145. // sane defaults.
  146. defaultRSInterval = time.Minute
  147. defaultRSTimeout = time.Second * 1
  148. defaultRSBackoff = time.Second * 30
  149. defaultRSAttempts = 1
  150. // defaultRemoteMaxHtlcs specifies the default limit for maximum
  151. // concurrent HTLCs the remote party may add to commitment transactions.
  152. // This value can be overridden with --default-remote-max-htlcs.
  153. defaultRemoteMaxHtlcs = 483
  154. // defaultMaxLocalCSVDelay is the maximum delay we accept on our
  155. // commitment output. The local csv delay maximum is now equal to
  156. // the remote csv delay maximum we require for the remote commitment
  157. // transaction.
  158. defaultMaxLocalCSVDelay = 2016
  159. // defaultChannelCommitInterval is the default maximum time between
  160. // receiving a channel state update and signing a new commitment.
  161. defaultChannelCommitInterval = 50 * time.Millisecond
  162. // maxChannelCommitInterval is the maximum time the commit interval can
  163. // be configured to.
  164. maxChannelCommitInterval = time.Hour
  165. // defaultPendingCommitInterval specifies the default timeout value
  166. // while waiting for the remote party to revoke a locally initiated
  167. // commitment state.
  168. defaultPendingCommitInterval = 1 * time.Minute
  169. // maxPendingCommitInterval specifies the max allowed duration when
  170. // waiting for the remote party to revoke a locally initiated
  171. // commitment state.
  172. maxPendingCommitInterval = 5 * time.Minute
  173. // defaultChannelCommitBatchSize is the default maximum number of
  174. // channel state updates that is accumulated before signing a new
  175. // commitment.
  176. defaultChannelCommitBatchSize = 10
  177. // defaultCoinSelectionStrategy is the coin selection strategy that is
  178. // used by default to fund transactions.
  179. defaultCoinSelectionStrategy = "largest"
  180. // defaultKeepFailedPaymentAttempts is the default setting for whether
  181. // to keep failed payments in the database.
  182. defaultKeepFailedPaymentAttempts = false
  183. // defaultGrpcServerPingTime is the default duration for the amount of
  184. // time of no activity after which the server pings the client to see if
  185. // the transport is still alive. If set below 1s, a minimum value of 1s
  186. // will be used instead.
  187. defaultGrpcServerPingTime = time.Minute
  188. // defaultGrpcServerPingTimeout is the default duration the server waits
  189. // after having pinged for keepalive check, and if no activity is seen
  190. // even after that the connection is closed.
  191. defaultGrpcServerPingTimeout = 20 * time.Second
  192. // defaultGrpcClientPingMinWait is the default minimum amount of time a
  193. // client should wait before sending a keepalive ping.
  194. defaultGrpcClientPingMinWait = 5 * time.Second
  195. // defaultHTTPHeaderTimeout is the default timeout for HTTP requests.
  196. DefaultHTTPHeaderTimeout = 5 * time.Second
  197. // BitcoinChainName is a string that represents the Bitcoin blockchain.
  198. BitcoinChainName = "bitcoin"
  199. bitcoindBackendName = "bitcoind"
  200. btcdBackendName = "btcd"
  201. neutrinoBackendName = "neutrino"
  202. )
  203. var (
  204. // DefaultLndDir is the default directory where lnd tries to find its
  205. // configuration file and store its data. This is a directory in the
  206. // user's application data, for example:
  207. // C:\Users\<username>\AppData\Local\Lnd on Windows
  208. // ~/.lnd on Linux
  209. // ~/Library/Application Support/Lnd on MacOS
  210. DefaultLndDir = btcutil.AppDataDir("lnd", false)
  211. // DefaultConfigFile is the default full path of lnd's configuration
  212. // file.
  213. DefaultConfigFile = filepath.Join(DefaultLndDir, lncfg.DefaultConfigFilename)
  214. defaultDataDir = filepath.Join(DefaultLndDir, defaultDataDirname)
  215. defaultLogDir = filepath.Join(DefaultLndDir, defaultLogDirname)
  216. defaultTowerDir = filepath.Join(defaultDataDir, defaultTowerSubDirname)
  217. defaultTLSCertPath = filepath.Join(DefaultLndDir, defaultTLSCertFilename)
  218. defaultTLSKeyPath = filepath.Join(DefaultLndDir, defaultTLSKeyFilename)
  219. defaultLetsEncryptDir = filepath.Join(DefaultLndDir, defaultLetsEncryptDirname)
  220. defaultBtcdDir = btcutil.AppDataDir(btcdBackendName, false)
  221. defaultBtcdRPCCertFile = filepath.Join(defaultBtcdDir, "rpc.cert")
  222. defaultBitcoindDir = btcutil.AppDataDir(BitcoinChainName, false)
  223. defaultTorSOCKS = net.JoinHostPort("localhost", strconv.Itoa(defaultTorSOCKSPort))
  224. defaultTorDNS = net.JoinHostPort(defaultTorDNSHost, strconv.Itoa(defaultTorDNSPort))
  225. defaultTorControl = net.JoinHostPort("localhost", strconv.Itoa(defaultTorControlPort))
  226. // bitcoindEsimateModes defines all the legal values for bitcoind's
  227. // estimatesmartfee RPC call.
  228. defaultBitcoindEstimateMode = "CONSERVATIVE"
  229. bitcoindEstimateModes = [2]string{"ECONOMICAL", defaultBitcoindEstimateMode}
  230. defaultPrunedNodeMaxPeers = 4
  231. )
  232. // Config defines the configuration options for lnd.
  233. //
  234. // See LoadConfig for further details regarding the configuration
  235. // loading+parsing process.
  236. //
  237. //nolint:lll
  238. type Config struct {
  239. ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
  240. LndDir string `long:"lnddir" description:"The base directory that contains lnd's data, logs, configuration file, etc. This option overwrites all other directory options."`
  241. ConfigFile string `short:"C" long:"configfile" description:"Path to configuration file"`
  242. DataDir string `short:"b" long:"datadir" description:"The directory to store lnd's data within"`
  243. 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."`
  244. TLSCertPath string `long:"tlscertpath" description:"Path to write the TLS certificate for lnd's RPC and REST services"`
  245. TLSKeyPath string `long:"tlskeypath" description:"Path to write the TLS private key for lnd's RPC and REST services"`
  246. TLSExtraIPs []string `long:"tlsextraip" description:"Adds an extra ip to the generated certificate"`
  247. TLSExtraDomains []string `long:"tlsextradomain" description:"Adds an extra domain to the generated certificate"`
  248. TLSAutoRefresh bool `long:"tlsautorefresh" description:"Re-generate TLS certificate and key if the IPs or domains are changed"`
  249. 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"`
  250. TLSCertDuration time.Duration `long:"tlscertduration" description:"The duration for which the auto-generated TLS certificate will be valid for"`
  251. TLSEncryptKey bool `long:"tlsencryptkey" description:"Automatically encrypts the TLS private key and generates ephemeral TLS key pairs when the wallet is locked or not initialized"`
  252. NoMacaroons bool `long:"no-macaroons" description:"Disable macaroon authentication, can only be used if server is not listening on a public interface."`
  253. AdminMacPath string `long:"adminmacaroonpath" description:"Path to write the admin macaroon for lnd's RPC and REST services if it doesn't exist"`
  254. ReadMacPath string `long:"readonlymacaroonpath" description:"Path to write the read-only macaroon for lnd's RPC and REST services if it doesn't exist"`
  255. InvoiceMacPath string `long:"invoicemacaroonpath" description:"Path to the invoice-only macaroon for lnd's RPC and REST services if it doesn't exist"`
  256. LogDir string `long:"logdir" description:"Directory to log output."`
  257. MaxLogFiles int `long:"maxlogfiles" description:"Maximum logfiles to keep (0 for no rotation)"`
  258. MaxLogFileSize int `long:"maxlogfilesize" description:"Maximum logfile size in MB"`
  259. 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"`
  260. LetsEncryptDir string `long:"letsencryptdir" description:"The directory to store Let's Encrypt certificates within"`
  261. 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."`
  262. LetsEncryptDomain string `long:"letsencryptdomain" description:"Request a Let's Encrypt certificate for this domain. Note that the certificate is only requested and stored when the first rpc connection comes in."`
  263. // We'll parse these 'raw' string arguments into real net.Addrs in the
  264. // loadConfig function. We need to expose the 'raw' strings so the
  265. // command line library can access them.
  266. // Only the parsed net.Addrs should be used!
  267. RawRPCListeners []string `long:"rpclisten" description:"Add an interface/port/socket to listen for RPC connections"`
  268. RawRESTListeners []string `long:"restlisten" description:"Add an interface/port/socket to listen for REST connections"`
  269. RawListeners []string `long:"listen" description:"Add an interface/port to listen for peer connections"`
  270. 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"`
  271. ExternalHosts []string `long:"externalhosts" description:"Add a hostname:port that should be periodically resolved to announce IPs for. If a port is not specified, the default (9735) will be used."`
  272. RPCListeners []net.Addr
  273. RESTListeners []net.Addr
  274. RestCORS []string `long:"restcors" description:"Add an ip:port/hostname to allow cross origin access from. To allow all origins, set as \"*\"."`
  275. Listeners []net.Addr
  276. ExternalIPs []net.Addr
  277. DisableListen bool `long:"nolisten" description:"Disable listening for incoming peer connections"`
  278. DisableRest bool `long:"norest" description:"Disable REST API"`
  279. DisableRestTLS bool `long:"no-rest-tls" description:"Disable TLS for REST connections"`
  280. WSPingInterval time.Duration `long:"ws-ping-interval" description:"The ping interval for REST based WebSocket connections, set to 0 to disable sending ping messages from the server side"`
  281. WSPongWait time.Duration `long:"ws-pong-wait" description:"The time we wait for a pong response message on REST based WebSocket connections before the connection is closed as inactive"`
  282. 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"`
  283. AddPeers []string `long:"addpeer" description:"Specify peers to connect to first"`
  284. MinBackoff time.Duration `long:"minbackoff" description:"Shortest backoff when reconnecting to persistent peers. Valid time units are {s, m, h}."`
  285. MaxBackoff time.Duration `long:"maxbackoff" description:"Longest backoff when reconnecting to persistent peers. Valid time units are {s, m, h}."`
  286. ConnectionTimeout time.Duration `long:"connectiontimeout" description:"The timeout value for network connections. Valid time units are {ms, s, m, h}."`
  287. 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"`
  288. CPUProfile string `long:"cpuprofile" description:"Write CPU profile to the specified file"`
  289. Profile string `long:"profile" description:"Enable HTTP profiling on either a port or host:port"`
  290. BlockingProfile int `long:"blockingprofile" description:"Used to enable a blocking profile to be served on the profiling port. This takes a value from 0 to 1, with 1 including every blocking event, and 0 including no events."`
  291. MutexProfile int `long:"mutexprofile" description:"Used to Enable a mutex profile to be served on the profiling port. This takes a value from 0 to 1, with 1 including every mutex event, and 0 including no events."`
  292. 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" hidden:"true"`
  293. 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."`
  294. MaxPendingChannels int `long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer."`
  295. BackupFilePath string `long:"backupfilepath" description:"The target location of the channel backup file"`
  296. FeeURL string `long:"feeurl" description:"DEPRECATED: Use 'fee.url' option. 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." hidden:"true"`
  297. Bitcoin *lncfg.Chain `group:"Bitcoin" namespace:"bitcoin"`
  298. BtcdMode *lncfg.Btcd `group:"btcd" namespace:"btcd"`
  299. BitcoindMode *lncfg.Bitcoind `group:"bitcoind" namespace:"bitcoind"`
  300. NeutrinoMode *lncfg.Neutrino `group:"neutrino" namespace:"neutrino"`
  301. BlockCacheSize uint64 `long:"blockcachesize" description:"The maximum capacity of the block cache"`
  302. Autopilot *lncfg.AutoPilot `group:"Autopilot" namespace:"autopilot"`
  303. Tor *lncfg.Tor `group:"Tor" namespace:"tor"`
  304. SubRPCServers *subRPCServerConfigs `group:"subrpc"`
  305. Hodl *hodl.Config `group:"hodl" namespace:"hodl"`
  306. NoNetBootstrap bool `long:"nobootstrap" description:"If true, then automatic network bootstrapping will not be attempted."`
  307. 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."`
  308. WalletUnlockPasswordFile string `long:"wallet-unlock-password-file" description:"The full path to a file (or pipe/device) that contains the password for unlocking the wallet; if set, no unlocking through RPC is possible and lnd will exit if no wallet exists or the password is incorrect; if wallet-unlock-allow-create is also set then lnd will ignore this flag if no wallet exists and allow a wallet to be created through RPC."`
  309. WalletUnlockAllowCreate bool `long:"wallet-unlock-allow-create" description:"Don't fail with an error if wallet-unlock-password-file is set but no wallet exists yet."`
  310. 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."`
  311. CoinSelectionStrategy string `long:"coin-selection-strategy" description:"The strategy to use for selecting coins for wallet transactions." choice:"largest" choice:"random"`
  312. 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."`
  313. TrickleDelay int `long:"trickledelay" description:"Time in milliseconds between each release of announcements to the network"`
  314. 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 re-enable or cancel a pending disables of the peer's channels on the network."`
  315. 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."`
  316. 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."`
  317. 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."`
  318. Alias string `long:"alias" description:"The node alias. Used as a moniker by peers and intelligence services"`
  319. Color string `long:"color" description:"The color of the node in hex format (i.e. '#3399FF'). Used to customize node appearance in intelligence services"`
  320. MinChanSize int64 `long:"minchansize" description:"The smallest channel size (in satoshis) that we should accept. Incoming channels smaller than this will be rejected"`
  321. MaxChanSize int64 `long:"maxchansize" description:"The largest channel size (in satoshis) that we should accept. Incoming channels larger than this will be rejected"`
  322. 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."`
  323. ChannelCommitInterval time.Duration `long:"channel-commit-interval" description:"The maximum time that is allowed to pass between receiving a channel state update and signing the next commitment. Setting this to a longer duration allows for more efficient channel operations at the cost of latency."`
  324. PendingCommitInterval time.Duration `long:"pending-commit-interval" description:"The maximum time that is allowed to pass while waiting for the remote party to revoke a locally initiated commitment state. Setting this to a longer duration if a slow response is expected from the remote party or large number of payments are attempted at the same time."`
  325. ChannelCommitBatchSize uint32 `long:"channel-commit-batch-size" description:"The maximum number of channel state updates that is accumulated before signing a new commitment."`
  326. KeepFailedPaymentAttempts bool `long:"keep-failed-payment-attempts" description:"Keeps persistent record of all failed payment attempts for successfully settled payments."`
  327. StoreFinalHtlcResolutions bool `long:"store-final-htlc-resolutions" description:"Persistently store the final resolution of incoming htlcs."`
  328. 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."`
  329. 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."`
  330. 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."`
  331. 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."`
  332. 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."`
  333. 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."`
  334. AcceptPositiveInboundFees bool `long:"accept-positive-inbound-fees" description:"If true, lnd will also allow setting positive inbound fees. By default, lnd only allows to set negative inbound fees (an inbound \"discount\") to remain backwards compatible with senders whose implementations do not yet support inbound fees."`
  335. // RequireInterceptor determines whether the HTLC interceptor is
  336. // registered regardless of whether the RPC is called or not.
  337. RequireInterceptor bool `long:"requireinterceptor" description:"Whether to always intercept HTLCs, even if no stream is attached"`
  338. 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"`
  339. MaxOutgoingCltvExpiry uint32 `long:"max-cltv-expiry" description:"The maximum number of blocks funds could be locked up for when forwarding payments."`
  340. 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]."`
  341. 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"`
  342. 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."`
  343. net tor.Net
  344. 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."`
  345. AcceptKeySend bool `long:"accept-keysend" description:"If true, spontaneous payments through keysend will be accepted. [experimental]"`
  346. AcceptAMP bool `long:"accept-amp" description:"If true, spontaneous payments via AMP will be accepted."`
  347. 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]"`
  348. GcCanceledInvoicesOnStartup bool `long:"gc-canceled-invoices-on-startup" description:"If true, we'll attempt to garbage collect canceled invoices upon start."`
  349. GcCanceledInvoicesOnTheFly bool `long:"gc-canceled-invoices-on-the-fly" description:"If true, we'll delete newly canceled invoices on the fly."`
  350. DustThreshold uint64 `long:"dust-threshold" description:"Sets the dust sum threshold in satoshis for a channel after which dust HTLC's will be failed."`
  351. Fee *lncfg.Fee `group:"fee" namespace:"fee"`
  352. Invoices *lncfg.Invoices `group:"invoices" namespace:"invoices"`
  353. Routing *lncfg.Routing `group:"routing" namespace:"routing"`
  354. Gossip *lncfg.Gossip `group:"gossip" namespace:"gossip"`
  355. Workers *lncfg.Workers `group:"workers" namespace:"workers"`
  356. Caches *lncfg.Caches `group:"caches" namespace:"caches"`
  357. Prometheus lncfg.Prometheus `group:"prometheus" namespace:"prometheus"`
  358. WtClient *lncfg.WtClient `group:"wtclient" namespace:"wtclient"`
  359. Watchtower *lncfg.Watchtower `group:"watchtower" namespace:"watchtower"`
  360. ProtocolOptions *lncfg.ProtocolOptions `group:"protocol" namespace:"protocol"`
  361. AllowCircularRoute bool `long:"allow-circular-route" description:"If true, our node will allow htlc forwards that arrive and depart on the same channel."`
  362. HealthChecks *lncfg.HealthCheckConfig `group:"healthcheck" namespace:"healthcheck"`
  363. DB *lncfg.DB `group:"db" namespace:"db"`
  364. Cluster *lncfg.Cluster `group:"cluster" namespace:"cluster"`
  365. RPCMiddleware *lncfg.RPCMiddleware `group:"rpcmiddleware" namespace:"rpcmiddleware"`
  366. RemoteSigner *lncfg.RemoteSigner `group:"remotesigner" namespace:"remotesigner"`
  367. Sweeper *lncfg.Sweeper `group:"sweeper" namespace:"sweeper"`
  368. Htlcswitch *lncfg.Htlcswitch `group:"htlcswitch" namespace:"htlcswitch"`
  369. GRPC *GRPCConfig `group:"grpc" namespace:"grpc"`
  370. // LogWriter is the root logger that all of the daemon's subloggers are
  371. // hooked up to.
  372. LogWriter *build.RotatingLogWriter
  373. // networkDir is the path to the directory of the currently active
  374. // network. This path will hold the files related to each different
  375. // network.
  376. networkDir string
  377. // ActiveNetParams contains parameters of the target chain.
  378. ActiveNetParams chainreg.BitcoinNetParams
  379. // Estimator is used to estimate routing probabilities.
  380. Estimator routing.Estimator
  381. // Dev specifies configs used for integration tests, which is always
  382. // empty if not built with `integration` flag.
  383. Dev *lncfg.DevConfig `group:"dev" namespace:"dev"`
  384. // HTTPHeaderTimeout is the maximum duration that the server will wait
  385. // before timing out reading the headers of an HTTP request.
  386. HTTPHeaderTimeout time.Duration `long:"http-header-timeout" description:"The maximum duration that the server will wait before timing out reading the headers of an HTTP request."`
  387. }
  388. // GRPCConfig holds the configuration options for the gRPC server.
  389. // See https://github.com/grpc/grpc-go/blob/v1.41.0/keepalive/keepalive.go#L50
  390. // for more details. Any value of 0 means we use the gRPC internal default
  391. // values.
  392. //
  393. //nolint:lll
  394. type GRPCConfig struct {
  395. // ServerPingTime is a duration for the amount of time of no activity
  396. // after which the server pings the client to see if the transport is
  397. // still alive. If set below 1s, a minimum value of 1s will be used
  398. // instead.
  399. ServerPingTime time.Duration `long:"server-ping-time" description:"How long the server waits on a gRPC stream with no activity before pinging the client."`
  400. // ServerPingTimeout is the duration the server waits after having
  401. // pinged for keepalive check, and if no activity is seen even after
  402. // that the connection is closed.
  403. ServerPingTimeout time.Duration `long:"server-ping-timeout" description:"How long the server waits for the response from the client for the keepalive ping response."`
  404. // ClientPingMinWait is the minimum amount of time a client should wait
  405. // before sending a keepalive ping.
  406. ClientPingMinWait time.Duration `long:"client-ping-min-wait" description:"The minimum amount of time the client should wait before sending a keepalive ping."`
  407. // ClientAllowPingWithoutStream specifies whether pings from the client
  408. // are allowed even if there are no active gRPC streams. This might be
  409. // useful to keep the underlying HTTP/2 connection open for future
  410. // requests.
  411. ClientAllowPingWithoutStream bool `long:"client-allow-ping-without-stream" description:"If true, the server allows keepalive pings from the client even when there are no active gRPC streams. This might be useful to keep the underlying HTTP/2 connection open for future requests."`
  412. }
  413. // DefaultConfig returns all default values for the Config struct.
  414. //
  415. //nolint:lll
  416. func DefaultConfig() Config {
  417. return Config{
  418. LndDir: DefaultLndDir,
  419. ConfigFile: DefaultConfigFile,
  420. DataDir: defaultDataDir,
  421. DebugLevel: defaultLogLevel,
  422. TLSCertPath: defaultTLSCertPath,
  423. TLSKeyPath: defaultTLSKeyPath,
  424. TLSCertDuration: defaultTLSCertDuration,
  425. LetsEncryptDir: defaultLetsEncryptDir,
  426. LetsEncryptListen: defaultLetsEncryptListen,
  427. LogDir: defaultLogDir,
  428. MaxLogFiles: defaultMaxLogFiles,
  429. MaxLogFileSize: defaultMaxLogFileSize,
  430. AcceptorTimeout: defaultAcceptorTimeout,
  431. WSPingInterval: lnrpc.DefaultPingInterval,
  432. WSPongWait: lnrpc.DefaultPongWait,
  433. Bitcoin: &lncfg.Chain{
  434. MinHTLCIn: chainreg.DefaultBitcoinMinHTLCInMSat,
  435. MinHTLCOut: chainreg.DefaultBitcoinMinHTLCOutMSat,
  436. BaseFee: chainreg.DefaultBitcoinBaseFeeMSat,
  437. FeeRate: chainreg.DefaultBitcoinFeeRate,
  438. TimeLockDelta: chainreg.DefaultBitcoinTimeLockDelta,
  439. MaxLocalDelay: defaultMaxLocalCSVDelay,
  440. Node: btcdBackendName,
  441. },
  442. BtcdMode: &lncfg.Btcd{
  443. Dir: defaultBtcdDir,
  444. RPCHost: defaultRPCHost,
  445. RPCCert: defaultBtcdRPCCertFile,
  446. },
  447. BitcoindMode: &lncfg.Bitcoind{
  448. Dir: defaultBitcoindDir,
  449. RPCHost: defaultRPCHost,
  450. EstimateMode: defaultBitcoindEstimateMode,
  451. PrunedNodeMaxPeers: defaultPrunedNodeMaxPeers,
  452. ZMQReadDeadline: defaultZMQReadDeadline,
  453. },
  454. NeutrinoMode: &lncfg.Neutrino{
  455. UserAgentName: neutrino.UserAgentName,
  456. UserAgentVersion: neutrino.UserAgentVersion,
  457. },
  458. BlockCacheSize: defaultBlockCacheSize,
  459. MaxPendingChannels: lncfg.DefaultMaxPendingChannels,
  460. NoSeedBackup: defaultNoSeedBackup,
  461. MinBackoff: defaultMinBackoff,
  462. MaxBackoff: defaultMaxBackoff,
  463. ConnectionTimeout: tor.DefaultConnTimeout,
  464. Fee: &lncfg.Fee{
  465. MinUpdateTimeout: lncfg.DefaultMinUpdateTimeout,
  466. MaxUpdateTimeout: lncfg.DefaultMaxUpdateTimeout,
  467. },
  468. SubRPCServers: &subRPCServerConfigs{
  469. SignRPC: &signrpc.Config{},
  470. RouterRPC: routerrpc.DefaultConfig(),
  471. PeersRPC: &peersrpc.Config{},
  472. },
  473. Autopilot: &lncfg.AutoPilot{
  474. MaxChannels: 5,
  475. Allocation: 0.6,
  476. MinChannelSize: int64(funding.MinChanFundingSize),
  477. MaxChannelSize: int64(MaxFundingAmount),
  478. MinConfs: 1,
  479. ConfTarget: autopilot.DefaultConfTarget,
  480. Heuristic: map[string]float64{
  481. "top_centrality": 1.0,
  482. },
  483. },
  484. PaymentsExpirationGracePeriod: defaultPaymentsExpirationGracePeriod,
  485. TrickleDelay: defaultTrickleDelay,
  486. ChanStatusSampleInterval: defaultChanStatusSampleInterval,
  487. ChanEnableTimeout: defaultChanEnableTimeout,
  488. ChanDisableTimeout: defaultChanDisableTimeout,
  489. HeightHintCacheQueryDisable: defaultHeightHintCacheQueryDisable,
  490. Alias: defaultAlias,
  491. Color: defaultColor,
  492. MinChanSize: int64(funding.MinChanFundingSize),
  493. MaxChanSize: int64(0),
  494. CoopCloseTargetConfs: defaultCoopCloseTargetConfs,
  495. DefaultRemoteMaxHtlcs: defaultRemoteMaxHtlcs,
  496. NumGraphSyncPeers: defaultMinPeers,
  497. HistoricalSyncInterval: discovery.DefaultHistoricalSyncInterval,
  498. Tor: &lncfg.Tor{
  499. SOCKS: defaultTorSOCKS,
  500. DNS: defaultTorDNS,
  501. Control: defaultTorControl,
  502. },
  503. net: &tor.ClearNet{},
  504. Workers: &lncfg.Workers{
  505. Read: lncfg.DefaultReadWorkers,
  506. Write: lncfg.DefaultWriteWorkers,
  507. Sig: lncfg.DefaultSigWorkers,
  508. },
  509. Caches: &lncfg.Caches{
  510. RejectCacheSize: channeldb.DefaultRejectCacheSize,
  511. ChannelCacheSize: channeldb.DefaultChannelCacheSize,
  512. },
  513. Prometheus: lncfg.DefaultPrometheus(),
  514. Watchtower: lncfg.DefaultWatchtowerCfg(defaultTowerDir),
  515. HealthChecks: &lncfg.HealthCheckConfig{
  516. ChainCheck: &lncfg.CheckConfig{
  517. Interval: defaultChainInterval,
  518. Timeout: defaultChainTimeout,
  519. Attempts: defaultChainAttempts,
  520. Backoff: defaultChainBackoff,
  521. },
  522. DiskCheck: &lncfg.DiskCheckConfig{
  523. RequiredRemaining: defaultRequiredDisk,
  524. CheckConfig: &lncfg.CheckConfig{
  525. Interval: defaultDiskInterval,
  526. Attempts: defaultDiskAttempts,
  527. Timeout: defaultDiskTimeout,
  528. Backoff: defaultDiskBackoff,
  529. },
  530. },
  531. TLSCheck: &lncfg.CheckConfig{
  532. Interval: defaultTLSInterval,
  533. Timeout: defaultTLSTimeout,
  534. Attempts: defaultTLSAttempts,
  535. Backoff: defaultTLSBackoff,
  536. },
  537. TorConnection: &lncfg.CheckConfig{
  538. Interval: defaultTCInterval,
  539. Timeout: defaultTCTimeout,
  540. Attempts: defaultTCAttempts,
  541. Backoff: defaultTCBackoff,
  542. },
  543. RemoteSigner: &lncfg.CheckConfig{
  544. Interval: defaultRSInterval,
  545. Timeout: defaultRSTimeout,
  546. Attempts: defaultRSAttempts,
  547. Backoff: defaultRSBackoff,
  548. },
  549. },
  550. Gossip: &lncfg.Gossip{
  551. MaxChannelUpdateBurst: discovery.DefaultMaxChannelUpdateBurst,
  552. ChannelUpdateInterval: discovery.DefaultChannelUpdateInterval,
  553. SubBatchDelay: discovery.DefaultSubBatchDelay,
  554. },
  555. Invoices: &lncfg.Invoices{
  556. HoldExpiryDelta: lncfg.DefaultHoldInvoiceExpiryDelta,
  557. },
  558. MaxOutgoingCltvExpiry: htlcswitch.DefaultMaxOutgoingCltvExpiry,
  559. MaxChannelFeeAllocation: htlcswitch.DefaultMaxLinkFeeAllocation,
  560. MaxCommitFeeRateAnchors: lnwallet.DefaultAnchorsCommitMaxFeeRateSatPerVByte,
  561. DustThreshold: uint64(htlcswitch.DefaultDustThreshold.ToSatoshis()),
  562. LogWriter: build.NewRotatingLogWriter(),
  563. DB: lncfg.DefaultDB(),
  564. Cluster: lncfg.DefaultCluster(),
  565. RPCMiddleware: lncfg.DefaultRPCMiddleware(),
  566. ActiveNetParams: chainreg.BitcoinTestNetParams,
  567. ChannelCommitInterval: defaultChannelCommitInterval,
  568. PendingCommitInterval: defaultPendingCommitInterval,
  569. ChannelCommitBatchSize: defaultChannelCommitBatchSize,
  570. CoinSelectionStrategy: defaultCoinSelectionStrategy,
  571. KeepFailedPaymentAttempts: defaultKeepFailedPaymentAttempts,
  572. RemoteSigner: &lncfg.RemoteSigner{
  573. Timeout: lncfg.DefaultRemoteSignerRPCTimeout,
  574. },
  575. Sweeper: lncfg.DefaultSweeperConfig(),
  576. Htlcswitch: &lncfg.Htlcswitch{
  577. MailboxDeliveryTimeout: htlcswitch.DefaultMailboxDeliveryTimeout,
  578. },
  579. GRPC: &GRPCConfig{
  580. ServerPingTime: defaultGrpcServerPingTime,
  581. ServerPingTimeout: defaultGrpcServerPingTimeout,
  582. ClientPingMinWait: defaultGrpcClientPingMinWait,
  583. },
  584. WtClient: lncfg.DefaultWtClientCfg(),
  585. HTTPHeaderTimeout: DefaultHTTPHeaderTimeout,
  586. }
  587. }
  588. // LoadConfig initializes and parses the config using a config file and command
  589. // line options.
  590. //
  591. // The configuration proceeds as follows:
  592. // 1. Start with a default config with sane settings
  593. // 2. Pre-parse the command line to check for an alternative config file
  594. // 3. Load configuration file overwriting defaults with any specified options
  595. // 4. Parse CLI options and overwrite/add any specified options
  596. func LoadConfig(interceptor signal.Interceptor) (*Config, error) {
  597. // Pre-parse the command line options to pick up an alternative config
  598. // file.
  599. preCfg := DefaultConfig()
  600. if _, err := flags.Parse(&preCfg); err != nil {
  601. return nil, err
  602. }
  603. // Show the version and exit if the version flag was specified.
  604. appName := filepath.Base(os.Args[0])
  605. appName = strings.TrimSuffix(appName, filepath.Ext(appName))
  606. usageMessage := fmt.Sprintf("Use %s -h to show usage", appName)
  607. if preCfg.ShowVersion {
  608. fmt.Println(appName, "version", build.Version(),
  609. "commit="+build.Commit)
  610. os.Exit(0)
  611. }
  612. // If the config file path has not been modified by the user, then we'll
  613. // use the default config file path. However, if the user has modified
  614. // their lnddir, then we should assume they intend to use the config
  615. // file within it.
  616. configFileDir := CleanAndExpandPath(preCfg.LndDir)
  617. configFilePath := CleanAndExpandPath(preCfg.ConfigFile)
  618. switch {
  619. // User specified --lnddir but no --configfile. Update the config file
  620. // path to the lnd config directory, but don't require it to exist.
  621. case configFileDir != DefaultLndDir &&
  622. configFilePath == DefaultConfigFile:
  623. configFilePath = filepath.Join(
  624. configFileDir, lncfg.DefaultConfigFilename,
  625. )
  626. // User did specify an explicit --configfile, so we check that it does
  627. // exist under that path to avoid surprises.
  628. case configFilePath != DefaultConfigFile:
  629. if !lnrpc.FileExists(configFilePath) {
  630. return nil, fmt.Errorf("specified config file does "+
  631. "not exist in %s", configFilePath)
  632. }
  633. }
  634. // Next, load any additional configuration options from the file.
  635. var configFileError error
  636. cfg := preCfg
  637. fileParser := flags.NewParser(&cfg, flags.Default)
  638. err := flags.NewIniParser(fileParser).ParseFile(configFilePath)
  639. if err != nil {
  640. // If it's a parsing related error, then we'll return
  641. // immediately, otherwise we can proceed as possibly the config
  642. // file doesn't exist which is OK.
  643. if _, ok := err.(*flags.IniError); ok {
  644. return nil, err
  645. }
  646. configFileError = err
  647. }
  648. // Finally, parse the remaining command line options again to ensure
  649. // they take precedence.
  650. flagParser := flags.NewParser(&cfg, flags.Default)
  651. if _, err := flagParser.Parse(); err != nil {
  652. return nil, err
  653. }
  654. // Make sure everything we just loaded makes sense.
  655. cleanCfg, err := ValidateConfig(
  656. cfg, interceptor, fileParser, flagParser,
  657. )
  658. if usageErr, ok := err.(*usageError); ok {
  659. // The logging system might not yet be initialized, so we also
  660. // write to stderr to make sure the error appears somewhere.
  661. _, _ = fmt.Fprintln(os.Stderr, usageMessage)
  662. ltndLog.Warnf("Incorrect usage: %v", usageMessage)
  663. // The log subsystem might not yet be initialized. But we still
  664. // try to log the error there since some packaging solutions
  665. // might only look at the log and not stdout/stderr.
  666. ltndLog.Warnf("Error validating config: %v", usageErr.err)
  667. return nil, usageErr.err
  668. }
  669. if err != nil {
  670. // The log subsystem might not yet be initialized. But we still
  671. // try to log the error there since some packaging solutions
  672. // might only look at the log and not stdout/stderr.
  673. ltndLog.Warnf("Error validating config: %v", err)
  674. return nil, err
  675. }
  676. // Warn about missing config file only after all other configuration is
  677. // done. This prevents the warning on help messages and invalid options.
  678. // Note this should go directly before the return.
  679. if configFileError != nil {
  680. ltndLog.Warnf("%v", configFileError)
  681. }
  682. // Finally, log warnings for deprecated config options if they are set.
  683. logWarningsForDeprecation(*cleanCfg)
  684. return cleanCfg, nil
  685. }
  686. // usageError is an error type that signals a problem with the supplied flags.
  687. type usageError struct {
  688. err error
  689. }
  690. // Error returns the error string.
  691. //
  692. // NOTE: This is part of the error interface.
  693. func (u *usageError) Error() string {
  694. return u.err.Error()
  695. }
  696. // ValidateConfig check the given configuration to be sane. This makes sure no
  697. // illegal values or combination of values are set. All file system paths are
  698. // normalized. The cleaned up config is returned on success.
  699. func ValidateConfig(cfg Config, interceptor signal.Interceptor, fileParser,
  700. flagParser *flags.Parser) (*Config, error) {
  701. // If the provided lnd directory is not the default, we'll modify the
  702. // path to all of the files and directories that will live within it.
  703. lndDir := CleanAndExpandPath(cfg.LndDir)
  704. if lndDir != DefaultLndDir {
  705. cfg.DataDir = filepath.Join(lndDir, defaultDataDirname)
  706. cfg.LetsEncryptDir = filepath.Join(
  707. lndDir, defaultLetsEncryptDirname,
  708. )
  709. cfg.TLSCertPath = filepath.Join(lndDir, defaultTLSCertFilename)
  710. cfg.TLSKeyPath = filepath.Join(lndDir, defaultTLSKeyFilename)
  711. cfg.LogDir = filepath.Join(lndDir, defaultLogDirname)
  712. // If the watchtower's directory is set to the default, i.e. the
  713. // user has not requested a different location, we'll move the
  714. // location to be relative to the specified lnd directory.
  715. if cfg.Watchtower.TowerDir == defaultTowerDir {
  716. cfg.Watchtower.TowerDir = filepath.Join(
  717. cfg.DataDir, defaultTowerSubDirname,
  718. )
  719. }
  720. }
  721. funcName := "ValidateConfig"
  722. mkErr := func(format string, args ...interface{}) error {
  723. return fmt.Errorf(funcName+": "+format, args...)
  724. }
  725. makeDirectory := func(dir string) error {
  726. err := os.MkdirAll(dir, 0700)
  727. if err != nil {
  728. // Show a nicer error message if it's because a symlink
  729. // is linked to a directory that does not exist
  730. // (probably because it's not mounted).
  731. if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
  732. link, lerr := os.Readlink(e.Path)
  733. if lerr == nil {
  734. str := "is symlink %s -> %s mounted?"
  735. err = fmt.Errorf(str, e.Path, link)
  736. }
  737. }
  738. str := "Failed to create lnd directory '%s': %v"
  739. return mkErr(str, dir, err)
  740. }
  741. return nil
  742. }
  743. // IsSet returns true if an option has been set in either the config
  744. // file or by a flag.
  745. isSet := func(field string) (bool, error) {
  746. fieldName, ok := reflect.TypeOf(Config{}).FieldByName(field)
  747. if !ok {
  748. str := "could not find field %s"
  749. return false, mkErr(str, field)
  750. }
  751. long, ok := fieldName.Tag.Lookup("long")
  752. if !ok {
  753. str := "field %s does not have a long tag"
  754. return false, mkErr(str, field)
  755. }
  756. // The user has the option to set the flag in either the config
  757. // file or as a command line flag. If any is set, we consider it
  758. // to be set, not applying any precedence rules here (since it
  759. // is a boolean the default is false anyway which would screw up
  760. // any precedence rules). Additionally, we need to also support
  761. // the use case where the config struct is embedded _within_
  762. // another struct with a prefix (as is the case with
  763. // lightning-terminal).
  764. fileOption := fileParser.FindOptionByLongName(long)
  765. fileOptionNested := fileParser.FindOptionByLongName(
  766. "lnd." + long,
  767. )
  768. flagOption := flagParser.FindOptionByLongName(long)
  769. flagOptionNested := flagParser.FindOptionByLongName(
  770. "lnd." + long,
  771. )
  772. return (fileOption != nil && fileOption.IsSet()) ||
  773. (fileOptionNested != nil && fileOptionNested.IsSet()) ||
  774. (flagOption != nil && flagOption.IsSet()) ||
  775. (flagOptionNested != nil && flagOptionNested.IsSet()),
  776. nil
  777. }
  778. // As soon as we're done parsing configuration options, ensure all paths
  779. // to directories and files are cleaned and expanded before attempting
  780. // to use them later on.
  781. cfg.DataDir = CleanAndExpandPath(cfg.DataDir)
  782. cfg.TLSCertPath = CleanAndExpandPath(cfg.TLSCertPath)
  783. cfg.TLSKeyPath = CleanAndExpandPath(cfg.TLSKeyPath)
  784. cfg.LetsEncryptDir = CleanAndExpandPath(cfg.LetsEncryptDir)
  785. cfg.AdminMacPath = CleanAndExpandPath(cfg.AdminMacPath)
  786. cfg.ReadMacPath = CleanAndExpandPath(cfg.ReadMacPath)
  787. cfg.InvoiceMacPath = CleanAndExpandPath(cfg.InvoiceMacPath)
  788. cfg.LogDir = CleanAndExpandPath(cfg.LogDir)
  789. cfg.BtcdMode.Dir = CleanAndExpandPath(cfg.BtcdMode.Dir)
  790. cfg.BitcoindMode.Dir = CleanAndExpandPath(cfg.BitcoindMode.Dir)
  791. cfg.BitcoindMode.ConfigPath = CleanAndExpandPath(
  792. cfg.BitcoindMode.ConfigPath,
  793. )
  794. cfg.BitcoindMode.RPCCookie = CleanAndExpandPath(cfg.BitcoindMode.RPCCookie)
  795. cfg.Tor.PrivateKeyPath = CleanAndExpandPath(cfg.Tor.PrivateKeyPath)
  796. cfg.Tor.WatchtowerKeyPath = CleanAndExpandPath(cfg.Tor.WatchtowerKeyPath)
  797. cfg.Watchtower.TowerDir = CleanAndExpandPath(cfg.Watchtower.TowerDir)
  798. cfg.BackupFilePath = CleanAndExpandPath(cfg.BackupFilePath)
  799. cfg.WalletUnlockPasswordFile = CleanAndExpandPath(
  800. cfg.WalletUnlockPasswordFile,
  801. )
  802. // Ensure that the user didn't attempt to specify negative values for
  803. // any of the autopilot params.
  804. if cfg.Autopilot.MaxChannels < 0 {
  805. str := "autopilot.maxchannels must be non-negative"
  806. return nil, mkErr(str)
  807. }
  808. if cfg.Autopilot.Allocation < 0 {
  809. str := "autopilot.allocation must be non-negative"
  810. return nil, mkErr(str)
  811. }
  812. if cfg.Autopilot.MinChannelSize < 0 {
  813. str := "autopilot.minchansize must be non-negative"
  814. return nil, mkErr(str)
  815. }
  816. if cfg.Autopilot.MaxChannelSize < 0 {
  817. str := "autopilot.maxchansize must be non-negative"
  818. return nil, mkErr(str)
  819. }
  820. if cfg.Autopilot.MinConfs < 0 {
  821. str := "autopilot.minconfs must be non-negative"
  822. return nil, mkErr(str)
  823. }
  824. if cfg.Autopilot.ConfTarget < 1 {
  825. str := "autopilot.conftarget must be positive"
  826. return nil, mkErr(str)
  827. }
  828. // Ensure that the specified values for the min and max channel size
  829. // are within the bounds of the normal chan size constraints.
  830. if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
  831. cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
  832. }
  833. if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
  834. cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
  835. }
  836. if _, err := validateAtplCfg(cfg.Autopilot); err != nil {
  837. return nil, mkErr("error validating autopilot: %v", err)
  838. }
  839. // Ensure that --maxchansize is properly handled when set by user.
  840. // For non-Wumbo channels this limit remains 16777215 satoshis by default
  841. // as specified in BOLT-02. For wumbo channels this limit is 1,000,000,000.
  842. // satoshis (10 BTC). Always enforce --maxchansize explicitly set by user.
  843. // If unset (marked by 0 value), then enforce proper default.
  844. if cfg.MaxChanSize == 0 {
  845. if cfg.ProtocolOptions.Wumbo() {
  846. cfg.MaxChanSize = int64(funding.MaxBtcFundingAmountWumbo)
  847. } else {
  848. cfg.MaxChanSize = int64(funding.MaxBtcFundingAmount)
  849. }
  850. }
  851. // Ensure that the user specified values for the min and max channel
  852. // size make sense.
  853. if cfg.MaxChanSize < cfg.MinChanSize {
  854. return nil, mkErr("invalid channel size parameters: "+
  855. "max channel size %v, must be no less than min chan "+
  856. "size %v", cfg.MaxChanSize, cfg.MinChanSize,
  857. )
  858. }
  859. // Don't allow superfluous --maxchansize greater than
  860. // BOLT 02 soft-limit for non-wumbo channel
  861. if !cfg.ProtocolOptions.Wumbo() &&
  862. cfg.MaxChanSize > int64(MaxFundingAmount) {
  863. return nil, mkErr("invalid channel size parameters: "+
  864. "maximum channel size %v is greater than maximum "+
  865. "non-wumbo channel size %v", cfg.MaxChanSize,
  866. MaxFundingAmount,
  867. )
  868. }
  869. // Ensure that the amount data for revoked commitment transactions is
  870. // stored if the watchtower client is active.
  871. if cfg.DB.NoRevLogAmtData && cfg.WtClient.Active {
  872. return nil, mkErr("revocation log amount data must be stored " +
  873. "if the watchtower client is active")
  874. }
  875. // Ensure a valid max channel fee allocation was set.
  876. if cfg.MaxChannelFeeAllocation <= 0 || cfg.MaxChannelFeeAllocation > 1 {
  877. return nil, mkErr("invalid max channel fee allocation: %v, "+
  878. "must be within (0, 1]", cfg.MaxChannelFeeAllocation)
  879. }
  880. if cfg.MaxCommitFeeRateAnchors < 1 {
  881. return nil, mkErr("invalid max commit fee rate anchors: %v, "+
  882. "must be at least 1 sat/vByte",
  883. cfg.MaxCommitFeeRateAnchors)
  884. }
  885. // Validate the Tor config parameters.
  886. socks, err := lncfg.ParseAddressString(
  887. cfg.Tor.SOCKS, strconv.Itoa(defaultTorSOCKSPort),
  888. cfg.net.ResolveTCPAddr,
  889. )
  890. if err != nil {
  891. return nil, err
  892. }
  893. cfg.Tor.SOCKS = socks.String()
  894. // We'll only attempt to normalize and resolve the DNS host if it hasn't
  895. // changed, as it doesn't need to be done for the default.
  896. if cfg.Tor.DNS != defaultTorDNS {
  897. dns, err := lncfg.ParseAddressString(
  898. cfg.Tor.DNS, strconv.Itoa(defaultTorDNSPort),
  899. cfg.net.ResolveTCPAddr,
  900. )
  901. if err != nil {
  902. return nil, mkErr("error parsing tor dns: %v", err)
  903. }
  904. cfg.Tor.DNS = dns.String()
  905. }
  906. control, err := lncfg.ParseAddressString(
  907. cfg.Tor.Control, strconv.Itoa(defaultTorControlPort),
  908. cfg.net.ResolveTCPAddr,
  909. )
  910. if err != nil {
  911. return nil, mkErr("error parsing tor control address: %v", err)
  912. }
  913. cfg.Tor.Control = control.String()
  914. // Ensure that tor socks host:port is not equal to tor control
  915. // host:port. This would lead to lnd not starting up properly.
  916. if cfg.Tor.SOCKS == cfg.Tor.Control {
  917. str := "tor.socks and tor.control can not us the same host:port"
  918. return nil, mkErr(str)
  919. }
  920. switch {
  921. case cfg.Tor.V2 && cfg.Tor.V3:
  922. return nil, mkErr("either tor.v2 or tor.v3 can be set, " +
  923. "but not both")
  924. case cfg.DisableListen && (cfg.Tor.V2 || cfg.Tor.V3):
  925. return nil, mkErr("listening must be enabled when enabling " +
  926. "inbound connections over Tor")
  927. }
  928. if cfg.Tor.PrivateKeyPath == "" {
  929. switch {
  930. case cfg.Tor.V2:
  931. cfg.Tor.PrivateKeyPath = filepath.Join(
  932. lndDir, defaultTorV2PrivateKeyFilename,
  933. )
  934. case cfg.Tor.V3:
  935. cfg.Tor.PrivateKeyPath = filepath.Join(
  936. lndDir, defaultTorV3PrivateKeyFilename,
  937. )
  938. }
  939. }
  940. if cfg.Tor.WatchtowerKeyPath == "" {
  941. switch {
  942. case cfg.Tor.V2:
  943. cfg.Tor.WatchtowerKeyPath = filepath.Join(
  944. cfg.Watchtower.TowerDir,
  945. defaultTorV2PrivateKeyFilename,
  946. )
  947. case cfg.Tor.V3:
  948. cfg.Tor.WatchtowerKeyPath = filepath.Join(
  949. cfg.Watchtower.TowerDir,
  950. defaultTorV3PrivateKeyFilename,
  951. )
  952. }
  953. }
  954. // Set up the network-related functions that will be used throughout
  955. // the daemon. We use the standard Go "net" package functions by
  956. // default. If we should be proxying all traffic through Tor, then
  957. // we'll use the Tor proxy specific functions in order to avoid leaking
  958. // our real information.
  959. if cfg.Tor.Active {
  960. cfg.net = &tor.ProxyNet{
  961. SOCKS: cfg.Tor.SOCKS,
  962. DNS: cfg.Tor.DNS,
  963. StreamIsolation: cfg.Tor.StreamIsolation,
  964. SkipProxyForClearNetTargets: cfg.Tor.SkipProxyForClearNetTargets,
  965. }
  966. }
  967. if cfg.DisableListen && cfg.NAT {
  968. return nil, mkErr("NAT traversal cannot be used when " +
  969. "listening is disabled")
  970. }
  971. if cfg.NAT && len(cfg.ExternalHosts) != 0 {
  972. return nil, mkErr("NAT support and externalhosts are " +
  973. "mutually exclusive, only one should be selected")
  974. }
  975. // Multiple networks can't be selected simultaneously. Count
  976. // number of network flags passed; assign active network params
  977. // while we're at it.
  978. numNets := 0
  979. if cfg.Bitcoin.MainNet {
  980. numNets++
  981. cfg.ActiveNetParams = chainreg.BitcoinMainNetParams
  982. }
  983. if cfg.Bitcoin.TestNet3 {
  984. numNets++
  985. cfg.ActiveNetParams = chainreg.BitcoinTestNetParams
  986. }
  987. if cfg.Bitcoin.RegTest {
  988. numNets++
  989. cfg.ActiveNetParams = chainreg.BitcoinRegTestNetParams
  990. }
  991. if cfg.Bitcoin.SimNet {
  992. numNets++
  993. cfg.ActiveNetParams = chainreg.BitcoinSimNetParams
  994. // For simnet, the btcsuite chain params uses a
  995. // cointype of 115. However, we override this in
  996. // chainreg/chainparams.go, but the raw ChainParam
  997. // field is used elsewhere. To ensure everything is
  998. // consistent, we'll also override the cointype within
  999. // the raw params.
  1000. targetCoinType := chainreg.BitcoinSigNetParams.CoinType
  1001. cfg.ActiveNetParams.Params.HDCoinType = targetCoinType
  1002. }
  1003. if cfg.Bitcoin.SigNet {
  1004. numNets++
  1005. cfg.ActiveNetParams = chainreg.BitcoinSigNetParams
  1006. // Let the user overwrite the default signet parameters.
  1007. // The challenge defines the actual signet network to
  1008. // join and the seed nodes are needed for network
  1009. // discovery.
  1010. sigNetChallenge := chaincfg.DefaultSignetChallenge
  1011. sigNetSeeds := chaincfg.DefaultSignetDNSSeeds
  1012. if cfg.Bitcoin.SigNetChallenge != "" {
  1013. challenge, err := hex.DecodeString(
  1014. cfg.Bitcoin.SigNetChallenge,
  1015. )
  1016. if err != nil {
  1017. return nil, mkErr("Invalid "+
  1018. "signet challenge, hex decode "+
  1019. "failed: %v", err)
  1020. }
  1021. sigNetChallenge = challenge
  1022. }
  1023. if len(cfg.Bitcoin.SigNetSeedNode) > 0 {
  1024. sigNetSeeds = make([]chaincfg.DNSSeed, len(
  1025. cfg.Bitcoin.SigNetSeedNode,
  1026. ))
  1027. for idx, seed := range cfg.Bitcoin.SigNetSeedNode {
  1028. sigNetSeeds[idx] = chaincfg.DNSSeed{
  1029. Host: seed,
  1030. HasFiltering: false,
  1031. }
  1032. }
  1033. }
  1034. chainParams := chaincfg.CustomSignetParams(
  1035. sigNetChallenge, sigNetSeeds,
  1036. )
  1037. cfg.ActiveNetParams.Params = &chainParams
  1038. }
  1039. if numNets > 1 {
  1040. str := "The mainnet, testnet, regtest, simnet and signet " +
  1041. "params can't be used together -- choose one " +
  1042. "of the five"
  1043. return nil, mkErr(str)
  1044. }
  1045. // The target network must be provided, otherwise, we won't
  1046. // know how to initialize the daemon.
  1047. if numNets == 0 {
  1048. str := "either --bitcoin.mainnet, or bitcoin.testnet," +
  1049. "bitcoin.simnet, bitcoin.regtest or bitcoin.signet " +
  1050. "must be specified"
  1051. return nil, mkErr(str)
  1052. }
  1053. err = cfg.Bitcoin.Validate(minTimeLockDelta, funding.MinBtcRemoteDelay)
  1054. if err != nil {
  1055. return nil, mkErr("error validating bitcoin params: %v", err)
  1056. }
  1057. switch cfg.Bitcoin.Node {
  1058. case btcdBackendName:
  1059. err := parseRPCParams(
  1060. cfg.Bitcoin, cfg.BtcdMode, cfg.ActiveNetParams,
  1061. )
  1062. if err != nil {
  1063. return nil, mkErr("unable to load RPC "+
  1064. "credentials for btcd: %v", err)
  1065. }
  1066. case bitcoindBackendName:
  1067. if cfg.Bitcoin.SimNet {
  1068. return nil, mkErr("bitcoind does not " +
  1069. "support simnet")
  1070. }
  1071. err := parseRPCParams(
  1072. cfg.Bitcoin, cfg.BitcoindMode, cfg.ActiveNetParams,
  1073. )
  1074. if err != nil {
  1075. return nil, mkErr("unable to load RPC "+
  1076. "credentials for bitcoind: %v", err)
  1077. }
  1078. case neutrinoBackendName:
  1079. // No need to get RPC parameters.
  1080. case "nochainbackend":
  1081. // Nothing to configure, we're running without any chain
  1082. // backend whatsoever (pure signing mode).
  1083. default:
  1084. str := "only btcd, bitcoind, and neutrino mode " +
  1085. "supported for bitcoin at this time"
  1086. return nil, mkErr(str)
  1087. }
  1088. cfg.Bitcoin.ChainDir = filepath.Join(
  1089. cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
  1090. )
  1091. // Ensure that the user didn't attempt to specify negative values for
  1092. // any of the autopilot params.
  1093. if cfg.Autopilot.MaxChannels < 0 {
  1094. str := "autopilot.maxchannels must be non-negative"
  1095. return nil, mkErr(str)
  1096. }
  1097. if cfg.Autopilot.Allocation < 0 {
  1098. str := "autopilot.allocation must be non-negative"
  1099. return nil, mkErr(str)
  1100. }
  1101. if cfg.Autopilot.MinChannelSize < 0 {
  1102. str := "autopilot.minchansize must be non-negative"
  1103. return nil, mkErr(str)
  1104. }
  1105. if cfg.Autopilot.MaxChannelSize < 0 {
  1106. str := "autopilot.maxchansize must be non-negative"
  1107. return nil, mkErr(str)
  1108. }
  1109. // Ensure that the specified values for the min and max channel size
  1110. // don't are within the bounds of the normal chan size constraints.
  1111. if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
  1112. cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
  1113. }
  1114. if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
  1115. cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
  1116. }
  1117. // Validate profile port or host:port.
  1118. if cfg.Profile != "" {
  1119. str := "%s: The profile port must be between 1024 and 65535"
  1120. // Try to parse Profile as a host:port.
  1121. _, hostPort, err := net.SplitHostPort(cfg.Profile)
  1122. if err == nil {
  1123. // Determine if the port is valid.
  1124. profilePort, err := strconv.Atoi(hostPort)
  1125. if err != nil || profilePort < 1024 || profilePort > 65535 {
  1126. return nil, &usageError{mkErr(str)}
  1127. }
  1128. } else {
  1129. // Try to parse Profile as a port.
  1130. profilePort, err := strconv.Atoi(cfg.Profile)
  1131. if err != nil || profilePort < 1024 || profilePort > 65535 {
  1132. return nil, &usageError{mkErr(str)}
  1133. }
  1134. // Since the user just set a port, we will serve debugging
  1135. // information over localhost.
  1136. cfg.Profile = net.JoinHostPort("127.0.0.1", cfg.Profile)
  1137. }
  1138. }
  1139. // We'll now construct the network directory which will be where we
  1140. // store all the data specific to this chain/network.
  1141. cfg.networkDir = filepath.Join(
  1142. cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
  1143. lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
  1144. )
  1145. // If a custom macaroon directory wasn't specified and the data
  1146. // directory has changed from the default path, then we'll also update
  1147. // the path for the macaroons to be generated.
  1148. if cfg.AdminMacPath == "" {
  1149. cfg.AdminMacPath = filepath.Join(
  1150. cfg.networkDir, defaultAdminMacFilename,
  1151. )
  1152. }
  1153. if cfg.ReadMacPath == "" {
  1154. cfg.ReadMacPath = filepath.Join(
  1155. cfg.networkDir, defaultReadMacFilename,
  1156. )
  1157. }
  1158. if cfg.InvoiceMacPath == "" {
  1159. cfg.InvoiceMacPath = filepath.Join(
  1160. cfg.networkDir, defaultInvoiceMacFilename,
  1161. )
  1162. }
  1163. towerDir := filepath.Join(
  1164. cfg.Watchtower.TowerDir, BitcoinChainName,
  1165. lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
  1166. )
  1167. // Create the lnd directory and all other sub-directories if they don't
  1168. // already exist. This makes sure that directory trees are also created
  1169. // for files that point to outside the lnddir.
  1170. dirs := []string{
  1171. lndDir, cfg.DataDir, cfg.networkDir,
  1172. cfg.LetsEncryptDir, towerDir, cfg.graphDatabaseDir(),
  1173. filepath.Dir(cfg.TLSCertPath), filepath.Dir(cfg.TLSKeyPath),
  1174. filepath.Dir(cfg.AdminMacPath), filepath.Dir(cfg.ReadMacPath),
  1175. filepath.Dir(cfg.InvoiceMacPath),
  1176. filepath.Dir(cfg.Tor.PrivateKeyPath),
  1177. filepath.Dir(cfg.Tor.WatchtowerKeyPath),
  1178. }
  1179. for _, dir := range dirs {
  1180. if err := makeDirectory(dir); err != nil {
  1181. return nil, err
  1182. }
  1183. }
  1184. // Similarly, if a custom back up file path wasn't specified, then
  1185. // we'll update the file location to match our set network directory.
  1186. if cfg.BackupFilePath == "" {
  1187. cfg.BackupFilePath = filepath.Join(
  1188. cfg.networkDir, chanbackup.DefaultBackupFileName,
  1189. )
  1190. }
  1191. // Append the network type to the log directory so it is "namespaced"
  1192. // per network in the same fashion as the data directory.
  1193. cfg.LogDir = filepath.Join(
  1194. cfg.LogDir, BitcoinChainName,
  1195. lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
  1196. )
  1197. // A log writer must be passed in, otherwise we can't function and would
  1198. // run into a panic later on.
  1199. if cfg.LogWriter == nil {
  1200. return nil, mkErr("log writer missing in config")
  1201. }
  1202. // Special show command to list supported subsystems and exit.
  1203. if cfg.DebugLevel == "show" {
  1204. fmt.Println("Supported subsystems",
  1205. cfg.LogWriter.SupportedSubsystems())
  1206. os.Exit(0)
  1207. }
  1208. // Initialize logging at the default logging level.
  1209. SetupLoggers(cfg.LogWriter, interceptor)
  1210. err = cfg.LogWriter.InitLogRotator(
  1211. filepath.Join(cfg.LogDir, defaultLogFilename),
  1212. cfg.MaxLogFileSize, cfg.MaxLogFiles,
  1213. )
  1214. if err != nil {
  1215. str := "log rotation setup failed: %v"
  1216. return nil, mkErr(str, err)
  1217. }
  1218. // Parse, validate, and set debug log level(s).
  1219. err = build.ParseAndSetDebugLevels(cfg.DebugLevel, cfg.LogWriter)
  1220. if err != nil {
  1221. str := "error parsing debug level: %v"
  1222. return nil, &usageError{mkErr(str, err)}
  1223. }
  1224. // At least one RPCListener is required. So listen on localhost per
  1225. // default.
  1226. if len(cfg.RawRPCListeners) == 0 {
  1227. addr := fmt.Sprintf("localhost:%d", defaultRPCPort)
  1228. cfg.RawRPCListeners = append(cfg.RawRPCListeners, addr)
  1229. }
  1230. // Listen on localhost if no REST listeners were specified.
  1231. if len(cfg.RawRESTListeners) == 0 {
  1232. addr := fmt.Sprintf("localhost:%d", defaultRESTPort)
  1233. cfg.RawRESTListeners = append(cfg.RawRESTListeners, addr)
  1234. }
  1235. // Listen on the default interface/port if no listeners were specified.
  1236. // An empty address string means default interface/address, which on
  1237. // most unix systems is the same as 0.0.0.0. If Tor is active, we
  1238. // default to only listening on localhost for hidden service
  1239. // connections.
  1240. if len(cfg.RawListeners) == 0 {
  1241. addr := fmt.Sprintf(":%d", defaultPeerPort)
  1242. if cfg.Tor.Active && !cfg.Tor.SkipProxyForClearNetTargets {
  1243. addr = fmt.Sprintf("localhost:%d", defaultPeerPort)
  1244. }
  1245. cfg.RawListeners = append(cfg.RawListeners, addr)
  1246. }
  1247. // Add default port to all RPC listener addresses if needed and remove
  1248. // duplicate addresses.
  1249. cfg.RPCListeners, err = lncfg.NormalizeAddresses(
  1250. cfg.RawRPCListeners, strconv.Itoa(defaultRPCPort),
  1251. cfg.net.ResolveTCPAddr,
  1252. )
  1253. if err != nil {
  1254. return nil, mkErr("error normalizing RPC listen addrs: %v", err)
  1255. }
  1256. // Add default port to all REST listener addresses if needed and remove
  1257. // duplicate addresses.
  1258. cfg.RESTListeners, err = lncfg.NormalizeAddresses(
  1259. cfg.RawRESTListeners, strconv.Itoa(defaultRESTPort),
  1260. cfg.net.ResolveTCPAddr,
  1261. )
  1262. if err != nil {
  1263. return nil, mkErr("error normalizing REST listen addrs: %v", err)
  1264. }
  1265. switch {
  1266. // The no seed backup and auto unlock are mutually exclusive.
  1267. case cfg.NoSeedBackup && cfg.WalletUnlockPasswordFile != "":
  1268. return nil, mkErr("cannot set noseedbackup and " +
  1269. "wallet-unlock-password-file at the same time")
  1270. // The "allow-create" flag cannot be set without the auto unlock file.
  1271. case cfg.WalletUnlockAllowCreate && cfg.WalletUnlockPasswordFile == "":
  1272. return nil, mkErr("cannot set wallet-unlock-allow-create " +
  1273. "without wallet-unlock-password-file")
  1274. // If a password file was specified, we need it to exist.
  1275. case cfg.WalletUnlockPasswordFile != "" &&
  1276. !lnrpc.FileExists(cfg.WalletUnlockPasswordFile):
  1277. return nil, mkErr("wallet unlock password file %s does "+
  1278. "not exist", cfg.WalletUnlockPasswordFile)
  1279. }
  1280. // For each of the RPC listeners (REST+gRPC), we'll ensure that users
  1281. // have specified a safe combo for authentication. If not, we'll bail
  1282. // out with an error. Since we don't allow disabling TLS for gRPC
  1283. // connections we pass in tlsActive=true.
  1284. err = lncfg.EnforceSafeAuthentication(
  1285. cfg.RPCListeners, !cfg.NoMacaroons, true,
  1286. )
  1287. if err != nil {
  1288. return nil, mkErr("error enforcing safe authentication on "+
  1289. "RPC ports: %v", err)
  1290. }
  1291. if cfg.DisableRest {
  1292. ltndLog.Infof("REST API is disabled!")
  1293. cfg.RESTListeners = nil
  1294. } else {
  1295. err = lncfg.EnforceSafeAuthentication(
  1296. cfg.RESTListeners, !cfg.NoMacaroons, !cfg.DisableRestTLS,
  1297. )
  1298. if err != nil {
  1299. return nil, mkErr("error enforcing safe "+
  1300. "authentication on REST ports: %v", err)
  1301. }
  1302. }
  1303. // Remove the listening addresses specified if listening is disabled.
  1304. if cfg.DisableListen {
  1305. ltndLog.Infof("Listening on the p2p interface is disabled!")
  1306. cfg.Listeners = nil
  1307. cfg.ExternalIPs = nil
  1308. } else {
  1309. // Add default port to all listener addresses if needed and remove
  1310. // duplicate addresses.
  1311. cfg.Listeners, err = lncfg.NormalizeAddresses(
  1312. cfg.RawListeners, strconv.Itoa(defaultPeerPort),
  1313. cfg.net.ResolveTCPAddr,
  1314. )
  1315. if err != nil {
  1316. return nil, mkErr("error normalizing p2p listen "+
  1317. "addrs: %v", err)
  1318. }
  1319. // Add default port to all external IP addresses if needed and remove
  1320. // duplicate addresses.
  1321. cfg.ExternalIPs, err = lncfg.NormalizeAddresses(
  1322. cfg.RawExternalIPs, strconv.Itoa(defaultPeerPort),
  1323. cfg.net.ResolveTCPAddr,
  1324. )
  1325. if err != nil {
  1326. return nil, err
  1327. }
  1328. // For the p2p port it makes no sense to listen to an Unix socket.
  1329. // Also, we would need to refactor the brontide listener to support
  1330. // that.
  1331. for _, p2pListener := range cfg.Listeners {
  1332. if lncfg.IsUnix(p2pListener) {
  1333. return nil, mkErr("unix socket addresses "+
  1334. "cannot be used for the p2p "+
  1335. "connection listener: %s", p2pListener)
  1336. }
  1337. }
  1338. }
  1339. // Ensure that the specified minimum backoff is below or equal to the
  1340. // maximum backoff.
  1341. if cfg.MinBackoff > cfg.MaxBackoff {
  1342. return nil, mkErr("maxbackoff must be greater than minbackoff")
  1343. }
  1344. // Newer versions of lnd added a new sub-config for bolt-specific
  1345. // parameters. However, we want to also allow existing users to use the
  1346. // value on the top-level config. If the outer config value is set,
  1347. // then we'll use that directly.
  1348. flagSet, err := isSet("SyncFreelist")
  1349. if err != nil {
  1350. return nil, mkErr("error parsing freelist sync flag: %v", err)
  1351. }
  1352. if flagSet {
  1353. cfg.DB.Bolt.NoFreelistSync = !cfg.SyncFreelist
  1354. }
  1355. // Parse any extra sqlite pragma options that may have been provided
  1356. // to determine if they override any of the defaults that we will
  1357. // otherwise add.
  1358. var (
  1359. defaultSynchronous = true
  1360. defaultAutoVacuum = true
  1361. defaultFullfsync = true
  1362. )
  1363. for _, option := range cfg.DB.Sqlite.PragmaOptions {
  1364. switch {
  1365. case strings.HasPrefix(option, "synchronous="):
  1366. defaultSynchronous = false
  1367. case strings.HasPrefix(option, "auto_vacuum="):
  1368. defaultAutoVacuum = false
  1369. case strings.HasPrefix(option, "fullfsync="):
  1370. defaultFullfsync = false
  1371. default:
  1372. }
  1373. }
  1374. if defaultSynchronous {
  1375. cfg.DB.Sqlite.PragmaOptions = append(
  1376. cfg.DB.Sqlite.PragmaOptions, "synchronous=full",
  1377. )
  1378. }
  1379. if defaultAutoVacuum {
  1380. cfg.DB.Sqlite.PragmaOptions = append(
  1381. cfg.DB.Sqlite.PragmaOptions, "auto_vacuum=incremental",
  1382. )
  1383. }
  1384. if defaultFullfsync {
  1385. cfg.DB.Sqlite.PragmaOptions = append(
  1386. cfg.DB.Sqlite.PragmaOptions, "fullfsync=true",
  1387. )
  1388. }
  1389. // Ensure that the user hasn't chosen a remote-max-htlc value greater
  1390. // than the protocol maximum.
  1391. maxRemoteHtlcs := uint16(input.MaxHTLCNumber / 2)
  1392. if cfg.DefaultRemoteMaxHtlcs > maxRemoteHtlcs {
  1393. return nil, mkErr("default-remote-max-htlcs (%v) must be "+
  1394. "less than %v", cfg.DefaultRemoteMaxHtlcs,
  1395. maxRemoteHtlcs)
  1396. }
  1397. // Clamp the ChannelCommitInterval so that commitment updates can still
  1398. // happen in a reasonable timeframe.
  1399. if cfg.ChannelCommitInterval > maxChannelCommitInterval {
  1400. return nil, mkErr("channel-commit-interval (%v) must be less "+
  1401. "than %v", cfg.ChannelCommitInterval,
  1402. maxChannelCommitInterval)
  1403. }
  1404. // Limit PendingCommitInterval so we don't wait too long for the remote
  1405. // party to send back a revoke.
  1406. if cfg.PendingCommitInterval > maxPendingCommitInterval {
  1407. return nil, mkErr("pending-commit-interval (%v) must be less "+
  1408. "than %v", cfg.PendingCommitInterval,
  1409. maxPendingCommitInterval)
  1410. }
  1411. if err := cfg.Gossip.Parse(); err != nil {
  1412. return nil, mkErr("error parsing gossip syncer: %v", err)
  1413. }
  1414. // Log a warning if our expiry delta is not greater than our incoming
  1415. // broadcast delta. We do not fail here because this value may be set
  1416. // to zero to intentionally keep lnd's behavior unchanged from when we
  1417. // didn't auto-cancel these invoices.
  1418. if cfg.Invoices.HoldExpiryDelta <= lncfg.DefaultIncomingBroadcastDelta {
  1419. ltndLog.Warnf("Invoice hold expiry delta: %v <= incoming "+
  1420. "delta: %v, accepted hold invoices will force close "+
  1421. "channels if they are not canceled manually",
  1422. cfg.Invoices.HoldExpiryDelta,
  1423. lncfg.DefaultIncomingBroadcastDelta)
  1424. }
  1425. // If the experimental protocol options specify any protocol messages
  1426. // that we want to handle as custom messages, set them now.
  1427. customMsg := cfg.ProtocolOptions.CustomMessageOverrides()
  1428. // We can safely set our custom override values during startup because
  1429. // startup is blocked on config parsing.
  1430. if err := lnwire.SetCustomOverrides(customMsg); err != nil {
  1431. return nil, mkErr("custom-message: %v", err)
  1432. }
  1433. // Validate the subconfigs for workers, caches, and the tower client.
  1434. err = lncfg.Validate(
  1435. cfg.Workers,
  1436. cfg.Caches,
  1437. cfg.WtClient,
  1438. cfg.DB,
  1439. cfg.Cluster,
  1440. cfg.HealthChecks,
  1441. cfg.RPCMiddleware,
  1442. cfg.RemoteSigner,
  1443. cfg.Sweeper,
  1444. cfg.Htlcswitch,
  1445. )
  1446. if err != nil {
  1447. return nil, err
  1448. }
  1449. // Finally, ensure that the user's color is correctly formatted,
  1450. // otherwise the server will not be able to start after the unlocking
  1451. // the wallet.
  1452. _, err = lncfg.ParseHexColor(cfg.Color)
  1453. if err != nil {
  1454. return nil, mkErr("unable to parse node color: %v", err)
  1455. }
  1456. // All good, return the sanitized result.
  1457. return &cfg, nil
  1458. }
  1459. // graphDatabaseDir returns the default directory where the local bolt graph db
  1460. // files are stored.
  1461. func (c *Config) graphDatabaseDir() string {
  1462. return filepath.Join(
  1463. c.DataDir, defaultGraphSubDirname,
  1464. lncfg.NormalizeNetwork(c.ActiveNetParams.Name),
  1465. )
  1466. }
  1467. // ImplementationConfig returns the configuration of what actual implementations
  1468. // should be used when creating the main lnd instance.
  1469. func (c *Config) ImplementationConfig(
  1470. interceptor signal.Interceptor) *ImplementationCfg {
  1471. // If we're using a remote signer, we still need the base wallet as a
  1472. // watch-only source of chain and address data. But we don't need any
  1473. // private key material in that btcwallet base wallet.
  1474. if c.RemoteSigner.Enable {
  1475. rpcImpl := NewRPCSignerWalletImpl(
  1476. c, ltndLog, interceptor,
  1477. c.RemoteSigner.MigrateWatchOnly,
  1478. )
  1479. return &ImplementationCfg{
  1480. GrpcRegistrar: rpcImpl,
  1481. RestRegistrar: rpcImpl,
  1482. ExternalValidator: rpcImpl,
  1483. DatabaseBuilder: NewDefaultDatabaseBuilder(
  1484. c, ltndLog,
  1485. ),
  1486. WalletConfigBuilder: rpcImpl,
  1487. ChainControlBuilder: rpcImpl,
  1488. }
  1489. }
  1490. defaultImpl := NewDefaultWalletImpl(c, ltndLog, interceptor, false)
  1491. return &ImplementationCfg{
  1492. GrpcRegistrar: defaultImpl,
  1493. RestRegistrar: defaultImpl,
  1494. ExternalValidator: defaultImpl,
  1495. DatabaseBuilder: NewDefaultDatabaseBuilder(c, ltndLog),
  1496. WalletConfigBuilder: defaultImpl,
  1497. ChainControlBuilder: defaultImpl,
  1498. }
  1499. }
  1500. // CleanAndExpandPath expands environment variables and leading ~ in the
  1501. // passed path, cleans the result, and returns it.
  1502. // This function is taken from https://github.com/btcsuite/btcd
  1503. func CleanAndExpandPath(path string) string {
  1504. if path == "" {
  1505. return ""
  1506. }
  1507. // Expand initial ~ to OS specific home directory.
  1508. if strings.HasPrefix(path, "~") {
  1509. var homeDir string
  1510. u, err := user.Current()
  1511. if err == nil {
  1512. homeDir = u.HomeDir
  1513. } else {
  1514. homeDir = os.Getenv("HOME")
  1515. }
  1516. path = strings.Replace(path, "~", homeDir, 1)
  1517. }
  1518. // NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
  1519. // but the variables can still be expanded via POSIX-style $VARIABLE.
  1520. return filepath.Clean(os.ExpandEnv(path))
  1521. }
  1522. func parseRPCParams(cConfig *lncfg.Chain, nodeConfig interface{},
  1523. netParams chainreg.BitcoinNetParams) error {
  1524. // First, we'll check our node config to make sure the RPC parameters
  1525. // were set correctly. We'll also determine the path to the conf file
  1526. // depending on the backend node.
  1527. var daemonName, confDir, confFile, confFileBase string
  1528. switch conf := nodeConfig.(type) {
  1529. case *lncfg.Btcd:
  1530. // Resolves environment variable references in RPCUser and
  1531. // RPCPass fields.
  1532. conf.RPCUser = supplyEnvValue(conf.RPCUser)
  1533. conf.RPCPass = supplyEnvValue(conf.RPCPass)
  1534. // If both RPCUser and RPCPass are set, we assume those
  1535. // credentials are good to use.
  1536. if conf.RPCUser != "" && conf.RPCPass != "" {
  1537. return nil
  1538. }
  1539. // Set the daemon name for displaying proper errors.
  1540. daemonName = btcdBackendName
  1541. confDir = conf.Dir
  1542. confFileBase = btcdBackendName
  1543. // If only ONE of RPCUser or RPCPass is set, we assume the
  1544. // user did that unintentionally.
  1545. if conf.RPCUser != "" || conf.RPCPass != "" {
  1546. return fmt.Errorf("please set both or neither of "+
  1547. "%[1]v.rpcuser, %[1]v.rpcpass", daemonName)
  1548. }
  1549. case *lncfg.Bitcoind:
  1550. // Ensure that if the ZMQ options are set, that they are not
  1551. // equal.
  1552. if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
  1553. err := checkZMQOptions(
  1554. conf.ZMQPubRawBlock, conf.ZMQPubRawTx,
  1555. )
  1556. if err != nil {
  1557. return err
  1558. }
  1559. }
  1560. // Ensure that if the estimate mode is set, that it is a legal
  1561. // value.
  1562. if conf.EstimateMode != "" {
  1563. err := checkEstimateMode(conf.EstimateMode)
  1564. if err != nil {
  1565. return err
  1566. }
  1567. }
  1568. // Set the daemon name for displaying proper errors.
  1569. daemonName = bitcoindBackendName
  1570. confDir = conf.Dir
  1571. confFile = conf.ConfigPath
  1572. confFileBase = BitcoinChainName
  1573. // Resolves environment variable references in RPCUser
  1574. // and RPCPass fields.
  1575. conf.RPCUser = supplyEnvValue(conf.RPCUser)
  1576. conf.RPCPass = supplyEnvValue(conf.RPCPass)
  1577. // Check that cookie and credentials don't contradict each
  1578. // other.
  1579. if (conf.RPCUser != "" || conf.RPCPass != "") &&
  1580. conf.RPCCookie != "" {
  1581. return fmt.Errorf("please only provide either "+
  1582. "%[1]v.rpccookie or %[1]v.rpcuser and "+
  1583. "%[1]v.rpcpass", daemonName)
  1584. }
  1585. // We convert the cookie into a user name and password.
  1586. if conf.RPCCookie != "" {
  1587. cookie, err := os.ReadFile(conf.RPCCookie)
  1588. if err != nil {
  1589. return fmt.Errorf("cannot read cookie file: %w",
  1590. err)
  1591. }
  1592. splitCookie := strings.Split(string(cookie), ":")
  1593. if len(splitCookie) != 2 {
  1594. return fmt.Errorf("cookie file has a wrong " +
  1595. "format")
  1596. }
  1597. conf.RPCUser = splitCookie[0]
  1598. conf.RPCPass = splitCookie[1]
  1599. }
  1600. if conf.RPCUser != "" && conf.RPCPass != "" {
  1601. // If all of RPCUser, RPCPass, ZMQBlockHost, and
  1602. // ZMQTxHost are set, we assume those parameters are
  1603. // good to use.
  1604. if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
  1605. return nil
  1606. }
  1607. // If RPCUser and RPCPass are set and RPCPolling is
  1608. // enabled, we assume the parameters are good to use.
  1609. if conf.RPCPolling {
  1610. return nil
  1611. }
  1612. }
  1613. // If not all of the parameters are set, we'll assume the user
  1614. // did this unintentionally.
  1615. if conf.RPCUser != "" || conf.RPCPass != "" ||
  1616. conf.ZMQPubRawBlock != "" || conf.ZMQPubRawTx != "" {
  1617. return fmt.Errorf("please set %[1]v.rpcuser and "+
  1618. "%[1]v.rpcpass (or %[1]v.rpccookie) together "+
  1619. "with %[1]v.zmqpubrawblock, %[1]v.zmqpubrawtx",
  1620. daemonName)
  1621. }
  1622. }
  1623. // If we're in simnet mode, then the running btcd instance won't read
  1624. // the RPC credentials from the configuration. So if lnd wasn't
  1625. // specified the parameters, then we won't be able to start.
  1626. if cConfig.SimNet {
  1627. return fmt.Errorf("rpcuser and rpcpass must be set to your " +
  1628. "btcd node's RPC parameters for simnet mode")
  1629. }
  1630. fmt.Println("Attempting automatic RPC configuration to " + daemonName)
  1631. if confFile == "" {
  1632. confFile = filepath.Join(confDir, fmt.Sprintf("%v.conf",
  1633. confFileBase))
  1634. }
  1635. switch cConfig.Node {
  1636. case btcdBackendName:
  1637. nConf := nodeConfig.(*lncfg.Btcd)
  1638. rpcUser, rpcPass, err := extractBtcdRPCParams(confFile)
  1639. if err != nil {
  1640. return fmt.Errorf("unable to extract RPC credentials: "+
  1641. "%v, cannot start w/o RPC connection", err)
  1642. }
  1643. nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
  1644. case bitcoindBackendName:
  1645. nConf := nodeConfig.(*lncfg.Bitcoind)
  1646. rpcUser, rpcPass, zmqBlockHost, zmqTxHost, err :=
  1647. extractBitcoindRPCParams(netParams.Params.Name,
  1648. nConf.Dir, confFile, nConf.RPCCookie)
  1649. if err != nil {
  1650. return fmt.Errorf("unable to extract RPC credentials: "+
  1651. "%v, cannot start w/o RPC connection", err)
  1652. }
  1653. nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
  1654. nConf.ZMQPubRawBlock, nConf.ZMQPubRawTx = zmqBlockHost, zmqTxHost
  1655. }
  1656. fmt.Printf("Automatically obtained %v's RPC credentials\n", daemonName)
  1657. return nil
  1658. }
  1659. // supplyEnvValue supplies the value of an environment variable from a string.
  1660. // It supports the following formats:
  1661. // 1) $ENV_VAR
  1662. // 2) ${ENV_VAR}
  1663. // 3) ${ENV_VAR:-DEFAULT}
  1664. //
  1665. // Standard environment variable naming conventions:
  1666. // - ENV_VAR contains letters, digits, and underscores, and does
  1667. // not start with a digit.
  1668. // - DEFAULT follows the rule that it can contain any characters except
  1669. // whitespace.
  1670. //
  1671. // Parameters:
  1672. // - value: The input string containing references to environment variables
  1673. // (if any).
  1674. //
  1675. // Returns:
  1676. // - string: The value of the specified environment variable, the default
  1677. // value if provided, or the original input string if no matching variable is
  1678. // found or set.
  1679. func supplyEnvValue(value string) string {
  1680. // Regex for $ENV_VAR format.
  1681. var reEnvVar = regexp.MustCompile(`^\$([a-zA-Z_][a-zA-Z0-9_]*)$`)
  1682. // Regex for ${ENV_VAR} format.
  1683. var reEnvVarWithBrackets = regexp.MustCompile(
  1684. `^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$`,
  1685. )
  1686. // Regex for ${ENV_VAR:-DEFAULT} format.
  1687. var reEnvVarWithDefault = regexp.MustCompile(
  1688. `^\$\{([a-zA-Z_][a-zA-Z0-9_]*):-([\S]+)\}$`,
  1689. )
  1690. // Match against supported formats.
  1691. switch {
  1692. case reEnvVarWithDefault.MatchString(value):
  1693. matches := reEnvVarWithDefault.FindStringSubmatch(value)
  1694. envVariable := matches[1]
  1695. defaultValue := matches[2]
  1696. if envValue := os.Getenv(envVariable); envValue != "" {
  1697. return envValue
  1698. }
  1699. return defaultValue
  1700. case reEnvVarWithBrackets.MatchString(value):
  1701. matches := reEnvVarWithBrackets.FindStringSubmatch(value)
  1702. envVariable := matches[1]
  1703. envValue := os.Getenv(envVariable)
  1704. return envValue
  1705. case reEnvVar.MatchString(value):
  1706. matches := reEnvVar.FindStringSubmatch(value)
  1707. envVariable := matches[1]
  1708. envValue := os.Getenv(envVariable)
  1709. return envValue
  1710. }
  1711. return value
  1712. }
  1713. // extractBtcdRPCParams attempts to extract the RPC credentials for an existing
  1714. // btcd instance. The passed path is expected to be the location of btcd's
  1715. // application data directory on the target system.
  1716. func extractBtcdRPCParams(btcdConfigPath string) (string, string, error) {
  1717. // First, we'll open up the btcd configuration file found at the target
  1718. // destination.
  1719. btcdConfigFile, err := os.Open(btcdConfigPath)
  1720. if err != nil {
  1721. return "", "", err
  1722. }
  1723. defer func() { _ = btcdConfigFile.Close() }()
  1724. // With the file open extract the contents of the configuration file so
  1725. // we can attempt to locate the RPC credentials.
  1726. configContents, err := io.ReadAll(btcdConfigFile)
  1727. if err != nil {
  1728. return "", "", err
  1729. }
  1730. // Attempt to locate the RPC user using a regular expression. If we
  1731. // don't have a match for our regular expression then we'll exit with
  1732. // an error.
  1733. rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
  1734. if err != nil {
  1735. return "", "", err
  1736. }
  1737. userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
  1738. if userSubmatches == nil {
  1739. return "", "", fmt.Errorf("unable to find rpcuser in config")
  1740. }
  1741. // Similarly, we'll use another regular expression to find the set
  1742. // rpcpass (if any). If we can't find the pass, then we'll exit with an
  1743. // error.
  1744. rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpass\s*=\s*([^\s]+)`)
  1745. if err != nil {
  1746. return "", "", err
  1747. }
  1748. passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
  1749. if passSubmatches == nil {
  1750. return "", "", fmt.Errorf("unable to find rpcuser in config")
  1751. }
  1752. return supplyEnvValue(string(userSubmatches[1])),
  1753. supplyEnvValue(string(passSubmatches[1])), nil
  1754. }
  1755. // extractBitcoindRPCParams attempts to extract the RPC credentials for an
  1756. // existing bitcoind node instance. The routine looks for a cookie first,
  1757. // optionally following the datadir configuration option in the bitcoin.conf. If
  1758. // it doesn't find one, it looks for rpcuser/rpcpassword.
  1759. func extractBitcoindRPCParams(networkName, bitcoindDataDir, bitcoindConfigPath,
  1760. rpcCookiePath string) (string, string, string, string, error) {
  1761. // First, we'll open up the bitcoind configuration file found at the
  1762. // target destination.
  1763. bitcoindConfigFile, err := os.Open(bitcoindConfigPath)
  1764. if err != nil {
  1765. return "", "", "", "", err
  1766. }
  1767. defer func() { _ = bitcoindConfigFile.Close() }()
  1768. // With the file open extract the contents of the configuration file so
  1769. // we can attempt to locate the RPC credentials.
  1770. configContents, err := io.ReadAll(bitcoindConfigFile)
  1771. if err != nil {
  1772. return "", "", "", "", err
  1773. }
  1774. // First, we'll look for the ZMQ hosts providing raw block and raw
  1775. // transaction notifications.
  1776. zmqBlockHostRE, err := regexp.Compile(
  1777. `(?m)^\s*zmqpubrawblock\s*=\s*([^\s]+)`,
  1778. )
  1779. if err != nil {
  1780. return "", "", "", "", err
  1781. }
  1782. zmqBlockHostSubmatches := zmqBlockHostRE.FindSubmatch(configContents)
  1783. if len(zmqBlockHostSubmatches) < 2 {
  1784. return "", "", "", "", fmt.Errorf("unable to find " +
  1785. "zmqpubrawblock in config")
  1786. }
  1787. zmqTxHostRE, err := regexp.Compile(`(?m)^\s*zmqpubrawtx\s*=\s*([^\s]+)`)
  1788. if err != nil {
  1789. return "", "", "", "", err
  1790. }
  1791. zmqTxHostSubmatches := zmqTxHostRE.FindSubmatch(configContents)
  1792. if len(zmqTxHostSubmatches) < 2 {
  1793. return "", "", "", "", errors.New("unable to find zmqpubrawtx " +
  1794. "in config")
  1795. }
  1796. zmqBlockHost := string(zmqBlockHostSubmatches[1])
  1797. zmqTxHost := string(zmqTxHostSubmatches[1])
  1798. if err := checkZMQOptions(zmqBlockHost, zmqTxHost); err != nil {
  1799. return "", "", "", "", err
  1800. }
  1801. // Next, we'll try to find an auth cookie. We need to detect the chain
  1802. // by seeing if one is specified in the configuration file.
  1803. dataDir := filepath.Dir(bitcoindConfigPath)
  1804. if bitcoindDataDir != "" {
  1805. dataDir = bitcoindDataDir
  1806. }
  1807. dataDirRE, err := regexp.Compile(`(?m)^\s*datadir\s*=\s*([^\s]+)`)
  1808. if err != nil {
  1809. return "", "", "", "", err
  1810. }
  1811. dataDirSubmatches := dataDirRE.FindSubmatch(configContents)
  1812. if dataDirSubmatches != nil {
  1813. dataDir = string(dataDirSubmatches[1])
  1814. }
  1815. var chainDir string
  1816. switch networkName {
  1817. case "mainnet":
  1818. chainDir = ""
  1819. case "regtest", "testnet3", "signet":
  1820. chainDir = networkName
  1821. default:
  1822. return "", "", "", "", fmt.Errorf("unexpected networkname %v", networkName)
  1823. }
  1824. cookiePath := filepath.Join(dataDir, chainDir, ".cookie")
  1825. if rpcCookiePath != "" {
  1826. cookiePath = rpcCookiePath
  1827. }
  1828. cookie, err := os.ReadFile(cookiePath)
  1829. if err == nil {
  1830. splitCookie := strings.Split(string(cookie), ":")
  1831. if len(splitCookie) == 2 {
  1832. return splitCookie[0], splitCookie[1], zmqBlockHost,
  1833. zmqTxHost, nil
  1834. }
  1835. }
  1836. // We didn't find a cookie, so we attempt to locate the RPC user using
  1837. // a regular expression. If we don't have a match for our regular
  1838. // expression then we'll exit with an error.
  1839. rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
  1840. if err != nil {
  1841. return "", "", "", "", err
  1842. }
  1843. userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
  1844. // Similarly, we'll use another regular expression to find the set
  1845. // rpcpass (if any). If we can't find the pass, then we'll exit with an
  1846. // error.
  1847. rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpassword\s*=\s*([^\s]+)`)
  1848. if err != nil {
  1849. return "", "", "", "", err
  1850. }
  1851. passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
  1852. // Exit with an error if the cookie file, is defined in config, and
  1853. // can not be found, with both rpcuser and rpcpassword undefined.
  1854. if rpcCookiePath != "" && userSubmatches == nil && passSubmatches == nil {
  1855. return "", "", "", "", fmt.Errorf("unable to open cookie file (%v)",
  1856. rpcCookiePath)
  1857. }
  1858. if userSubmatches == nil {
  1859. return "", "", "", "", fmt.Errorf("unable to find rpcuser in " +
  1860. "config")
  1861. }
  1862. if passSubmatches == nil {
  1863. return "", "", "", "", fmt.Errorf("unable to find rpcpassword " +
  1864. "in config")
  1865. }
  1866. return supplyEnvValue(string(userSubmatches[1])),
  1867. supplyEnvValue(string(passSubmatches[1])),
  1868. zmqBlockHost, zmqTxHost, nil
  1869. }
  1870. // checkZMQOptions ensures that the provided addresses to use as the hosts for
  1871. // ZMQ rawblock and rawtx notifications are different.
  1872. func checkZMQOptions(zmqBlockHost, zmqTxHost string) error {
  1873. if zmqBlockHost == zmqTxHost {
  1874. return errors.New("zmqpubrawblock and zmqpubrawtx must be set " +
  1875. "to different addresses")
  1876. }
  1877. return nil
  1878. }
  1879. // checkEstimateMode ensures that the provided estimate mode is legal.
  1880. func checkEstimateMode(estimateMode string) error {
  1881. for _, mode := range bitcoindEstimateModes {
  1882. if estimateMode == mode {
  1883. return nil
  1884. }
  1885. }
  1886. return fmt.Errorf("estimatemode must be one of the following: %v",
  1887. bitcoindEstimateModes[:])
  1888. }
  1889. // configToFlatMap converts the given config struct into a flat map of
  1890. // key/value pairs using the dot notation we are used to from the config file
  1891. // or command line flags. It also returns a map containing deprecated config
  1892. // options.
  1893. func configToFlatMap(cfg Config) (map[string]string,
  1894. map[string]struct{}, error) {
  1895. result := make(map[string]string)
  1896. // deprecated stores a map of deprecated options found in the config
  1897. // that are set by the users. A config option is considered as
  1898. // deprecated if it has a `hidden` flag.
  1899. deprecated := make(map[string]struct{})
  1900. // redact is the helper function that redacts sensitive values like
  1901. // passwords.
  1902. redact := func(key, value string) string {
  1903. sensitiveKeySuffixes := []string{
  1904. "pass",
  1905. "password",
  1906. "dsn",
  1907. }
  1908. for _, suffix := range sensitiveKeySuffixes {
  1909. if strings.HasSuffix(key, suffix) {
  1910. return "[redacted]"
  1911. }
  1912. }
  1913. return value
  1914. }
  1915. // printConfig is the helper function that goes into nested structs
  1916. // recursively. Because we call it recursively, we need to declare it
  1917. // before we define it.
  1918. var printConfig func(reflect.Value, string)
  1919. printConfig = func(obj reflect.Value, prefix string) {
  1920. // Turn struct pointers into the actual struct, so we can
  1921. // iterate over the fields as we would with a struct value.
  1922. if obj.Kind() == reflect.Ptr {
  1923. obj = obj.Elem()
  1924. }
  1925. // Abort on nil values.
  1926. if !obj.IsValid() {
  1927. return
  1928. }
  1929. // Loop over all fields of the struct and inspect the type.
  1930. for i := 0; i < obj.NumField(); i++ {
  1931. field := obj.Field(i)
  1932. fieldType := obj.Type().Field(i)
  1933. longName := fieldType.Tag.Get("long")
  1934. namespace := fieldType.Tag.Get("namespace")
  1935. group := fieldType.Tag.Get("group")
  1936. hidden := fieldType.Tag.Get("hidden")
  1937. switch {
  1938. // We have a long name defined, this is a config value.
  1939. case longName != "":
  1940. key := longName
  1941. if prefix != "" {
  1942. key = prefix + "." + key
  1943. }
  1944. // Add the value directly to the flattened map.
  1945. result[key] = redact(key, fmt.Sprintf(
  1946. "%v", field.Interface(),
  1947. ))
  1948. // If there's a hidden flag, it's deprecated.
  1949. if hidden == "true" && !field.IsZero() {
  1950. deprecated[key] = struct{}{}
  1951. }
  1952. // We have no long name but a namespace, this is a
  1953. // nested struct.
  1954. case longName == "" && namespace != "":
  1955. key := namespace
  1956. if prefix != "" {
  1957. key = prefix + "." + key
  1958. }
  1959. printConfig(field, key)
  1960. // Just a group means this is a dummy struct to house
  1961. // multiple config values, the group name doesn't go
  1962. // into the final field name.
  1963. case longName == "" && group != "":
  1964. printConfig(field, prefix)
  1965. // Anonymous means embedded struct. We need to recurse
  1966. // into it but without adding anything to the prefix.
  1967. case fieldType.Anonymous:
  1968. printConfig(field, prefix)
  1969. default:
  1970. continue
  1971. }
  1972. }
  1973. }
  1974. // Turn the whole config struct into a flat map.
  1975. printConfig(reflect.ValueOf(cfg), "")
  1976. return result, deprecated, nil
  1977. }
  1978. // logWarningsForDeprecation logs a warning if a deprecated config option is
  1979. // set.
  1980. func logWarningsForDeprecation(cfg Config) {
  1981. _, deprecated, err := configToFlatMap(cfg)
  1982. if err != nil {
  1983. ltndLog.Errorf("Convert configs to map: %v", err)
  1984. }
  1985. for k := range deprecated {
  1986. ltndLog.Warnf("Config '%s' is deprecated, please remove it", k)
  1987. }
  1988. }