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

lightningnetwork / lnd / 13980275562

20 Mar 2025 10:06PM UTC coverage: 58.6% (-10.2%) from 68.789%
13980275562

Pull #9623

github

web-flow
Merge b9b960345 into 09b674508
Pull Request #9623: Size msg test msg

0 of 1518 new or added lines in 42 files covered. (0.0%)

26603 existing lines in 443 files now uncovered.

96807 of 165200 relevant lines covered (58.6%)

1.82 hits per line

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

54.04
/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 number of restricted slots
242
        // we'll allocate in the server.
243
        DefaultNumRestrictedSlots = 30
244

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

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

252
        defaultPrunedNodeMaxPeers = 4
253
        defaultNeutrinoMaxPeers   = 8
254
)
255

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

265
        // DefaultConfigFile is the default full path of lnd's configuration
266
        // file.
267
        DefaultConfigFile = filepath.Join(DefaultLndDir, lncfg.DefaultConfigFilename)
268

269
        defaultDataDir = filepath.Join(DefaultLndDir, defaultDataDirname)
270
        defaultLogDir  = filepath.Join(DefaultLndDir, defaultLogDirname)
271

272
        defaultTowerDir = filepath.Join(defaultDataDir, defaultTowerSubDirname)
273

274
        defaultTLSCertPath    = filepath.Join(DefaultLndDir, defaultTLSCertFilename)
275
        defaultTLSKeyPath     = filepath.Join(DefaultLndDir, defaultTLSKeyFilename)
276
        defaultLetsEncryptDir = filepath.Join(DefaultLndDir, defaultLetsEncryptDirname)
277

278
        defaultBtcdDir         = btcutil.AppDataDir(btcdBackendName, false)
279
        defaultBtcdRPCCertFile = filepath.Join(defaultBtcdDir, "rpc.cert")
280

281
        defaultBitcoindDir = btcutil.AppDataDir(BitcoinChainName, false)
282

283
        defaultTorSOCKS   = net.JoinHostPort("localhost", strconv.Itoa(defaultTorSOCKSPort))
284
        defaultTorDNS     = net.JoinHostPort(defaultTorDNSHost, strconv.Itoa(defaultTorDNSPort))
285
        defaultTorControl = net.JoinHostPort("localhost", strconv.Itoa(defaultTorControlPort))
286

287
        // bitcoindEsimateModes defines all the legal values for bitcoind's
288
        // estimatesmartfee RPC call.
289
        defaultBitcoindEstimateMode = "CONSERVATIVE"
290
        bitcoindEstimateModes       = [2]string{"ECONOMICAL", defaultBitcoindEstimateMode}
291
)
292

293
// Config defines the configuration options for lnd.
294
//
295
// See LoadConfig for further details regarding the configuration
296
// loading+parsing process.
297
//
298
//nolint:ll
299
type Config struct {
300
        ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
301

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

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

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

325
        LetsEncryptDir    string `long:"letsencryptdir" description:"The directory to store Let's Encrypt certificates within"`
326
        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."`
327
        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."`
328

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

354
        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"`
355

356
        CPUProfile      string `long:"cpuprofile" description:"DEPRECATED: Use 'pprof.cpuprofile' option. Write CPU profile to the specified file" hidden:"true"`
357
        Profile         string `long:"profile" description:"DEPRECATED: Use 'pprof.profile' option. Enable HTTP profiling on either a port or host:port" hidden:"true"`
358
        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"`
359
        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"`
360

361
        Pprof *lncfg.Pprof `group:"Pprof" namespace:"pprof"`
362

363
        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"`
364
        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."`
365
        MaxPendingChannels int    `long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer."`
366
        BackupFilePath     string `long:"backupfilepath" description:"The target location of the channel backup file"`
367

368
        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."`
369

370
        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"`
371

372
        Bitcoin      *lncfg.Chain    `group:"Bitcoin" namespace:"bitcoin"`
373
        BtcdMode     *lncfg.Btcd     `group:"btcd" namespace:"btcd"`
374
        BitcoindMode *lncfg.Bitcoind `group:"bitcoind" namespace:"bitcoind"`
375
        NeutrinoMode *lncfg.Neutrino `group:"neutrino" namespace:"neutrino"`
376

377
        BlockCacheSize uint64 `long:"blockcachesize" description:"The maximum capacity of the block cache"`
378

379
        Autopilot *lncfg.AutoPilot `group:"Autopilot" namespace:"autopilot"`
380

381
        Tor *lncfg.Tor `group:"Tor" namespace:"tor"`
382

383
        SubRPCServers *subRPCServerConfigs `group:"subrpc"`
384

385
        Hodl *hodl.Config `group:"hodl" namespace:"hodl"`
386

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

389
        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."`
390
        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."`
391
        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."`
392

393
        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."`
394

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

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

409
        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."`
410

411
        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."`
412

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

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

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

419
        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."`
420

421
        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."`
422
        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."`
423

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

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

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

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

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

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

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

440
        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]."`
441

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

444
        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."`
445

446
        net tor.Net
447

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

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

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

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

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

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

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

462
        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."`
463

464
        Fee *lncfg.Fee `group:"fee" namespace:"fee"`
465

466
        Invoices *lncfg.Invoices `group:"invoices" namespace:"invoices"`
467

468
        Routing *lncfg.Routing `group:"routing" namespace:"routing"`
469

470
        Gossip *lncfg.Gossip `group:"gossip" namespace:"gossip"`
471

472
        Workers *lncfg.Workers `group:"workers" namespace:"workers"`
473

474
        Caches *lncfg.Caches `group:"caches" namespace:"caches"`
475

476
        Prometheus lncfg.Prometheus `group:"prometheus" namespace:"prometheus"`
477

478
        WtClient *lncfg.WtClient `group:"wtclient" namespace:"wtclient"`
479

480
        Watchtower *lncfg.Watchtower `group:"watchtower" namespace:"watchtower"`
481

482
        ProtocolOptions *lncfg.ProtocolOptions `group:"protocol" namespace:"protocol"`
483

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

486
        HealthChecks *lncfg.HealthCheckConfig `group:"healthcheck" namespace:"healthcheck"`
487

488
        DB *lncfg.DB `group:"db" namespace:"db"`
489

490
        Cluster *lncfg.Cluster `group:"cluster" namespace:"cluster"`
491

492
        RPCMiddleware *lncfg.RPCMiddleware `group:"rpcmiddleware" namespace:"rpcmiddleware"`
493

494
        RemoteSigner *lncfg.RemoteSigner `group:"remotesigner" namespace:"remotesigner"`
495

496
        Sweeper *lncfg.Sweeper `group:"sweeper" namespace:"sweeper"`
497

498
        Htlcswitch *lncfg.Htlcswitch `group:"htlcswitch" namespace:"htlcswitch"`
499

500
        GRPC *GRPCConfig `group:"grpc" namespace:"grpc"`
501

502
        // SubLogMgr is the root logger that all the daemon's subloggers are
503
        // hooked up to.
504
        SubLogMgr  *build.SubLoggerManager
505
        LogRotator *build.RotatingLogWriter
506
        LogConfig  *build.LogConfig `group:"logging" namespace:"logging"`
507

508
        // networkDir is the path to the directory of the currently active
509
        // network. This path will hold the files related to each different
510
        // network.
511
        networkDir string
512

513
        // ActiveNetParams contains parameters of the target chain.
514
        ActiveNetParams chainreg.BitcoinNetParams
515

516
        // Estimator is used to estimate routing probabilities.
517
        Estimator routing.Estimator
518

519
        // Dev specifies configs used for integration tests, which is always
520
        // empty if not built with `integration` flag.
521
        Dev *lncfg.DevConfig `group:"dev" namespace:"dev"`
522

523
        // HTTPHeaderTimeout is the maximum duration that the server will wait
524
        // before timing out reading the headers of an HTTP request.
525
        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."`
526

527
        // NumRestrictedSlots is the number of restricted slots we'll allocate
528
        // in the server.
529
        NumRestrictedSlots uint64 `long:"num-restricted-slots" description:"The number of restricted slots we'll allocate in the server."`
530
}
531

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

545
        // ServerPingTimeout is the duration the server waits after having
546
        // pinged for keepalive check, and if no activity is seen even after
547
        // that the connection is closed.
548
        ServerPingTimeout time.Duration `long:"server-ping-timeout" description:"How long the server waits for the response from the client for the keepalive ping response."`
549

550
        // ClientPingMinWait is the minimum amount of time a client should wait
551
        // before sending a keepalive ping.
552
        ClientPingMinWait time.Duration `long:"client-ping-min-wait" description:"The minimum amount of time the client should wait before sending a keepalive ping."`
553

554
        // ClientAllowPingWithoutStream specifies whether pings from the client
555
        // are allowed even if there are no active gRPC streams. This might be
556
        // useful to keep the underlying HTTP/2 connection open for future
557
        // requests.
558
        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."`
559
}
560

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

3✔
612
                Fee: &lncfg.Fee{
3✔
613
                        MinUpdateTimeout: lncfg.DefaultMinUpdateTimeout,
3✔
614
                        MaxUpdateTimeout: lncfg.DefaultMaxUpdateTimeout,
3✔
615
                },
3✔
616

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

755
// LoadConfig initializes and parses the config using a config file and command
756
// line options.
757
//
758
// The configuration proceeds as follows:
759
//  1. Start with a default config with sane settings
760
//  2. Pre-parse the command line to check for an alternative config file
761
//  3. Load configuration file overwriting defaults with any specified options
762
//  4. Parse CLI options and overwrite/add any specified options
763
func LoadConfig(interceptor signal.Interceptor) (*Config, error) {
3✔
764
        // Pre-parse the command line options to pick up an alternative config
3✔
765
        // file.
3✔
766
        preCfg := DefaultConfig()
3✔
767
        if _, err := flags.Parse(&preCfg); err != nil {
3✔
768
                return nil, err
×
769
        }
×
770

771
        // Show the version and exit if the version flag was specified.
772
        appName := filepath.Base(os.Args[0])
3✔
773
        appName = strings.TrimSuffix(appName, filepath.Ext(appName))
3✔
774
        usageMessage := fmt.Sprintf("Use %s -h to show usage", appName)
3✔
775
        if preCfg.ShowVersion {
3✔
776
                fmt.Println(appName, "version", build.Version(),
×
777
                        "commit="+build.Commit)
×
778
                os.Exit(0)
×
779
        }
×
780

781
        // If the config file path has not been modified by the user, then we'll
782
        // use the default config file path. However, if the user has modified
783
        // their lnddir, then we should assume they intend to use the config
784
        // file within it.
785
        configFileDir := CleanAndExpandPath(preCfg.LndDir)
3✔
786
        configFilePath := CleanAndExpandPath(preCfg.ConfigFile)
3✔
787
        switch {
3✔
788
        // User specified --lnddir but no --configfile. Update the config file
789
        // path to the lnd config directory, but don't require it to exist.
790
        case configFileDir != DefaultLndDir &&
791
                configFilePath == DefaultConfigFile:
3✔
792

3✔
793
                configFilePath = filepath.Join(
3✔
794
                        configFileDir, lncfg.DefaultConfigFilename,
3✔
795
                )
3✔
796

797
        // User did specify an explicit --configfile, so we check that it does
798
        // exist under that path to avoid surprises.
799
        case configFilePath != DefaultConfigFile:
×
800
                if !lnrpc.FileExists(configFilePath) {
×
801
                        return nil, fmt.Errorf("specified config file does "+
×
802
                                "not exist in %s", configFilePath)
×
803
                }
×
804
        }
805

806
        // Next, load any additional configuration options from the file.
807
        var configFileError error
3✔
808
        cfg := preCfg
3✔
809
        fileParser := flags.NewParser(&cfg, flags.Default)
3✔
810
        err := flags.NewIniParser(fileParser).ParseFile(configFilePath)
3✔
811
        if err != nil {
6✔
812
                // If it's a parsing related error, then we'll return
3✔
813
                // immediately, otherwise we can proceed as possibly the config
3✔
814
                // file doesn't exist which is OK.
3✔
815
                if lnutils.ErrorAs[*flags.IniError](err) ||
3✔
816
                        lnutils.ErrorAs[*flags.Error](err) {
3✔
817

×
818
                        return nil, err
×
819
                }
×
820

821
                configFileError = err
3✔
822
        }
823

824
        // Finally, parse the remaining command line options again to ensure
825
        // they take precedence.
826
        flagParser := flags.NewParser(&cfg, flags.Default)
3✔
827
        if _, err := flagParser.Parse(); err != nil {
3✔
828
                return nil, err
×
829
        }
×
830

831
        // Make sure everything we just loaded makes sense.
832
        cleanCfg, err := ValidateConfig(
3✔
833
                cfg, interceptor, fileParser, flagParser,
3✔
834
        )
3✔
835
        var usageErr *lncfg.UsageError
3✔
836
        if errors.As(err, &usageErr) {
3✔
837
                // The logging system might not yet be initialized, so we also
×
838
                // write to stderr to make sure the error appears somewhere.
×
839
                _, _ = fmt.Fprintln(os.Stderr, usageMessage)
×
840
                ltndLog.Warnf("Incorrect usage: %v", usageMessage)
×
841

×
842
                // The log subsystem might not yet be initialized. But we still
×
843
                // try to log the error there since some packaging solutions
×
844
                // might only look at the log and not stdout/stderr.
×
845
                ltndLog.Warnf("Error validating config: %v", err)
×
846

×
847
                return nil, err
×
848
        }
×
849
        if err != nil {
3✔
850
                // The log subsystem might not yet be initialized. But we still
×
851
                // try to log the error there since some packaging solutions
×
852
                // might only look at the log and not stdout/stderr.
×
853
                ltndLog.Warnf("Error validating config: %v", err)
×
854

×
855
                return nil, err
×
856
        }
×
857

858
        // Warn about missing config file only after all other configuration is
859
        // done. This prevents the warning on help messages and invalid options.
860
        // Note this should go directly before the return.
861
        if configFileError != nil {
6✔
862
                ltndLog.Warnf("%v", configFileError)
3✔
863
        }
3✔
864

865
        // Finally, log warnings for deprecated config options if they are set.
866
        logWarningsForDeprecation(*cleanCfg)
3✔
867

3✔
868
        return cleanCfg, nil
3✔
869
}
870

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

3✔
877
        // Special show command to list supported subsystems and exit.
3✔
878
        if cfg.DebugLevel == "show" {
6✔
879
                subLogMgr := build.NewSubLoggerManager()
3✔
880

3✔
881
                // Initialize logging at the default logging level.
3✔
882
                SetupLoggers(subLogMgr, interceptor)
3✔
883

3✔
884
                fmt.Println("Supported subsystems",
3✔
885
                        subLogMgr.SupportedSubsystems())
3✔
886
                os.Exit(0)
3✔
887
        }
3✔
888

889
        // If the provided lnd directory is not the default, we'll modify the
890
        // path to all of the files and directories that will live within it.
891
        lndDir := CleanAndExpandPath(cfg.LndDir)
3✔
892
        if lndDir != DefaultLndDir {
6✔
893
                cfg.DataDir = filepath.Join(lndDir, defaultDataDirname)
3✔
894
                cfg.LetsEncryptDir = filepath.Join(
3✔
895
                        lndDir, defaultLetsEncryptDirname,
3✔
896
                )
3✔
897
                cfg.TLSCertPath = filepath.Join(lndDir, defaultTLSCertFilename)
3✔
898
                cfg.TLSKeyPath = filepath.Join(lndDir, defaultTLSKeyFilename)
3✔
899
                cfg.LogDir = filepath.Join(lndDir, defaultLogDirname)
3✔
900

3✔
901
                // If the watchtower's directory is set to the default, i.e. the
3✔
902
                // user has not requested a different location, we'll move the
3✔
903
                // location to be relative to the specified lnd directory.
3✔
904
                if cfg.Watchtower.TowerDir == defaultTowerDir {
6✔
905
                        cfg.Watchtower.TowerDir = filepath.Join(
3✔
906
                                cfg.DataDir, defaultTowerSubDirname,
3✔
907
                        )
3✔
908
                }
3✔
909
        }
910

911
        funcName := "ValidateConfig"
3✔
912
        mkErr := func(format string, args ...interface{}) error {
3✔
913
                return fmt.Errorf(funcName+": "+format, args...)
×
914
        }
×
915
        makeDirectory := func(dir string) error {
6✔
916
                err := os.MkdirAll(dir, 0700)
3✔
917
                if err != nil {
3✔
918
                        // Show a nicer error message if it's because a symlink
×
919
                        // is linked to a directory that does not exist
×
920
                        // (probably because it's not mounted).
×
921
                        if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
×
922
                                link, lerr := os.Readlink(e.Path)
×
923
                                if lerr == nil {
×
924
                                        str := "is symlink %s -> %s mounted?"
×
925
                                        err = fmt.Errorf(str, e.Path, link)
×
926
                                }
×
927
                        }
928

929
                        str := "Failed to create lnd directory '%s': %v"
×
930
                        return mkErr(str, dir, err)
×
931
                }
932

933
                return nil
3✔
934
        }
935

936
        // IsSet returns true if an option has been set in either the config
937
        // file or by a flag.
938
        isSet := func(field string) (bool, error) {
6✔
939
                fieldName, ok := reflect.TypeOf(Config{}).FieldByName(field)
3✔
940
                if !ok {
3✔
941
                        str := "could not find field %s"
×
942
                        return false, mkErr(str, field)
×
943
                }
×
944

945
                long, ok := fieldName.Tag.Lookup("long")
3✔
946
                if !ok {
3✔
947
                        str := "field %s does not have a long tag"
×
948
                        return false, mkErr(str, field)
×
949
                }
×
950

951
                // The user has the option to set the flag in either the config
952
                // file or as a command line flag. If any is set, we consider it
953
                // to be set, not applying any precedence rules here (since it
954
                // is a boolean the default is false anyway which would screw up
955
                // any precedence rules). Additionally, we need to also support
956
                // the use case where the config struct is embedded _within_
957
                // another struct with a prefix (as is the case with
958
                // lightning-terminal).
959
                fileOption := fileParser.FindOptionByLongName(long)
3✔
960
                fileOptionNested := fileParser.FindOptionByLongName(
3✔
961
                        "lnd." + long,
3✔
962
                )
3✔
963
                flagOption := flagParser.FindOptionByLongName(long)
3✔
964
                flagOptionNested := flagParser.FindOptionByLongName(
3✔
965
                        "lnd." + long,
3✔
966
                )
3✔
967

3✔
968
                return (fileOption != nil && fileOption.IsSet()) ||
3✔
969
                                (fileOptionNested != nil && fileOptionNested.IsSet()) ||
3✔
970
                                (flagOption != nil && flagOption.IsSet()) ||
3✔
971
                                (flagOptionNested != nil && flagOptionNested.IsSet()),
3✔
972
                        nil
3✔
973
        }
974

975
        // As soon as we're done parsing configuration options, ensure all paths
976
        // to directories and files are cleaned and expanded before attempting
977
        // to use them later on.
978
        cfg.DataDir = CleanAndExpandPath(cfg.DataDir)
3✔
979
        cfg.TLSCertPath = CleanAndExpandPath(cfg.TLSCertPath)
3✔
980
        cfg.TLSKeyPath = CleanAndExpandPath(cfg.TLSKeyPath)
3✔
981
        cfg.LetsEncryptDir = CleanAndExpandPath(cfg.LetsEncryptDir)
3✔
982
        cfg.AdminMacPath = CleanAndExpandPath(cfg.AdminMacPath)
3✔
983
        cfg.ReadMacPath = CleanAndExpandPath(cfg.ReadMacPath)
3✔
984
        cfg.InvoiceMacPath = CleanAndExpandPath(cfg.InvoiceMacPath)
3✔
985
        cfg.LogDir = CleanAndExpandPath(cfg.LogDir)
3✔
986
        cfg.BtcdMode.Dir = CleanAndExpandPath(cfg.BtcdMode.Dir)
3✔
987
        cfg.BitcoindMode.Dir = CleanAndExpandPath(cfg.BitcoindMode.Dir)
3✔
988
        cfg.BitcoindMode.ConfigPath = CleanAndExpandPath(
3✔
989
                cfg.BitcoindMode.ConfigPath,
3✔
990
        )
3✔
991
        cfg.BitcoindMode.RPCCookie = CleanAndExpandPath(cfg.BitcoindMode.RPCCookie)
3✔
992
        cfg.Tor.PrivateKeyPath = CleanAndExpandPath(cfg.Tor.PrivateKeyPath)
3✔
993
        cfg.Tor.WatchtowerKeyPath = CleanAndExpandPath(cfg.Tor.WatchtowerKeyPath)
3✔
994
        cfg.Watchtower.TowerDir = CleanAndExpandPath(cfg.Watchtower.TowerDir)
3✔
995
        cfg.BackupFilePath = CleanAndExpandPath(cfg.BackupFilePath)
3✔
996
        cfg.WalletUnlockPasswordFile = CleanAndExpandPath(
3✔
997
                cfg.WalletUnlockPasswordFile,
3✔
998
        )
3✔
999

3✔
1000
        // Ensure that the user didn't attempt to specify negative values for
3✔
1001
        // any of the autopilot params.
3✔
1002
        if cfg.Autopilot.MaxChannels < 0 {
3✔
1003
                str := "autopilot.maxchannels must be non-negative"
×
1004

×
1005
                return nil, mkErr(str)
×
1006
        }
×
1007
        if cfg.Autopilot.Allocation < 0 {
3✔
1008
                str := "autopilot.allocation must be non-negative"
×
1009

×
1010
                return nil, mkErr(str)
×
1011
        }
×
1012
        if cfg.Autopilot.MinChannelSize < 0 {
3✔
1013
                str := "autopilot.minchansize must be non-negative"
×
1014

×
1015
                return nil, mkErr(str)
×
1016
        }
×
1017
        if cfg.Autopilot.MaxChannelSize < 0 {
3✔
1018
                str := "autopilot.maxchansize must be non-negative"
×
1019

×
1020
                return nil, mkErr(str)
×
1021
        }
×
1022
        if cfg.Autopilot.MinConfs < 0 {
3✔
1023
                str := "autopilot.minconfs must be non-negative"
×
1024

×
1025
                return nil, mkErr(str)
×
1026
        }
×
1027
        if cfg.Autopilot.ConfTarget < 1 {
3✔
1028
                str := "autopilot.conftarget must be positive"
×
1029

×
1030
                return nil, mkErr(str)
×
1031
        }
×
1032

1033
        // Ensure that the specified values for the min and max channel size
1034
        // are within the bounds of the normal chan size constraints.
1035
        if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
3✔
1036
                cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
×
1037
        }
×
1038
        if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
3✔
1039
                cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
×
1040
        }
×
1041

1042
        if _, err := validateAtplCfg(cfg.Autopilot); err != nil {
3✔
1043
                return nil, mkErr("error validating autopilot: %v", err)
×
1044
        }
×
1045

1046
        // Ensure that --maxchansize is properly handled when set by user.
1047
        // For non-Wumbo channels this limit remains 16777215 satoshis by default
1048
        // as specified in BOLT-02. For wumbo channels this limit is 1,000,000,000.
1049
        // satoshis (10 BTC). Always enforce --maxchansize explicitly set by user.
1050
        // If unset (marked by 0 value), then enforce proper default.
1051
        if cfg.MaxChanSize == 0 {
6✔
1052
                if cfg.ProtocolOptions.Wumbo() {
6✔
1053
                        cfg.MaxChanSize = int64(funding.MaxBtcFundingAmountWumbo)
3✔
1054
                } else {
6✔
1055
                        cfg.MaxChanSize = int64(funding.MaxBtcFundingAmount)
3✔
1056
                }
3✔
1057
        }
1058

1059
        // Ensure that the user specified values for the min and max channel
1060
        // size make sense.
1061
        if cfg.MaxChanSize < cfg.MinChanSize {
3✔
1062
                return nil, mkErr("invalid channel size parameters: "+
×
1063
                        "max channel size %v, must be no less than min chan "+
×
1064
                        "size %v", cfg.MaxChanSize, cfg.MinChanSize,
×
1065
                )
×
1066
        }
×
1067

1068
        // Don't allow superfluous --maxchansize greater than
1069
        // BOLT 02 soft-limit for non-wumbo channel
1070
        if !cfg.ProtocolOptions.Wumbo() &&
3✔
1071
                cfg.MaxChanSize > int64(MaxFundingAmount) {
3✔
1072

×
1073
                return nil, mkErr("invalid channel size parameters: "+
×
1074
                        "maximum channel size %v is greater than maximum "+
×
1075
                        "non-wumbo channel size %v", cfg.MaxChanSize,
×
1076
                        MaxFundingAmount,
×
1077
                )
×
1078
        }
×
1079

1080
        // Ensure that the amount data for revoked commitment transactions is
1081
        // stored if the watchtower client is active.
1082
        if cfg.DB.NoRevLogAmtData && cfg.WtClient.Active {
3✔
1083
                return nil, mkErr("revocation log amount data must be stored " +
×
1084
                        "if the watchtower client is active")
×
1085
        }
×
1086

1087
        // Ensure a valid max channel fee allocation was set.
1088
        if cfg.MaxChannelFeeAllocation <= 0 || cfg.MaxChannelFeeAllocation > 1 {
3✔
1089
                return nil, mkErr("invalid max channel fee allocation: %v, "+
×
1090
                        "must be within (0, 1]", cfg.MaxChannelFeeAllocation)
×
1091
        }
×
1092

1093
        if cfg.MaxCommitFeeRateAnchors < 1 {
3✔
1094
                return nil, mkErr("invalid max commit fee rate anchors: %v, "+
×
1095
                        "must be at least 1 sat/vByte",
×
1096
                        cfg.MaxCommitFeeRateAnchors)
×
1097
        }
×
1098

1099
        // Validate the Tor config parameters.
1100
        socks, err := lncfg.ParseAddressString(
3✔
1101
                cfg.Tor.SOCKS, strconv.Itoa(defaultTorSOCKSPort),
3✔
1102
                cfg.net.ResolveTCPAddr,
3✔
1103
        )
3✔
1104
        if err != nil {
3✔
1105
                return nil, err
×
1106
        }
×
1107
        cfg.Tor.SOCKS = socks.String()
3✔
1108

3✔
1109
        // We'll only attempt to normalize and resolve the DNS host if it hasn't
3✔
1110
        // changed, as it doesn't need to be done for the default.
3✔
1111
        if cfg.Tor.DNS != defaultTorDNS {
3✔
1112
                dns, err := lncfg.ParseAddressString(
×
1113
                        cfg.Tor.DNS, strconv.Itoa(defaultTorDNSPort),
×
1114
                        cfg.net.ResolveTCPAddr,
×
1115
                )
×
1116
                if err != nil {
×
1117
                        return nil, mkErr("error parsing tor dns: %v", err)
×
1118
                }
×
1119
                cfg.Tor.DNS = dns.String()
×
1120
        }
1121

1122
        control, err := lncfg.ParseAddressString(
3✔
1123
                cfg.Tor.Control, strconv.Itoa(defaultTorControlPort),
3✔
1124
                cfg.net.ResolveTCPAddr,
3✔
1125
        )
3✔
1126
        if err != nil {
3✔
1127
                return nil, mkErr("error parsing tor control address: %v", err)
×
1128
        }
×
1129
        cfg.Tor.Control = control.String()
3✔
1130

3✔
1131
        // Ensure that tor socks host:port is not equal to tor control
3✔
1132
        // host:port. This would lead to lnd not starting up properly.
3✔
1133
        if cfg.Tor.SOCKS == cfg.Tor.Control {
3✔
1134
                str := "tor.socks and tor.control can not us the same host:port"
×
1135

×
1136
                return nil, mkErr(str)
×
1137
        }
×
1138

1139
        switch {
3✔
1140
        case cfg.Tor.V2 && cfg.Tor.V3:
×
1141
                return nil, mkErr("either tor.v2 or tor.v3 can be set, " +
×
1142
                        "but not both")
×
1143
        case cfg.DisableListen && (cfg.Tor.V2 || cfg.Tor.V3):
×
1144
                return nil, mkErr("listening must be enabled when enabling " +
×
1145
                        "inbound connections over Tor")
×
1146
        }
1147

1148
        if cfg.Tor.PrivateKeyPath == "" {
6✔
1149
                switch {
3✔
1150
                case cfg.Tor.V2:
×
1151
                        cfg.Tor.PrivateKeyPath = filepath.Join(
×
1152
                                lndDir, defaultTorV2PrivateKeyFilename,
×
1153
                        )
×
1154
                case cfg.Tor.V3:
×
1155
                        cfg.Tor.PrivateKeyPath = filepath.Join(
×
1156
                                lndDir, defaultTorV3PrivateKeyFilename,
×
1157
                        )
×
1158
                }
1159
        }
1160

1161
        if cfg.Tor.WatchtowerKeyPath == "" {
6✔
1162
                switch {
3✔
1163
                case cfg.Tor.V2:
×
1164
                        cfg.Tor.WatchtowerKeyPath = filepath.Join(
×
1165
                                cfg.Watchtower.TowerDir,
×
1166
                                defaultTorV2PrivateKeyFilename,
×
1167
                        )
×
1168
                case cfg.Tor.V3:
×
1169
                        cfg.Tor.WatchtowerKeyPath = filepath.Join(
×
1170
                                cfg.Watchtower.TowerDir,
×
1171
                                defaultTorV3PrivateKeyFilename,
×
1172
                        )
×
1173
                }
1174
        }
1175

1176
        // Set up the network-related functions that will be used throughout
1177
        // the daemon. We use the standard Go "net" package functions by
1178
        // default. If we should be proxying all traffic through Tor, then
1179
        // we'll use the Tor proxy specific functions in order to avoid leaking
1180
        // our real information.
1181
        if cfg.Tor.Active {
3✔
1182
                cfg.net = &tor.ProxyNet{
×
1183
                        SOCKS:                       cfg.Tor.SOCKS,
×
1184
                        DNS:                         cfg.Tor.DNS,
×
1185
                        StreamIsolation:             cfg.Tor.StreamIsolation,
×
1186
                        SkipProxyForClearNetTargets: cfg.Tor.SkipProxyForClearNetTargets,
×
1187
                }
×
1188
        }
×
1189

1190
        if cfg.DisableListen && cfg.NAT {
3✔
1191
                return nil, mkErr("NAT traversal cannot be used when " +
×
1192
                        "listening is disabled")
×
1193
        }
×
1194
        if cfg.NAT && len(cfg.ExternalHosts) != 0 {
3✔
1195
                return nil, mkErr("NAT support and externalhosts are " +
×
1196
                        "mutually exclusive, only one should be selected")
×
1197
        }
×
1198

1199
        // Multiple networks can't be selected simultaneously.  Count
1200
        // number of network flags passed; assign active network params
1201
        // while we're at it.
1202
        numNets := 0
3✔
1203
        if cfg.Bitcoin.MainNet {
3✔
1204
                numNets++
×
1205
                cfg.ActiveNetParams = chainreg.BitcoinMainNetParams
×
1206
        }
×
1207
        if cfg.Bitcoin.TestNet3 {
3✔
1208
                numNets++
×
1209
                cfg.ActiveNetParams = chainreg.BitcoinTestNetParams
×
1210
        }
×
1211
        if cfg.Bitcoin.RegTest {
6✔
1212
                numNets++
3✔
1213
                cfg.ActiveNetParams = chainreg.BitcoinRegTestNetParams
3✔
1214
        }
3✔
1215
        if cfg.Bitcoin.SimNet {
3✔
1216
                numNets++
×
1217
                cfg.ActiveNetParams = chainreg.BitcoinSimNetParams
×
1218

×
1219
                // For simnet, the btcsuite chain params uses a
×
1220
                // cointype of 115. However, we override this in
×
1221
                // chainreg/chainparams.go, but the raw ChainParam
×
1222
                // field is used elsewhere. To ensure everything is
×
1223
                // consistent, we'll also override the cointype within
×
1224
                // the raw params.
×
1225
                targetCoinType := chainreg.BitcoinSigNetParams.CoinType
×
1226
                cfg.ActiveNetParams.Params.HDCoinType = targetCoinType
×
1227
        }
×
1228
        if cfg.Bitcoin.SigNet {
3✔
1229
                numNets++
×
1230
                cfg.ActiveNetParams = chainreg.BitcoinSigNetParams
×
1231

×
1232
                // Let the user overwrite the default signet parameters.
×
1233
                // The challenge defines the actual signet network to
×
1234
                // join and the seed nodes are needed for network
×
1235
                // discovery.
×
1236
                sigNetChallenge := chaincfg.DefaultSignetChallenge
×
1237
                sigNetSeeds := chaincfg.DefaultSignetDNSSeeds
×
1238
                if cfg.Bitcoin.SigNetChallenge != "" {
×
1239
                        challenge, err := hex.DecodeString(
×
1240
                                cfg.Bitcoin.SigNetChallenge,
×
1241
                        )
×
1242
                        if err != nil {
×
1243
                                return nil, mkErr("Invalid "+
×
1244
                                        "signet challenge, hex decode "+
×
1245
                                        "failed: %v", err)
×
1246
                        }
×
1247
                        sigNetChallenge = challenge
×
1248
                }
1249

1250
                if len(cfg.Bitcoin.SigNetSeedNode) > 0 {
×
1251
                        sigNetSeeds = make([]chaincfg.DNSSeed, len(
×
1252
                                cfg.Bitcoin.SigNetSeedNode,
×
1253
                        ))
×
1254
                        for idx, seed := range cfg.Bitcoin.SigNetSeedNode {
×
1255
                                sigNetSeeds[idx] = chaincfg.DNSSeed{
×
1256
                                        Host:         seed,
×
1257
                                        HasFiltering: false,
×
1258
                                }
×
1259
                        }
×
1260
                }
1261

1262
                chainParams := chaincfg.CustomSignetParams(
×
1263
                        sigNetChallenge, sigNetSeeds,
×
1264
                )
×
1265
                cfg.ActiveNetParams.Params = &chainParams
×
1266
        }
1267
        if numNets > 1 {
3✔
1268
                str := "The mainnet, testnet, regtest, simnet and signet " +
×
1269
                        "params can't be used together -- choose one " +
×
1270
                        "of the five"
×
1271

×
1272
                return nil, mkErr(str)
×
1273
        }
×
1274

1275
        // The target network must be provided, otherwise, we won't
1276
        // know how to initialize the daemon.
1277
        if numNets == 0 {
3✔
1278
                str := "either --bitcoin.mainnet, or bitcoin.testnet, " +
×
1279
                        "bitcoin.simnet, bitcoin.regtest or bitcoin.signet " +
×
1280
                        "must be specified"
×
1281

×
1282
                return nil, mkErr(str)
×
1283
        }
×
1284

1285
        err = cfg.Bitcoin.Validate(minTimeLockDelta, funding.MinBtcRemoteDelay)
3✔
1286
        if err != nil {
3✔
1287
                return nil, mkErr("error validating bitcoin params: %v", err)
×
1288
        }
×
1289

1290
        switch cfg.Bitcoin.Node {
3✔
1291
        case btcdBackendName:
1✔
1292
                err := parseRPCParams(
1✔
1293
                        cfg.Bitcoin, cfg.BtcdMode, cfg.ActiveNetParams,
1✔
1294
                )
1✔
1295
                if err != nil {
1✔
1296
                        return nil, mkErr("unable to load RPC "+
×
1297
                                "credentials for btcd: %v", err)
×
1298
                }
×
1299
        case bitcoindBackendName:
1✔
1300
                if cfg.Bitcoin.SimNet {
1✔
1301
                        return nil, mkErr("bitcoind does not " +
×
1302
                                "support simnet")
×
1303
                }
×
1304

1305
                err := parseRPCParams(
1✔
1306
                        cfg.Bitcoin, cfg.BitcoindMode, cfg.ActiveNetParams,
1✔
1307
                )
1✔
1308
                if err != nil {
1✔
1309
                        return nil, mkErr("unable to load RPC "+
×
1310
                                "credentials for bitcoind: %v", err)
×
1311
                }
×
1312
        case neutrinoBackendName:
1✔
1313
                // No need to get RPC parameters.
1314

1315
        case "nochainbackend":
×
1316
                // Nothing to configure, we're running without any chain
1317
                // backend whatsoever (pure signing mode).
1318

1319
        default:
×
1320
                str := "only btcd, bitcoind, and neutrino mode " +
×
1321
                        "supported for bitcoin at this time"
×
1322

×
1323
                return nil, mkErr(str)
×
1324
        }
1325

1326
        cfg.Bitcoin.ChainDir = filepath.Join(
3✔
1327
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
3✔
1328
        )
3✔
1329

3✔
1330
        // Ensure that the user didn't attempt to specify negative values for
3✔
1331
        // any of the autopilot params.
3✔
1332
        if cfg.Autopilot.MaxChannels < 0 {
3✔
1333
                str := "autopilot.maxchannels must be non-negative"
×
1334

×
1335
                return nil, mkErr(str)
×
1336
        }
×
1337
        if cfg.Autopilot.Allocation < 0 {
3✔
1338
                str := "autopilot.allocation must be non-negative"
×
1339

×
1340
                return nil, mkErr(str)
×
1341
        }
×
1342
        if cfg.Autopilot.MinChannelSize < 0 {
3✔
1343
                str := "autopilot.minchansize must be non-negative"
×
1344

×
1345
                return nil, mkErr(str)
×
1346
        }
×
1347
        if cfg.Autopilot.MaxChannelSize < 0 {
3✔
1348
                str := "autopilot.maxchansize must be non-negative"
×
1349

×
1350
                return nil, mkErr(str)
×
1351
        }
×
1352

1353
        // Ensure that the specified values for the min and max channel size
1354
        // don't are within the bounds of the normal chan size constraints.
1355
        if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
3✔
1356
                cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
×
1357
        }
×
1358
        if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
3✔
1359
                cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
×
1360
        }
×
1361

1362
        // We'll now construct the network directory which will be where we
1363
        // store all the data specific to this chain/network.
1364
        cfg.networkDir = filepath.Join(
3✔
1365
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
3✔
1366
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1367
        )
3✔
1368

3✔
1369
        // If a custom macaroon directory wasn't specified and the data
3✔
1370
        // directory has changed from the default path, then we'll also update
3✔
1371
        // the path for the macaroons to be generated.
3✔
1372
        if cfg.AdminMacPath == "" {
3✔
1373
                cfg.AdminMacPath = filepath.Join(
×
1374
                        cfg.networkDir, defaultAdminMacFilename,
×
1375
                )
×
1376
        }
×
1377
        if cfg.ReadMacPath == "" {
3✔
1378
                cfg.ReadMacPath = filepath.Join(
×
1379
                        cfg.networkDir, defaultReadMacFilename,
×
1380
                )
×
1381
        }
×
1382
        if cfg.InvoiceMacPath == "" {
3✔
1383
                cfg.InvoiceMacPath = filepath.Join(
×
1384
                        cfg.networkDir, defaultInvoiceMacFilename,
×
1385
                )
×
1386
        }
×
1387

1388
        towerDir := filepath.Join(
3✔
1389
                cfg.Watchtower.TowerDir, BitcoinChainName,
3✔
1390
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1391
        )
3✔
1392

3✔
1393
        // Create the lnd directory and all other sub-directories if they don't
3✔
1394
        // already exist. This makes sure that directory trees are also created
3✔
1395
        // for files that point to outside the lnddir.
3✔
1396
        dirs := []string{
3✔
1397
                lndDir, cfg.DataDir, cfg.networkDir,
3✔
1398
                cfg.LetsEncryptDir, towerDir, cfg.graphDatabaseDir(),
3✔
1399
                filepath.Dir(cfg.TLSCertPath), filepath.Dir(cfg.TLSKeyPath),
3✔
1400
                filepath.Dir(cfg.AdminMacPath), filepath.Dir(cfg.ReadMacPath),
3✔
1401
                filepath.Dir(cfg.InvoiceMacPath),
3✔
1402
                filepath.Dir(cfg.Tor.PrivateKeyPath),
3✔
1403
                filepath.Dir(cfg.Tor.WatchtowerKeyPath),
3✔
1404
        }
3✔
1405
        for _, dir := range dirs {
6✔
1406
                if err := makeDirectory(dir); err != nil {
3✔
1407
                        return nil, err
×
1408
                }
×
1409
        }
1410

1411
        // Similarly, if a custom back up file path wasn't specified, then
1412
        // we'll update the file location to match our set network directory.
1413
        if cfg.BackupFilePath == "" {
6✔
1414
                cfg.BackupFilePath = filepath.Join(
3✔
1415
                        cfg.networkDir, chanbackup.DefaultBackupFileName,
3✔
1416
                )
3✔
1417
        }
3✔
1418

1419
        // Append the network type to the log directory so it is "namespaced"
1420
        // per network in the same fashion as the data directory.
1421
        cfg.LogDir = filepath.Join(
3✔
1422
                cfg.LogDir, BitcoinChainName,
3✔
1423
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1424
        )
3✔
1425

3✔
1426
        if err := cfg.LogConfig.Validate(); err != nil {
3✔
1427
                return nil, mkErr("error validating logging config: %w", err)
×
1428
        }
×
1429

1430
        // If a sub-log manager was not already created, then we'll create one
1431
        // now using the default log handlers.
1432
        if cfg.SubLogMgr == nil {
6✔
1433
                cfg.SubLogMgr = build.NewSubLoggerManager(
3✔
1434
                        build.NewDefaultLogHandlers(
3✔
1435
                                cfg.LogConfig, cfg.LogRotator,
3✔
1436
                        )...,
3✔
1437
                )
3✔
1438
        }
3✔
1439

1440
        // Initialize logging at the default logging level.
1441
        SetupLoggers(cfg.SubLogMgr, interceptor)
3✔
1442

3✔
1443
        if cfg.MaxLogFiles != 0 {
3✔
1444
                if cfg.LogConfig.File.MaxLogFiles !=
×
1445
                        build.DefaultMaxLogFiles {
×
1446

×
1447
                        return nil, mkErr("cannot set both maxlogfiles and "+
×
1448
                                "logging.file.max-files", err)
×
1449
                }
×
1450

1451
                cfg.LogConfig.File.MaxLogFiles = cfg.MaxLogFiles
×
1452
        }
1453
        if cfg.MaxLogFileSize != 0 {
3✔
1454
                if cfg.LogConfig.File.MaxLogFileSize !=
×
1455
                        build.DefaultMaxLogFileSize {
×
1456

×
1457
                        return nil, mkErr("cannot set both maxlogfilesize and "+
×
1458
                                "logging.file.max-file-size", err)
×
1459
                }
×
1460

1461
                cfg.LogConfig.File.MaxLogFileSize = cfg.MaxLogFileSize
×
1462
        }
1463

1464
        err = cfg.LogRotator.InitLogRotator(
3✔
1465
                cfg.LogConfig.File,
3✔
1466
                filepath.Join(cfg.LogDir, defaultLogFilename),
3✔
1467
        )
3✔
1468
        if err != nil {
3✔
1469
                str := "log rotation setup failed: %v"
×
1470
                return nil, mkErr(str, err)
×
1471
        }
×
1472

1473
        // Parse, validate, and set debug log level(s).
1474
        err = build.ParseAndSetDebugLevels(cfg.DebugLevel, cfg.SubLogMgr)
3✔
1475
        if err != nil {
3✔
1476
                str := "error parsing debug level: %v"
×
1477
                return nil, &lncfg.UsageError{Err: mkErr(str, err)}
×
1478
        }
×
1479

1480
        // At least one RPCListener is required. So listen on localhost per
1481
        // default.
1482
        if len(cfg.RawRPCListeners) == 0 {
3✔
1483
                addr := fmt.Sprintf("localhost:%d", defaultRPCPort)
×
1484
                cfg.RawRPCListeners = append(cfg.RawRPCListeners, addr)
×
1485
        }
×
1486

1487
        // Listen on localhost if no REST listeners were specified.
1488
        if len(cfg.RawRESTListeners) == 0 {
3✔
1489
                addr := fmt.Sprintf("localhost:%d", defaultRESTPort)
×
1490
                cfg.RawRESTListeners = append(cfg.RawRESTListeners, addr)
×
1491
        }
×
1492

1493
        // Listen on the default interface/port if no listeners were specified.
1494
        // An empty address string means default interface/address, which on
1495
        // most unix systems is the same as 0.0.0.0. If Tor is active, we
1496
        // default to only listening on localhost for hidden service
1497
        // connections.
1498
        if len(cfg.RawListeners) == 0 {
3✔
1499
                addr := fmt.Sprintf(":%d", defaultPeerPort)
×
1500
                if cfg.Tor.Active && !cfg.Tor.SkipProxyForClearNetTargets {
×
1501
                        addr = fmt.Sprintf("localhost:%d", defaultPeerPort)
×
1502
                }
×
1503
                cfg.RawListeners = append(cfg.RawListeners, addr)
×
1504
        }
1505

1506
        // Add default port to all RPC listener addresses if needed and remove
1507
        // duplicate addresses.
1508
        cfg.RPCListeners, err = lncfg.NormalizeAddresses(
3✔
1509
                cfg.RawRPCListeners, strconv.Itoa(defaultRPCPort),
3✔
1510
                cfg.net.ResolveTCPAddr,
3✔
1511
        )
3✔
1512
        if err != nil {
3✔
1513
                return nil, mkErr("error normalizing RPC listen addrs: %v", err)
×
1514
        }
×
1515

1516
        // Add default port to all REST listener addresses if needed and remove
1517
        // duplicate addresses.
1518
        cfg.RESTListeners, err = lncfg.NormalizeAddresses(
3✔
1519
                cfg.RawRESTListeners, strconv.Itoa(defaultRESTPort),
3✔
1520
                cfg.net.ResolveTCPAddr,
3✔
1521
        )
3✔
1522
        if err != nil {
3✔
1523
                return nil, mkErr("error normalizing REST listen addrs: %v", err)
×
1524
        }
×
1525

1526
        switch {
3✔
1527
        // The no seed backup and auto unlock are mutually exclusive.
1528
        case cfg.NoSeedBackup && cfg.WalletUnlockPasswordFile != "":
×
1529
                return nil, mkErr("cannot set noseedbackup and " +
×
1530
                        "wallet-unlock-password-file at the same time")
×
1531

1532
        // The "allow-create" flag cannot be set without the auto unlock file.
1533
        case cfg.WalletUnlockAllowCreate && cfg.WalletUnlockPasswordFile == "":
×
1534
                return nil, mkErr("cannot set wallet-unlock-allow-create " +
×
1535
                        "without wallet-unlock-password-file")
×
1536

1537
        // If a password file was specified, we need it to exist.
1538
        case cfg.WalletUnlockPasswordFile != "" &&
1539
                !lnrpc.FileExists(cfg.WalletUnlockPasswordFile):
×
1540

×
1541
                return nil, mkErr("wallet unlock password file %s does "+
×
1542
                        "not exist", cfg.WalletUnlockPasswordFile)
×
1543
        }
1544

1545
        // For each of the RPC listeners (REST+gRPC), we'll ensure that users
1546
        // have specified a safe combo for authentication. If not, we'll bail
1547
        // out with an error. Since we don't allow disabling TLS for gRPC
1548
        // connections we pass in tlsActive=true.
1549
        err = lncfg.EnforceSafeAuthentication(
3✔
1550
                cfg.RPCListeners, !cfg.NoMacaroons, true,
3✔
1551
        )
3✔
1552
        if err != nil {
3✔
1553
                return nil, mkErr("error enforcing safe authentication on "+
×
1554
                        "RPC ports: %v", err)
×
1555
        }
×
1556

1557
        if cfg.DisableRest {
3✔
1558
                ltndLog.Infof("REST API is disabled!")
×
1559
                cfg.RESTListeners = nil
×
1560
        } else {
3✔
1561
                err = lncfg.EnforceSafeAuthentication(
3✔
1562
                        cfg.RESTListeners, !cfg.NoMacaroons, !cfg.DisableRestTLS,
3✔
1563
                )
3✔
1564
                if err != nil {
3✔
1565
                        return nil, mkErr("error enforcing safe "+
×
1566
                                "authentication on REST ports: %v", err)
×
1567
                }
×
1568
        }
1569

1570
        // Remove the listening addresses specified if listening is disabled.
1571
        if cfg.DisableListen {
6✔
1572
                ltndLog.Infof("Listening on the p2p interface is disabled!")
3✔
1573
                cfg.Listeners = nil
3✔
1574
                cfg.ExternalIPs = nil
3✔
1575
        } else {
6✔
1576

3✔
1577
                // Add default port to all listener addresses if needed and remove
3✔
1578
                // duplicate addresses.
3✔
1579
                cfg.Listeners, err = lncfg.NormalizeAddresses(
3✔
1580
                        cfg.RawListeners, strconv.Itoa(defaultPeerPort),
3✔
1581
                        cfg.net.ResolveTCPAddr,
3✔
1582
                )
3✔
1583
                if err != nil {
3✔
1584
                        return nil, mkErr("error normalizing p2p listen "+
×
1585
                                "addrs: %v", err)
×
1586
                }
×
1587

1588
                // Add default port to all external IP addresses if needed and remove
1589
                // duplicate addresses.
1590
                cfg.ExternalIPs, err = lncfg.NormalizeAddresses(
3✔
1591
                        cfg.RawExternalIPs, strconv.Itoa(defaultPeerPort),
3✔
1592
                        cfg.net.ResolveTCPAddr,
3✔
1593
                )
3✔
1594
                if err != nil {
3✔
1595
                        return nil, err
×
1596
                }
×
1597

1598
                // For the p2p port it makes no sense to listen to an Unix socket.
1599
                // Also, we would need to refactor the brontide listener to support
1600
                // that.
1601
                for _, p2pListener := range cfg.Listeners {
6✔
1602
                        if lncfg.IsUnix(p2pListener) {
3✔
1603
                                return nil, mkErr("unix socket addresses "+
×
1604
                                        "cannot be used for the p2p "+
×
1605
                                        "connection listener: %s", p2pListener)
×
1606
                        }
×
1607
                }
1608
        }
1609

1610
        // Ensure that the specified minimum backoff is below or equal to the
1611
        // maximum backoff.
1612
        if cfg.MinBackoff > cfg.MaxBackoff {
3✔
1613
                return nil, mkErr("maxbackoff must be greater than minbackoff")
×
1614
        }
×
1615

1616
        // Newer versions of lnd added a new sub-config for bolt-specific
1617
        // parameters. However, we want to also allow existing users to use the
1618
        // value on the top-level config. If the outer config value is set,
1619
        // then we'll use that directly.
1620
        flagSet, err := isSet("SyncFreelist")
3✔
1621
        if err != nil {
3✔
1622
                return nil, mkErr("error parsing freelist sync flag: %v", err)
×
1623
        }
×
1624
        if flagSet {
3✔
1625
                cfg.DB.Bolt.NoFreelistSync = !cfg.SyncFreelist
×
1626
        }
×
1627

1628
        // Parse any extra sqlite pragma options that may have been provided
1629
        // to determine if they override any of the defaults that we will
1630
        // otherwise add.
1631
        var (
3✔
1632
                defaultSynchronous = true
3✔
1633
                defaultAutoVacuum  = true
3✔
1634
                defaultFullfsync   = true
3✔
1635
        )
3✔
1636
        for _, option := range cfg.DB.Sqlite.PragmaOptions {
3✔
1637
                switch {
×
1638
                case strings.HasPrefix(option, "synchronous="):
×
1639
                        defaultSynchronous = false
×
1640

1641
                case strings.HasPrefix(option, "auto_vacuum="):
×
1642
                        defaultAutoVacuum = false
×
1643

1644
                case strings.HasPrefix(option, "fullfsync="):
×
1645
                        defaultFullfsync = false
×
1646

1647
                default:
×
1648
                }
1649
        }
1650

1651
        if defaultSynchronous {
6✔
1652
                cfg.DB.Sqlite.PragmaOptions = append(
3✔
1653
                        cfg.DB.Sqlite.PragmaOptions, "synchronous=full",
3✔
1654
                )
3✔
1655
        }
3✔
1656

1657
        if defaultAutoVacuum {
6✔
1658
                cfg.DB.Sqlite.PragmaOptions = append(
3✔
1659
                        cfg.DB.Sqlite.PragmaOptions, "auto_vacuum=incremental",
3✔
1660
                )
3✔
1661
        }
3✔
1662

1663
        if defaultFullfsync {
6✔
1664
                cfg.DB.Sqlite.PragmaOptions = append(
3✔
1665
                        cfg.DB.Sqlite.PragmaOptions, "fullfsync=true",
3✔
1666
                )
3✔
1667
        }
3✔
1668

1669
        // Ensure that the user hasn't chosen a remote-max-htlc value greater
1670
        // than the protocol maximum.
1671
        maxRemoteHtlcs := uint16(input.MaxHTLCNumber / 2)
3✔
1672
        if cfg.DefaultRemoteMaxHtlcs > maxRemoteHtlcs {
3✔
1673
                return nil, mkErr("default-remote-max-htlcs (%v) must be "+
×
1674
                        "less than %v", cfg.DefaultRemoteMaxHtlcs,
×
1675
                        maxRemoteHtlcs)
×
1676
        }
×
1677

1678
        // Clamp the ChannelCommitInterval so that commitment updates can still
1679
        // happen in a reasonable timeframe.
1680
        if cfg.ChannelCommitInterval > maxChannelCommitInterval {
3✔
1681
                return nil, mkErr("channel-commit-interval (%v) must be less "+
×
1682
                        "than %v", cfg.ChannelCommitInterval,
×
1683
                        maxChannelCommitInterval)
×
1684
        }
×
1685

1686
        // Limit PendingCommitInterval so we don't wait too long for the remote
1687
        // party to send back a revoke.
1688
        if cfg.PendingCommitInterval > maxPendingCommitInterval {
3✔
1689
                return nil, mkErr("pending-commit-interval (%v) must be less "+
×
1690
                        "than %v", cfg.PendingCommitInterval,
×
1691
                        maxPendingCommitInterval)
×
1692
        }
×
1693

1694
        if err := cfg.Gossip.Parse(); err != nil {
3✔
1695
                return nil, mkErr("error parsing gossip syncer: %v", err)
×
1696
        }
×
1697

1698
        // If the experimental protocol options specify any protocol messages
1699
        // that we want to handle as custom messages, set them now.
1700
        customMsg := cfg.ProtocolOptions.CustomMessageOverrides()
3✔
1701

3✔
1702
        // We can safely set our custom override values during startup because
3✔
1703
        // startup is blocked on config parsing.
3✔
1704
        if err := lnwire.SetCustomOverrides(customMsg); err != nil {
3✔
1705
                return nil, mkErr("custom-message: %v", err)
×
1706
        }
×
1707

1708
        // Map old pprof flags to new pprof group flags.
1709
        //
1710
        // NOTE: This is a temporary measure to ensure compatibility with old
1711
        // flags.
1712
        if cfg.CPUProfile != "" {
3✔
1713
                if cfg.Pprof.CPUProfile != "" {
×
1714
                        return nil, mkErr("cpuprofile and pprof.cpuprofile " +
×
1715
                                "are mutually exclusive")
×
1716
                }
×
1717
                cfg.Pprof.CPUProfile = cfg.CPUProfile
×
1718
        }
1719
        if cfg.Profile != "" {
3✔
1720
                if cfg.Pprof.Profile != "" {
×
1721
                        return nil, mkErr("profile and pprof.profile " +
×
1722
                                "are mutually exclusive")
×
1723
                }
×
1724
                cfg.Pprof.Profile = cfg.Profile
×
1725
        }
1726
        if cfg.BlockingProfile != 0 {
3✔
1727
                if cfg.Pprof.BlockingProfile != 0 {
×
1728
                        return nil, mkErr("blockingprofile and " +
×
1729
                                "pprof.blockingprofile are mutually exclusive")
×
1730
                }
×
1731
                cfg.Pprof.BlockingProfile = cfg.BlockingProfile
×
1732
        }
1733
        if cfg.MutexProfile != 0 {
3✔
1734
                if cfg.Pprof.MutexProfile != 0 {
×
1735
                        return nil, mkErr("mutexprofile and " +
×
1736
                                "pprof.mutexprofile are mutually exclusive")
×
1737
                }
×
1738
                cfg.Pprof.MutexProfile = cfg.MutexProfile
×
1739
        }
1740

1741
        // Don't allow both the old dust-threshold and the new
1742
        // channel-max-fee-exposure to be set.
1743
        if cfg.DustThreshold != 0 && cfg.MaxFeeExposure != 0 {
3✔
1744
                return nil, mkErr("cannot set both dust-threshold and " +
×
1745
                        "channel-max-fee-exposure")
×
1746
        }
×
1747

1748
        switch {
3✔
1749
        // Use the old dust-threshold as the max fee exposure if it is set and
1750
        // the new option is not.
1751
        case cfg.DustThreshold != 0:
×
1752
                cfg.MaxFeeExposure = cfg.DustThreshold
×
1753

1754
        // Use the default max fee exposure if the new option is not set and
1755
        // the old one is not set either.
1756
        case cfg.MaxFeeExposure == 0:
3✔
1757
                cfg.MaxFeeExposure = uint64(
3✔
1758
                        htlcswitch.DefaultMaxFeeExposure.ToSatoshis(),
3✔
1759
                )
3✔
1760
        }
1761

1762
        // Validate the subconfigs for workers, caches, and the tower client.
1763
        err = lncfg.Validate(
3✔
1764
                cfg.Workers,
3✔
1765
                cfg.Caches,
3✔
1766
                cfg.WtClient,
3✔
1767
                cfg.DB,
3✔
1768
                cfg.Cluster,
3✔
1769
                cfg.HealthChecks,
3✔
1770
                cfg.RPCMiddleware,
3✔
1771
                cfg.RemoteSigner,
3✔
1772
                cfg.Sweeper,
3✔
1773
                cfg.Htlcswitch,
3✔
1774
                cfg.Invoices,
3✔
1775
                cfg.Routing,
3✔
1776
                cfg.Pprof,
3✔
1777
                cfg.Gossip,
3✔
1778
        )
3✔
1779
        if err != nil {
3✔
1780
                return nil, err
×
1781
        }
×
1782

1783
        // Finally, ensure that the user's color is correctly formatted,
1784
        // otherwise the server will not be able to start after the unlocking
1785
        // the wallet.
1786
        _, err = lncfg.ParseHexColor(cfg.Color)
3✔
1787
        if err != nil {
3✔
1788
                return nil, mkErr("unable to parse node color: %v", err)
×
1789
        }
×
1790

1791
        // All good, return the sanitized result.
1792
        return &cfg, nil
3✔
1793
}
1794

1795
// graphDatabaseDir returns the default directory where the local bolt graph db
1796
// files are stored.
1797
func (c *Config) graphDatabaseDir() string {
3✔
1798
        return filepath.Join(
3✔
1799
                c.DataDir, defaultGraphSubDirname,
3✔
1800
                lncfg.NormalizeNetwork(c.ActiveNetParams.Name),
3✔
1801
        )
3✔
1802
}
3✔
1803

1804
// ImplementationConfig returns the configuration of what actual implementations
1805
// should be used when creating the main lnd instance.
1806
func (c *Config) ImplementationConfig(
1807
        interceptor signal.Interceptor) *ImplementationCfg {
3✔
1808

3✔
1809
        // If we're using a remote signer, we still need the base wallet as a
3✔
1810
        // watch-only source of chain and address data. But we don't need any
3✔
1811
        // private key material in that btcwallet base wallet.
3✔
1812
        if c.RemoteSigner.Enable {
6✔
1813
                rpcImpl := NewRPCSignerWalletImpl(
3✔
1814
                        c, ltndLog, interceptor,
3✔
1815
                        c.RemoteSigner.MigrateWatchOnly,
3✔
1816
                )
3✔
1817
                return &ImplementationCfg{
3✔
1818
                        GrpcRegistrar:     rpcImpl,
3✔
1819
                        RestRegistrar:     rpcImpl,
3✔
1820
                        ExternalValidator: rpcImpl,
3✔
1821
                        DatabaseBuilder: NewDefaultDatabaseBuilder(
3✔
1822
                                c, ltndLog,
3✔
1823
                        ),
3✔
1824
                        WalletConfigBuilder: rpcImpl,
3✔
1825
                        ChainControlBuilder: rpcImpl,
3✔
1826
                }
3✔
1827
        }
3✔
1828

1829
        defaultImpl := NewDefaultWalletImpl(c, ltndLog, interceptor, false)
3✔
1830
        return &ImplementationCfg{
3✔
1831
                GrpcRegistrar:       defaultImpl,
3✔
1832
                RestRegistrar:       defaultImpl,
3✔
1833
                ExternalValidator:   defaultImpl,
3✔
1834
                DatabaseBuilder:     NewDefaultDatabaseBuilder(c, ltndLog),
3✔
1835
                WalletConfigBuilder: defaultImpl,
3✔
1836
                ChainControlBuilder: defaultImpl,
3✔
1837
        }
3✔
1838
}
1839

1840
// CleanAndExpandPath expands environment variables and leading ~ in the
1841
// passed path, cleans the result, and returns it.
1842
// This function is taken from https://github.com/btcsuite/btcd
1843
func CleanAndExpandPath(path string) string {
3✔
1844
        if path == "" {
6✔
1845
                return ""
3✔
1846
        }
3✔
1847

1848
        // Expand initial ~ to OS specific home directory.
1849
        if strings.HasPrefix(path, "~") {
3✔
1850
                var homeDir string
×
1851
                u, err := user.Current()
×
1852
                if err == nil {
×
1853
                        homeDir = u.HomeDir
×
1854
                } else {
×
1855
                        homeDir = os.Getenv("HOME")
×
1856
                }
×
1857

1858
                path = strings.Replace(path, "~", homeDir, 1)
×
1859
        }
1860

1861
        // NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
1862
        // but the variables can still be expanded via POSIX-style $VARIABLE.
1863
        return filepath.Clean(os.ExpandEnv(path))
3✔
1864
}
1865

1866
func parseRPCParams(cConfig *lncfg.Chain, nodeConfig interface{},
1867
        netParams chainreg.BitcoinNetParams) error {
2✔
1868

2✔
1869
        // First, we'll check our node config to make sure the RPC parameters
2✔
1870
        // were set correctly. We'll also determine the path to the conf file
2✔
1871
        // depending on the backend node.
2✔
1872
        var daemonName, confDir, confFile, confFileBase string
2✔
1873
        switch conf := nodeConfig.(type) {
2✔
1874
        case *lncfg.Btcd:
1✔
1875
                // Resolves environment variable references in RPCUser and
1✔
1876
                // RPCPass fields.
1✔
1877
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
1✔
1878
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
1✔
1879

1✔
1880
                // If both RPCUser and RPCPass are set, we assume those
1✔
1881
                // credentials are good to use.
1✔
1882
                if conf.RPCUser != "" && conf.RPCPass != "" {
2✔
1883
                        return nil
1✔
1884
                }
1✔
1885

1886
                // Set the daemon name for displaying proper errors.
1887
                daemonName = btcdBackendName
×
1888
                confDir = conf.Dir
×
1889
                confFileBase = btcdBackendName
×
1890

×
1891
                // If only ONE of RPCUser or RPCPass is set, we assume the
×
1892
                // user did that unintentionally.
×
1893
                if conf.RPCUser != "" || conf.RPCPass != "" {
×
1894
                        return fmt.Errorf("please set both or neither of "+
×
1895
                                "%[1]v.rpcuser, %[1]v.rpcpass", daemonName)
×
1896
                }
×
1897

1898
        case *lncfg.Bitcoind:
1✔
1899
                // Ensure that if the ZMQ options are set, that they are not
1✔
1900
                // equal.
1✔
1901
                if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
2✔
1902
                        err := checkZMQOptions(
1✔
1903
                                conf.ZMQPubRawBlock, conf.ZMQPubRawTx,
1✔
1904
                        )
1✔
1905
                        if err != nil {
1✔
1906
                                return err
×
1907
                        }
×
1908
                }
1909

1910
                // Ensure that if the estimate mode is set, that it is a legal
1911
                // value.
1912
                if conf.EstimateMode != "" {
2✔
1913
                        err := checkEstimateMode(conf.EstimateMode)
1✔
1914
                        if err != nil {
1✔
1915
                                return err
×
1916
                        }
×
1917
                }
1918

1919
                // Set the daemon name for displaying proper errors.
1920
                daemonName = bitcoindBackendName
1✔
1921
                confDir = conf.Dir
1✔
1922
                confFile = conf.ConfigPath
1✔
1923
                confFileBase = BitcoinChainName
1✔
1924

1✔
1925
                // Resolves environment variable references in RPCUser
1✔
1926
                // and RPCPass fields.
1✔
1927
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
1✔
1928
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
1✔
1929

1✔
1930
                // Check that cookie and credentials don't contradict each
1✔
1931
                // other.
1✔
1932
                if (conf.RPCUser != "" || conf.RPCPass != "") &&
1✔
1933
                        conf.RPCCookie != "" {
1✔
1934

×
1935
                        return fmt.Errorf("please only provide either "+
×
1936
                                "%[1]v.rpccookie or %[1]v.rpcuser and "+
×
1937
                                "%[1]v.rpcpass", daemonName)
×
1938
                }
×
1939

1940
                // We convert the cookie into a user name and password.
1941
                if conf.RPCCookie != "" {
1✔
1942
                        cookie, err := os.ReadFile(conf.RPCCookie)
×
1943
                        if err != nil {
×
1944
                                return fmt.Errorf("cannot read cookie file: %w",
×
1945
                                        err)
×
1946
                        }
×
1947

1948
                        splitCookie := strings.Split(string(cookie), ":")
×
1949
                        if len(splitCookie) != 2 {
×
1950
                                return fmt.Errorf("cookie file has a wrong " +
×
1951
                                        "format")
×
1952
                        }
×
1953
                        conf.RPCUser = splitCookie[0]
×
1954
                        conf.RPCPass = splitCookie[1]
×
1955
                }
1956

1957
                if conf.RPCUser != "" && conf.RPCPass != "" {
2✔
1958
                        // If all of RPCUser, RPCPass, ZMQBlockHost, and
1✔
1959
                        // ZMQTxHost are set, we assume those parameters are
1✔
1960
                        // good to use.
1✔
1961
                        if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
2✔
1962
                                return nil
1✔
1963
                        }
1✔
1964

1965
                        // If RPCUser and RPCPass are set and RPCPolling is
1966
                        // enabled, we assume the parameters are good to use.
1967
                        if conf.RPCPolling {
×
1968
                                return nil
×
1969
                        }
×
1970
                }
1971

1972
                // If not all of the parameters are set, we'll assume the user
1973
                // did this unintentionally.
1974
                if conf.RPCUser != "" || conf.RPCPass != "" ||
×
1975
                        conf.ZMQPubRawBlock != "" || conf.ZMQPubRawTx != "" {
×
1976

×
1977
                        return fmt.Errorf("please set %[1]v.rpcuser and "+
×
1978
                                "%[1]v.rpcpass (or %[1]v.rpccookie) together "+
×
1979
                                "with %[1]v.zmqpubrawblock, %[1]v.zmqpubrawtx",
×
1980
                                daemonName)
×
1981
                }
×
1982
        }
1983

1984
        // If we're in simnet mode, then the running btcd instance won't read
1985
        // the RPC credentials from the configuration. So if lnd wasn't
1986
        // specified the parameters, then we won't be able to start.
1987
        if cConfig.SimNet {
×
1988
                return fmt.Errorf("rpcuser and rpcpass must be set to your " +
×
1989
                        "btcd node's RPC parameters for simnet mode")
×
1990
        }
×
1991

1992
        fmt.Println("Attempting automatic RPC configuration to " + daemonName)
×
1993

×
1994
        if confFile == "" {
×
1995
                confFile = filepath.Join(confDir, fmt.Sprintf("%v.conf",
×
1996
                        confFileBase))
×
1997
        }
×
1998
        switch cConfig.Node {
×
1999
        case btcdBackendName:
×
2000
                nConf := nodeConfig.(*lncfg.Btcd)
×
2001
                rpcUser, rpcPass, err := extractBtcdRPCParams(confFile)
×
2002
                if err != nil {
×
2003
                        return fmt.Errorf("unable to extract RPC credentials: "+
×
2004
                                "%v, cannot start w/o RPC connection", err)
×
2005
                }
×
2006
                nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
×
2007

2008
        case bitcoindBackendName:
×
2009
                nConf := nodeConfig.(*lncfg.Bitcoind)
×
2010
                rpcUser, rpcPass, zmqBlockHost, zmqTxHost, err :=
×
2011
                        extractBitcoindRPCParams(netParams.Params.Name,
×
2012
                                nConf.Dir, confFile, nConf.RPCCookie)
×
2013
                if err != nil {
×
2014
                        return fmt.Errorf("unable to extract RPC credentials: "+
×
2015
                                "%v, cannot start w/o RPC connection", err)
×
2016
                }
×
2017
                nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
×
2018
                nConf.ZMQPubRawBlock, nConf.ZMQPubRawTx = zmqBlockHost, zmqTxHost
×
2019
        }
2020

2021
        fmt.Printf("Automatically obtained %v's RPC credentials\n", daemonName)
×
2022
        return nil
×
2023
}
2024

2025
// supplyEnvValue supplies the value of an environment variable from a string.
2026
// It supports the following formats:
2027
// 1) $ENV_VAR
2028
// 2) ${ENV_VAR}
2029
// 3) ${ENV_VAR:-DEFAULT}
2030
//
2031
// Standard environment variable naming conventions:
2032
// - ENV_VAR contains letters, digits, and underscores, and does
2033
// not start with a digit.
2034
// - DEFAULT follows the rule that it can contain any characters except
2035
// whitespace.
2036
//
2037
// Parameters:
2038
// - value: The input string containing references to environment variables
2039
// (if any).
2040
//
2041
// Returns:
2042
// - string: The value of the specified environment variable, the default
2043
// value if provided, or the original input string if no matching variable is
2044
// found or set.
2045
func supplyEnvValue(value string) string {
2✔
2046
        // Regex for $ENV_VAR format.
2✔
2047
        var reEnvVar = regexp.MustCompile(`^\$([a-zA-Z_][a-zA-Z0-9_]*)$`)
2✔
2048

2✔
2049
        // Regex for ${ENV_VAR} format.
2✔
2050
        var reEnvVarWithBrackets = regexp.MustCompile(
2✔
2051
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$`,
2✔
2052
        )
2✔
2053

2✔
2054
        // Regex for ${ENV_VAR:-DEFAULT} format.
2✔
2055
        var reEnvVarWithDefault = regexp.MustCompile(
2✔
2056
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*):-([\S]+)\}$`,
2✔
2057
        )
2✔
2058

2✔
2059
        // Match against supported formats.
2✔
2060
        switch {
2✔
UNCOV
2061
        case reEnvVarWithDefault.MatchString(value):
×
UNCOV
2062
                matches := reEnvVarWithDefault.FindStringSubmatch(value)
×
UNCOV
2063
                envVariable := matches[1]
×
UNCOV
2064
                defaultValue := matches[2]
×
UNCOV
2065
                if envValue := os.Getenv(envVariable); envValue != "" {
×
UNCOV
2066
                        return envValue
×
UNCOV
2067
                }
×
2068

UNCOV
2069
                return defaultValue
×
2070

2071
        case reEnvVarWithBrackets.MatchString(value):
×
2072
                matches := reEnvVarWithBrackets.FindStringSubmatch(value)
×
2073
                envVariable := matches[1]
×
2074
                envValue := os.Getenv(envVariable)
×
2075

×
2076
                return envValue
×
2077

UNCOV
2078
        case reEnvVar.MatchString(value):
×
UNCOV
2079
                matches := reEnvVar.FindStringSubmatch(value)
×
UNCOV
2080
                envVariable := matches[1]
×
UNCOV
2081
                envValue := os.Getenv(envVariable)
×
UNCOV
2082

×
UNCOV
2083
                return envValue
×
2084
        }
2085

2086
        return value
2✔
2087
}
2088

2089
// extractBtcdRPCParams attempts to extract the RPC credentials for an existing
2090
// btcd instance. The passed path is expected to be the location of btcd's
2091
// application data directory on the target system.
2092
func extractBtcdRPCParams(btcdConfigPath string) (string, string, error) {
×
2093
        // First, we'll open up the btcd configuration file found at the target
×
2094
        // destination.
×
2095
        btcdConfigFile, err := os.Open(btcdConfigPath)
×
2096
        if err != nil {
×
2097
                return "", "", err
×
2098
        }
×
2099
        defer func() { _ = btcdConfigFile.Close() }()
×
2100

2101
        // With the file open extract the contents of the configuration file so
2102
        // we can attempt to locate the RPC credentials.
2103
        configContents, err := io.ReadAll(btcdConfigFile)
×
2104
        if err != nil {
×
2105
                return "", "", err
×
2106
        }
×
2107

2108
        // Attempt to locate the RPC user using a regular expression. If we
2109
        // don't have a match for our regular expression then we'll exit with
2110
        // an error.
2111
        rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
×
2112
        if err != nil {
×
2113
                return "", "", err
×
2114
        }
×
2115
        userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
×
2116
        if userSubmatches == nil {
×
2117
                return "", "", fmt.Errorf("unable to find rpcuser in config")
×
2118
        }
×
2119

2120
        // Similarly, we'll use another regular expression to find the set
2121
        // rpcpass (if any). If we can't find the pass, then we'll exit with an
2122
        // error.
2123
        rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpass\s*=\s*([^\s]+)`)
×
2124
        if err != nil {
×
2125
                return "", "", err
×
2126
        }
×
2127
        passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
×
2128
        if passSubmatches == nil {
×
2129
                return "", "", fmt.Errorf("unable to find rpcuser in config")
×
2130
        }
×
2131

2132
        return supplyEnvValue(string(userSubmatches[1])),
×
2133
                supplyEnvValue(string(passSubmatches[1])), nil
×
2134
}
2135

2136
// extractBitcoindRPCParams attempts to extract the RPC credentials for an
2137
// existing bitcoind node instance. The routine looks for a cookie first,
2138
// optionally following the datadir configuration option in the bitcoin.conf. If
2139
// it doesn't find one, it looks for rpcuser/rpcpassword.
2140
func extractBitcoindRPCParams(networkName, bitcoindDataDir, bitcoindConfigPath,
2141
        rpcCookiePath string) (string, string, string, string, error) {
×
2142

×
2143
        // First, we'll open up the bitcoind configuration file found at the
×
2144
        // target destination.
×
2145
        bitcoindConfigFile, err := os.Open(bitcoindConfigPath)
×
2146
        if err != nil {
×
2147
                return "", "", "", "", err
×
2148
        }
×
2149
        defer func() { _ = bitcoindConfigFile.Close() }()
×
2150

2151
        // With the file open extract the contents of the configuration file so
2152
        // we can attempt to locate the RPC credentials.
2153
        configContents, err := io.ReadAll(bitcoindConfigFile)
×
2154
        if err != nil {
×
2155
                return "", "", "", "", err
×
2156
        }
×
2157

2158
        // First, we'll look for the ZMQ hosts providing raw block and raw
2159
        // transaction notifications.
2160
        zmqBlockHostRE, err := regexp.Compile(
×
2161
                `(?m)^\s*zmqpubrawblock\s*=\s*([^\s]+)`,
×
2162
        )
×
2163
        if err != nil {
×
2164
                return "", "", "", "", err
×
2165
        }
×
2166
        zmqBlockHostSubmatches := zmqBlockHostRE.FindSubmatch(configContents)
×
2167
        if len(zmqBlockHostSubmatches) < 2 {
×
2168
                return "", "", "", "", fmt.Errorf("unable to find " +
×
2169
                        "zmqpubrawblock in config")
×
2170
        }
×
2171
        zmqTxHostRE, err := regexp.Compile(`(?m)^\s*zmqpubrawtx\s*=\s*([^\s]+)`)
×
2172
        if err != nil {
×
2173
                return "", "", "", "", err
×
2174
        }
×
2175
        zmqTxHostSubmatches := zmqTxHostRE.FindSubmatch(configContents)
×
2176
        if len(zmqTxHostSubmatches) < 2 {
×
2177
                return "", "", "", "", errors.New("unable to find zmqpubrawtx " +
×
2178
                        "in config")
×
2179
        }
×
2180
        zmqBlockHost := string(zmqBlockHostSubmatches[1])
×
2181
        zmqTxHost := string(zmqTxHostSubmatches[1])
×
2182
        if err := checkZMQOptions(zmqBlockHost, zmqTxHost); err != nil {
×
2183
                return "", "", "", "", err
×
2184
        }
×
2185

2186
        // Next, we'll try to find an auth cookie. We need to detect the chain
2187
        // by seeing if one is specified in the configuration file.
2188
        dataDir := filepath.Dir(bitcoindConfigPath)
×
2189
        if bitcoindDataDir != "" {
×
2190
                dataDir = bitcoindDataDir
×
2191
        }
×
2192
        dataDirRE, err := regexp.Compile(`(?m)^\s*datadir\s*=\s*([^\s]+)`)
×
2193
        if err != nil {
×
2194
                return "", "", "", "", err
×
2195
        }
×
2196
        dataDirSubmatches := dataDirRE.FindSubmatch(configContents)
×
2197
        if dataDirSubmatches != nil {
×
2198
                dataDir = string(dataDirSubmatches[1])
×
2199
        }
×
2200

2201
        var chainDir string
×
2202
        switch networkName {
×
2203
        case "mainnet":
×
2204
                chainDir = ""
×
2205
        case "regtest", "testnet3", "signet":
×
2206
                chainDir = networkName
×
2207
        default:
×
2208
                return "", "", "", "", fmt.Errorf("unexpected networkname %v", networkName)
×
2209
        }
2210

2211
        cookiePath := filepath.Join(dataDir, chainDir, ".cookie")
×
2212
        if rpcCookiePath != "" {
×
2213
                cookiePath = rpcCookiePath
×
2214
        }
×
2215
        cookie, err := os.ReadFile(cookiePath)
×
2216
        if err == nil {
×
2217
                splitCookie := strings.Split(string(cookie), ":")
×
2218
                if len(splitCookie) == 2 {
×
2219
                        return splitCookie[0], splitCookie[1], zmqBlockHost,
×
2220
                                zmqTxHost, nil
×
2221
                }
×
2222
        }
2223

2224
        // We didn't find a cookie, so we attempt to locate the RPC user using
2225
        // a regular expression. If we  don't have a match for our regular
2226
        // expression then we'll exit with an error.
2227
        rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
×
2228
        if err != nil {
×
2229
                return "", "", "", "", err
×
2230
        }
×
2231
        userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
×
2232

×
2233
        // Similarly, we'll use another regular expression to find the set
×
2234
        // rpcpass (if any). If we can't find the pass, then we'll exit with an
×
2235
        // error.
×
2236
        rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpassword\s*=\s*([^\s]+)`)
×
2237
        if err != nil {
×
2238
                return "", "", "", "", err
×
2239
        }
×
2240
        passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
×
2241

×
2242
        // Exit with an error if the cookie file, is defined in config, and
×
2243
        // can not be found, with both rpcuser and rpcpassword undefined.
×
2244
        if rpcCookiePath != "" && userSubmatches == nil && passSubmatches == nil {
×
2245
                return "", "", "", "", fmt.Errorf("unable to open cookie file (%v)",
×
2246
                        rpcCookiePath)
×
2247
        }
×
2248

2249
        if userSubmatches == nil {
×
2250
                return "", "", "", "", fmt.Errorf("unable to find rpcuser in " +
×
2251
                        "config")
×
2252
        }
×
2253
        if passSubmatches == nil {
×
2254
                return "", "", "", "", fmt.Errorf("unable to find rpcpassword " +
×
2255
                        "in config")
×
2256
        }
×
2257

2258
        return supplyEnvValue(string(userSubmatches[1])),
×
2259
                supplyEnvValue(string(passSubmatches[1])),
×
2260
                zmqBlockHost, zmqTxHost, nil
×
2261
}
2262

2263
// checkZMQOptions ensures that the provided addresses to use as the hosts for
2264
// ZMQ rawblock and rawtx notifications are different.
2265
func checkZMQOptions(zmqBlockHost, zmqTxHost string) error {
1✔
2266
        if zmqBlockHost == zmqTxHost {
1✔
2267
                return errors.New("zmqpubrawblock and zmqpubrawtx must be set " +
×
2268
                        "to different addresses")
×
2269
        }
×
2270

2271
        return nil
1✔
2272
}
2273

2274
// checkEstimateMode ensures that the provided estimate mode is legal.
2275
func checkEstimateMode(estimateMode string) error {
1✔
2276
        for _, mode := range bitcoindEstimateModes {
2✔
2277
                if estimateMode == mode {
2✔
2278
                        return nil
1✔
2279
                }
1✔
2280
        }
2281

2282
        return fmt.Errorf("estimatemode must be one of the following: %v",
×
2283
                bitcoindEstimateModes[:])
×
2284
}
2285

2286
// configToFlatMap converts the given config struct into a flat map of
2287
// key/value pairs using the dot notation we are used to from the config file
2288
// or command line flags. It also returns a map containing deprecated config
2289
// options.
2290
func configToFlatMap(cfg Config) (map[string]string,
2291
        map[string]struct{}, error) {
3✔
2292

3✔
2293
        result := make(map[string]string)
3✔
2294

3✔
2295
        // deprecated stores a map of deprecated options found in the config
3✔
2296
        // that are set by the users. A config option is considered as
3✔
2297
        // deprecated if it has a `hidden` flag.
3✔
2298
        deprecated := make(map[string]struct{})
3✔
2299

3✔
2300
        // redact is the helper function that redacts sensitive values like
3✔
2301
        // passwords.
3✔
2302
        redact := func(key, value string) string {
6✔
2303
                sensitiveKeySuffixes := []string{
3✔
2304
                        "pass",
3✔
2305
                        "password",
3✔
2306
                        "dsn",
3✔
2307
                }
3✔
2308
                for _, suffix := range sensitiveKeySuffixes {
6✔
2309
                        if strings.HasSuffix(key, suffix) {
6✔
2310
                                return "[redacted]"
3✔
2311
                        }
3✔
2312
                }
2313

2314
                return value
3✔
2315
        }
2316

2317
        // printConfig is the helper function that goes into nested structs
2318
        // recursively. Because we call it recursively, we need to declare it
2319
        // before we define it.
2320
        var printConfig func(reflect.Value, string)
3✔
2321
        printConfig = func(obj reflect.Value, prefix string) {
6✔
2322
                // Turn struct pointers into the actual struct, so we can
3✔
2323
                // iterate over the fields as we would with a struct value.
3✔
2324
                if obj.Kind() == reflect.Ptr {
6✔
2325
                        obj = obj.Elem()
3✔
2326
                }
3✔
2327

2328
                // Abort on nil values.
2329
                if !obj.IsValid() {
3✔
UNCOV
2330
                        return
×
UNCOV
2331
                }
×
2332

2333
                // Loop over all fields of the struct and inspect the type.
2334
                for i := 0; i < obj.NumField(); i++ {
6✔
2335
                        field := obj.Field(i)
3✔
2336
                        fieldType := obj.Type().Field(i)
3✔
2337

3✔
2338
                        longName := fieldType.Tag.Get("long")
3✔
2339
                        namespace := fieldType.Tag.Get("namespace")
3✔
2340
                        group := fieldType.Tag.Get("group")
3✔
2341
                        hidden := fieldType.Tag.Get("hidden")
3✔
2342

3✔
2343
                        switch {
3✔
2344
                        // We have a long name defined, this is a config value.
2345
                        case longName != "":
3✔
2346
                                key := longName
3✔
2347
                                if prefix != "" {
6✔
2348
                                        key = prefix + "." + key
3✔
2349
                                }
3✔
2350

2351
                                // Add the value directly to the flattened map.
2352
                                result[key] = redact(key, fmt.Sprintf(
3✔
2353
                                        "%v", field.Interface(),
3✔
2354
                                ))
3✔
2355

3✔
2356
                                // If there's a hidden flag, it's deprecated.
3✔
2357
                                if hidden == "true" && !field.IsZero() {
3✔
UNCOV
2358
                                        deprecated[key] = struct{}{}
×
UNCOV
2359
                                }
×
2360

2361
                        // We have no long name but a namespace, this is a
2362
                        // nested struct.
2363
                        case longName == "" && namespace != "":
3✔
2364
                                key := namespace
3✔
2365
                                if prefix != "" {
6✔
2366
                                        key = prefix + "." + key
3✔
2367
                                }
3✔
2368

2369
                                printConfig(field, key)
3✔
2370

2371
                        // Just a group means this is a dummy struct to house
2372
                        // multiple config values, the group name doesn't go
2373
                        // into the final field name.
2374
                        case longName == "" && group != "":
3✔
2375
                                printConfig(field, prefix)
3✔
2376

2377
                        // Anonymous means embedded struct. We need to recurse
2378
                        // into it but without adding anything to the prefix.
2379
                        case fieldType.Anonymous:
3✔
2380
                                printConfig(field, prefix)
3✔
2381

2382
                        default:
3✔
2383
                                continue
3✔
2384
                        }
2385
                }
2386
        }
2387

2388
        // Turn the whole config struct into a flat map.
2389
        printConfig(reflect.ValueOf(cfg), "")
3✔
2390

3✔
2391
        return result, deprecated, nil
3✔
2392
}
2393

2394
// logWarningsForDeprecation logs a warning if a deprecated config option is
2395
// set.
2396
func logWarningsForDeprecation(cfg Config) {
3✔
2397
        _, deprecated, err := configToFlatMap(cfg)
3✔
2398
        if err != nil {
3✔
2399
                ltndLog.Errorf("Convert configs to map: %v", err)
×
2400
        }
×
2401

2402
        for k := range deprecated {
3✔
2403
                ltndLog.Warnf("Config '%s' is deprecated, please remove it", k)
×
2404
        }
×
2405
}
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