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

lightningnetwork / lnd / 14358372723

09 Apr 2025 01:26PM UTC coverage: 56.696% (-12.3%) from 69.037%
14358372723

Pull #9696

github

web-flow
Merge e2837e400 into 867d27d68
Pull Request #9696: Add `development_guidelines.md` for both human and machine

107055 of 188823 relevant lines covered (56.7%)

22721.56 hits per line

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

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

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

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

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

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

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

×
795
                configFilePath = filepath.Join(
×
796
                        configFileDir, lncfg.DefaultConfigFilename,
×
797
                )
×
798

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

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

×
820
                        return nil, err
×
821
                }
×
822

823
                configFileError = err
×
824
        }
825

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

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

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

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

×
857
                return nil, err
×
858
        }
×
859

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

867
        // Finally, log warnings for deprecated config options if they are set.
868
        logWarningsForDeprecation(*cleanCfg)
×
869

×
870
        return cleanCfg, nil
×
871
}
872

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

×
879
        // Special show command to list supported subsystems and exit.
×
880
        if cfg.DebugLevel == "show" {
×
881
                subLogMgr := build.NewSubLoggerManager()
×
882

×
883
                // Initialize logging at the default logging level.
×
884
                SetupLoggers(subLogMgr, interceptor)
×
885

×
886
                fmt.Println("Supported subsystems",
×
887
                        subLogMgr.SupportedSubsystems())
×
888
                os.Exit(0)
×
889
        }
×
890

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

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

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

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

935
                return nil
×
936
        }
937

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

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

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

×
970
                return (fileOption != nil && fileOption.IsSet()) ||
×
971
                                (fileOptionNested != nil && fileOptionNested.IsSet()) ||
×
972
                                (flagOption != nil && flagOption.IsSet()) ||
×
973
                                (flagOptionNested != nil && flagOptionNested.IsSet()),
×
974
                        nil
×
975
        }
976

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

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

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

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

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

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

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

×
1032
                return nil, mkErr(str)
×
1033
        }
×
1034

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1138
                return nil, mkErr(str)
×
1139
        }
×
1140

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

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

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

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

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

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

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

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

1256
                if len(cfg.Bitcoin.SigNetSeedNode) > 0 {
×
1257
                        sigNetSeeds = make([]chaincfg.DNSSeed, len(
×
1258
                                cfg.Bitcoin.SigNetSeedNode,
×
1259
                        ))
×
1260
                        for idx, seed := range cfg.Bitcoin.SigNetSeedNode {
×
1261
                                sigNetSeeds[idx] = chaincfg.DNSSeed{
×
1262
                                        Host:         seed,
×
1263
                                        HasFiltering: false,
×
1264
                                }
×
1265
                        }
×
1266
                }
1267

1268
                chainParams := chaincfg.CustomSignetParams(
×
1269
                        sigNetChallenge, sigNetSeeds,
×
1270
                )
×
1271
                cfg.ActiveNetParams.Params = &chainParams
×
1272
        }
1273
        if numNets > 1 {
×
1274
                str := "The mainnet, testnet, testnet4, regtest, simnet and " +
×
1275
                        "signet params can't be used together -- choose one " +
×
1276
                        "of the five"
×
1277

×
1278
                return nil, mkErr(str)
×
1279
        }
×
1280

1281
        // The target network must be provided, otherwise, we won't
1282
        // know how to initialize the daemon.
1283
        if numNets == 0 {
×
1284
                str := "either --bitcoin.mainnet, or --bitcoin.testnet, " +
×
1285
                        "--bitcoin.testnet4, --bitcoin.simnet, " +
×
1286
                        "--bitcoin.regtest or --bitcoin.signet must be " +
×
1287
                        "specified"
×
1288

×
1289
                return nil, mkErr(str)
×
1290
        }
×
1291

1292
        err = cfg.Bitcoin.Validate(minTimeLockDelta, funding.MinBtcRemoteDelay)
×
1293
        if err != nil {
×
1294
                return nil, mkErr("error validating bitcoin params: %v", err)
×
1295
        }
×
1296

1297
        switch cfg.Bitcoin.Node {
×
1298
        case btcdBackendName:
×
1299
                err := parseRPCParams(
×
1300
                        cfg.Bitcoin, cfg.BtcdMode, cfg.ActiveNetParams,
×
1301
                )
×
1302
                if err != nil {
×
1303
                        return nil, mkErr("unable to load RPC "+
×
1304
                                "credentials for btcd: %v", err)
×
1305
                }
×
1306
        case bitcoindBackendName:
×
1307
                if cfg.Bitcoin.SimNet {
×
1308
                        return nil, mkErr("bitcoind does not " +
×
1309
                                "support simnet")
×
1310
                }
×
1311

1312
                err := parseRPCParams(
×
1313
                        cfg.Bitcoin, cfg.BitcoindMode, cfg.ActiveNetParams,
×
1314
                )
×
1315
                if err != nil {
×
1316
                        return nil, mkErr("unable to load RPC "+
×
1317
                                "credentials for bitcoind: %v", err)
×
1318
                }
×
1319
        case neutrinoBackendName:
×
1320
                // No need to get RPC parameters.
1321

1322
        case "nochainbackend":
×
1323
                // Nothing to configure, we're running without any chain
1324
                // backend whatsoever (pure signing mode).
1325

1326
        default:
×
1327
                str := "only btcd, bitcoind, and neutrino mode " +
×
1328
                        "supported for bitcoin at this time"
×
1329

×
1330
                return nil, mkErr(str)
×
1331
        }
1332

1333
        cfg.Bitcoin.ChainDir = filepath.Join(
×
1334
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
×
1335
        )
×
1336

×
1337
        // Ensure that the user didn't attempt to specify negative values for
×
1338
        // any of the autopilot params.
×
1339
        if cfg.Autopilot.MaxChannels < 0 {
×
1340
                str := "autopilot.maxchannels must be non-negative"
×
1341

×
1342
                return nil, mkErr(str)
×
1343
        }
×
1344
        if cfg.Autopilot.Allocation < 0 {
×
1345
                str := "autopilot.allocation must be non-negative"
×
1346

×
1347
                return nil, mkErr(str)
×
1348
        }
×
1349
        if cfg.Autopilot.MinChannelSize < 0 {
×
1350
                str := "autopilot.minchansize must be non-negative"
×
1351

×
1352
                return nil, mkErr(str)
×
1353
        }
×
1354
        if cfg.Autopilot.MaxChannelSize < 0 {
×
1355
                str := "autopilot.maxchansize must be non-negative"
×
1356

×
1357
                return nil, mkErr(str)
×
1358
        }
×
1359

1360
        // Ensure that the specified values for the min and max channel size
1361
        // don't are within the bounds of the normal chan size constraints.
1362
        if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
×
1363
                cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
×
1364
        }
×
1365
        if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
×
1366
                cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
×
1367
        }
×
1368

1369
        // We'll now construct the network directory which will be where we
1370
        // store all the data specific to this chain/network.
1371
        cfg.networkDir = filepath.Join(
×
1372
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
×
1373
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
×
1374
        )
×
1375

×
1376
        // If a custom macaroon directory wasn't specified and the data
×
1377
        // directory has changed from the default path, then we'll also update
×
1378
        // the path for the macaroons to be generated.
×
1379
        if cfg.AdminMacPath == "" {
×
1380
                cfg.AdminMacPath = filepath.Join(
×
1381
                        cfg.networkDir, defaultAdminMacFilename,
×
1382
                )
×
1383
        }
×
1384
        if cfg.ReadMacPath == "" {
×
1385
                cfg.ReadMacPath = filepath.Join(
×
1386
                        cfg.networkDir, defaultReadMacFilename,
×
1387
                )
×
1388
        }
×
1389
        if cfg.InvoiceMacPath == "" {
×
1390
                cfg.InvoiceMacPath = filepath.Join(
×
1391
                        cfg.networkDir, defaultInvoiceMacFilename,
×
1392
                )
×
1393
        }
×
1394

1395
        towerDir := filepath.Join(
×
1396
                cfg.Watchtower.TowerDir, BitcoinChainName,
×
1397
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
×
1398
        )
×
1399

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

1418
        // Similarly, if a custom back up file path wasn't specified, then
1419
        // we'll update the file location to match our set network directory.
1420
        if cfg.BackupFilePath == "" {
×
1421
                cfg.BackupFilePath = filepath.Join(
×
1422
                        cfg.networkDir, chanbackup.DefaultBackupFileName,
×
1423
                )
×
1424
        }
×
1425

1426
        // Append the network type to the log directory so it is "namespaced"
1427
        // per network in the same fashion as the data directory.
1428
        cfg.LogDir = filepath.Join(
×
1429
                cfg.LogDir, BitcoinChainName,
×
1430
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
×
1431
        )
×
1432

×
1433
        if err := cfg.LogConfig.Validate(); err != nil {
×
1434
                return nil, mkErr("error validating logging config: %w", err)
×
1435
        }
×
1436

1437
        // If a sub-log manager was not already created, then we'll create one
1438
        // now using the default log handlers.
1439
        if cfg.SubLogMgr == nil {
×
1440
                cfg.SubLogMgr = build.NewSubLoggerManager(
×
1441
                        build.NewDefaultLogHandlers(
×
1442
                                cfg.LogConfig, cfg.LogRotator,
×
1443
                        )...,
×
1444
                )
×
1445
        }
×
1446

1447
        // Initialize logging at the default logging level.
1448
        SetupLoggers(cfg.SubLogMgr, interceptor)
×
1449

×
1450
        if cfg.MaxLogFiles != 0 {
×
1451
                if cfg.LogConfig.File.MaxLogFiles !=
×
1452
                        build.DefaultMaxLogFiles {
×
1453

×
1454
                        return nil, mkErr("cannot set both maxlogfiles and "+
×
1455
                                "logging.file.max-files", err)
×
1456
                }
×
1457

1458
                cfg.LogConfig.File.MaxLogFiles = cfg.MaxLogFiles
×
1459
        }
1460
        if cfg.MaxLogFileSize != 0 {
×
1461
                if cfg.LogConfig.File.MaxLogFileSize !=
×
1462
                        build.DefaultMaxLogFileSize {
×
1463

×
1464
                        return nil, mkErr("cannot set both maxlogfilesize and "+
×
1465
                                "logging.file.max-file-size", err)
×
1466
                }
×
1467

1468
                cfg.LogConfig.File.MaxLogFileSize = cfg.MaxLogFileSize
×
1469
        }
1470

1471
        err = cfg.LogRotator.InitLogRotator(
×
1472
                cfg.LogConfig.File,
×
1473
                filepath.Join(cfg.LogDir, defaultLogFilename),
×
1474
        )
×
1475
        if err != nil {
×
1476
                str := "log rotation setup failed: %v"
×
1477
                return nil, mkErr(str, err)
×
1478
        }
×
1479

1480
        // Parse, validate, and set debug log level(s).
1481
        err = build.ParseAndSetDebugLevels(cfg.DebugLevel, cfg.SubLogMgr)
×
1482
        if err != nil {
×
1483
                str := "error parsing debug level: %v"
×
1484
                return nil, &lncfg.UsageError{Err: mkErr(str, err)}
×
1485
        }
×
1486

1487
        // At least one RPCListener is required. So listen on localhost per
1488
        // default.
1489
        if len(cfg.RawRPCListeners) == 0 {
×
1490
                addr := fmt.Sprintf("localhost:%d", defaultRPCPort)
×
1491
                cfg.RawRPCListeners = append(cfg.RawRPCListeners, addr)
×
1492
        }
×
1493

1494
        // Listen on localhost if no REST listeners were specified.
1495
        if len(cfg.RawRESTListeners) == 0 {
×
1496
                addr := fmt.Sprintf("localhost:%d", defaultRESTPort)
×
1497
                cfg.RawRESTListeners = append(cfg.RawRESTListeners, addr)
×
1498
        }
×
1499

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

1513
        // Add default port to all RPC listener addresses if needed and remove
1514
        // duplicate addresses.
1515
        cfg.RPCListeners, err = lncfg.NormalizeAddresses(
×
1516
                cfg.RawRPCListeners, strconv.Itoa(defaultRPCPort),
×
1517
                cfg.net.ResolveTCPAddr,
×
1518
        )
×
1519
        if err != nil {
×
1520
                return nil, mkErr("error normalizing RPC listen addrs: %v", err)
×
1521
        }
×
1522

1523
        // Add default port to all REST listener addresses if needed and remove
1524
        // duplicate addresses.
1525
        cfg.RESTListeners, err = lncfg.NormalizeAddresses(
×
1526
                cfg.RawRESTListeners, strconv.Itoa(defaultRESTPort),
×
1527
                cfg.net.ResolveTCPAddr,
×
1528
        )
×
1529
        if err != nil {
×
1530
                return nil, mkErr("error normalizing REST listen addrs: %v", err)
×
1531
        }
×
1532

1533
        switch {
×
1534
        // The no seed backup and auto unlock are mutually exclusive.
1535
        case cfg.NoSeedBackup && cfg.WalletUnlockPasswordFile != "":
×
1536
                return nil, mkErr("cannot set noseedbackup and " +
×
1537
                        "wallet-unlock-password-file at the same time")
×
1538

1539
        // The "allow-create" flag cannot be set without the auto unlock file.
1540
        case cfg.WalletUnlockAllowCreate && cfg.WalletUnlockPasswordFile == "":
×
1541
                return nil, mkErr("cannot set wallet-unlock-allow-create " +
×
1542
                        "without wallet-unlock-password-file")
×
1543

1544
        // If a password file was specified, we need it to exist.
1545
        case cfg.WalletUnlockPasswordFile != "" &&
1546
                !lnrpc.FileExists(cfg.WalletUnlockPasswordFile):
×
1547

×
1548
                return nil, mkErr("wallet unlock password file %s does "+
×
1549
                        "not exist", cfg.WalletUnlockPasswordFile)
×
1550
        }
1551

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

1564
        if cfg.DisableRest {
×
1565
                ltndLog.Infof("REST API is disabled!")
×
1566
                cfg.RESTListeners = nil
×
1567
        } else {
×
1568
                err = lncfg.EnforceSafeAuthentication(
×
1569
                        cfg.RESTListeners, !cfg.NoMacaroons, !cfg.DisableRestTLS,
×
1570
                )
×
1571
                if err != nil {
×
1572
                        return nil, mkErr("error enforcing safe "+
×
1573
                                "authentication on REST ports: %v", err)
×
1574
                }
×
1575
        }
1576

1577
        // Remove the listening addresses specified if listening is disabled.
1578
        if cfg.DisableListen {
×
1579
                ltndLog.Infof("Listening on the p2p interface is disabled!")
×
1580
                cfg.Listeners = nil
×
1581
                cfg.ExternalIPs = nil
×
1582
        } else {
×
1583

×
1584
                // Add default port to all listener addresses if needed and remove
×
1585
                // duplicate addresses.
×
1586
                cfg.Listeners, err = lncfg.NormalizeAddresses(
×
1587
                        cfg.RawListeners, strconv.Itoa(defaultPeerPort),
×
1588
                        cfg.net.ResolveTCPAddr,
×
1589
                )
×
1590
                if err != nil {
×
1591
                        return nil, mkErr("error normalizing p2p listen "+
×
1592
                                "addrs: %v", err)
×
1593
                }
×
1594

1595
                // Add default port to all external IP addresses if needed and remove
1596
                // duplicate addresses.
1597
                cfg.ExternalIPs, err = lncfg.NormalizeAddresses(
×
1598
                        cfg.RawExternalIPs, strconv.Itoa(defaultPeerPort),
×
1599
                        cfg.net.ResolveTCPAddr,
×
1600
                )
×
1601
                if err != nil {
×
1602
                        return nil, err
×
1603
                }
×
1604

1605
                // For the p2p port it makes no sense to listen to an Unix socket.
1606
                // Also, we would need to refactor the brontide listener to support
1607
                // that.
1608
                for _, p2pListener := range cfg.Listeners {
×
1609
                        if lncfg.IsUnix(p2pListener) {
×
1610
                                return nil, mkErr("unix socket addresses "+
×
1611
                                        "cannot be used for the p2p "+
×
1612
                                        "connection listener: %s", p2pListener)
×
1613
                        }
×
1614
                }
1615
        }
1616

1617
        // Ensure that the specified minimum backoff is below or equal to the
1618
        // maximum backoff.
1619
        if cfg.MinBackoff > cfg.MaxBackoff {
×
1620
                return nil, mkErr("maxbackoff must be greater than minbackoff")
×
1621
        }
×
1622

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

1635
        // Parse any extra sqlite pragma options that may have been provided
1636
        // to determine if they override any of the defaults that we will
1637
        // otherwise add.
1638
        var (
×
1639
                defaultSynchronous = true
×
1640
                defaultAutoVacuum  = true
×
1641
                defaultFullfsync   = true
×
1642
        )
×
1643
        for _, option := range cfg.DB.Sqlite.PragmaOptions {
×
1644
                switch {
×
1645
                case strings.HasPrefix(option, "synchronous="):
×
1646
                        defaultSynchronous = false
×
1647

1648
                case strings.HasPrefix(option, "auto_vacuum="):
×
1649
                        defaultAutoVacuum = false
×
1650

1651
                case strings.HasPrefix(option, "fullfsync="):
×
1652
                        defaultFullfsync = false
×
1653

1654
                default:
×
1655
                }
1656
        }
1657

1658
        if defaultSynchronous {
×
1659
                cfg.DB.Sqlite.PragmaOptions = append(
×
1660
                        cfg.DB.Sqlite.PragmaOptions, "synchronous=full",
×
1661
                )
×
1662
        }
×
1663

1664
        if defaultAutoVacuum {
×
1665
                cfg.DB.Sqlite.PragmaOptions = append(
×
1666
                        cfg.DB.Sqlite.PragmaOptions, "auto_vacuum=incremental",
×
1667
                )
×
1668
        }
×
1669

1670
        if defaultFullfsync {
×
1671
                cfg.DB.Sqlite.PragmaOptions = append(
×
1672
                        cfg.DB.Sqlite.PragmaOptions, "fullfsync=true",
×
1673
                )
×
1674
        }
×
1675

1676
        // Ensure that the user hasn't chosen a remote-max-htlc value greater
1677
        // than the protocol maximum.
1678
        maxRemoteHtlcs := uint16(input.MaxHTLCNumber / 2)
×
1679
        if cfg.DefaultRemoteMaxHtlcs > maxRemoteHtlcs {
×
1680
                return nil, mkErr("default-remote-max-htlcs (%v) must be "+
×
1681
                        "less than %v", cfg.DefaultRemoteMaxHtlcs,
×
1682
                        maxRemoteHtlcs)
×
1683
        }
×
1684

1685
        // Clamp the ChannelCommitInterval so that commitment updates can still
1686
        // happen in a reasonable timeframe.
1687
        if cfg.ChannelCommitInterval > maxChannelCommitInterval {
×
1688
                return nil, mkErr("channel-commit-interval (%v) must be less "+
×
1689
                        "than %v", cfg.ChannelCommitInterval,
×
1690
                        maxChannelCommitInterval)
×
1691
        }
×
1692

1693
        // Limit PendingCommitInterval so we don't wait too long for the remote
1694
        // party to send back a revoke.
1695
        if cfg.PendingCommitInterval > maxPendingCommitInterval {
×
1696
                return nil, mkErr("pending-commit-interval (%v) must be less "+
×
1697
                        "than %v", cfg.PendingCommitInterval,
×
1698
                        maxPendingCommitInterval)
×
1699
        }
×
1700

1701
        if err := cfg.Gossip.Parse(); err != nil {
×
1702
                return nil, mkErr("error parsing gossip syncer: %v", err)
×
1703
        }
×
1704

1705
        // If the experimental protocol options specify any protocol messages
1706
        // that we want to handle as custom messages, set them now.
1707
        customMsg := cfg.ProtocolOptions.CustomMessageOverrides()
×
1708

×
1709
        // We can safely set our custom override values during startup because
×
1710
        // startup is blocked on config parsing.
×
1711
        if err := lnwire.SetCustomOverrides(customMsg); err != nil {
×
1712
                return nil, mkErr("custom-message: %v", err)
×
1713
        }
×
1714

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

1748
        // Don't allow both the old dust-threshold and the new
1749
        // channel-max-fee-exposure to be set.
1750
        if cfg.DustThreshold != 0 && cfg.MaxFeeExposure != 0 {
×
1751
                return nil, mkErr("cannot set both dust-threshold and " +
×
1752
                        "channel-max-fee-exposure")
×
1753
        }
×
1754

1755
        switch {
×
1756
        // Use the old dust-threshold as the max fee exposure if it is set and
1757
        // the new option is not.
1758
        case cfg.DustThreshold != 0:
×
1759
                cfg.MaxFeeExposure = cfg.DustThreshold
×
1760

1761
        // Use the default max fee exposure if the new option is not set and
1762
        // the old one is not set either.
1763
        case cfg.MaxFeeExposure == 0:
×
1764
                cfg.MaxFeeExposure = uint64(
×
1765
                        htlcswitch.DefaultMaxFeeExposure.ToSatoshis(),
×
1766
                )
×
1767
        }
1768

1769
        // Validate the subconfigs for workers, caches, and the tower client.
1770
        err = lncfg.Validate(
×
1771
                cfg.Workers,
×
1772
                cfg.Caches,
×
1773
                cfg.WtClient,
×
1774
                cfg.DB,
×
1775
                cfg.Cluster,
×
1776
                cfg.HealthChecks,
×
1777
                cfg.RPCMiddleware,
×
1778
                cfg.RemoteSigner,
×
1779
                cfg.Sweeper,
×
1780
                cfg.Htlcswitch,
×
1781
                cfg.Invoices,
×
1782
                cfg.Routing,
×
1783
                cfg.Pprof,
×
1784
                cfg.Gossip,
×
1785
        )
×
1786
        if err != nil {
×
1787
                return nil, err
×
1788
        }
×
1789

1790
        // Finally, ensure that the user's color is correctly formatted,
1791
        // otherwise the server will not be able to start after the unlocking
1792
        // the wallet.
1793
        _, err = lncfg.ParseHexColor(cfg.Color)
×
1794
        if err != nil {
×
1795
                return nil, mkErr("unable to parse node color: %v", err)
×
1796
        }
×
1797

1798
        // All good, return the sanitized result.
1799
        return &cfg, nil
×
1800
}
1801

1802
// graphDatabaseDir returns the default directory where the local bolt graph db
1803
// files are stored.
1804
func (c *Config) graphDatabaseDir() string {
×
1805
        return filepath.Join(
×
1806
                c.DataDir, defaultGraphSubDirname,
×
1807
                lncfg.NormalizeNetwork(c.ActiveNetParams.Name),
×
1808
        )
×
1809
}
×
1810

1811
// ImplementationConfig returns the configuration of what actual implementations
1812
// should be used when creating the main lnd instance.
1813
func (c *Config) ImplementationConfig(
1814
        interceptor signal.Interceptor) *ImplementationCfg {
×
1815

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

1836
        defaultImpl := NewDefaultWalletImpl(c, ltndLog, interceptor, false)
×
1837
        return &ImplementationCfg{
×
1838
                GrpcRegistrar:       defaultImpl,
×
1839
                RestRegistrar:       defaultImpl,
×
1840
                ExternalValidator:   defaultImpl,
×
1841
                DatabaseBuilder:     NewDefaultDatabaseBuilder(c, ltndLog),
×
1842
                WalletConfigBuilder: defaultImpl,
×
1843
                ChainControlBuilder: defaultImpl,
×
1844
        }
×
1845
}
1846

1847
// CleanAndExpandPath expands environment variables and leading ~ in the
1848
// passed path, cleans the result, and returns it.
1849
// This function is taken from https://github.com/btcsuite/btcd
1850
func CleanAndExpandPath(path string) string {
×
1851
        if path == "" {
×
1852
                return ""
×
1853
        }
×
1854

1855
        // Expand initial ~ to OS specific home directory.
1856
        if strings.HasPrefix(path, "~") {
×
1857
                var homeDir string
×
1858
                u, err := user.Current()
×
1859
                if err == nil {
×
1860
                        homeDir = u.HomeDir
×
1861
                } else {
×
1862
                        homeDir = os.Getenv("HOME")
×
1863
                }
×
1864

1865
                path = strings.Replace(path, "~", homeDir, 1)
×
1866
        }
1867

1868
        // NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
1869
        // but the variables can still be expanded via POSIX-style $VARIABLE.
1870
        return filepath.Clean(os.ExpandEnv(path))
×
1871
}
1872

1873
func parseRPCParams(cConfig *lncfg.Chain, nodeConfig interface{},
1874
        netParams chainreg.BitcoinNetParams) error {
×
1875

×
1876
        // First, we'll check our node config to make sure the RPC parameters
×
1877
        // were set correctly. We'll also determine the path to the conf file
×
1878
        // depending on the backend node.
×
1879
        var daemonName, confDir, confFile, confFileBase string
×
1880
        switch conf := nodeConfig.(type) {
×
1881
        case *lncfg.Btcd:
×
1882
                // Resolves environment variable references in RPCUser and
×
1883
                // RPCPass fields.
×
1884
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
×
1885
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
×
1886

×
1887
                // If both RPCUser and RPCPass are set, we assume those
×
1888
                // credentials are good to use.
×
1889
                if conf.RPCUser != "" && conf.RPCPass != "" {
×
1890
                        return nil
×
1891
                }
×
1892

1893
                // Set the daemon name for displaying proper errors.
1894
                daemonName = btcdBackendName
×
1895
                confDir = conf.Dir
×
1896
                confFileBase = btcdBackendName
×
1897

×
1898
                // If only ONE of RPCUser or RPCPass is set, we assume the
×
1899
                // user did that unintentionally.
×
1900
                if conf.RPCUser != "" || conf.RPCPass != "" {
×
1901
                        return fmt.Errorf("please set both or neither of "+
×
1902
                                "%[1]v.rpcuser, %[1]v.rpcpass", daemonName)
×
1903
                }
×
1904

1905
        case *lncfg.Bitcoind:
×
1906
                // Ensure that if the ZMQ options are set, that they are not
×
1907
                // equal.
×
1908
                if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
×
1909
                        err := checkZMQOptions(
×
1910
                                conf.ZMQPubRawBlock, conf.ZMQPubRawTx,
×
1911
                        )
×
1912
                        if err != nil {
×
1913
                                return err
×
1914
                        }
×
1915
                }
1916

1917
                // Ensure that if the estimate mode is set, that it is a legal
1918
                // value.
1919
                if conf.EstimateMode != "" {
×
1920
                        err := checkEstimateMode(conf.EstimateMode)
×
1921
                        if err != nil {
×
1922
                                return err
×
1923
                        }
×
1924
                }
1925

1926
                // Set the daemon name for displaying proper errors.
1927
                daemonName = bitcoindBackendName
×
1928
                confDir = conf.Dir
×
1929
                confFile = conf.ConfigPath
×
1930
                confFileBase = BitcoinChainName
×
1931

×
1932
                // Resolves environment variable references in RPCUser
×
1933
                // and RPCPass fields.
×
1934
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
×
1935
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
×
1936

×
1937
                // Check that cookie and credentials don't contradict each
×
1938
                // other.
×
1939
                if (conf.RPCUser != "" || conf.RPCPass != "") &&
×
1940
                        conf.RPCCookie != "" {
×
1941

×
1942
                        return fmt.Errorf("please only provide either "+
×
1943
                                "%[1]v.rpccookie or %[1]v.rpcuser and "+
×
1944
                                "%[1]v.rpcpass", daemonName)
×
1945
                }
×
1946

1947
                // We convert the cookie into a user name and password.
1948
                if conf.RPCCookie != "" {
×
1949
                        cookie, err := os.ReadFile(conf.RPCCookie)
×
1950
                        if err != nil {
×
1951
                                return fmt.Errorf("cannot read cookie file: %w",
×
1952
                                        err)
×
1953
                        }
×
1954

1955
                        splitCookie := strings.Split(string(cookie), ":")
×
1956
                        if len(splitCookie) != 2 {
×
1957
                                return fmt.Errorf("cookie file has a wrong " +
×
1958
                                        "format")
×
1959
                        }
×
1960
                        conf.RPCUser = splitCookie[0]
×
1961
                        conf.RPCPass = splitCookie[1]
×
1962
                }
1963

1964
                if conf.RPCUser != "" && conf.RPCPass != "" {
×
1965
                        // If all of RPCUser, RPCPass, ZMQBlockHost, and
×
1966
                        // ZMQTxHost are set, we assume those parameters are
×
1967
                        // good to use.
×
1968
                        if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
×
1969
                                return nil
×
1970
                        }
×
1971

1972
                        // If RPCUser and RPCPass are set and RPCPolling is
1973
                        // enabled, we assume the parameters are good to use.
1974
                        if conf.RPCPolling {
×
1975
                                return nil
×
1976
                        }
×
1977
                }
1978

1979
                // If not all of the parameters are set, we'll assume the user
1980
                // did this unintentionally.
1981
                if conf.RPCUser != "" || conf.RPCPass != "" ||
×
1982
                        conf.ZMQPubRawBlock != "" || conf.ZMQPubRawTx != "" {
×
1983

×
1984
                        return fmt.Errorf("please set %[1]v.rpcuser and "+
×
1985
                                "%[1]v.rpcpass (or %[1]v.rpccookie) together "+
×
1986
                                "with %[1]v.zmqpubrawblock, %[1]v.zmqpubrawtx",
×
1987
                                daemonName)
×
1988
                }
×
1989
        }
1990

1991
        // If we're in simnet mode, then the running btcd instance won't read
1992
        // the RPC credentials from the configuration. So if lnd wasn't
1993
        // specified the parameters, then we won't be able to start.
1994
        if cConfig.SimNet {
×
1995
                return fmt.Errorf("rpcuser and rpcpass must be set to your " +
×
1996
                        "btcd node's RPC parameters for simnet mode")
×
1997
        }
×
1998

1999
        fmt.Println("Attempting automatic RPC configuration to " + daemonName)
×
2000

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

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

2028
        fmt.Printf("Automatically obtained %v's RPC credentials\n", daemonName)
×
2029
        return nil
×
2030
}
2031

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

7✔
2056
        // Regex for ${ENV_VAR} format.
7✔
2057
        var reEnvVarWithBrackets = regexp.MustCompile(
7✔
2058
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$`,
7✔
2059
        )
7✔
2060

7✔
2061
        // Regex for ${ENV_VAR:-DEFAULT} format.
7✔
2062
        var reEnvVarWithDefault = regexp.MustCompile(
7✔
2063
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*):-([\S]+)\}$`,
7✔
2064
        )
7✔
2065

7✔
2066
        // Match against supported formats.
7✔
2067
        switch {
7✔
2068
        case reEnvVarWithDefault.MatchString(value):
3✔
2069
                matches := reEnvVarWithDefault.FindStringSubmatch(value)
3✔
2070
                envVariable := matches[1]
3✔
2071
                defaultValue := matches[2]
3✔
2072
                if envValue := os.Getenv(envVariable); envValue != "" {
4✔
2073
                        return envValue
1✔
2074
                }
1✔
2075

2076
                return defaultValue
2✔
2077

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

×
2083
                return envValue
×
2084

2085
        case reEnvVar.MatchString(value):
3✔
2086
                matches := reEnvVar.FindStringSubmatch(value)
3✔
2087
                envVariable := matches[1]
3✔
2088
                envValue := os.Getenv(envVariable)
3✔
2089

3✔
2090
                return envValue
3✔
2091
        }
2092

2093
        return value
1✔
2094
}
2095

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

2108
        // With the file open extract the contents of the configuration file so
2109
        // we can attempt to locate the RPC credentials.
2110
        configContents, err := io.ReadAll(btcdConfigFile)
×
2111
        if err != nil {
×
2112
                return "", "", err
×
2113
        }
×
2114

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

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

2139
        return supplyEnvValue(string(userSubmatches[1])),
×
2140
                supplyEnvValue(string(passSubmatches[1])), nil
×
2141
}
2142

2143
// extractBitcoindRPCParams attempts to extract the RPC credentials for an
2144
// existing bitcoind node instance. The routine looks for a cookie first,
2145
// optionally following the datadir configuration option in the bitcoin.conf. If
2146
// it doesn't find one, it looks for rpcuser/rpcpassword.
2147
func extractBitcoindRPCParams(networkName, bitcoindDataDir, bitcoindConfigPath,
2148
        rpcCookiePath string) (string, string, string, string, error) {
×
2149

×
2150
        // First, we'll open up the bitcoind configuration file found at the
×
2151
        // target destination.
×
2152
        bitcoindConfigFile, err := os.Open(bitcoindConfigPath)
×
2153
        if err != nil {
×
2154
                return "", "", "", "", err
×
2155
        }
×
2156
        defer func() { _ = bitcoindConfigFile.Close() }()
×
2157

2158
        // With the file open extract the contents of the configuration file so
2159
        // we can attempt to locate the RPC credentials.
2160
        configContents, err := io.ReadAll(bitcoindConfigFile)
×
2161
        if err != nil {
×
2162
                return "", "", "", "", err
×
2163
        }
×
2164

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

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

2208
        var chainDir string
×
2209
        switch networkName {
×
2210
        case "mainnet":
×
2211
                chainDir = ""
×
2212
        case "regtest", "testnet3", "testnet4", "signet":
×
2213
                chainDir = networkName
×
2214
        default:
×
2215
                return "", "", "", "", fmt.Errorf("unexpected networkname %v", networkName)
×
2216
        }
2217

2218
        cookiePath := filepath.Join(dataDir, chainDir, ".cookie")
×
2219
        if rpcCookiePath != "" {
×
2220
                cookiePath = rpcCookiePath
×
2221
        }
×
2222
        cookie, err := os.ReadFile(cookiePath)
×
2223
        if err == nil {
×
2224
                splitCookie := strings.Split(string(cookie), ":")
×
2225
                if len(splitCookie) == 2 {
×
2226
                        return splitCookie[0], splitCookie[1], zmqBlockHost,
×
2227
                                zmqTxHost, nil
×
2228
                }
×
2229
        }
2230

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

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

×
2249
        // Exit with an error if the cookie file, is defined in config, and
×
2250
        // can not be found, with both rpcuser and rpcpassword undefined.
×
2251
        if rpcCookiePath != "" && userSubmatches == nil && passSubmatches == nil {
×
2252
                return "", "", "", "", fmt.Errorf("unable to open cookie file (%v)",
×
2253
                        rpcCookiePath)
×
2254
        }
×
2255

2256
        if userSubmatches == nil {
×
2257
                return "", "", "", "", fmt.Errorf("unable to find rpcuser in " +
×
2258
                        "config")
×
2259
        }
×
2260
        if passSubmatches == nil {
×
2261
                return "", "", "", "", fmt.Errorf("unable to find rpcpassword " +
×
2262
                        "in config")
×
2263
        }
×
2264

2265
        return supplyEnvValue(string(userSubmatches[1])),
×
2266
                supplyEnvValue(string(passSubmatches[1])),
×
2267
                zmqBlockHost, zmqTxHost, nil
×
2268
}
2269

2270
// checkZMQOptions ensures that the provided addresses to use as the hosts for
2271
// ZMQ rawblock and rawtx notifications are different.
2272
func checkZMQOptions(zmqBlockHost, zmqTxHost string) error {
×
2273
        if zmqBlockHost == zmqTxHost {
×
2274
                return errors.New("zmqpubrawblock and zmqpubrawtx must be set " +
×
2275
                        "to different addresses")
×
2276
        }
×
2277

2278
        return nil
×
2279
}
2280

2281
// checkEstimateMode ensures that the provided estimate mode is legal.
2282
func checkEstimateMode(estimateMode string) error {
×
2283
        for _, mode := range bitcoindEstimateModes {
×
2284
                if estimateMode == mode {
×
2285
                        return nil
×
2286
                }
×
2287
        }
2288

2289
        return fmt.Errorf("estimatemode must be one of the following: %v",
×
2290
                bitcoindEstimateModes[:])
×
2291
}
2292

2293
// configToFlatMap converts the given config struct into a flat map of
2294
// key/value pairs using the dot notation we are used to from the config file
2295
// or command line flags. It also returns a map containing deprecated config
2296
// options.
2297
func configToFlatMap(cfg Config) (map[string]string,
2298
        map[string]struct{}, error) {
1✔
2299

1✔
2300
        result := make(map[string]string)
1✔
2301

1✔
2302
        // deprecated stores a map of deprecated options found in the config
1✔
2303
        // that are set by the users. A config option is considered as
1✔
2304
        // deprecated if it has a `hidden` flag.
1✔
2305
        deprecated := make(map[string]struct{})
1✔
2306

1✔
2307
        // redact is the helper function that redacts sensitive values like
1✔
2308
        // passwords.
1✔
2309
        redact := func(key, value string) string {
316✔
2310
                sensitiveKeySuffixes := []string{
315✔
2311
                        "pass",
315✔
2312
                        "password",
315✔
2313
                        "dsn",
315✔
2314
                }
315✔
2315
                for _, suffix := range sensitiveKeySuffixes {
1,253✔
2316
                        if strings.HasSuffix(key, suffix) {
943✔
2317
                                return "[redacted]"
5✔
2318
                        }
5✔
2319
                }
2320

2321
                return value
310✔
2322
        }
2323

2324
        // printConfig is the helper function that goes into nested structs
2325
        // recursively. Because we call it recursively, we need to declare it
2326
        // before we define it.
2327
        var printConfig func(reflect.Value, string)
1✔
2328
        printConfig = func(obj reflect.Value, prefix string) {
62✔
2329
                // Turn struct pointers into the actual struct, so we can
61✔
2330
                // iterate over the fields as we would with a struct value.
61✔
2331
                if obj.Kind() == reflect.Ptr {
117✔
2332
                        obj = obj.Elem()
56✔
2333
                }
56✔
2334

2335
                // Abort on nil values.
2336
                if !obj.IsValid() {
73✔
2337
                        return
12✔
2338
                }
12✔
2339

2340
                // Loop over all fields of the struct and inspect the type.
2341
                for i := 0; i < obj.NumField(); i++ {
441✔
2342
                        field := obj.Field(i)
392✔
2343
                        fieldType := obj.Type().Field(i)
392✔
2344

392✔
2345
                        longName := fieldType.Tag.Get("long")
392✔
2346
                        namespace := fieldType.Tag.Get("namespace")
392✔
2347
                        group := fieldType.Tag.Get("group")
392✔
2348
                        hidden := fieldType.Tag.Get("hidden")
392✔
2349

392✔
2350
                        switch {
392✔
2351
                        // We have a long name defined, this is a config value.
2352
                        case longName != "":
315✔
2353
                                key := longName
315✔
2354
                                if prefix != "" {
532✔
2355
                                        key = prefix + "." + key
217✔
2356
                                }
217✔
2357

2358
                                // Add the value directly to the flattened map.
2359
                                result[key] = redact(key, fmt.Sprintf(
315✔
2360
                                        "%v", field.Interface(),
315✔
2361
                                ))
315✔
2362

315✔
2363
                                // If there's a hidden flag, it's deprecated.
315✔
2364
                                if hidden == "true" && !field.IsZero() {
316✔
2365
                                        deprecated[key] = struct{}{}
1✔
2366
                                }
1✔
2367

2368
                        // We have no long name but a namespace, this is a
2369
                        // nested struct.
2370
                        case longName == "" && namespace != "":
54✔
2371
                                key := namespace
54✔
2372
                                if prefix != "" {
69✔
2373
                                        key = prefix + "." + key
15✔
2374
                                }
15✔
2375

2376
                                printConfig(field, key)
54✔
2377

2378
                        // Just a group means this is a dummy struct to house
2379
                        // multiple config values, the group name doesn't go
2380
                        // into the final field name.
2381
                        case longName == "" && group != "":
1✔
2382
                                printConfig(field, prefix)
1✔
2383

2384
                        // Anonymous means embedded struct. We need to recurse
2385
                        // into it but without adding anything to the prefix.
2386
                        case fieldType.Anonymous:
5✔
2387
                                printConfig(field, prefix)
5✔
2388

2389
                        default:
17✔
2390
                                continue
17✔
2391
                        }
2392
                }
2393
        }
2394

2395
        // Turn the whole config struct into a flat map.
2396
        printConfig(reflect.ValueOf(cfg), "")
1✔
2397

1✔
2398
        return result, deprecated, nil
1✔
2399
}
2400

2401
// logWarningsForDeprecation logs a warning if a deprecated config option is
2402
// set.
2403
func logWarningsForDeprecation(cfg Config) {
×
2404
        _, deprecated, err := configToFlatMap(cfg)
×
2405
        if err != nil {
×
2406
                ltndLog.Errorf("Convert configs to map: %v", err)
×
2407
        }
×
2408

2409
        for k := range deprecated {
×
2410
                ltndLog.Warnf("Config '%s' is deprecated, please remove it", k)
×
2411
        }
×
2412
}
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