• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 19338576814

13 Nov 2025 04:31PM UTC coverage: 65.209% (-0.01%) from 65.219%
19338576814

Pull #10367

github

web-flow
Merge ade491779 into f6005ed35
Pull Request #10367: multi: rename experimental endorsement signal to accountable

65 of 85 new or added lines in 11 files covered. (76.47%)

1775 existing lines in 24 files now uncovered.

137557 of 210947 relevant lines covered (65.21%)

20763.21 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

55.43
/config.go
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

5
package lnd
6

7
import (
8
        "encoding/hex"
9
        "errors"
10
        "fmt"
11
        "io"
12
        "net"
13
        "os"
14
        "os/user"
15
        "path/filepath"
16
        "reflect"
17
        "regexp"
18
        "strconv"
19
        "strings"
20
        "time"
21

22
        "github.com/btcsuite/btcd/btcutil"
23
        "github.com/btcsuite/btcd/chaincfg"
24
        flags "github.com/jessevdk/go-flags"
25
        "github.com/lightninglabs/neutrino"
26
        "github.com/lightningnetwork/lnd/autopilot"
27
        "github.com/lightningnetwork/lnd/build"
28
        "github.com/lightningnetwork/lnd/chainreg"
29
        "github.com/lightningnetwork/lnd/chanbackup"
30
        "github.com/lightningnetwork/lnd/channeldb"
31
        "github.com/lightningnetwork/lnd/discovery"
32
        "github.com/lightningnetwork/lnd/funding"
33
        "github.com/lightningnetwork/lnd/htlcswitch"
34
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
35
        "github.com/lightningnetwork/lnd/input"
36
        "github.com/lightningnetwork/lnd/lncfg"
37
        "github.com/lightningnetwork/lnd/lnrpc"
38
        "github.com/lightningnetwork/lnd/lnrpc/peersrpc"
39
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
40
        "github.com/lightningnetwork/lnd/lnrpc/signrpc"
41
        "github.com/lightningnetwork/lnd/lnutils"
42
        "github.com/lightningnetwork/lnd/lnwallet"
43
        "github.com/lightningnetwork/lnd/lnwire"
44
        "github.com/lightningnetwork/lnd/routing"
45
        "github.com/lightningnetwork/lnd/signal"
46
        "github.com/lightningnetwork/lnd/tor"
47
)
48

49
const (
50
        defaultDataDirname        = "data"
51
        defaultChainSubDirname    = "chain"
52
        defaultGraphSubDirname    = "graph"
53
        defaultTowerSubDirname    = "watchtower"
54
        defaultTLSCertFilename    = "tls.cert"
55
        defaultTLSKeyFilename     = "tls.key"
56
        defaultAdminMacFilename   = "admin.macaroon"
57
        defaultReadMacFilename    = "readonly.macaroon"
58
        defaultInvoiceMacFilename = "invoice.macaroon"
59
        defaultLogLevel           = "info"
60
        defaultLogDirname         = "logs"
61
        defaultLogFilename        = "lnd.log"
62
        defaultRPCPort            = 10009
63
        defaultRESTPort           = 8080
64
        defaultPeerPort           = 9735
65
        defaultRPCHost            = "localhost"
66

67
        defaultNoSeedBackup                  = false
68
        defaultPaymentsExpirationGracePeriod = time.Duration(0)
69
        defaultTrickleDelay                  = 90 * 1000
70
        defaultChanStatusSampleInterval      = time.Minute
71
        defaultChanEnableTimeout             = 19 * time.Minute
72
        defaultChanDisableTimeout            = 20 * time.Minute
73
        defaultHeightHintCacheQueryDisable   = false
74
        defaultMinBackoff                    = time.Second
75
        defaultMaxBackoff                    = time.Hour
76
        defaultLetsEncryptDirname            = "letsencrypt"
77
        defaultLetsEncryptListen             = ":80"
78

79
        defaultTorSOCKSPort            = 9050
80
        defaultTorDNSHost              = "soa.nodes.lightning.directory"
81
        defaultTorDNSPort              = 53
82
        defaultTorControlPort          = 9051
83
        defaultTorV2PrivateKeyFilename = "v2_onion_private_key"
84
        defaultTorV3PrivateKeyFilename = "v3_onion_private_key"
85

86
        // defaultZMQReadDeadline is the default read deadline to be used for
87
        // both the block and tx ZMQ subscriptions.
88
        defaultZMQReadDeadline = 5 * time.Second
89

90
        // DefaultAutogenValidity is the default validity of a self-signed
91
        // certificate. The value corresponds to 14 months
92
        // (14 months * 30 days * 24 hours).
93
        defaultTLSCertDuration = 14 * 30 * 24 * time.Hour
94

95
        // minTimeLockDelta is the minimum timelock we require for incoming
96
        // HTLCs on our channels.
97
        minTimeLockDelta = routing.MinCLTVDelta
98

99
        // MaxTimeLockDelta is the maximum CLTV delta that can be applied to
100
        // forwarded HTLCs.
101
        MaxTimeLockDelta = routing.MaxCLTVDelta
102

103
        // defaultAcceptorTimeout is the time after which an RPCAcceptor will time
104
        // out and return false if it hasn't yet received a response.
105
        defaultAcceptorTimeout = 15 * time.Second
106

107
        defaultAlias = ""
108
        defaultColor = "#3399FF"
109

110
        // defaultCoopCloseTargetConfs is the default confirmation target
111
        // that will be used to estimate a fee rate to use during a
112
        // cooperative channel closure initiated by a remote peer. By default
113
        // we'll set this to a lax value since we weren't the ones that
114
        // initiated the channel closure.
115
        defaultCoopCloseTargetConfs = 6
116

117
        // defaultBlockCacheSize is the size (in bytes) of blocks that will be
118
        // keep in memory if no size is specified.
119
        defaultBlockCacheSize uint64 = 20 * 1024 * 1024 // 20 MB
120

121
        // defaultHostSampleInterval is the default amount of time that the
122
        // HostAnnouncer will wait between DNS resolutions to check if the
123
        // backing IP of a host has changed.
124
        defaultHostSampleInterval = time.Minute * 5
125

126
        defaultChainInterval = time.Minute
127
        defaultChainTimeout  = time.Second * 30
128
        defaultChainBackoff  = time.Minute * 2
129
        defaultChainAttempts = 3
130

131
        // Set defaults for a health check which ensures that we have space
132
        // available on disk. Although this check is off by default so that we
133
        // avoid breaking any existing setups (particularly on mobile), we still
134
        // set the other default values so that the health check can be easily
135
        // enabled with sane defaults.
136
        defaultRequiredDisk = 0.1
137
        defaultDiskInterval = time.Hour * 12
138
        defaultDiskTimeout  = time.Second * 5
139
        defaultDiskBackoff  = time.Minute
140
        defaultDiskAttempts = 0
141

142
        // Set defaults for a health check which ensures that the TLS certificate
143
        // is not expired. Although this check is off by default (not all setups
144
        // require it), we still set the other default values so that the health
145
        // check can be easily enabled with sane defaults.
146
        defaultTLSInterval = time.Minute
147
        defaultTLSTimeout  = time.Second * 5
148
        defaultTLSBackoff  = time.Minute
149
        defaultTLSAttempts = 0
150

151
        // Set defaults for a health check which ensures that the tor
152
        // connection is alive. Although this check is off by default (not all
153
        // setups require it), we still set the other default values so that
154
        // the health check can be easily enabled with sane defaults.
155
        defaultTCInterval = time.Minute
156
        defaultTCTimeout  = time.Second * 5
157
        defaultTCBackoff  = time.Minute
158
        defaultTCAttempts = 0
159

160
        // Set defaults for a health check which ensures that the remote signer
161
        // RPC connection is alive. Although this check is off by default (only
162
        // active when remote signing is turned on), we still set the other
163
        // default values so that the health check can be easily enabled with
164
        // sane defaults.
165
        defaultRSInterval = time.Minute
166
        defaultRSTimeout  = time.Second * 1
167
        defaultRSBackoff  = time.Second * 30
168
        defaultRSAttempts = 1
169

170
        // Set defaults for a health check which ensures that the leader
171
        // election is functioning correctly. Although this check is off by
172
        // default (as etcd leader election is only used in a clustered setup),
173
        // we still set the default values so that the health check can be
174
        // easily enabled with sane defaults. Note that by default we only run
175
        // this check once, as it is critical for the node's operation.
176
        defaultLeaderCheckInterval = time.Minute
177
        defaultLeaderCheckTimeout  = time.Second * 5
178
        defaultLeaderCheckBackoff  = time.Second * 5
179
        defaultLeaderCheckAttempts = 1
180

181
        // defaultRemoteMaxHtlcs specifies the default limit for maximum
182
        // concurrent HTLCs the remote party may add to commitment transactions.
183
        // This value can be overridden with --default-remote-max-htlcs.
184
        defaultRemoteMaxHtlcs = 483
185

186
        // defaultMaxLocalCSVDelay is the maximum delay we accept on our
187
        // commitment output. The local csv delay maximum is now equal to
188
        // the remote csv delay maximum we require for the remote commitment
189
        // transaction.
190
        defaultMaxLocalCSVDelay = 2016
191

192
        // defaultChannelCommitInterval is the default maximum time between
193
        // receiving a channel state update and signing a new commitment.
194
        defaultChannelCommitInterval = 50 * time.Millisecond
195

196
        // maxChannelCommitInterval is the maximum time the commit interval can
197
        // be configured to.
198
        maxChannelCommitInterval = time.Hour
199

200
        // defaultPendingCommitInterval specifies the default timeout value
201
        // while waiting for the remote party to revoke a locally initiated
202
        // commitment state.
203
        defaultPendingCommitInterval = 1 * time.Minute
204

205
        // maxPendingCommitInterval specifies the max allowed duration when
206
        // waiting for the remote party to revoke a locally initiated
207
        // commitment state.
208
        maxPendingCommitInterval = 5 * time.Minute
209

210
        // defaultChannelCommitBatchSize is the default maximum number of
211
        // channel state updates that is accumulated before signing a new
212
        // commitment.
213
        defaultChannelCommitBatchSize = 10
214

215
        // defaultCoinSelectionStrategy is the coin selection strategy that is
216
        // used by default to fund transactions.
217
        defaultCoinSelectionStrategy = "largest"
218

219
        // defaultKeepFailedPaymentAttempts is the default setting for whether
220
        // to keep failed payments in the database.
221
        defaultKeepFailedPaymentAttempts = false
222

223
        // defaultGrpcServerPingTime is the default duration for the amount of
224
        // time of no activity after which the server pings the client to see if
225
        // the transport is still alive. If set below 1s, a minimum value of 1s
226
        // will be used instead.
227
        defaultGrpcServerPingTime = time.Minute
228

229
        // defaultGrpcServerPingTimeout is the default duration the server waits
230
        // after having pinged for keepalive check, and if no activity is seen
231
        // even after that the connection is closed.
232
        defaultGrpcServerPingTimeout = 20 * time.Second
233

234
        // defaultGrpcClientPingMinWait is the default minimum amount of time a
235
        // client should wait before sending a keepalive ping.
236
        defaultGrpcClientPingMinWait = 5 * time.Second
237

238
        // defaultHTTPHeaderTimeout is the default timeout for HTTP requests.
239
        DefaultHTTPHeaderTimeout = 5 * time.Second
240

241
        // DefaultNumRestrictedSlots is the default max number of incoming
242
        // connections allowed in the server. Outbound connections are not
243
        // restricted.
244
        DefaultNumRestrictedSlots = 100
245

246
        // BitcoinChainName is a string that represents the Bitcoin blockchain.
247
        BitcoinChainName = "bitcoin"
248

249
        bitcoindBackendName = "bitcoind"
250
        btcdBackendName     = "btcd"
251
        neutrinoBackendName = "neutrino"
252

253
        defaultPrunedNodeMaxPeers = 4
254
        defaultNeutrinoMaxPeers   = 8
255

256
        // defaultNoDisconnectOnPongFailure is the default value for whether we
257
        // should *not* disconnect from a peer if we don't receive a pong
258
        // response in time after we send a ping.
259
        defaultNoDisconnectOnPongFailure = false
260
)
261

262
var (
263
        // DefaultLndDir is the default directory where lnd tries to find its
264
        // configuration file and store its data. This is a directory in the
265
        // user's application data, for example:
266
        //   C:\Users\<username>\AppData\Local\Lnd on Windows
267
        //   ~/.lnd on Linux
268
        //   ~/Library/Application Support/Lnd on MacOS
269
        DefaultLndDir = btcutil.AppDataDir("lnd", false)
270

271
        // DefaultConfigFile is the default full path of lnd's configuration
272
        // file.
273
        DefaultConfigFile = filepath.Join(DefaultLndDir, lncfg.DefaultConfigFilename)
274

275
        defaultDataDir = filepath.Join(DefaultLndDir, defaultDataDirname)
276
        defaultLogDir  = filepath.Join(DefaultLndDir, defaultLogDirname)
277

278
        defaultTowerDir = filepath.Join(defaultDataDir, defaultTowerSubDirname)
279

280
        defaultTLSCertPath    = filepath.Join(DefaultLndDir, defaultTLSCertFilename)
281
        defaultTLSKeyPath     = filepath.Join(DefaultLndDir, defaultTLSKeyFilename)
282
        defaultLetsEncryptDir = filepath.Join(DefaultLndDir, defaultLetsEncryptDirname)
283

284
        defaultBtcdDir         = btcutil.AppDataDir(btcdBackendName, false)
285
        defaultBtcdRPCCertFile = filepath.Join(defaultBtcdDir, "rpc.cert")
286

287
        defaultBitcoindDir = btcutil.AppDataDir(BitcoinChainName, false)
288

289
        defaultTorSOCKS   = net.JoinHostPort("localhost", strconv.Itoa(defaultTorSOCKSPort))
290
        defaultTorDNS     = net.JoinHostPort(defaultTorDNSHost, strconv.Itoa(defaultTorDNSPort))
291
        defaultTorControl = net.JoinHostPort("localhost", strconv.Itoa(defaultTorControlPort))
292

293
        // bitcoindEsimateModes defines all the legal values for bitcoind's
294
        // estimatesmartfee RPC call.
295
        defaultBitcoindEstimateMode = "CONSERVATIVE"
296
        bitcoindEstimateModes       = [2]string{"ECONOMICAL", defaultBitcoindEstimateMode}
297
)
298

299
// Config defines the configuration options for lnd.
300
//
301
// See LoadConfig for further details regarding the configuration
302
// loading+parsing process.
303
//
304
//nolint:ll
305
type Config struct {
306
        ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
307

308
        LndDir       string `long:"lnddir" description:"The base directory that contains lnd's data, logs, configuration file, etc. This option overwrites all other directory options."`
309
        ConfigFile   string `short:"C" long:"configfile" description:"Path to configuration file"`
310
        DataDir      string `short:"b" long:"datadir" description:"The directory to store lnd's data within"`
311
        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."`
312

313
        TLSCertPath        string        `long:"tlscertpath" description:"Path to write the TLS certificate for lnd's RPC and REST services"`
314
        TLSKeyPath         string        `long:"tlskeypath" description:"Path to write the TLS private key for lnd's RPC and REST services"`
315
        TLSExtraIPs        []string      `long:"tlsextraip" description:"Adds an extra ip to the generated certificate"`
316
        TLSExtraDomains    []string      `long:"tlsextradomain" description:"Adds an extra domain to the generated certificate"`
317
        TLSAutoRefresh     bool          `long:"tlsautorefresh" description:"Re-generate TLS certificate and key if the IPs or domains are changed"`
318
        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"`
319
        TLSCertDuration    time.Duration `long:"tlscertduration" description:"The duration for which the auto-generated TLS certificate will be valid for"`
320
        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"`
321

322
        NoMacaroons     bool          `long:"no-macaroons" description:"Disable macaroon authentication, can only be used if server is not listening on a public interface."`
323
        AdminMacPath    string        `long:"adminmacaroonpath" description:"Path to write the admin macaroon for lnd's RPC and REST services if it doesn't exist"`
324
        ReadMacPath     string        `long:"readonlymacaroonpath" description:"Path to write the read-only macaroon for lnd's RPC and REST services if it doesn't exist"`
325
        InvoiceMacPath  string        `long:"invoicemacaroonpath" description:"Path to the invoice-only macaroon for lnd's RPC and REST services if it doesn't exist"`
326
        LogDir          string        `long:"logdir" description:"Directory to log output."`
327
        MaxLogFiles     int           `long:"maxlogfiles" description:"Maximum logfiles to keep (0 for no rotation). DEPRECATED: use --logging.file.max-files instead" hidden:"true"`
328
        MaxLogFileSize  int           `long:"maxlogfilesize" description:"Maximum logfile size in MB. DEPRECATED: use --logging.file.max-file-size instead" hidden:"true"`
329
        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"`
330

331
        LetsEncryptDir    string `long:"letsencryptdir" description:"The directory to store Let's Encrypt certificates within"`
332
        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."`
333
        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."`
334

335
        // We'll parse these 'raw' string arguments into real net.Addrs in the
336
        // loadConfig function. We need to expose the 'raw' strings so the
337
        // command line library can access them.
338
        // Only the parsed net.Addrs should be used!
339
        RawRPCListeners   []string `long:"rpclisten" description:"Add an interface/port/socket to listen for RPC connections"`
340
        RawRESTListeners  []string `long:"restlisten" description:"Add an interface/port/socket to listen for REST connections"`
341
        RawListeners      []string `long:"listen" description:"Add an interface/port to listen for peer connections"`
342
        RawExternalIPs    []string `long:"externalip" description:"Add an ip:port (local addresses we listen on) to advertise to the network (default port 9735 is used if port is not specified). Note: Removing this option does not clear previously advertised addresses; remove them with 'lncli peers updatenodeannouncement --address_remove=host:port'."`
343
        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."`
344
        RPCListeners      []net.Addr
345
        RESTListeners     []net.Addr
346
        RestCORS          []string `long:"restcors" description:"Add an ip:port/hostname to allow cross origin access from. To allow all origins, set as \"*\"."`
347
        Listeners         []net.Addr
348
        ExternalIPs       []net.Addr
349
        DisableListen     bool          `long:"nolisten" description:"Disable listening for incoming peer connections"`
350
        DisableRest       bool          `long:"norest" description:"Disable REST API"`
351
        DisableRestTLS    bool          `long:"no-rest-tls" description:"Disable TLS for REST connections"`
352
        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"`
353
        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"`
354
        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"`
355
        AddPeers          []string      `long:"addpeer" description:"Specify peers to connect to first"`
356
        MinBackoff        time.Duration `long:"minbackoff" description:"Shortest backoff when reconnecting to persistent peers. Valid time units are {s, m, h}."`
357
        MaxBackoff        time.Duration `long:"maxbackoff" description:"Longest backoff when reconnecting to persistent peers. Valid time units are {s, m, h}."`
358
        ConnectionTimeout time.Duration `long:"connectiontimeout" description:"The timeout value for network connections. Valid time units are {ms, s, m, h}."`
359

360
        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"`
361

362
        CPUProfile      string `long:"cpuprofile" description:"DEPRECATED: Use 'pprof.cpuprofile' option. Write CPU profile to the specified file" hidden:"true"`
363
        Profile         string `long:"profile" description:"DEPRECATED: Use 'pprof.profile' option. Enable HTTP profiling on either a port or host:port" hidden:"true"`
364
        BlockingProfile int    `long:"blockingprofile" description:"DEPRECATED: Use 'pprof.blockingprofile' option. 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." hidden:"true"`
365
        MutexProfile    int    `long:"mutexprofile" description:"DEPRECATED: Use 'pprof.mutexprofile' option. 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." hidden:"true"`
366

367
        Pprof *lncfg.Pprof `group:"Pprof" namespace:"pprof"`
368

369
        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"`
370
        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."`
371
        MaxPendingChannels int    `long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer."`
372
        BackupFilePath     string `long:"backupfilepath" description:"The target location of the channel backup file"`
373

374
        NoBackupArchive bool `long:"no-backup-archive" description:"If set to true, channel backups will be deleted or replaced rather than being archived to a separate location."`
375

376
        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"`
377

378
        Bitcoin      *lncfg.Chain    `group:"Bitcoin" namespace:"bitcoin"`
379
        BtcdMode     *lncfg.Btcd     `group:"btcd" namespace:"btcd"`
380
        BitcoindMode *lncfg.Bitcoind `group:"bitcoind" namespace:"bitcoind"`
381
        NeutrinoMode *lncfg.Neutrino `group:"neutrino" namespace:"neutrino"`
382

383
        BlockCacheSize uint64 `long:"blockcachesize" description:"The maximum capacity of the block cache"`
384

385
        Autopilot *lncfg.AutoPilot `group:"Autopilot" namespace:"autopilot"`
386

387
        Tor *lncfg.Tor `group:"Tor" namespace:"tor"`
388

389
        SubRPCServers *subRPCServerConfigs `group:"subrpc"`
390

391
        Hodl *hodl.Config `group:"hodl" namespace:"hodl"`
392

393
        NoNetBootstrap bool `long:"nobootstrap" description:"If true, then automatic network bootstrapping will not be attempted."`
394

395
        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."`
396
        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."`
397
        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."`
398

399
        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."`
400

401
        CoinSelectionStrategy string `long:"coin-selection-strategy" description:"The strategy to use for selecting coins for wallet transactions." choice:"largest" choice:"random"`
402

403
        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."`
404
        TrickleDelay                  int           `long:"trickledelay" description:"Time in milliseconds between each release of announcements to the network"`
405
        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."`
406
        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."`
407
        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."`
408
        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."`
409
        Alias                         string        `long:"alias" description:"The node alias. Used as a moniker by peers and intelligence services"`
410
        Color                         string        `long:"color" description:"The color of the node in hex format (i.e. '#3399FF'). Used to customize node appearance in intelligence services"`
411
        MinChanSize                   int64         `long:"minchansize" description:"The smallest channel size (in satoshis) that we should accept. Incoming channels smaller than this will be rejected"`
412
        MaxChanSize                   int64         `long:"maxchansize" description:"The largest channel size (in satoshis) that we should accept. Incoming channels larger than this will be rejected"`
413
        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."`
414

415
        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."`
416

417
        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."`
418

419
        ChannelCommitBatchSize uint32 `long:"channel-commit-batch-size" description:"The maximum number of channel state updates that is accumulated before signing a new commitment."`
420

421
        KeepFailedPaymentAttempts bool `long:"keep-failed-payment-attempts" description:"Keeps persistent record of all failed payment attempts for successfully settled payments."`
422

423
        StoreFinalHtlcResolutions bool `long:"store-final-htlc-resolutions" description:"Persistently store the final resolution of incoming htlcs."`
424

425
        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."`
426

427
        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."`
428
        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."`
429

430
        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."`
431

432
        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."`
433

434
        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."`
435

436
        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."`
437

438
        // RequireInterceptor determines whether the HTLC interceptor is
439
        // registered regardless of whether the RPC is called or not.
440
        RequireInterceptor bool `long:"requireinterceptor" description:"Whether to always intercept HTLCs, even if no stream is attached"`
441

442
        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"`
443

444
        MaxOutgoingCltvExpiry uint32 `long:"max-cltv-expiry" description:"The maximum number of blocks funds could be locked up for when forwarding payments."`
445

446
        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]."`
447

448
        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"`
449

450
        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."`
451

452
        net tor.Net
453

454
        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."`
455

456
        AcceptKeySend bool `long:"accept-keysend" description:"If true, spontaneous payments through keysend will be accepted. [experimental]"`
457

458
        AcceptAMP bool `long:"accept-amp" description:"If true, spontaneous payments via AMP will be accepted."`
459

460
        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]"`
461

462
        GcCanceledInvoicesOnStartup bool `long:"gc-canceled-invoices-on-startup" description:"If true, we'll attempt to garbage collect canceled invoices upon start."`
463

464
        GcCanceledInvoicesOnTheFly bool `long:"gc-canceled-invoices-on-the-fly" description:"If true, we'll delete newly canceled invoices on the fly."`
465

466
        DustThreshold uint64 `long:"dust-threshold" description:"DEPRECATED: Sets the max fee exposure in satoshis for a channel after which HTLC's will be failed." hidden:"true"`
467

468
        MaxFeeExposure uint64 `long:"channel-max-fee-exposure" description:" Limits the maximum fee exposure in satoshis of a channel. This value is enforced for all channels and is independent of the channel initiator."`
469

470
        Fee *lncfg.Fee `group:"fee" namespace:"fee"`
471

472
        Invoices *lncfg.Invoices `group:"invoices" namespace:"invoices"`
473

474
        Routing *lncfg.Routing `group:"routing" namespace:"routing"`
475

476
        Gossip *lncfg.Gossip `group:"gossip" namespace:"gossip"`
477

478
        Workers *lncfg.Workers `group:"workers" namespace:"workers"`
479

480
        Caches *lncfg.Caches `group:"caches" namespace:"caches"`
481

482
        Prometheus lncfg.Prometheus `group:"prometheus" namespace:"prometheus"`
483

484
        WtClient *lncfg.WtClient `group:"wtclient" namespace:"wtclient"`
485

486
        Watchtower *lncfg.Watchtower `group:"watchtower" namespace:"watchtower"`
487

488
        ProtocolOptions *lncfg.ProtocolOptions `group:"protocol" namespace:"protocol"`
489

490
        AllowCircularRoute bool `long:"allow-circular-route" description:"If true, our node will allow htlc forwards that arrive and depart on the same channel."`
491

492
        HealthChecks *lncfg.HealthCheckConfig `group:"healthcheck" namespace:"healthcheck"`
493

494
        DB *lncfg.DB `group:"db" namespace:"db"`
495

496
        Cluster *lncfg.Cluster `group:"cluster" namespace:"cluster"`
497

498
        RPCMiddleware *lncfg.RPCMiddleware `group:"rpcmiddleware" namespace:"rpcmiddleware"`
499

500
        RemoteSigner *lncfg.RemoteSigner `group:"remotesigner" namespace:"remotesigner"`
501

502
        Sweeper *lncfg.Sweeper `group:"sweeper" namespace:"sweeper"`
503

504
        Htlcswitch *lncfg.Htlcswitch `group:"htlcswitch" namespace:"htlcswitch"`
505

506
        GRPC *GRPCConfig `group:"grpc" namespace:"grpc"`
507

508
        // SubLogMgr is the root logger that all the daemon's subloggers are
509
        // hooked up to.
510
        SubLogMgr  *build.SubLoggerManager
511
        LogRotator *build.RotatingLogWriter
512
        LogConfig  *build.LogConfig `group:"logging" namespace:"logging"`
513

514
        // networkDir is the path to the directory of the currently active
515
        // network. This path will hold the files related to each different
516
        // network.
517
        networkDir string
518

519
        // ActiveNetParams contains parameters of the target chain.
520
        ActiveNetParams chainreg.BitcoinNetParams
521

522
        // Estimator is used to estimate routing probabilities.
523
        Estimator routing.Estimator
524

525
        // Dev specifies configs used for integration tests, which is always
526
        // empty if not built with `integration` flag.
527
        Dev *lncfg.DevConfig `group:"dev" namespace:"dev"`
528

529
        // HTTPHeaderTimeout is the maximum duration that the server will wait
530
        // before timing out reading the headers of an HTTP request.
531
        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."`
532

533
        // NumRestrictedSlots is the max number of incoming connections allowed
534
        // in the server. Outbound connections are not restricted.
535
        NumRestrictedSlots uint64 `long:"num-restricted-slots" description:"The max number of incoming connections allowed in the server. Outbound connections are not restricted."`
536

537
        // NoDisconnectOnPongFailure controls if we'll disconnect if a peer
538
        // doesn't respond to a pong in time.
539
        NoDisconnectOnPongFailure bool `long:"no-disconnect-on-pong-failure" description:"If true, a peer will *not* be disconnected if a pong is not received in time or is mismatched. Defaults to false, meaning peers *will* be disconnected on pong failure."`
540
}
541

542
// GRPCConfig holds the configuration options for the gRPC server.
543
// See https://github.com/grpc/grpc-go/blob/v1.41.0/keepalive/keepalive.go#L50
544
// for more details. Any value of 0 means we use the gRPC internal default
545
// values.
546
//
547
//nolint:ll
548
type GRPCConfig struct {
549
        // ServerPingTime is a duration for the amount of time of no activity
550
        // after which the server pings the client to see if the transport is
551
        // still alive. If set below 1s, a minimum value of 1s will be used
552
        // instead.
553
        ServerPingTime time.Duration `long:"server-ping-time" description:"How long the server waits on a gRPC stream with no activity before pinging the client."`
554

555
        // ServerPingTimeout is the duration the server waits after having
556
        // pinged for keepalive check, and if no activity is seen even after
557
        // that the connection is closed.
558
        ServerPingTimeout time.Duration `long:"server-ping-timeout" description:"How long the server waits for the response from the client for the keepalive ping response."`
559

560
        // ClientPingMinWait is the minimum amount of time a client should wait
561
        // before sending a keepalive ping.
562
        ClientPingMinWait time.Duration `long:"client-ping-min-wait" description:"The minimum amount of time the client should wait before sending a keepalive ping."`
563

564
        // ClientAllowPingWithoutStream specifies whether pings from the client
565
        // are allowed even if there are no active gRPC streams. This might be
566
        // useful to keep the underlying HTTP/2 connection open for future
567
        // requests.
568
        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."`
569
}
570

571
// DefaultConfig returns all default values for the Config struct.
572
//
573
//nolint:ll
574
func DefaultConfig() Config {
575
        return Config{
576
                LndDir:            DefaultLndDir,
577
                ConfigFile:        DefaultConfigFile,
578
                DataDir:           defaultDataDir,
579
                DebugLevel:        defaultLogLevel,
580
                TLSCertPath:       defaultTLSCertPath,
581
                TLSKeyPath:        defaultTLSKeyPath,
582
                TLSCertDuration:   defaultTLSCertDuration,
583
                LetsEncryptDir:    defaultLetsEncryptDir,
4✔
584
                LetsEncryptListen: defaultLetsEncryptListen,
4✔
585
                LogDir:            defaultLogDir,
4✔
586
                AcceptorTimeout:   defaultAcceptorTimeout,
4✔
587
                WSPingInterval:    lnrpc.DefaultPingInterval,
4✔
588
                WSPongWait:        lnrpc.DefaultPongWait,
4✔
589
                Bitcoin: &lncfg.Chain{
4✔
590
                        MinHTLCIn:     chainreg.DefaultBitcoinMinHTLCInMSat,
4✔
591
                        MinHTLCOut:    chainreg.DefaultBitcoinMinHTLCOutMSat,
4✔
592
                        BaseFee:       chainreg.DefaultBitcoinBaseFeeMSat,
4✔
593
                        FeeRate:       chainreg.DefaultBitcoinFeeRate,
4✔
594
                        TimeLockDelta: chainreg.DefaultBitcoinTimeLockDelta,
4✔
595
                        MaxLocalDelay: defaultMaxLocalCSVDelay,
4✔
596
                        Node:          btcdBackendName,
4✔
597
                },
4✔
598
                BtcdMode: &lncfg.Btcd{
4✔
599
                        Dir:     defaultBtcdDir,
4✔
600
                        RPCHost: defaultRPCHost,
4✔
601
                        RPCCert: defaultBtcdRPCCertFile,
4✔
602
                },
4✔
603
                BitcoindMode: &lncfg.Bitcoind{
4✔
604
                        Dir:                defaultBitcoindDir,
4✔
605
                        RPCHost:            defaultRPCHost,
4✔
606
                        EstimateMode:       defaultBitcoindEstimateMode,
4✔
607
                        PrunedNodeMaxPeers: defaultPrunedNodeMaxPeers,
4✔
608
                        ZMQReadDeadline:    defaultZMQReadDeadline,
4✔
609
                },
4✔
610
                NeutrinoMode: &lncfg.Neutrino{
4✔
611
                        UserAgentName:    neutrino.UserAgentName,
4✔
612
                        UserAgentVersion: neutrino.UserAgentVersion,
4✔
613
                        MaxPeers:         defaultNeutrinoMaxPeers,
4✔
614
                },
4✔
615
                BlockCacheSize:     defaultBlockCacheSize,
4✔
616
                MaxPendingChannels: lncfg.DefaultMaxPendingChannels,
4✔
617
                NoSeedBackup:       defaultNoSeedBackup,
4✔
618
                MinBackoff:         defaultMinBackoff,
4✔
619
                MaxBackoff:         defaultMaxBackoff,
4✔
620
                ConnectionTimeout:  tor.DefaultConnTimeout,
4✔
621

4✔
622
                Fee: &lncfg.Fee{
4✔
623
                        MinUpdateTimeout: lncfg.DefaultMinUpdateTimeout,
4✔
624
                        MaxUpdateTimeout: lncfg.DefaultMaxUpdateTimeout,
4✔
625
                },
4✔
626

4✔
627
                SubRPCServers: &subRPCServerConfigs{
4✔
628
                        SignRPC:   &signrpc.Config{},
4✔
629
                        RouterRPC: routerrpc.DefaultConfig(),
4✔
630
                        PeersRPC:  &peersrpc.Config{},
4✔
631
                },
4✔
632
                Autopilot: &lncfg.AutoPilot{
4✔
633
                        MaxChannels:    5,
4✔
634
                        Allocation:     0.6,
4✔
635
                        MinChannelSize: int64(funding.MinChanFundingSize),
4✔
636
                        MaxChannelSize: int64(MaxFundingAmount),
4✔
637
                        MinConfs:       1,
4✔
638
                        ConfTarget:     autopilot.DefaultConfTarget,
4✔
639
                        Heuristic: map[string]float64{
4✔
640
                                "top_centrality": 1.0,
4✔
641
                        },
4✔
642
                },
4✔
643
                PaymentsExpirationGracePeriod: defaultPaymentsExpirationGracePeriod,
4✔
644
                TrickleDelay:                  defaultTrickleDelay,
4✔
645
                ChanStatusSampleInterval:      defaultChanStatusSampleInterval,
4✔
646
                ChanEnableTimeout:             defaultChanEnableTimeout,
4✔
647
                ChanDisableTimeout:            defaultChanDisableTimeout,
4✔
648
                HeightHintCacheQueryDisable:   defaultHeightHintCacheQueryDisable,
4✔
649
                Alias:                         defaultAlias,
4✔
650
                Color:                         defaultColor,
4✔
651
                MinChanSize:                   int64(funding.MinChanFundingSize),
4✔
652
                MaxChanSize:                   int64(0),
4✔
653
                CoopCloseTargetConfs:          defaultCoopCloseTargetConfs,
4✔
654
                DefaultRemoteMaxHtlcs:         defaultRemoteMaxHtlcs,
4✔
655
                NumGraphSyncPeers:             defaultMinPeers,
4✔
656
                HistoricalSyncInterval:        discovery.DefaultHistoricalSyncInterval,
4✔
657
                Tor: &lncfg.Tor{
4✔
658
                        SOCKS:   defaultTorSOCKS,
4✔
659
                        DNS:     defaultTorDNS,
4✔
660
                        Control: defaultTorControl,
4✔
661
                },
4✔
662
                net: &tor.ClearNet{},
4✔
663
                Workers: &lncfg.Workers{
4✔
664
                        Read:  lncfg.DefaultReadWorkers,
4✔
665
                        Write: lncfg.DefaultWriteWorkers,
4✔
666
                        Sig:   lncfg.DefaultSigWorkers,
4✔
667
                },
4✔
668
                Caches: &lncfg.Caches{
4✔
669
                        RejectCacheSize:  channeldb.DefaultRejectCacheSize,
4✔
670
                        ChannelCacheSize: channeldb.DefaultChannelCacheSize,
4✔
671
                },
4✔
672
                Prometheus: lncfg.DefaultPrometheus(),
4✔
673
                Watchtower: lncfg.DefaultWatchtowerCfg(defaultTowerDir),
4✔
674
                HealthChecks: &lncfg.HealthCheckConfig{
4✔
675
                        ChainCheck: &lncfg.CheckConfig{
4✔
676
                                Interval: defaultChainInterval,
4✔
677
                                Timeout:  defaultChainTimeout,
4✔
678
                                Attempts: defaultChainAttempts,
4✔
679
                                Backoff:  defaultChainBackoff,
4✔
680
                        },
4✔
681
                        DiskCheck: &lncfg.DiskCheckConfig{
4✔
682
                                RequiredRemaining: defaultRequiredDisk,
4✔
683
                                CheckConfig: &lncfg.CheckConfig{
4✔
684
                                        Interval: defaultDiskInterval,
4✔
685
                                        Attempts: defaultDiskAttempts,
4✔
686
                                        Timeout:  defaultDiskTimeout,
4✔
687
                                        Backoff:  defaultDiskBackoff,
4✔
688
                                },
4✔
689
                        },
4✔
690
                        TLSCheck: &lncfg.CheckConfig{
4✔
691
                                Interval: defaultTLSInterval,
4✔
692
                                Timeout:  defaultTLSTimeout,
4✔
693
                                Attempts: defaultTLSAttempts,
4✔
694
                                Backoff:  defaultTLSBackoff,
4✔
695
                        },
4✔
696
                        TorConnection: &lncfg.CheckConfig{
4✔
697
                                Interval: defaultTCInterval,
4✔
698
                                Timeout:  defaultTCTimeout,
4✔
699
                                Attempts: defaultTCAttempts,
4✔
700
                                Backoff:  defaultTCBackoff,
4✔
701
                        },
4✔
702
                        RemoteSigner: &lncfg.CheckConfig{
4✔
703
                                Interval: defaultRSInterval,
4✔
704
                                Timeout:  defaultRSTimeout,
4✔
705
                                Attempts: defaultRSAttempts,
4✔
706
                                Backoff:  defaultRSBackoff,
4✔
707
                        },
4✔
708
                        LeaderCheck: &lncfg.CheckConfig{
4✔
709
                                Interval: defaultLeaderCheckInterval,
4✔
710
                                Timeout:  defaultLeaderCheckTimeout,
4✔
711
                                Attempts: defaultLeaderCheckAttempts,
4✔
712
                                Backoff:  defaultLeaderCheckBackoff,
4✔
713
                        },
4✔
714
                },
4✔
715
                Gossip: &lncfg.Gossip{
4✔
716
                        MaxChannelUpdateBurst: discovery.DefaultMaxChannelUpdateBurst,
4✔
717
                        ChannelUpdateInterval: discovery.DefaultChannelUpdateInterval,
4✔
718
                        SubBatchDelay:         discovery.DefaultSubBatchDelay,
4✔
719
                        AnnouncementConf:      discovery.DefaultProofMatureDelta,
4✔
720
                        MsgRateBytes:          discovery.DefaultMsgBytesPerSecond,
4✔
721
                        MsgBurstBytes:         discovery.DefaultMsgBytesBurst,
4✔
722
                        FilterConcurrency:     discovery.DefaultFilterConcurrency,
4✔
723
                        BanThreshold:          discovery.DefaultBanThreshold,
4✔
724
                        PeerMsgRateBytes:      discovery.DefaultPeerMsgBytesPerSecond,
4✔
725
                },
4✔
726
                Invoices: &lncfg.Invoices{
4✔
727
                        HoldExpiryDelta: lncfg.DefaultHoldInvoiceExpiryDelta,
4✔
728
                },
4✔
729
                Routing: &lncfg.Routing{
4✔
730
                        BlindedPaths: lncfg.BlindedPaths{
4✔
731
                                MinNumRealHops:           lncfg.DefaultMinNumRealBlindedPathHops,
4✔
732
                                NumHops:                  lncfg.DefaultNumBlindedPathHops,
4✔
733
                                MaxNumPaths:              lncfg.DefaultMaxNumBlindedPaths,
4✔
734
                                PolicyIncreaseMultiplier: lncfg.DefaultBlindedPathPolicyIncreaseMultiplier,
4✔
735
                                PolicyDecreaseMultiplier: lncfg.DefaultBlindedPathPolicyDecreaseMultiplier,
4✔
736
                        },
4✔
737
                },
4✔
738
                MaxOutgoingCltvExpiry:     htlcswitch.DefaultMaxOutgoingCltvExpiry,
4✔
739
                MaxChannelFeeAllocation:   htlcswitch.DefaultMaxLinkFeeAllocation,
4✔
740
                MaxCommitFeeRateAnchors:   lnwallet.DefaultAnchorsCommitMaxFeeRateSatPerVByte,
4✔
741
                LogRotator:                build.NewRotatingLogWriter(),
4✔
742
                DB:                        lncfg.DefaultDB(),
4✔
743
                Cluster:                   lncfg.DefaultCluster(),
4✔
744
                RPCMiddleware:             lncfg.DefaultRPCMiddleware(),
4✔
745
                ActiveNetParams:           chainreg.BitcoinTestNetParams,
4✔
746
                ChannelCommitInterval:     defaultChannelCommitInterval,
4✔
747
                PendingCommitInterval:     defaultPendingCommitInterval,
4✔
748
                ChannelCommitBatchSize:    defaultChannelCommitBatchSize,
4✔
749
                CoinSelectionStrategy:     defaultCoinSelectionStrategy,
4✔
750
                KeepFailedPaymentAttempts: defaultKeepFailedPaymentAttempts,
4✔
751
                RemoteSigner: &lncfg.RemoteSigner{
4✔
752
                        Timeout: lncfg.DefaultRemoteSignerRPCTimeout,
4✔
753
                },
4✔
754
                Sweeper: lncfg.DefaultSweeperConfig(),
4✔
755
                Htlcswitch: &lncfg.Htlcswitch{
4✔
756
                        MailboxDeliveryTimeout: htlcswitch.DefaultMailboxDeliveryTimeout,
4✔
757
                        QuiescenceTimeout:      lncfg.DefaultQuiescenceTimeout,
4✔
758
                },
4✔
759
                GRPC: &GRPCConfig{
4✔
760
                        ServerPingTime:    defaultGrpcServerPingTime,
4✔
761
                        ServerPingTimeout: defaultGrpcServerPingTimeout,
4✔
762
                        ClientPingMinWait: defaultGrpcClientPingMinWait,
4✔
763
                },
4✔
764
                LogConfig:                 build.DefaultLogConfig(),
4✔
765
                WtClient:                  lncfg.DefaultWtClientCfg(),
4✔
766
                HTTPHeaderTimeout:         DefaultHTTPHeaderTimeout,
4✔
767
                NumRestrictedSlots:        DefaultNumRestrictedSlots,
4✔
768
                NoDisconnectOnPongFailure: defaultNoDisconnectOnPongFailure,
4✔
769
        }
4✔
770
}
4✔
771

4✔
772
// LoadConfig initializes and parses the config using a config file and command
4✔
773
// line options.
4✔
774
//
4✔
775
// The configuration proceeds as follows:
4✔
776
//  1. Start with a default config with sane settings
4✔
777
//  2. Pre-parse the command line to check for an alternative config file
4✔
778
//  3. Load configuration file overwriting defaults with any specified options
4✔
779
//  4. Parse CLI options and overwrite/add any specified options
4✔
780
func LoadConfig(interceptor signal.Interceptor) (*Config, error) {
781
        // Pre-parse the command line options to pick up an alternative config
782
        // file.
783
        preCfg := DefaultConfig()
784
        if _, err := flags.Parse(&preCfg); err != nil {
785
                return nil, err
786
        }
787

788
        // Show the version and exit if the version flag was specified.
789
        appName := filepath.Base(os.Args[0])
3✔
790
        appName = strings.TrimSuffix(appName, filepath.Ext(appName))
3✔
791
        usageMessage := fmt.Sprintf("Use %s -h to show usage", appName)
3✔
792
        if preCfg.ShowVersion {
3✔
793
                fmt.Println(appName, "version", build.Version(),
3✔
794
                        "commit="+build.Commit)
×
795
                os.Exit(0)
×
796
        }
797

798
        // If the config file path has not been modified by the user, then we'll
3✔
799
        // use the default config file path. However, if the user has modified
3✔
800
        // their lnddir, then we should assume they intend to use the config
3✔
801
        // file within it.
3✔
UNCOV
802
        configFileDir := CleanAndExpandPath(preCfg.LndDir)
×
UNCOV
803
        configFilePath := CleanAndExpandPath(preCfg.ConfigFile)
×
UNCOV
804
        switch {
×
UNCOV
805
        // User specified --lnddir but no --configfile. Update the config file
×
806
        // path to the lnd config directory, but don't require it to exist.
807
        case configFileDir != DefaultLndDir &&
808
                configFilePath == DefaultConfigFile:
809

810
                configFilePath = filepath.Join(
811
                        configFileDir, lncfg.DefaultConfigFilename,
3✔
812
                )
3✔
813

3✔
814
        // User did specify an explicit --configfile, so we check that it does
815
        // exist under that path to avoid surprises.
816
        case configFilePath != DefaultConfigFile:
817
                if !lnrpc.FileExists(configFilePath) {
3✔
818
                        return nil, fmt.Errorf("specified config file does "+
3✔
819
                                "not exist in %s", configFilePath)
3✔
820
                }
3✔
821
        }
3✔
822

823
        // Next, load any additional configuration options from the file.
824
        var configFileError error
UNCOV
825
        cfg := preCfg
×
UNCOV
826
        fileParser := flags.NewParser(&cfg, flags.Default)
×
UNCOV
827
        err := flags.NewIniParser(fileParser).ParseFile(configFilePath)
×
UNCOV
828
        if err != nil {
×
UNCOV
829
                // If it's a parsing related error, then we'll return
×
830
                // immediately, otherwise we can proceed as possibly the config
831
                // file doesn't exist which is OK.
832
                if lnutils.ErrorAs[*flags.IniError](err) ||
833
                        lnutils.ErrorAs[*flags.Error](err) {
3✔
834

3✔
835
                        return nil, err
3✔
836
                }
3✔
837

6✔
838
                configFileError = err
3✔
839
        }
3✔
840

3✔
841
        // Finally, parse the remaining command line options again to ensure
3✔
842
        // they take precedence.
3✔
UNCOV
843
        flagParser := flags.NewParser(&cfg, flags.Default)
×
UNCOV
844
        if _, err := flagParser.Parse(); err != nil {
×
845
                return nil, err
×
846
        }
847

3✔
848
        // Make sure everything we just loaded makes sense.
849
        cleanCfg, err := ValidateConfig(
850
                cfg, interceptor, fileParser, flagParser,
851
        )
852
        var usageErr *lncfg.UsageError
3✔
853
        if errors.As(err, &usageErr) {
3✔
854
                // The logging system might not yet be initialized, so we also
×
855
                // write to stderr to make sure the error appears somewhere.
×
856
                _, _ = fmt.Fprintln(os.Stderr, usageMessage)
857
                ltndLog.Warnf("Incorrect usage: %v", usageMessage)
858

3✔
859
                // The log subsystem might not yet be initialized. But we still
3✔
860
                // try to log the error there since some packaging solutions
3✔
861
                // might only look at the log and not stdout/stderr.
3✔
862
                ltndLog.Warnf("Error validating config: %v", err)
3✔
863

×
864
                return nil, err
×
865
        }
×
UNCOV
866
        if err != nil {
×
867
                // The log subsystem might not yet be initialized. But we still
×
868
                // try to log the error there since some packaging solutions
×
869
                // might only look at the log and not stdout/stderr.
×
870
                ltndLog.Warnf("Error validating config: %v", err)
×
871

×
872
                return nil, err
×
873
        }
×
UNCOV
874

×
875
        // Warn about missing config file only after all other configuration is
3✔
UNCOV
876
        // done. This prevents the warning on help messages and invalid options.
×
UNCOV
877
        // Note this should go directly before the return.
×
UNCOV
878
        if configFileError != nil {
×
UNCOV
879
                ltndLog.Warnf("%v", configFileError)
×
UNCOV
880
        }
×
UNCOV
881

×
UNCOV
882
        // Finally, log warnings for deprecated config options if they are set.
×
883
        logWarningsForDeprecation(*cleanCfg)
884

885
        return cleanCfg, nil
886
}
887

6✔
888
// ValidateConfig check the given configuration to be sane. This makes sure no
3✔
889
// illegal values or combination of values are set. All file system paths are
3✔
890
// normalized. The cleaned up config is returned on success.
891
func ValidateConfig(cfg Config, interceptor signal.Interceptor, fileParser,
892
        flagParser *flags.Parser) (*Config, error) {
3✔
893

3✔
894
        // Special show command to list supported subsystems and exit.
3✔
895
        if cfg.DebugLevel == "show" {
896
                subLogMgr := build.NewSubLoggerManager()
897

898
                // Initialize logging at the default logging level.
899
                SetupLoggers(subLogMgr, interceptor)
900

901
                fmt.Println("Supported subsystems",
3✔
902
                        subLogMgr.SupportedSubsystems())
3✔
903
                os.Exit(0)
3✔
904
        }
6✔
905

3✔
906
        // If the provided lnd directory is not the default, we'll modify the
3✔
907
        // path to all of the files and directories that will live within it.
3✔
908
        lndDir := CleanAndExpandPath(cfg.LndDir)
3✔
909
        if lndDir != DefaultLndDir {
3✔
910
                cfg.DataDir = filepath.Join(lndDir, defaultDataDirname)
3✔
911
                cfg.LetsEncryptDir = filepath.Join(
3✔
912
                        lndDir, defaultLetsEncryptDirname,
3✔
913
                )
3✔
914
                cfg.TLSCertPath = filepath.Join(lndDir, defaultTLSCertFilename)
915
                cfg.TLSKeyPath = filepath.Join(lndDir, defaultTLSKeyFilename)
916
                cfg.LogDir = filepath.Join(lndDir, defaultLogDirname)
917

3✔
918
                // If the watchtower's directory is set to the default, i.e. the
6✔
919
                // user has not requested a different location, we'll move the
3✔
920
                // location to be relative to the specified lnd directory.
3✔
921
                if cfg.Watchtower.TowerDir == defaultTowerDir {
3✔
922
                        cfg.Watchtower.TowerDir = filepath.Join(
3✔
923
                                cfg.DataDir, defaultTowerSubDirname,
3✔
924
                        )
3✔
925
                }
3✔
926
        }
3✔
927

3✔
928
        funcName := "ValidateConfig"
3✔
929
        mkErr := func(format string, args ...interface{}) error {
3✔
930
                return fmt.Errorf(funcName+": "+format, args...)
6✔
931
        }
3✔
932
        makeDirectory := func(dir string) error {
3✔
933
                err := os.MkdirAll(dir, 0700)
3✔
934
                if err != nil {
3✔
935
                        // Show a nicer error message if it's because a symlink
936
                        // is linked to a directory that does not exist
937
                        // (probably because it's not mounted).
3✔
938
                        if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
3✔
939
                                link, lerr := os.Readlink(e.Path)
×
940
                                if lerr == nil {
×
941
                                        str := "is symlink %s -> %s mounted?"
6✔
942
                                        err = fmt.Errorf(str, e.Path, link)
3✔
943
                                }
3✔
UNCOV
944
                        }
×
UNCOV
945

×
946
                        str := "Failed to create lnd directory '%s': %v"
×
947
                        return mkErr(str, dir, err)
×
UNCOV
948
                }
×
UNCOV
949

×
UNCOV
950
                return nil
×
UNCOV
951
        }
×
UNCOV
952

×
953
        // IsSet returns true if an option has been set in either the config
954
        // file or by a flag.
UNCOV
955
        isSet := func(field string) (bool, error) {
×
UNCOV
956
                fieldName, ok := reflect.TypeOf(Config{}).FieldByName(field)
×
957
                if !ok {
958
                        str := "could not find field %s"
959
                        return false, mkErr(str, field)
3✔
960
                }
961

962
                long, ok := fieldName.Tag.Lookup("long")
963
                if !ok {
964
                        str := "field %s does not have a long tag"
6✔
965
                        return false, mkErr(str, field)
3✔
966
                }
3✔
UNCOV
967

×
UNCOV
968
                // The user has the option to set the flag in either the config
×
UNCOV
969
                // file or as a command line flag. If any is set, we consider it
×
970
                // to be set, not applying any precedence rules here (since it
971
                // is a boolean the default is false anyway which would screw up
3✔
972
                // any precedence rules). Additionally, we need to also support
3✔
UNCOV
973
                // the use case where the config struct is embedded _within_
×
UNCOV
974
                // another struct with a prefix (as is the case with
×
UNCOV
975
                // lightning-terminal).
×
976
                fileOption := fileParser.FindOptionByLongName(long)
977
                fileOptionNested := fileParser.FindOptionByLongName(
978
                        "lnd." + long,
979
                )
980
                flagOption := flagParser.FindOptionByLongName(long)
981
                flagOptionNested := flagParser.FindOptionByLongName(
982
                        "lnd." + long,
983
                )
984

985
                return (fileOption != nil && fileOption.IsSet()) ||
3✔
986
                                (fileOptionNested != nil && fileOptionNested.IsSet()) ||
3✔
987
                                (flagOption != nil && flagOption.IsSet()) ||
3✔
988
                                (flagOptionNested != nil && flagOptionNested.IsSet()),
3✔
989
                        nil
3✔
990
        }
3✔
991

3✔
992
        // As soon as we're done parsing configuration options, ensure all paths
3✔
993
        // to directories and files are cleaned and expanded before attempting
3✔
994
        // to use them later on.
3✔
995
        cfg.DataDir = CleanAndExpandPath(cfg.DataDir)
3✔
996
        cfg.TLSCertPath = CleanAndExpandPath(cfg.TLSCertPath)
3✔
997
        cfg.TLSKeyPath = CleanAndExpandPath(cfg.TLSKeyPath)
3✔
998
        cfg.LetsEncryptDir = CleanAndExpandPath(cfg.LetsEncryptDir)
3✔
999
        cfg.AdminMacPath = CleanAndExpandPath(cfg.AdminMacPath)
1000
        cfg.ReadMacPath = CleanAndExpandPath(cfg.ReadMacPath)
1001
        cfg.InvoiceMacPath = CleanAndExpandPath(cfg.InvoiceMacPath)
1002
        cfg.LogDir = CleanAndExpandPath(cfg.LogDir)
1003
        cfg.BtcdMode.Dir = CleanAndExpandPath(cfg.BtcdMode.Dir)
1004
        cfg.BitcoindMode.Dir = CleanAndExpandPath(cfg.BitcoindMode.Dir)
3✔
1005
        cfg.BitcoindMode.ConfigPath = CleanAndExpandPath(
3✔
1006
                cfg.BitcoindMode.ConfigPath,
3✔
1007
        )
3✔
1008
        cfg.BitcoindMode.RPCCookie = CleanAndExpandPath(cfg.BitcoindMode.RPCCookie)
3✔
1009
        cfg.Tor.PrivateKeyPath = CleanAndExpandPath(cfg.Tor.PrivateKeyPath)
3✔
1010
        cfg.Tor.WatchtowerKeyPath = CleanAndExpandPath(cfg.Tor.WatchtowerKeyPath)
3✔
1011
        cfg.Watchtower.TowerDir = CleanAndExpandPath(cfg.Watchtower.TowerDir)
3✔
1012
        cfg.BackupFilePath = CleanAndExpandPath(cfg.BackupFilePath)
3✔
1013
        cfg.WalletUnlockPasswordFile = CleanAndExpandPath(
3✔
1014
                cfg.WalletUnlockPasswordFile,
3✔
1015
        )
3✔
1016

3✔
1017
        // Ensure that the user didn't attempt to specify negative values for
3✔
1018
        // any of the autopilot params.
3✔
1019
        if cfg.Autopilot.MaxChannels < 0 {
3✔
1020
                str := "autopilot.maxchannels must be non-negative"
3✔
1021

3✔
1022
                return nil, mkErr(str)
3✔
1023
        }
3✔
1024
        if cfg.Autopilot.Allocation < 0 {
3✔
1025
                str := "autopilot.allocation must be non-negative"
3✔
1026

3✔
1027
                return nil, mkErr(str)
3✔
1028
        }
3✔
UNCOV
1029
        if cfg.Autopilot.MinChannelSize < 0 {
×
1030
                str := "autopilot.minchansize must be non-negative"
×
1031

×
1032
                return nil, mkErr(str)
×
1033
        }
3✔
UNCOV
1034
        if cfg.Autopilot.MaxChannelSize < 0 {
×
1035
                str := "autopilot.maxchansize must be non-negative"
×
1036

×
1037
                return nil, mkErr(str)
×
1038
        }
3✔
UNCOV
1039
        if cfg.Autopilot.MinConfs < 0 {
×
1040
                str := "autopilot.minconfs must be non-negative"
×
1041

×
1042
                return nil, mkErr(str)
×
1043
        }
3✔
UNCOV
1044
        if cfg.Autopilot.ConfTarget < 1 {
×
1045
                str := "autopilot.conftarget must be positive"
×
1046

×
1047
                return nil, mkErr(str)
×
1048
        }
3✔
UNCOV
1049

×
UNCOV
1050
        // Ensure that the specified values for the min and max channel size
×
UNCOV
1051
        // are within the bounds of the normal chan size constraints.
×
UNCOV
1052
        if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
×
1053
                cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
3✔
1054
        }
×
UNCOV
1055
        if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
×
1056
                cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
×
1057
        }
×
1058

1059
        if _, err := validateAtplCfg(cfg.Autopilot); err != nil {
1060
                return nil, mkErr("error validating autopilot: %v", err)
1061
        }
3✔
UNCOV
1062

×
UNCOV
1063
        // Ensure that --maxchansize is properly handled when set by user.
×
1064
        // For non-Wumbo channels this limit remains 16777215 satoshis by default
3✔
UNCOV
1065
        // as specified in BOLT-02. For wumbo channels this limit is 1,000,000,000.
×
UNCOV
1066
        // satoshis (10 BTC). Always enforce --maxchansize explicitly set by user.
×
1067
        // If unset (marked by 0 value), then enforce proper default.
1068
        if cfg.MaxChanSize == 0 {
3✔
UNCOV
1069
                if cfg.ProtocolOptions.Wumbo() {
×
UNCOV
1070
                        cfg.MaxChanSize = int64(funding.MaxBtcFundingAmountWumbo)
×
1071
                } else {
1072
                        cfg.MaxChanSize = int64(funding.MaxBtcFundingAmount)
1073
                }
1074
        }
1075

1076
        // Ensure that the user specified values for the min and max channel
1077
        // size make sense.
6✔
1078
        if cfg.MaxChanSize < cfg.MinChanSize {
6✔
1079
                return nil, mkErr("invalid channel size parameters: "+
3✔
1080
                        "max channel size %v, must be no less than min chan "+
6✔
1081
                        "size %v", cfg.MaxChanSize, cfg.MinChanSize,
3✔
1082
                )
3✔
1083
        }
1084

1085
        // Don't allow superfluous --maxchansize greater than
1086
        // BOLT 02 soft-limit for non-wumbo channel
1087
        if !cfg.ProtocolOptions.Wumbo() &&
3✔
UNCOV
1088
                cfg.MaxChanSize > int64(MaxFundingAmount) {
×
1089

×
1090
                return nil, mkErr("invalid channel size parameters: "+
×
1091
                        "maximum channel size %v is greater than maximum "+
×
1092
                        "non-wumbo channel size %v", cfg.MaxChanSize,
×
1093
                        MaxFundingAmount,
1094
                )
1095
        }
1096

3✔
1097
        // Ensure that the amount data for revoked commitment transactions is
3✔
UNCOV
1098
        // stored if the watchtower client is active.
×
UNCOV
1099
        if cfg.DB.NoRevLogAmtData && cfg.WtClient.Active {
×
1100
                return nil, mkErr("revocation log amount data must be stored " +
×
1101
                        "if the watchtower client is active")
×
1102
        }
×
UNCOV
1103

×
UNCOV
1104
        // Ensure a valid max channel fee allocation was set.
×
1105
        if cfg.MaxChannelFeeAllocation <= 0 || cfg.MaxChannelFeeAllocation > 1 {
1106
                return nil, mkErr("invalid max channel fee allocation: %v, "+
1107
                        "must be within (0, 1]", cfg.MaxChannelFeeAllocation)
1108
        }
3✔
UNCOV
1109

×
UNCOV
1110
        if cfg.MaxCommitFeeRateAnchors < 1 {
×
1111
                return nil, mkErr("invalid max commit fee rate anchors: %v, "+
×
1112
                        "must be at least 1 sat/vByte",
1113
                        cfg.MaxCommitFeeRateAnchors)
1114
        }
3✔
UNCOV
1115

×
UNCOV
1116
        // Validate the Tor config parameters.
×
UNCOV
1117
        socks, err := lncfg.ParseAddressString(
×
1118
                cfg.Tor.SOCKS, strconv.Itoa(defaultTorSOCKSPort),
1119
                cfg.net.ResolveTCPAddr,
3✔
UNCOV
1120
        )
×
UNCOV
1121
        if err != nil {
×
1122
                return nil, err
×
1123
        }
×
1124
        cfg.Tor.SOCKS = socks.String()
1125

1126
        // We'll only attempt to normalize and resolve the DNS host if it hasn't
3✔
1127
        // changed, as it doesn't need to be done for the default.
3✔
1128
        if cfg.Tor.DNS != defaultTorDNS {
3✔
1129
                dns, err := lncfg.ParseAddressString(
3✔
1130
                        cfg.Tor.DNS, strconv.Itoa(defaultTorDNSPort),
3✔
1131
                        cfg.net.ResolveTCPAddr,
×
1132
                )
×
1133
                if err != nil {
3✔
1134
                        return nil, mkErr("error parsing tor dns: %v", err)
3✔
1135
                }
3✔
1136
                cfg.Tor.DNS = dns.String()
3✔
1137
        }
3✔
UNCOV
1138

×
UNCOV
1139
        control, err := lncfg.ParseAddressString(
×
UNCOV
1140
                cfg.Tor.Control, strconv.Itoa(defaultTorControlPort),
×
UNCOV
1141
                cfg.net.ResolveTCPAddr,
×
UNCOV
1142
        )
×
UNCOV
1143
        if err != nil {
×
1144
                return nil, mkErr("error parsing tor control address: %v", err)
×
1145
        }
×
1146
        cfg.Tor.Control = control.String()
1147

1148
        // Ensure that tor socks host:port is not equal to tor control
3✔
1149
        // host:port. This would lead to lnd not starting up properly.
3✔
1150
        if cfg.Tor.SOCKS == cfg.Tor.Control {
3✔
1151
                str := "tor.socks and tor.control can not us the same host:port"
3✔
1152

3✔
1153
                return nil, mkErr(str)
×
1154
        }
×
1155

3✔
1156
        switch {
3✔
1157
        case cfg.Tor.V2 && cfg.Tor.V3:
3✔
1158
                return nil, mkErr("either tor.v2 or tor.v3 can be set, " +
3✔
1159
                        "but not both")
3✔
1160
        case cfg.DisableListen && (cfg.Tor.V2 || cfg.Tor.V3):
×
1161
                return nil, mkErr("listening must be enabled when enabling " +
×
1162
                        "inbound connections over Tor")
×
UNCOV
1163
        }
×
1164

1165
        if cfg.Tor.PrivateKeyPath == "" {
3✔
UNCOV
1166
                switch {
×
1167
                case cfg.Tor.V2:
×
1168
                        cfg.Tor.PrivateKeyPath = filepath.Join(
×
1169
                                lndDir, defaultTorV2PrivateKeyFilename,
×
1170
                        )
×
1171
                case cfg.Tor.V3:
×
1172
                        cfg.Tor.PrivateKeyPath = filepath.Join(
1173
                                lndDir, defaultTorV3PrivateKeyFilename,
1174
                        )
6✔
1175
                }
3✔
UNCOV
1176
        }
×
UNCOV
1177

×
UNCOV
1178
        if cfg.Tor.WatchtowerKeyPath == "" {
×
UNCOV
1179
                switch {
×
1180
                case cfg.Tor.V2:
×
1181
                        cfg.Tor.WatchtowerKeyPath = filepath.Join(
×
1182
                                cfg.Watchtower.TowerDir,
×
1183
                                defaultTorV2PrivateKeyFilename,
×
1184
                        )
1185
                case cfg.Tor.V3:
1186
                        cfg.Tor.WatchtowerKeyPath = filepath.Join(
1187
                                cfg.Watchtower.TowerDir,
6✔
1188
                                defaultTorV3PrivateKeyFilename,
3✔
1189
                        )
×
UNCOV
1190
                }
×
UNCOV
1191
        }
×
UNCOV
1192

×
UNCOV
1193
        // Set up the network-related functions that will be used throughout
×
UNCOV
1194
        // the daemon. We use the standard Go "net" package functions by
×
UNCOV
1195
        // default. If we should be proxying all traffic through Tor, then
×
UNCOV
1196
        // we'll use the Tor proxy specific functions in order to avoid leaking
×
UNCOV
1197
        // our real information.
×
UNCOV
1198
        if cfg.Tor.Active {
×
1199
                cfg.net = &tor.ProxyNet{
1200
                        SOCKS:                       cfg.Tor.SOCKS,
1201
                        DNS:                         cfg.Tor.DNS,
1202
                        StreamIsolation:             cfg.Tor.StreamIsolation,
1203
                        SkipProxyForClearNetTargets: cfg.Tor.SkipProxyForClearNetTargets,
1204
                }
1205
        }
1206

1207
        if cfg.DisableListen && cfg.NAT {
3✔
1208
                return nil, mkErr("NAT traversal cannot be used when " +
×
1209
                        "listening is disabled")
×
1210
        }
×
UNCOV
1211
        if cfg.NAT && len(cfg.ExternalHosts) != 0 {
×
1212
                return nil, mkErr("NAT support and externalhosts are " +
×
1213
                        "mutually exclusive, only one should be selected")
×
1214
        }
×
1215

1216
        // Multiple networks can't be selected simultaneously.  Count
3✔
UNCOV
1217
        // number of network flags passed; assign active network params
×
UNCOV
1218
        // while we're at it.
×
UNCOV
1219
        numNets := 0
×
1220
        if cfg.Bitcoin.MainNet {
3✔
1221
                numNets++
×
1222
                cfg.ActiveNetParams = chainreg.BitcoinMainNetParams
×
1223
        }
×
1224
        if cfg.Bitcoin.TestNet3 {
1225
                numNets++
1226
                cfg.ActiveNetParams = chainreg.BitcoinTestNetParams
1227
        }
1228
        if cfg.Bitcoin.TestNet4 {
3✔
1229
                numNets++
3✔
1230
                cfg.ActiveNetParams = chainreg.BitcoinTestNet4Params
×
1231
        }
×
UNCOV
1232
        if cfg.Bitcoin.RegTest {
×
1233
                numNets++
3✔
UNCOV
1234
                cfg.ActiveNetParams = chainreg.BitcoinRegTestNetParams
×
UNCOV
1235
        }
×
UNCOV
1236
        if cfg.Bitcoin.SimNet {
×
1237
                numNets++
3✔
1238
                cfg.ActiveNetParams = chainreg.BitcoinSimNetParams
×
1239

×
1240
                // For simnet, the btcsuite chain params uses a
×
1241
                // cointype of 115. However, we override this in
6✔
1242
                // chainreg/chainparams.go, but the raw ChainParam
3✔
1243
                // field is used elsewhere. To ensure everything is
3✔
1244
                // consistent, we'll also override the cointype within
3✔
1245
                // the raw params.
3✔
1246
                targetCoinType := chainreg.BitcoinSigNetParams.CoinType
×
1247
                cfg.ActiveNetParams.Params.HDCoinType = targetCoinType
×
1248
        }
×
UNCOV
1249
        if cfg.Bitcoin.SigNet {
×
1250
                numNets++
×
1251
                cfg.ActiveNetParams = chainreg.BitcoinSigNetParams
×
1252

×
1253
                // Let the user overwrite the default signet parameters.
×
1254
                // The challenge defines the actual signet network to
×
1255
                // join and the seed nodes are needed for network
×
1256
                // discovery.
×
1257
                sigNetChallenge := chaincfg.DefaultSignetChallenge
×
1258
                sigNetSeeds := chaincfg.DefaultSignetDNSSeeds
3✔
1259
                if cfg.Bitcoin.SigNetChallenge != "" {
×
1260
                        challenge, err := hex.DecodeString(
×
1261
                                cfg.Bitcoin.SigNetChallenge,
×
1262
                        )
×
1263
                        if err != nil {
×
1264
                                return nil, mkErr("Invalid "+
×
1265
                                        "signet challenge, hex decode "+
×
1266
                                        "failed: %v", err)
×
1267
                        }
×
1268
                        sigNetChallenge = challenge
×
UNCOV
1269
                }
×
UNCOV
1270

×
1271
                if len(cfg.Bitcoin.SigNetSeedNode) > 0 {
×
1272
                        sigNetSeeds = make([]chaincfg.DNSSeed, len(
×
1273
                                cfg.Bitcoin.SigNetSeedNode,
×
1274
                        ))
×
1275
                        for idx, seed := range cfg.Bitcoin.SigNetSeedNode {
×
1276
                                sigNetSeeds[idx] = chaincfg.DNSSeed{
×
1277
                                        Host:         seed,
×
1278
                                        HasFiltering: false,
1279
                                }
1280
                        }
×
UNCOV
1281
                }
×
UNCOV
1282

×
1283
                chainParams := chaincfg.CustomSignetParams(
×
1284
                        sigNetChallenge, sigNetSeeds,
×
1285
                )
×
1286
                cfg.ActiveNetParams.Params = &chainParams
×
UNCOV
1287
        }
×
UNCOV
1288
        if numNets > 1 {
×
1289
                str := "The mainnet, testnet, testnet4, regtest, simnet and " +
×
1290
                        "signet params can't be used together -- choose one " +
1291
                        "of the five"
1292

×
1293
                return nil, mkErr(str)
×
1294
        }
×
UNCOV
1295

×
1296
        // The target network must be provided, otherwise, we won't
1297
        // know how to initialize the daemon.
3✔
UNCOV
1298
        if numNets == 0 {
×
1299
                str := "either --bitcoin.mainnet, or --bitcoin.testnet, " +
×
1300
                        "--bitcoin.testnet4, --bitcoin.simnet, " +
×
1301
                        "--bitcoin.regtest or --bitcoin.signet must be " +
×
1302
                        "specified"
×
1303

×
1304
                return nil, mkErr(str)
1305
        }
1306

1307
        err = cfg.Bitcoin.Validate(minTimeLockDelta, funding.MinBtcRemoteDelay)
3✔
UNCOV
1308
        if err != nil {
×
1309
                return nil, mkErr("error validating bitcoin params: %v", err)
×
1310
        }
×
UNCOV
1311

×
UNCOV
1312
        switch cfg.Bitcoin.Node {
×
UNCOV
1313
        case btcdBackendName:
×
UNCOV
1314
                err := parseRPCParams(
×
1315
                        cfg.Bitcoin, cfg.BtcdMode, cfg.ActiveNetParams,
1316
                )
3✔
1317
                if err != nil {
3✔
1318
                        return nil, mkErr("unable to load RPC "+
×
1319
                                "credentials for btcd: %v", err)
×
1320
                }
1321
        case bitcoindBackendName:
3✔
1322
                if cfg.Bitcoin.SimNet {
1✔
1323
                        return nil, mkErr("bitcoind does not " +
1✔
1324
                                "support simnet")
1✔
1325
                }
1✔
1326

1✔
UNCOV
1327
                err := parseRPCParams(
×
UNCOV
1328
                        cfg.Bitcoin, cfg.BitcoindMode, cfg.ActiveNetParams,
×
UNCOV
1329
                )
×
1330
                if err != nil {
1✔
1331
                        return nil, mkErr("unable to load RPC "+
1✔
1332
                                "credentials for bitcoind: %v", err)
×
1333
                }
×
UNCOV
1334
        case neutrinoBackendName:
×
1335
                // No need to get RPC parameters.
1336

1✔
1337
        case "nochainbackend":
1✔
1338
                // Nothing to configure, we're running without any chain
1✔
1339
                // backend whatsoever (pure signing mode).
1✔
UNCOV
1340

×
1341
        default:
×
1342
                str := "only btcd, bitcoind, and neutrino mode " +
×
1343
                        "supported for bitcoin at this time"
1✔
1344

1345
                return nil, mkErr(str)
UNCOV
1346
        }
×
1347

1348
        cfg.Bitcoin.ChainDir = filepath.Join(
1349
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
UNCOV
1350
        )
×
UNCOV
1351

×
UNCOV
1352
        // Ensure that the user didn't attempt to specify negative values for
×
UNCOV
1353
        // any of the autopilot params.
×
UNCOV
1354
        if cfg.Autopilot.MaxChannels < 0 {
×
1355
                str := "autopilot.maxchannels must be non-negative"
1356

1357
                return nil, mkErr(str)
3✔
1358
        }
3✔
1359
        if cfg.Autopilot.Allocation < 0 {
3✔
1360
                str := "autopilot.allocation must be non-negative"
3✔
1361

3✔
1362
                return nil, mkErr(str)
3✔
1363
        }
3✔
UNCOV
1364
        if cfg.Autopilot.MinChannelSize < 0 {
×
1365
                str := "autopilot.minchansize must be non-negative"
×
1366

×
1367
                return nil, mkErr(str)
×
1368
        }
3✔
UNCOV
1369
        if cfg.Autopilot.MaxChannelSize < 0 {
×
1370
                str := "autopilot.maxchansize must be non-negative"
×
1371

×
1372
                return nil, mkErr(str)
×
1373
        }
3✔
UNCOV
1374

×
UNCOV
1375
        // Ensure that the specified values for the min and max channel size
×
UNCOV
1376
        // don't are within the bounds of the normal chan size constraints.
×
UNCOV
1377
        if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
×
1378
                cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
3✔
1379
        }
×
UNCOV
1380
        if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
×
1381
                cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
×
1382
        }
×
1383

1384
        // We'll now construct the network directory which will be where we
1385
        // store all the data specific to this chain/network.
1386
        cfg.networkDir = filepath.Join(
3✔
UNCOV
1387
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
×
UNCOV
1388
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
×
1389
        )
3✔
UNCOV
1390

×
UNCOV
1391
        // If a custom macaroon directory wasn't specified and the data
×
1392
        // directory has changed from the default path, then we'll also update
1393
        // the path for the macaroons to be generated.
1394
        if cfg.AdminMacPath == "" {
1395
                cfg.AdminMacPath = filepath.Join(
3✔
1396
                        cfg.networkDir, defaultAdminMacFilename,
3✔
1397
                )
3✔
1398
        }
3✔
1399
        if cfg.ReadMacPath == "" {
3✔
1400
                cfg.ReadMacPath = filepath.Join(
3✔
1401
                        cfg.networkDir, defaultReadMacFilename,
3✔
1402
                )
3✔
1403
        }
3✔
UNCOV
1404
        if cfg.InvoiceMacPath == "" {
×
1405
                cfg.InvoiceMacPath = filepath.Join(
×
1406
                        cfg.networkDir, defaultInvoiceMacFilename,
×
1407
                )
×
1408
        }
3✔
UNCOV
1409

×
UNCOV
1410
        towerDir := filepath.Join(
×
UNCOV
1411
                cfg.Watchtower.TowerDir, BitcoinChainName,
×
UNCOV
1412
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
×
1413
        )
3✔
UNCOV
1414

×
UNCOV
1415
        // Create the lnd directory and all other sub-directories if they don't
×
UNCOV
1416
        // already exist. This makes sure that directory trees are also created
×
UNCOV
1417
        // for files that point to outside the lnddir.
×
1418
        dirs := []string{
1419
                lndDir, cfg.DataDir, cfg.networkDir,
3✔
1420
                cfg.LetsEncryptDir, towerDir, cfg.graphDatabaseDir(),
3✔
1421
                filepath.Dir(cfg.TLSCertPath), filepath.Dir(cfg.TLSKeyPath),
3✔
1422
                filepath.Dir(cfg.AdminMacPath), filepath.Dir(cfg.ReadMacPath),
3✔
1423
                filepath.Dir(cfg.InvoiceMacPath),
3✔
1424
                filepath.Dir(cfg.Tor.PrivateKeyPath),
3✔
1425
                filepath.Dir(cfg.Tor.WatchtowerKeyPath),
3✔
1426
        }
3✔
1427
        for _, dir := range dirs {
3✔
1428
                if err := makeDirectory(dir); err != nil {
3✔
1429
                        return nil, err
3✔
1430
                }
3✔
1431
        }
3✔
1432

3✔
1433
        // Similarly, if a custom back up file path wasn't specified, then
3✔
1434
        // we'll update the file location to match our set network directory.
3✔
1435
        if cfg.BackupFilePath == "" {
3✔
1436
                cfg.BackupFilePath = filepath.Join(
6✔
1437
                        cfg.networkDir, chanbackup.DefaultBackupFileName,
3✔
UNCOV
1438
                )
×
UNCOV
1439
        }
×
1440

1441
        // Append the network type to the log directory so it is "namespaced"
1442
        // per network in the same fashion as the data directory.
1443
        cfg.LogDir = filepath.Join(
1444
                cfg.LogDir, BitcoinChainName,
6✔
1445
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1446
        )
3✔
1447

3✔
1448
        if err := cfg.LogConfig.Validate(); err != nil {
3✔
1449
                return nil, mkErr("error validating logging config: %w", err)
1450
        }
1451

1452
        // If a sub-log manager was not already created, then we'll create one
3✔
1453
        // now using the default log handlers.
3✔
1454
        if cfg.SubLogMgr == nil {
3✔
1455
                cfg.SubLogMgr = build.NewSubLoggerManager(
3✔
1456
                        build.NewDefaultLogHandlers(
3✔
1457
                                cfg.LogConfig, cfg.LogRotator,
3✔
UNCOV
1458
                        )...,
×
UNCOV
1459
                )
×
1460
        }
1461

1462
        // Initialize logging at the default logging level.
1463
        SetupLoggers(cfg.SubLogMgr, interceptor)
6✔
1464

3✔
1465
        if cfg.MaxLogFiles != 0 {
3✔
1466
                if cfg.LogConfig.File.MaxLogFiles !=
3✔
1467
                        build.DefaultMaxLogFiles {
3✔
1468

3✔
1469
                        return nil, mkErr("cannot set both maxlogfiles and "+
3✔
1470
                                "logging.file.max-files", err)
1471
                }
1472

3✔
1473
                cfg.LogConfig.File.MaxLogFiles = cfg.MaxLogFiles
3✔
1474
        }
3✔
UNCOV
1475
        if cfg.MaxLogFileSize != 0 {
×
1476
                if cfg.LogConfig.File.MaxLogFileSize !=
×
1477
                        build.DefaultMaxLogFileSize {
×
1478

×
1479
                        return nil, mkErr("cannot set both maxlogfilesize and "+
×
1480
                                "logging.file.max-file-size", err)
×
1481
                }
UNCOV
1482

×
1483
                cfg.LogConfig.File.MaxLogFileSize = cfg.MaxLogFileSize
1484
        }
3✔
UNCOV
1485

×
UNCOV
1486
        err = cfg.LogRotator.InitLogRotator(
×
UNCOV
1487
                cfg.LogConfig.File,
×
UNCOV
1488
                filepath.Join(cfg.LogDir, defaultLogFilename),
×
UNCOV
1489
        )
×
UNCOV
1490
        if err != nil {
×
1491
                str := "log rotation setup failed: %v"
1492
                return nil, mkErr(str, err)
×
1493
        }
1494

1495
        // Parse, validate, and set debug log level(s).
3✔
1496
        err = build.ParseAndSetDebugLevels(cfg.DebugLevel, cfg.SubLogMgr)
3✔
1497
        if err != nil {
3✔
1498
                str := "error parsing debug level: %v"
3✔
1499
                return nil, &lncfg.UsageError{Err: mkErr(str, err)}
3✔
1500
        }
×
UNCOV
1501

×
UNCOV
1502
        // At least one RPCListener is required. So listen on localhost per
×
1503
        // default.
1504
        if len(cfg.RawRPCListeners) == 0 {
1505
                addr := fmt.Sprintf("localhost:%d", defaultRPCPort)
3✔
1506
                cfg.RawRPCListeners = append(cfg.RawRPCListeners, addr)
3✔
1507
        }
×
UNCOV
1508

×
UNCOV
1509
        // Listen on localhost if no REST listeners were specified.
×
1510
        if len(cfg.RawRESTListeners) == 0 {
1511
                addr := fmt.Sprintf("localhost:%d", defaultRESTPort)
1512
                cfg.RawRESTListeners = append(cfg.RawRESTListeners, addr)
1513
        }
3✔
UNCOV
1514

×
UNCOV
1515
        // Listen on the default interface/port if no listeners were specified.
×
UNCOV
1516
        // An empty address string means default interface/address, which on
×
1517
        // most unix systems is the same as 0.0.0.0. If Tor is active, we
1518
        // default to only listening on localhost for hidden service
1519
        // connections.
3✔
UNCOV
1520
        if len(cfg.RawListeners) == 0 {
×
1521
                addr := fmt.Sprintf(":%d", defaultPeerPort)
×
1522
                if cfg.Tor.Active && !cfg.Tor.SkipProxyForClearNetTargets {
×
1523
                        addr = fmt.Sprintf("localhost:%d", defaultPeerPort)
1524
                }
1525
                cfg.RawListeners = append(cfg.RawListeners, addr)
1526
        }
1527

1528
        // Add default port to all RPC listener addresses if needed and remove
1529
        // duplicate addresses.
3✔
UNCOV
1530
        cfg.RPCListeners, err = lncfg.NormalizeAddresses(
×
UNCOV
1531
                cfg.RawRPCListeners, strconv.Itoa(defaultRPCPort),
×
UNCOV
1532
                cfg.net.ResolveTCPAddr,
×
UNCOV
1533
        )
×
UNCOV
1534
        if err != nil {
×
1535
                return nil, mkErr("error normalizing RPC listen addrs: %v", err)
1536
        }
1537

1538
        // Add default port to all REST listener addresses if needed and remove
1539
        // duplicate addresses.
3✔
1540
        cfg.RESTListeners, err = lncfg.NormalizeAddresses(
3✔
1541
                cfg.RawRESTListeners, strconv.Itoa(defaultRESTPort),
3✔
1542
                cfg.net.ResolveTCPAddr,
3✔
1543
        )
3✔
UNCOV
1544
        if err != nil {
×
1545
                return nil, mkErr("error normalizing REST listen addrs: %v", err)
×
1546
        }
1547

1548
        switch {
1549
        // The no seed backup and auto unlock are mutually exclusive.
3✔
1550
        case cfg.NoSeedBackup && cfg.WalletUnlockPasswordFile != "":
3✔
1551
                return nil, mkErr("cannot set noseedbackup and " +
3✔
1552
                        "wallet-unlock-password-file at the same time")
3✔
1553

3✔
UNCOV
1554
        // The "allow-create" flag cannot be set without the auto unlock file.
×
1555
        case cfg.WalletUnlockAllowCreate && cfg.WalletUnlockPasswordFile == "":
×
1556
                return nil, mkErr("cannot set wallet-unlock-allow-create " +
1557
                        "without wallet-unlock-password-file")
3✔
1558

UNCOV
1559
        // If a password file was specified, we need it to exist.
×
UNCOV
1560
        case cfg.WalletUnlockPasswordFile != "" &&
×
1561
                !lnrpc.FileExists(cfg.WalletUnlockPasswordFile):
×
1562

1563
                return nil, mkErr("wallet unlock password file %s does "+
1564
                        "not exist", cfg.WalletUnlockPasswordFile)
×
UNCOV
1565
        }
×
UNCOV
1566

×
1567
        // For each of the RPC listeners (REST+gRPC), we'll ensure that users
1568
        // have specified a safe combo for authentication. If not, we'll bail
1569
        // out with an error. Since we don't allow disabling TLS for gRPC
UNCOV
1570
        // connections we pass in tlsActive=true.
×
UNCOV
1571
        err = lncfg.EnforceSafeAuthentication(
×
UNCOV
1572
                cfg.RPCListeners, !cfg.NoMacaroons, true,
×
UNCOV
1573
        )
×
1574
        if err != nil {
1575
                return nil, mkErr("error enforcing safe authentication on "+
1576
                        "RPC ports: %v", err)
1577
        }
1578

1579
        if cfg.DisableRest {
1580
                ltndLog.Infof("REST API is disabled!")
3✔
1581
                cfg.RESTListeners = nil
3✔
1582
        } else {
3✔
1583
                err = lncfg.EnforceSafeAuthentication(
3✔
UNCOV
1584
                        cfg.RESTListeners, !cfg.NoMacaroons, !cfg.DisableRestTLS,
×
UNCOV
1585
                )
×
UNCOV
1586
                if err != nil {
×
1587
                        return nil, mkErr("error enforcing safe "+
1588
                                "authentication on REST ports: %v", err)
3✔
1589
                }
×
UNCOV
1590
        }
×
1591

3✔
1592
        // Remove the listening addresses specified if listening is disabled.
3✔
1593
        if cfg.DisableListen {
3✔
1594
                ltndLog.Infof("Listening on the p2p interface is disabled!")
3✔
1595
                cfg.Listeners = nil
3✔
UNCOV
1596
                cfg.ExternalIPs = nil
×
UNCOV
1597
        } else {
×
UNCOV
1598

×
1599
                // Add default port to all listener addresses if needed and remove
1600
                // duplicate addresses.
1601
                cfg.Listeners, err = lncfg.NormalizeAddresses(
1602
                        cfg.RawListeners, strconv.Itoa(defaultPeerPort),
6✔
1603
                        cfg.net.ResolveTCPAddr,
3✔
1604
                )
3✔
1605
                if err != nil {
3✔
1606
                        return nil, mkErr("error normalizing p2p listen "+
6✔
1607
                                "addrs: %v", err)
3✔
1608
                }
3✔
1609

3✔
1610
                // Add default port to all external IP addresses if needed and remove
3✔
1611
                // duplicate addresses.
3✔
1612
                cfg.ExternalIPs, err = lncfg.NormalizeAddresses(
3✔
1613
                        cfg.RawExternalIPs, strconv.Itoa(defaultPeerPort),
3✔
1614
                        cfg.net.ResolveTCPAddr,
3✔
UNCOV
1615
                )
×
UNCOV
1616
                if err != nil {
×
1617
                        return nil, err
×
1618
                }
1619

1620
                // For the p2p port it makes no sense to listen to an Unix socket.
1621
                // Also, we would need to refactor the brontide listener to support
3✔
1622
                // that.
3✔
1623
                for _, p2pListener := range cfg.Listeners {
3✔
1624
                        if lncfg.IsUnix(p2pListener) {
3✔
1625
                                return nil, mkErr("unix socket addresses "+
3✔
1626
                                        "cannot be used for the p2p "+
×
1627
                                        "connection listener: %s", p2pListener)
×
1628
                        }
1629
                }
1630
        }
1631

1632
        // Ensure that the specified minimum backoff is below or equal to the
6✔
1633
        // maximum backoff.
3✔
UNCOV
1634
        if cfg.MinBackoff > cfg.MaxBackoff {
×
1635
                return nil, mkErr("maxbackoff must be greater than minbackoff")
×
1636
        }
×
UNCOV
1637

×
1638
        // Newer versions of lnd added a new sub-config for bolt-specific
1639
        // parameters. However, we want to also allow existing users to use the
1640
        // value on the top-level config. If the outer config value is set,
1641
        // then we'll use that directly.
1642
        flagSet, err := isSet("SyncFreelist")
1643
        if err != nil {
3✔
1644
                return nil, mkErr("error parsing freelist sync flag: %v", err)
×
1645
        }
×
1646
        if flagSet {
1647
                cfg.DB.Bolt.NoFreelistSync = !cfg.SyncFreelist
1648
        }
1649

1650
        // Parse any extra sqlite pragma options that may have been provided
1651
        // to determine if they override any of the defaults that we will
3✔
1652
        // otherwise add.
3✔
UNCOV
1653
        var (
×
UNCOV
1654
                defaultSynchronous = true
×
1655
                defaultAutoVacuum  = true
3✔
UNCOV
1656
                defaultFullfsync   = true
×
UNCOV
1657
        )
×
1658
        for _, option := range cfg.DB.Sqlite.PragmaOptions {
1659
                switch {
1660
                case strings.HasPrefix(option, "synchronous="):
1661
                        defaultSynchronous = false
1662

3✔
1663
                case strings.HasPrefix(option, "auto_vacuum="):
3✔
1664
                        defaultAutoVacuum = false
3✔
1665

3✔
1666
                case strings.HasPrefix(option, "fullfsync="):
3✔
1667
                        defaultFullfsync = false
3✔
UNCOV
1668

×
1669
                default:
×
UNCOV
1670
                }
×
1671
        }
UNCOV
1672

×
UNCOV
1673
        if defaultSynchronous {
×
1674
                cfg.DB.Sqlite.PragmaOptions = append(
UNCOV
1675
                        cfg.DB.Sqlite.PragmaOptions, "synchronous=full",
×
UNCOV
1676
                )
×
1677
        }
UNCOV
1678

×
1679
        if defaultAutoVacuum {
1680
                cfg.DB.Sqlite.PragmaOptions = append(
1681
                        cfg.DB.Sqlite.PragmaOptions, "auto_vacuum=incremental",
1682
                )
6✔
1683
        }
3✔
1684

3✔
1685
        if defaultFullfsync {
3✔
1686
                cfg.DB.Sqlite.PragmaOptions = append(
3✔
1687
                        cfg.DB.Sqlite.PragmaOptions, "fullfsync=true",
1688
                )
6✔
1689
        }
3✔
1690

3✔
1691
        // Ensure that the user hasn't chosen a remote-max-htlc value greater
3✔
1692
        // than the protocol maximum.
3✔
1693
        maxRemoteHtlcs := uint16(input.MaxHTLCNumber / 2)
1694
        if cfg.DefaultRemoteMaxHtlcs > maxRemoteHtlcs {
6✔
1695
                return nil, mkErr("default-remote-max-htlcs (%v) must be "+
3✔
1696
                        "less than %v", cfg.DefaultRemoteMaxHtlcs,
3✔
1697
                        maxRemoteHtlcs)
3✔
1698
        }
3✔
1699

1700
        // Clamp the ChannelCommitInterval so that commitment updates can still
1701
        // happen in a reasonable timeframe.
1702
        if cfg.ChannelCommitInterval > maxChannelCommitInterval {
3✔
1703
                return nil, mkErr("channel-commit-interval (%v) must be less "+
3✔
1704
                        "than %v", cfg.ChannelCommitInterval,
×
1705
                        maxChannelCommitInterval)
×
1706
        }
×
UNCOV
1707

×
1708
        // Limit PendingCommitInterval so we don't wait too long for the remote
1709
        // party to send back a revoke.
1710
        if cfg.PendingCommitInterval > maxPendingCommitInterval {
1711
                return nil, mkErr("pending-commit-interval (%v) must be less "+
3✔
1712
                        "than %v", cfg.PendingCommitInterval,
×
1713
                        maxPendingCommitInterval)
×
1714
        }
×
UNCOV
1715

×
1716
        if err := cfg.Gossip.Parse(); err != nil {
1717
                return nil, mkErr("error parsing gossip syncer: %v", err)
1718
        }
1719

3✔
UNCOV
1720
        // If the experimental protocol options specify any protocol messages
×
UNCOV
1721
        // that we want to handle as custom messages, set them now.
×
UNCOV
1722
        customMsg := cfg.ProtocolOptions.CustomMessageOverrides()
×
UNCOV
1723

×
1724
        // We can safely set our custom override values during startup because
1725
        // startup is blocked on config parsing.
3✔
UNCOV
1726
        if err := lnwire.SetCustomOverrides(customMsg); err != nil {
×
1727
                return nil, mkErr("custom-message: %v", err)
×
1728
        }
1729

1730
        // Map old pprof flags to new pprof group flags.
1731
        //
3✔
1732
        // NOTE: This is a temporary measure to ensure compatibility with old
3✔
1733
        // flags.
3✔
1734
        if cfg.CPUProfile != "" {
3✔
1735
                if cfg.Pprof.CPUProfile != "" {
3✔
1736
                        return nil, mkErr("cpuprofile and pprof.cpuprofile " +
×
1737
                                "are mutually exclusive")
×
1738
                }
1739
                cfg.Pprof.CPUProfile = cfg.CPUProfile
1740
        }
1741
        if cfg.Profile != "" {
1742
                if cfg.Pprof.Profile != "" {
1743
                        return nil, mkErr("profile and pprof.profile " +
3✔
1744
                                "are mutually exclusive")
×
1745
                }
×
1746
                cfg.Pprof.Profile = cfg.Profile
×
UNCOV
1747
        }
×
UNCOV
1748
        if cfg.BlockingProfile != 0 {
×
1749
                if cfg.Pprof.BlockingProfile != 0 {
1750
                        return nil, mkErr("blockingprofile and " +
3✔
1751
                                "pprof.blockingprofile are mutually exclusive")
×
1752
                }
×
1753
                cfg.Pprof.BlockingProfile = cfg.BlockingProfile
×
UNCOV
1754
        }
×
UNCOV
1755
        if cfg.MutexProfile != 0 {
×
1756
                if cfg.Pprof.MutexProfile != 0 {
1757
                        return nil, mkErr("mutexprofile and " +
3✔
1758
                                "pprof.mutexprofile are mutually exclusive")
×
1759
                }
×
1760
                cfg.Pprof.MutexProfile = cfg.MutexProfile
×
UNCOV
1761
        }
×
UNCOV
1762

×
1763
        // Don't allow both the old dust-threshold and the new
1764
        // channel-max-fee-exposure to be set.
3✔
UNCOV
1765
        if cfg.DustThreshold != 0 && cfg.MaxFeeExposure != 0 {
×
1766
                return nil, mkErr("cannot set both dust-threshold and " +
×
1767
                        "channel-max-fee-exposure")
×
1768
        }
×
UNCOV
1769

×
1770
        switch {
1771
        // Use the old dust-threshold as the max fee exposure if it is set and
1772
        // the new option is not.
1773
        case cfg.DustThreshold != 0:
1774
                cfg.MaxFeeExposure = cfg.DustThreshold
3✔
UNCOV
1775

×
UNCOV
1776
        // Use the default max fee exposure if the new option is not set and
×
UNCOV
1777
        // the old one is not set either.
×
1778
        case cfg.MaxFeeExposure == 0:
1779
                cfg.MaxFeeExposure = uint64(
3✔
1780
                        htlcswitch.DefaultMaxFeeExposure.ToSatoshis(),
1781
                )
UNCOV
1782
        }
×
UNCOV
1783

×
1784
        // Validate the subconfigs for workers, caches, and the tower client.
1785
        err = lncfg.Validate(
1786
                cfg.Workers,
1787
                cfg.Caches,
3✔
1788
                cfg.WtClient,
3✔
1789
                cfg.DB,
3✔
1790
                cfg.Cluster,
3✔
1791
                cfg.HealthChecks,
1792
                cfg.RPCMiddleware,
1793
                cfg.RemoteSigner,
1794
                cfg.Sweeper,
3✔
1795
                cfg.Htlcswitch,
3✔
1796
                cfg.Invoices,
3✔
1797
                cfg.Routing,
3✔
1798
                cfg.Pprof,
3✔
1799
                cfg.Gossip,
3✔
1800
        )
3✔
1801
        if err != nil {
3✔
1802
                return nil, err
3✔
1803
        }
3✔
1804

3✔
1805
        // Finally, ensure that the user's color is correctly formatted,
3✔
1806
        // otherwise the server will not be able to start after the unlocking
3✔
1807
        // the wallet.
3✔
1808
        _, err = lncfg.ParseHexColor(cfg.Color)
3✔
1809
        if err != nil {
3✔
1810
                return nil, mkErr("unable to parse node color: %v", err)
3✔
1811
        }
×
UNCOV
1812

×
1813
        // All good, return the sanitized result.
1814
        return &cfg, nil
1815
}
1816

1817
// graphDatabaseDir returns the default directory where the local bolt graph db
3✔
1818
// files are stored.
3✔
UNCOV
1819
func (c *Config) graphDatabaseDir() string {
×
UNCOV
1820
        return filepath.Join(
×
1821
                c.DataDir, defaultGraphSubDirname,
1822
                lncfg.NormalizeNetwork(c.ActiveNetParams.Name),
1823
        )
3✔
1824
}
1825

1826
// ImplementationConfig returns the configuration of what actual implementations
1827
// should be used when creating the main lnd instance.
1828
func (c *Config) ImplementationConfig(
3✔
1829
        interceptor signal.Interceptor) *ImplementationCfg {
3✔
1830

3✔
1831
        // If we're using a remote signer, we still need the base wallet as a
3✔
1832
        // watch-only source of chain and address data. But we don't need any
3✔
1833
        // private key material in that btcwallet base wallet.
3✔
1834
        if c.RemoteSigner.Enable {
1835
                rpcImpl := NewRPCSignerWalletImpl(
1836
                        c, ltndLog, interceptor,
1837
                        c.RemoteSigner.MigrateWatchOnly,
1838
                )
3✔
1839
                return &ImplementationCfg{
3✔
1840
                        GrpcRegistrar:     rpcImpl,
3✔
1841
                        RestRegistrar:     rpcImpl,
3✔
1842
                        ExternalValidator: rpcImpl,
3✔
1843
                        DatabaseBuilder: NewDefaultDatabaseBuilder(
6✔
1844
                                c, ltndLog,
3✔
1845
                        ),
3✔
1846
                        WalletConfigBuilder: rpcImpl,
3✔
1847
                        ChainControlBuilder: rpcImpl,
3✔
1848
                }
3✔
1849
        }
3✔
1850

3✔
1851
        defaultImpl := NewDefaultWalletImpl(c, ltndLog, interceptor, false)
3✔
1852
        return &ImplementationCfg{
3✔
1853
                GrpcRegistrar:       defaultImpl,
3✔
1854
                RestRegistrar:       defaultImpl,
3✔
1855
                ExternalValidator:   defaultImpl,
3✔
1856
                DatabaseBuilder:     NewDefaultDatabaseBuilder(c, ltndLog),
3✔
1857
                WalletConfigBuilder: defaultImpl,
3✔
1858
                ChainControlBuilder: defaultImpl,
3✔
1859
        }
1860
}
3✔
1861

3✔
1862
// CleanAndExpandPath expands environment variables and leading ~ in the
3✔
1863
// passed path, cleans the result, and returns it.
3✔
1864
// This function is taken from https://github.com/btcsuite/btcd
3✔
1865
func CleanAndExpandPath(path string) string {
3✔
1866
        if path == "" {
3✔
1867
                return ""
3✔
1868
        }
3✔
1869

1870
        // Expand initial ~ to OS specific home directory.
1871
        if strings.HasPrefix(path, "~") {
1872
                var homeDir string
1873
                u, err := user.Current()
1874
                if err == nil {
3✔
1875
                        homeDir = u.HomeDir
6✔
1876
                } else {
3✔
1877
                        homeDir = os.Getenv("HOME")
3✔
1878
                }
1879

1880
                path = strings.Replace(path, "~", homeDir, 1)
3✔
UNCOV
1881
        }
×
UNCOV
1882

×
UNCOV
1883
        // NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
×
UNCOV
1884
        // but the variables can still be expanded via POSIX-style $VARIABLE.
×
UNCOV
1885
        return filepath.Clean(os.ExpandEnv(path))
×
UNCOV
1886
}
×
UNCOV
1887

×
1888
func parseRPCParams(cConfig *lncfg.Chain, nodeConfig interface{},
UNCOV
1889
        netParams chainreg.BitcoinNetParams) error {
×
1890

1891
        // First, we'll check our node config to make sure the RPC parameters
1892
        // were set correctly. We'll also determine the path to the conf file
1893
        // depending on the backend node.
1894
        var daemonName, confDir, confFile, confFileBase string
3✔
1895
        switch conf := nodeConfig.(type) {
1896
        case *lncfg.Btcd:
1897
                // Resolves environment variable references in RPCUser and
1898
                // RPCPass fields.
2✔
1899
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
2✔
1900
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
2✔
1901

2✔
1902
                // If both RPCUser and RPCPass are set, we assume those
2✔
1903
                // credentials are good to use.
2✔
1904
                if conf.RPCUser != "" && conf.RPCPass != "" {
2✔
1905
                        return nil
1✔
1906
                }
1✔
1907

1✔
1908
                // Set the daemon name for displaying proper errors.
1✔
1909
                daemonName = btcdBackendName
1✔
1910
                confDir = conf.Dir
1✔
1911
                confFileBase = btcdBackendName
1✔
1912

1✔
1913
                // If only ONE of RPCUser or RPCPass is set, we assume the
2✔
1914
                // user did that unintentionally.
1✔
1915
                if conf.RPCUser != "" || conf.RPCPass != "" {
1✔
1916
                        return fmt.Errorf("please set both or neither of "+
1917
                                "%[1]v.rpcuser, %[1]v.rpcpass", daemonName)
1918
                }
×
UNCOV
1919

×
UNCOV
1920
        case *lncfg.Bitcoind:
×
UNCOV
1921
                // Ensure that if the ZMQ options are set, that they are not
×
UNCOV
1922
                // equal.
×
UNCOV
1923
                if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
×
UNCOV
1924
                        err := checkZMQOptions(
×
UNCOV
1925
                                conf.ZMQPubRawBlock, conf.ZMQPubRawTx,
×
UNCOV
1926
                        )
×
UNCOV
1927
                        if err != nil {
×
1928
                                return err
1929
                        }
1✔
1930
                }
1✔
1931

1✔
1932
                // Ensure that if the estimate mode is set, that it is a legal
2✔
1933
                // value.
1✔
1934
                if conf.EstimateMode != "" {
1✔
1935
                        err := checkEstimateMode(conf.EstimateMode)
1✔
1936
                        if err != nil {
1✔
1937
                                return err
×
1938
                        }
×
1939
                }
1940

1941
                // Set the daemon name for displaying proper errors.
1942
                daemonName = bitcoindBackendName
1943
                confDir = conf.Dir
2✔
1944
                confFile = conf.ConfigPath
1✔
1945
                confFileBase = BitcoinChainName
1✔
UNCOV
1946

×
UNCOV
1947
                // Resolves environment variable references in RPCUser
×
1948
                // and RPCPass fields.
1949
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
1950
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
1951

1✔
1952
                // Check that cookie and credentials don't contradict each
1✔
1953
                // other.
1✔
1954
                if (conf.RPCUser != "" || conf.RPCPass != "") &&
1✔
1955
                        conf.RPCCookie != "" {
1✔
1956

1✔
1957
                        return fmt.Errorf("please only provide either "+
1✔
1958
                                "%[1]v.rpccookie or %[1]v.rpcuser and "+
1✔
1959
                                "%[1]v.rpcpass", daemonName)
1✔
1960
                }
1✔
1961

1✔
1962
                // We convert the cookie into a user name and password.
1✔
1963
                if conf.RPCCookie != "" {
1✔
1964
                        cookie, err := os.ReadFile(conf.RPCCookie)
1✔
1965
                        if err != nil {
×
1966
                                return fmt.Errorf("cannot read cookie file: %w",
×
1967
                                        err)
×
1968
                        }
×
UNCOV
1969

×
1970
                        splitCookie := strings.Split(string(cookie), ":")
1971
                        if len(splitCookie) != 2 {
1972
                                return fmt.Errorf("cookie file has a wrong " +
1✔
1973
                                        "format")
×
1974
                        }
×
1975
                        conf.RPCUser = splitCookie[0]
×
1976
                        conf.RPCPass = splitCookie[1]
×
UNCOV
1977
                }
×
1978

UNCOV
1979
                if conf.RPCUser != "" && conf.RPCPass != "" {
×
UNCOV
1980
                        // If all of RPCUser, RPCPass, ZMQBlockHost, and
×
UNCOV
1981
                        // ZMQTxHost are set, we assume those parameters are
×
UNCOV
1982
                        // good to use.
×
UNCOV
1983
                        if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
×
UNCOV
1984
                                return nil
×
UNCOV
1985
                        }
×
1986

1987
                        // If RPCUser and RPCPass are set and RPCPolling is
1988
                        // enabled, we assume the parameters are good to use.
2✔
1989
                        if conf.RPCPolling {
1✔
1990
                                return nil
1✔
1991
                        }
1✔
1992
                }
2✔
1993

1✔
1994
                // If not all of the parameters are set, we'll assume the user
1✔
1995
                // did this unintentionally.
1996
                if conf.RPCUser != "" || conf.RPCPass != "" ||
1997
                        conf.ZMQPubRawBlock != "" || conf.ZMQPubRawTx != "" {
1998

×
1999
                        return fmt.Errorf("please set %[1]v.rpcuser and "+
×
2000
                                "%[1]v.rpcpass (or %[1]v.rpccookie) together "+
×
2001
                                "with %[1]v.zmqpubrawblock, %[1]v.zmqpubrawtx",
2002
                                daemonName)
2003
                }
2004
        }
UNCOV
2005

×
UNCOV
2006
        // If we're in simnet mode, then the running btcd instance won't read
×
UNCOV
2007
        // the RPC credentials from the configuration. So if lnd wasn't
×
UNCOV
2008
        // specified the parameters, then we won't be able to start.
×
2009
        if cConfig.SimNet {
×
2010
                return fmt.Errorf("rpcuser and rpcpass must be set to your " +
×
2011
                        "btcd node's RPC parameters for simnet mode")
×
2012
        }
×
2013

2014
        fmt.Println("Attempting automatic RPC configuration to " + daemonName)
2015

2016
        if confFile == "" {
2017
                confFile = filepath.Join(confDir, fmt.Sprintf("%v.conf",
2018
                        confFileBase))
×
2019
        }
×
2020
        switch cConfig.Node {
×
2021
        case btcdBackendName:
×
2022
                nConf := nodeConfig.(*lncfg.Btcd)
2023
                rpcUser, rpcPass, err := extractBtcdRPCParams(confFile)
×
2024
                if err != nil {
×
2025
                        return fmt.Errorf("unable to extract RPC credentials: "+
×
2026
                                "%v, cannot start w/o RPC connection", err)
×
2027
                }
×
2028
                nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
×
UNCOV
2029

×
2030
        case bitcoindBackendName:
×
2031
                nConf := nodeConfig.(*lncfg.Bitcoind)
×
2032
                rpcUser, rpcPass, zmqBlockHost, zmqTxHost, err :=
×
2033
                        extractBitcoindRPCParams(netParams.Params.Name,
×
2034
                                nConf.Dir, confFile, nConf.RPCCookie)
×
2035
                if err != nil {
×
2036
                        return fmt.Errorf("unable to extract RPC credentials: "+
×
2037
                                "%v, cannot start w/o RPC connection", err)
×
2038
                }
2039
                nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
×
2040
                nConf.ZMQPubRawBlock, nConf.ZMQPubRawTx = zmqBlockHost, zmqTxHost
×
UNCOV
2041
        }
×
UNCOV
2042

×
2043
        fmt.Printf("Automatically obtained %v's RPC credentials\n", daemonName)
×
2044
        return nil
×
UNCOV
2045
}
×
UNCOV
2046

×
UNCOV
2047
// supplyEnvValue supplies the value of an environment variable from a string.
×
UNCOV
2048
// It supports the following formats:
×
UNCOV
2049
// 1) $ENV_VAR
×
2050
// 2) ${ENV_VAR}
2051
// 3) ${ENV_VAR:-DEFAULT}
UNCOV
2052
//
×
UNCOV
2053
// Standard environment variable naming conventions:
×
2054
// - ENV_VAR contains letters, digits, and underscores, and does
2055
// not start with a digit.
2056
// - DEFAULT follows the rule that it can contain any characters except
2057
// whitespace.
2058
//
2059
// Parameters:
2060
// - value: The input string containing references to environment variables
2061
// (if any).
2062
//
2063
// Returns:
2064
// - string: The value of the specified environment variable, the default
2065
// value if provided, or the original input string if no matching variable is
2066
// found or set.
2067
func supplyEnvValue(value string) string {
2068
        // Regex for $ENV_VAR format.
2069
        var reEnvVar = regexp.MustCompile(`^\$([a-zA-Z_][a-zA-Z0-9_]*)$`)
2070

2071
        // Regex for ${ENV_VAR} format.
2072
        var reEnvVarWithBrackets = regexp.MustCompile(
2073
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$`,
2074
        )
2075

2076
        // Regex for ${ENV_VAR:-DEFAULT} format.
9✔
2077
        var reEnvVarWithDefault = regexp.MustCompile(
9✔
2078
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*):-([\S]+)\}$`,
9✔
2079
        )
9✔
2080

9✔
2081
        // Match against supported formats.
9✔
2082
        switch {
9✔
2083
        case reEnvVarWithDefault.MatchString(value):
9✔
2084
                matches := reEnvVarWithDefault.FindStringSubmatch(value)
9✔
2085
                envVariable := matches[1]
9✔
2086
                defaultValue := matches[2]
9✔
2087
                if envValue := os.Getenv(envVariable); envValue != "" {
9✔
2088
                        return envValue
9✔
2089
                }
9✔
2090

9✔
2091
                return defaultValue
9✔
2092

3✔
2093
        case reEnvVarWithBrackets.MatchString(value):
3✔
2094
                matches := reEnvVarWithBrackets.FindStringSubmatch(value)
3✔
2095
                envVariable := matches[1]
3✔
2096
                envValue := os.Getenv(envVariable)
4✔
2097

1✔
2098
                return envValue
1✔
2099

2100
        case reEnvVar.MatchString(value):
2✔
2101
                matches := reEnvVar.FindStringSubmatch(value)
UNCOV
2102
                envVariable := matches[1]
×
UNCOV
2103
                envValue := os.Getenv(envVariable)
×
UNCOV
2104

×
UNCOV
2105
                return envValue
×
UNCOV
2106
        }
×
UNCOV
2107

×
2108
        return value
2109
}
3✔
2110

3✔
2111
// extractBtcdRPCParams attempts to extract the RPC credentials for an existing
3✔
2112
// btcd instance. The passed path is expected to be the location of btcd's
3✔
2113
// application data directory on the target system.
3✔
2114
func extractBtcdRPCParams(btcdConfigPath string) (string, string, error) {
3✔
2115
        // First, we'll open up the btcd configuration file found at the target
2116
        // destination.
2117
        btcdConfigFile, err := os.Open(btcdConfigPath)
3✔
2118
        if err != nil {
2119
                return "", "", err
2120
        }
2121
        defer func() { _ = btcdConfigFile.Close() }()
2122

UNCOV
2123
        // With the file open extract the contents of the configuration file so
×
UNCOV
2124
        // we can attempt to locate the RPC credentials.
×
2125
        configContents, err := io.ReadAll(btcdConfigFile)
×
2126
        if err != nil {
×
2127
                return "", "", err
×
2128
        }
×
UNCOV
2129

×
UNCOV
2130
        // Attempt to locate the RPC user using a regular expression. If we
×
2131
        // don't have a match for our regular expression then we'll exit with
2132
        // an error.
2133
        rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
2134
        if err != nil {
×
2135
                return "", "", err
×
2136
        }
×
2137
        userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
×
2138
        if userSubmatches == nil {
2139
                return "", "", fmt.Errorf("unable to find rpcuser in config")
2140
        }
2141

UNCOV
2142
        // Similarly, we'll use another regular expression to find the set
×
UNCOV
2143
        // rpcpass (if any). If we can't find the pass, then we'll exit with an
×
UNCOV
2144
        // error.
×
2145
        rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpass\s*=\s*([^\s]+)`)
×
2146
        if err != nil {
×
2147
                return "", "", err
×
2148
        }
×
2149
        passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
×
2150
        if passSubmatches == nil {
2151
                return "", "", fmt.Errorf("unable to find rpcuser in config")
2152
        }
2153

2154
        return supplyEnvValue(string(userSubmatches[1])),
×
2155
                supplyEnvValue(string(passSubmatches[1])), nil
×
UNCOV
2156
}
×
UNCOV
2157

×
UNCOV
2158
// extractBitcoindRPCParams attempts to extract the RPC credentials for an
×
UNCOV
2159
// existing bitcoind node instance. The routine looks for a cookie first,
×
UNCOV
2160
// optionally following the datadir configuration option in the bitcoin.conf. If
×
UNCOV
2161
// it doesn't find one, it looks for rpcuser/rpcpassword.
×
2162
func extractBitcoindRPCParams(networkName, bitcoindDataDir, bitcoindConfigPath,
2163
        rpcCookiePath string) (string, string, string, string, error) {
×
2164

×
2165
        // First, we'll open up the bitcoind configuration file found at the
2166
        // target destination.
2167
        bitcoindConfigFile, err := os.Open(bitcoindConfigPath)
2168
        if err != nil {
2169
                return "", "", "", "", err
2170
        }
2171
        defer func() { _ = bitcoindConfigFile.Close() }()
UNCOV
2172

×
UNCOV
2173
        // With the file open extract the contents of the configuration file so
×
UNCOV
2174
        // we can attempt to locate the RPC credentials.
×
2175
        configContents, err := io.ReadAll(bitcoindConfigFile)
×
2176
        if err != nil {
×
2177
                return "", "", "", "", err
×
2178
        }
×
UNCOV
2179

×
UNCOV
2180
        // First, we'll look for the ZMQ hosts providing raw block and raw
×
2181
        // transaction notifications.
2182
        zmqBlockHostRE, err := regexp.Compile(
2183
                `(?m)^\s*zmqpubrawblock\s*=\s*([^\s]+)`,
2184
        )
×
2185
        if err != nil {
×
2186
                return "", "", "", "", err
×
2187
        }
×
2188
        zmqBlockHostSubmatches := zmqBlockHostRE.FindSubmatch(configContents)
2189
        if len(zmqBlockHostSubmatches) < 2 {
2190
                return "", "", "", "", fmt.Errorf("unable to find " +
2191
                        "zmqpubrawblock in config")
×
2192
        }
×
2193
        zmqTxHostRE, err := regexp.Compile(`(?m)^\s*zmqpubrawtx\s*=\s*([^\s]+)`)
×
2194
        if err != nil {
×
2195
                return "", "", "", "", err
×
2196
        }
×
2197
        zmqTxHostSubmatches := zmqTxHostRE.FindSubmatch(configContents)
×
2198
        if len(zmqTxHostSubmatches) < 2 {
×
2199
                return "", "", "", "", errors.New("unable to find zmqpubrawtx " +
×
2200
                        "in config")
×
2201
        }
×
2202
        zmqBlockHost := string(zmqBlockHostSubmatches[1])
×
2203
        zmqTxHost := string(zmqTxHostSubmatches[1])
×
2204
        if err := checkZMQOptions(zmqBlockHost, zmqTxHost); err != nil {
×
2205
                return "", "", "", "", err
×
2206
        }
×
UNCOV
2207

×
UNCOV
2208
        // Next, we'll try to find an auth cookie. We need to detect the chain
×
UNCOV
2209
        // by seeing if one is specified in the configuration file.
×
2210
        dataDir := filepath.Dir(bitcoindConfigPath)
×
2211
        if bitcoindDataDir != "" {
×
2212
                dataDir = bitcoindDataDir
×
2213
        }
×
2214
        dataDirRE, err := regexp.Compile(`(?m)^\s*datadir\s*=\s*([^\s]+)`)
×
2215
        if err != nil {
×
2216
                return "", "", "", "", err
2217
        }
2218
        dataDirSubmatches := dataDirRE.FindSubmatch(configContents)
2219
        if dataDirSubmatches != nil {
×
2220
                dataDir = string(dataDirSubmatches[1])
×
2221
        }
×
UNCOV
2222

×
2223
        var chainDir string
×
2224
        switch networkName {
×
2225
        case "mainnet":
×
2226
                chainDir = ""
×
2227
        case "regtest", "testnet3", "testnet4", "signet":
×
2228
                chainDir = networkName
×
2229
        default:
×
2230
                return "", "", "", "", fmt.Errorf("unexpected networkname %v", networkName)
×
2231
        }
UNCOV
2232

×
2233
        cookiePath := filepath.Join(dataDir, chainDir, ".cookie")
×
2234
        if rpcCookiePath != "" {
×
2235
                cookiePath = rpcCookiePath
×
2236
        }
×
2237
        cookie, err := os.ReadFile(cookiePath)
×
2238
        if err == nil {
×
2239
                splitCookie := strings.Split(string(cookie), ":")
×
2240
                if len(splitCookie) == 2 {
2241
                        return splitCookie[0], splitCookie[1], zmqBlockHost,
2242
                                zmqTxHost, nil
×
2243
                }
×
UNCOV
2244
        }
×
UNCOV
2245

×
UNCOV
2246
        // We didn't find a cookie, so we attempt to locate the RPC user using
×
UNCOV
2247
        // a regular expression. If we  don't have a match for our regular
×
UNCOV
2248
        // expression then we'll exit with an error.
×
2249
        rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
×
2250
        if err != nil {
×
2251
                return "", "", "", "", err
×
2252
        }
×
2253
        userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
2254

2255
        // Similarly, we'll use another regular expression to find the set
2256
        // rpcpass (if any). If we can't find the pass, then we'll exit with an
2257
        // error.
2258
        rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpassword\s*=\s*([^\s]+)`)
×
2259
        if err != nil {
×
2260
                return "", "", "", "", err
×
2261
        }
×
2262
        passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
×
2263

×
2264
        // Exit with an error if the cookie file, is defined in config, and
×
2265
        // can not be found, with both rpcuser and rpcpassword undefined.
×
2266
        if rpcCookiePath != "" && userSubmatches == nil && passSubmatches == nil {
×
2267
                return "", "", "", "", fmt.Errorf("unable to open cookie file (%v)",
×
2268
                        rpcCookiePath)
×
2269
        }
×
UNCOV
2270

×
2271
        if userSubmatches == nil {
×
2272
                return "", "", "", "", fmt.Errorf("unable to find rpcuser in " +
×
2273
                        "config")
×
2274
        }
×
2275
        if passSubmatches == nil {
×
2276
                return "", "", "", "", fmt.Errorf("unable to find rpcpassword " +
×
2277
                        "in config")
×
2278
        }
×
2279

2280
        return supplyEnvValue(string(userSubmatches[1])),
×
2281
                supplyEnvValue(string(passSubmatches[1])),
×
2282
                zmqBlockHost, zmqTxHost, nil
×
UNCOV
2283
}
×
UNCOV
2284

×
UNCOV
2285
// checkZMQOptions ensures that the provided addresses to use as the hosts for
×
UNCOV
2286
// ZMQ rawblock and rawtx notifications are different.
×
UNCOV
2287
func checkZMQOptions(zmqBlockHost, zmqTxHost string) error {
×
2288
        if zmqBlockHost == zmqTxHost {
2289
                return errors.New("zmqpubrawblock and zmqpubrawtx must be set " +
×
2290
                        "to different addresses")
×
2291
        }
×
2292

2293
        return nil
2294
}
2295

2296
// checkEstimateMode ensures that the provided estimate mode is legal.
1✔
2297
func checkEstimateMode(estimateMode string) error {
1✔
UNCOV
2298
        for _, mode := range bitcoindEstimateModes {
×
UNCOV
2299
                if estimateMode == mode {
×
UNCOV
2300
                        return nil
×
2301
                }
2302
        }
1✔
2303

2304
        return fmt.Errorf("estimatemode must be one of the following: %v",
2305
                bitcoindEstimateModes[:])
2306
}
1✔
2307

2✔
2308
// configToFlatMap converts the given config struct into a flat map of
2✔
2309
// key/value pairs using the dot notation we are used to from the config file
1✔
2310
// or command line flags. It also returns a map containing deprecated config
1✔
2311
// options.
2312
func configToFlatMap(cfg Config) (map[string]string,
UNCOV
2313
        map[string]struct{}, error) {
×
UNCOV
2314

×
2315
        result := make(map[string]string)
2316

2317
        // deprecated stores a map of deprecated options found in the config
2318
        // that are set by the users. A config option is considered as
2319
        // deprecated if it has a `hidden` flag.
2320
        deprecated := make(map[string]struct{})
2321

2322
        // redact is the helper function that redacts sensitive values like
4✔
2323
        // passwords.
4✔
2324
        redact := func(key, value string) string {
4✔
2325
                sensitiveKeySuffixes := []string{
4✔
2326
                        "pass",
4✔
2327
                        "password",
4✔
2328
                        "dsn",
4✔
2329
                }
4✔
2330
                for _, suffix := range sensitiveKeySuffixes {
4✔
2331
                        if strings.HasSuffix(key, suffix) {
4✔
2332
                                return "[redacted]"
4✔
2333
                        }
333✔
2334
                }
329✔
2335

329✔
2336
                return value
329✔
2337
        }
329✔
2338

329✔
2339
        // printConfig is the helper function that goes into nested structs
1,303✔
2340
        // recursively. Because we call it recursively, we need to declare it
982✔
2341
        // before we define it.
8✔
2342
        var printConfig func(reflect.Value, string)
8✔
2343
        printConfig = func(obj reflect.Value, prefix string) {
2344
                // Turn struct pointers into the actual struct, so we can
2345
                // iterate over the fields as we would with a struct value.
324✔
2346
                if obj.Kind() == reflect.Ptr {
2347
                        obj = obj.Elem()
2348
                }
2349

2350
                // Abort on nil values.
2351
                if !obj.IsValid() {
4✔
2352
                        return
70✔
2353
                }
66✔
2354

66✔
2355
                // Loop over all fields of the struct and inspect the type.
125✔
2356
                for i := 0; i < obj.NumField(); i++ {
59✔
2357
                        field := obj.Field(i)
59✔
2358
                        fieldType := obj.Type().Field(i)
2359

2360
                        longName := fieldType.Tag.Get("long")
78✔
2361
                        namespace := fieldType.Tag.Get("namespace")
12✔
2362
                        group := fieldType.Tag.Get("group")
12✔
2363
                        hidden := fieldType.Tag.Get("hidden")
2364

2365
                        switch {
462✔
2366
                        // We have a long name defined, this is a config value.
408✔
2367
                        case longName != "":
408✔
2368
                                key := longName
408✔
2369
                                if prefix != "" {
408✔
2370
                                        key = prefix + "." + key
408✔
2371
                                }
408✔
2372

408✔
2373
                                // Add the value directly to the flattened map.
408✔
2374
                                result[key] = redact(key, fmt.Sprintf(
408✔
2375
                                        "%v", field.Interface(),
2376
                                ))
329✔
2377

329✔
2378
                                // If there's a hidden flag, it's deprecated.
558✔
2379
                                if hidden == "true" && !field.IsZero() {
229✔
2380
                                        deprecated[key] = struct{}{}
229✔
2381
                                }
2382

2383
                        // We have no long name but a namespace, this is a
329✔
2384
                        // nested struct.
329✔
2385
                        case longName == "" && namespace != "":
329✔
2386
                                key := namespace
329✔
2387
                                if prefix != "" {
329✔
2388
                                        key = prefix + "." + key
331✔
2389
                                }
2✔
2390

2✔
2391
                                printConfig(field, key)
2392

2393
                        // Just a group means this is a dummy struct to house
2394
                        // multiple config values, the group name doesn't go
59✔
2395
                        // into the final field name.
59✔
2396
                        case longName == "" && group != "":
79✔
2397
                                printConfig(field, prefix)
20✔
2398

20✔
2399
                        // Anonymous means embedded struct. We need to recurse
2400
                        // into it but without adding anything to the prefix.
59✔
2401
                        case fieldType.Anonymous:
2402
                                printConfig(field, prefix)
2403

2404
                        default:
2405
                                continue
4✔
2406
                        }
4✔
2407
                }
2408
        }
2409

2410
        // Turn the whole config struct into a flat map.
8✔
2411
        printConfig(reflect.ValueOf(cfg), "")
8✔
2412

2413
        return result, deprecated, nil
20✔
2414
}
20✔
2415

2416
// logWarningsForDeprecation logs a warning if a deprecated config option is
2417
// set.
2418
func logWarningsForDeprecation(cfg Config) {
2419
        _, deprecated, err := configToFlatMap(cfg)
2420
        if err != nil {
4✔
2421
                ltndLog.Errorf("Convert configs to map: %v", err)
4✔
2422
        }
4✔
2423

2424
        for k := range deprecated {
2425
                ltndLog.Warnf("Config '%s' is deprecated, please remove it", k)
2426
        }
2427
}
3✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc