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

lightningnetwork / lnd / 13035292482

29 Jan 2025 03:59PM UTC coverage: 49.3% (-9.5%) from 58.777%
13035292482

Pull #9456

github

mohamedawnallah
docs: update release-notes-0.19.0.md

In this commit, we warn users about the removal
of RPCs `SendToRoute`, `SendToRouteSync`, `SendPayment`,
and `SendPaymentSync` in the next release 0.20.
Pull Request #9456: lnrpc+docs: deprecate warning `SendToRoute`, `SendToRouteSync`, `SendPayment`, and `SendPaymentSync` in Release 0.19

100634 of 204126 relevant lines covered (49.3%)

1.54 hits per line

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

53.91
/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
        // BitcoinChainName is a string that represents the Bitcoin blockchain.
242
        BitcoinChainName = "bitcoin"
243

244
        bitcoindBackendName = "bitcoind"
245
        btcdBackendName     = "btcd"
246
        neutrinoBackendName = "neutrino"
247
)
248

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

258
        // DefaultConfigFile is the default full path of lnd's configuration
259
        // file.
260
        DefaultConfigFile = filepath.Join(DefaultLndDir, lncfg.DefaultConfigFilename)
261

262
        defaultDataDir = filepath.Join(DefaultLndDir, defaultDataDirname)
263
        defaultLogDir  = filepath.Join(DefaultLndDir, defaultLogDirname)
264

265
        defaultTowerDir = filepath.Join(defaultDataDir, defaultTowerSubDirname)
266

267
        defaultTLSCertPath    = filepath.Join(DefaultLndDir, defaultTLSCertFilename)
268
        defaultTLSKeyPath     = filepath.Join(DefaultLndDir, defaultTLSKeyFilename)
269
        defaultLetsEncryptDir = filepath.Join(DefaultLndDir, defaultLetsEncryptDirname)
270

271
        defaultBtcdDir         = btcutil.AppDataDir(btcdBackendName, false)
272
        defaultBtcdRPCCertFile = filepath.Join(defaultBtcdDir, "rpc.cert")
273

274
        defaultBitcoindDir = btcutil.AppDataDir(BitcoinChainName, false)
275

276
        defaultTorSOCKS   = net.JoinHostPort("localhost", strconv.Itoa(defaultTorSOCKSPort))
277
        defaultTorDNS     = net.JoinHostPort(defaultTorDNSHost, strconv.Itoa(defaultTorDNSPort))
278
        defaultTorControl = net.JoinHostPort("localhost", strconv.Itoa(defaultTorControlPort))
279

280
        // bitcoindEsimateModes defines all the legal values for bitcoind's
281
        // estimatesmartfee RPC call.
282
        defaultBitcoindEstimateMode = "CONSERVATIVE"
283
        bitcoindEstimateModes       = [2]string{"ECONOMICAL", defaultBitcoindEstimateMode}
284

285
        defaultPrunedNodeMaxPeers = 4
286
)
287

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

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

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

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

320
        LetsEncryptDir    string `long:"letsencryptdir" description:"The directory to store Let's Encrypt certificates within"`
321
        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."`
322
        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."`
323

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

349
        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"`
350

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

356
        Pprof *lncfg.Pprof `group:"Pprof" namespace:"pprof"`
357

358
        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"`
359
        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."`
360
        MaxPendingChannels int    `long:"maxpendingchannels" description:"The maximum number of incoming pending channels permitted per peer."`
361
        BackupFilePath     string `long:"backupfilepath" description:"The target location of the channel backup file"`
362

363
        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"`
364

365
        Bitcoin      *lncfg.Chain    `group:"Bitcoin" namespace:"bitcoin"`
366
        BtcdMode     *lncfg.Btcd     `group:"btcd" namespace:"btcd"`
367
        BitcoindMode *lncfg.Bitcoind `group:"bitcoind" namespace:"bitcoind"`
368
        NeutrinoMode *lncfg.Neutrino `group:"neutrino" namespace:"neutrino"`
369

370
        BlockCacheSize uint64 `long:"blockcachesize" description:"The maximum capacity of the block cache"`
371

372
        Autopilot *lncfg.AutoPilot `group:"Autopilot" namespace:"autopilot"`
373

374
        Tor *lncfg.Tor `group:"Tor" namespace:"tor"`
375

376
        SubRPCServers *subRPCServerConfigs `group:"subrpc"`
377

378
        Hodl *hodl.Config `group:"hodl" namespace:"hodl"`
379

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

382
        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."`
383
        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."`
384
        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."`
385

386
        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."`
387

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

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

402
        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."`
403

404
        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."`
405

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

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

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

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

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

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

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

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

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

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

429
        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"`
430

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

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

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

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

439
        net tor.Net
440

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

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

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

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

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

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

453
        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"`
454

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

457
        Fee *lncfg.Fee `group:"fee" namespace:"fee"`
458

459
        Invoices *lncfg.Invoices `group:"invoices" namespace:"invoices"`
460

461
        Routing *lncfg.Routing `group:"routing" namespace:"routing"`
462

463
        Gossip *lncfg.Gossip `group:"gossip" namespace:"gossip"`
464

465
        Workers *lncfg.Workers `group:"workers" namespace:"workers"`
466

467
        Caches *lncfg.Caches `group:"caches" namespace:"caches"`
468

469
        Prometheus lncfg.Prometheus `group:"prometheus" namespace:"prometheus"`
470

471
        WtClient *lncfg.WtClient `group:"wtclient" namespace:"wtclient"`
472

473
        Watchtower *lncfg.Watchtower `group:"watchtower" namespace:"watchtower"`
474

475
        ProtocolOptions *lncfg.ProtocolOptions `group:"protocol" namespace:"protocol"`
476

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

479
        HealthChecks *lncfg.HealthCheckConfig `group:"healthcheck" namespace:"healthcheck"`
480

481
        DB *lncfg.DB `group:"db" namespace:"db"`
482

483
        Cluster *lncfg.Cluster `group:"cluster" namespace:"cluster"`
484

485
        RPCMiddleware *lncfg.RPCMiddleware `group:"rpcmiddleware" namespace:"rpcmiddleware"`
486

487
        RemoteSigner *lncfg.RemoteSigner `group:"remotesigner" namespace:"remotesigner"`
488

489
        Sweeper *lncfg.Sweeper `group:"sweeper" namespace:"sweeper"`
490

491
        Htlcswitch *lncfg.Htlcswitch `group:"htlcswitch" namespace:"htlcswitch"`
492

493
        GRPC *GRPCConfig `group:"grpc" namespace:"grpc"`
494

495
        // SubLogMgr is the root logger that all the daemon's subloggers are
496
        // hooked up to.
497
        SubLogMgr  *build.SubLoggerManager
498
        LogRotator *build.RotatingLogWriter
499
        LogConfig  *build.LogConfig `group:"logging" namespace:"logging"`
500

501
        // networkDir is the path to the directory of the currently active
502
        // network. This path will hold the files related to each different
503
        // network.
504
        networkDir string
505

506
        // ActiveNetParams contains parameters of the target chain.
507
        ActiveNetParams chainreg.BitcoinNetParams
508

509
        // Estimator is used to estimate routing probabilities.
510
        Estimator routing.Estimator
511

512
        // Dev specifies configs used for integration tests, which is always
513
        // empty if not built with `integration` flag.
514
        Dev *lncfg.DevConfig `group:"dev" namespace:"dev"`
515

516
        // HTTPHeaderTimeout is the maximum duration that the server will wait
517
        // before timing out reading the headers of an HTTP request.
518
        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."`
519
}
520

521
// GRPCConfig holds the configuration options for the gRPC server.
522
// See https://github.com/grpc/grpc-go/blob/v1.41.0/keepalive/keepalive.go#L50
523
// for more details. Any value of 0 means we use the gRPC internal default
524
// values.
525
//
526
//nolint:ll
527
type GRPCConfig struct {
528
        // ServerPingTime is a duration for the amount of time of no activity
529
        // after which the server pings the client to see if the transport is
530
        // still alive. If set below 1s, a minimum value of 1s will be used
531
        // instead.
532
        ServerPingTime time.Duration `long:"server-ping-time" description:"How long the server waits on a gRPC stream with no activity before pinging the client."`
533

534
        // ServerPingTimeout is the duration the server waits after having
535
        // pinged for keepalive check, and if no activity is seen even after
536
        // that the connection is closed.
537
        ServerPingTimeout time.Duration `long:"server-ping-timeout" description:"How long the server waits for the response from the client for the keepalive ping response."`
538

539
        // ClientPingMinWait is the minimum amount of time a client should wait
540
        // before sending a keepalive ping.
541
        ClientPingMinWait time.Duration `long:"client-ping-min-wait" description:"The minimum amount of time the client should wait before sending a keepalive ping."`
542

543
        // ClientAllowPingWithoutStream specifies whether pings from the client
544
        // are allowed even if there are no active gRPC streams. This might be
545
        // useful to keep the underlying HTTP/2 connection open for future
546
        // requests.
547
        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."`
548
}
549

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

3✔
600
                Fee: &lncfg.Fee{
3✔
601
                        MinUpdateTimeout: lncfg.DefaultMinUpdateTimeout,
3✔
602
                        MaxUpdateTimeout: lncfg.DefaultMaxUpdateTimeout,
3✔
603
                },
3✔
604

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

3✔
742
// LoadConfig initializes and parses the config using a config file and command
3✔
743
// line options.
744
//
745
// The configuration proceeds as follows:
746
//  1. Start with a default config with sane settings
747
//  2. Pre-parse the command line to check for an alternative config file
748
//  3. Load configuration file overwriting defaults with any specified options
749
//  4. Parse CLI options and overwrite/add any specified options
750
func LoadConfig(interceptor signal.Interceptor) (*Config, error) {
751
        // Pre-parse the command line options to pick up an alternative config
752
        // file.
3✔
753
        preCfg := DefaultConfig()
3✔
754
        if _, err := flags.Parse(&preCfg); err != nil {
3✔
755
                return nil, err
3✔
756
        }
3✔
757

×
758
        // Show the version and exit if the version flag was specified.
×
759
        appName := filepath.Base(os.Args[0])
760
        appName = strings.TrimSuffix(appName, filepath.Ext(appName))
761
        usageMessage := fmt.Sprintf("Use %s -h to show usage", appName)
3✔
762
        if preCfg.ShowVersion {
3✔
763
                fmt.Println(appName, "version", build.Version(),
3✔
764
                        "commit="+build.Commit)
3✔
765
                os.Exit(0)
×
766
        }
×
767

×
768
        // If the config file path has not been modified by the user, then we'll
×
769
        // use the default config file path. However, if the user has modified
770
        // their lnddir, then we should assume they intend to use the config
771
        // file within it.
772
        configFileDir := CleanAndExpandPath(preCfg.LndDir)
773
        configFilePath := CleanAndExpandPath(preCfg.ConfigFile)
774
        switch {
3✔
775
        // User specified --lnddir but no --configfile. Update the config file
3✔
776
        // path to the lnd config directory, but don't require it to exist.
3✔
777
        case configFileDir != DefaultLndDir &&
778
                configFilePath == DefaultConfigFile:
779

780
                configFilePath = filepath.Join(
3✔
781
                        configFileDir, lncfg.DefaultConfigFilename,
3✔
782
                )
3✔
783

3✔
784
        // User did specify an explicit --configfile, so we check that it does
3✔
785
        // exist under that path to avoid surprises.
786
        case configFilePath != DefaultConfigFile:
787
                if !lnrpc.FileExists(configFilePath) {
788
                        return nil, fmt.Errorf("specified config file does "+
×
789
                                "not exist in %s", configFilePath)
×
790
                }
×
791
        }
×
792

×
793
        // Next, load any additional configuration options from the file.
794
        var configFileError error
795
        cfg := preCfg
796
        fileParser := flags.NewParser(&cfg, flags.Default)
3✔
797
        err := flags.NewIniParser(fileParser).ParseFile(configFilePath)
3✔
798
        if err != nil {
3✔
799
                // If it's a parsing related error, then we'll return
3✔
800
                // immediately, otherwise we can proceed as possibly the config
6✔
801
                // file doesn't exist which is OK.
3✔
802
                if lnutils.ErrorAs[*flags.IniError](err) ||
3✔
803
                        lnutils.ErrorAs[*flags.Error](err) {
3✔
804

3✔
805
                        return nil, err
3✔
806
                }
×
807

×
808
                configFileError = err
×
809
        }
810

3✔
811
        // Finally, parse the remaining command line options again to ensure
812
        // they take precedence.
813
        flagParser := flags.NewParser(&cfg, flags.Default)
814
        if _, err := flagParser.Parse(); err != nil {
815
                return nil, err
3✔
816
        }
3✔
817

×
818
        // Make sure everything we just loaded makes sense.
×
819
        cleanCfg, err := ValidateConfig(
820
                cfg, interceptor, fileParser, flagParser,
821
        )
3✔
822
        var usageErr *lncfg.UsageError
3✔
823
        if errors.As(err, &usageErr) {
3✔
824
                // The logging system might not yet be initialized, so we also
3✔
825
                // write to stderr to make sure the error appears somewhere.
3✔
826
                _, _ = fmt.Fprintln(os.Stderr, usageMessage)
×
827
                ltndLog.Warnf("Incorrect usage: %v", usageMessage)
×
828

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

×
834
                return nil, err
×
835
        }
×
836
        if err != nil {
×
837
                // The log subsystem might not yet be initialized. But we still
×
838
                // try to log the error there since some packaging solutions
3✔
839
                // might only look at the log and not stdout/stderr.
×
840
                ltndLog.Warnf("Error validating config: %v", err)
×
841

×
842
                return nil, err
×
843
        }
×
844

×
845
        // Warn about missing config file only after all other configuration is
×
846
        // done. This prevents the warning on help messages and invalid options.
847
        // Note this should go directly before the return.
848
        if configFileError != nil {
849
                ltndLog.Warnf("%v", configFileError)
850
        }
6✔
851

3✔
852
        // Finally, log warnings for deprecated config options if they are set.
3✔
853
        logWarningsForDeprecation(*cleanCfg)
854

855
        return cleanCfg, nil
3✔
856
}
3✔
857

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

864
        // Special show command to list supported subsystems and exit.
3✔
865
        if cfg.DebugLevel == "show" {
3✔
866
                subLogMgr := build.NewSubLoggerManager()
3✔
867

6✔
868
                // Initialize logging at the default logging level.
3✔
869
                SetupLoggers(subLogMgr, interceptor)
3✔
870

3✔
871
                fmt.Println("Supported subsystems",
3✔
872
                        subLogMgr.SupportedSubsystems())
3✔
873
                os.Exit(0)
3✔
874
        }
3✔
875

3✔
876
        // If the provided lnd directory is not the default, we'll modify the
3✔
877
        // path to all of the files and directories that will live within it.
878
        lndDir := CleanAndExpandPath(cfg.LndDir)
879
        if lndDir != DefaultLndDir {
880
                cfg.DataDir = filepath.Join(lndDir, defaultDataDirname)
3✔
881
                cfg.LetsEncryptDir = filepath.Join(
6✔
882
                        lndDir, defaultLetsEncryptDirname,
3✔
883
                )
3✔
884
                cfg.TLSCertPath = filepath.Join(lndDir, defaultTLSCertFilename)
3✔
885
                cfg.TLSKeyPath = filepath.Join(lndDir, defaultTLSKeyFilename)
3✔
886
                cfg.LogDir = filepath.Join(lndDir, defaultLogDirname)
3✔
887

3✔
888
                // If the watchtower's directory is set to the default, i.e. the
3✔
889
                // user has not requested a different location, we'll move the
3✔
890
                // location to be relative to the specified lnd directory.
3✔
891
                if cfg.Watchtower.TowerDir == defaultTowerDir {
3✔
892
                        cfg.Watchtower.TowerDir = filepath.Join(
3✔
893
                                cfg.DataDir, defaultTowerSubDirname,
6✔
894
                        )
3✔
895
                }
3✔
896
        }
3✔
897

3✔
898
        funcName := "ValidateConfig"
899
        mkErr := func(format string, args ...interface{}) error {
900
                return fmt.Errorf(funcName+": "+format, args...)
3✔
901
        }
3✔
902
        makeDirectory := func(dir string) error {
×
903
                err := os.MkdirAll(dir, 0700)
×
904
                if err != nil {
6✔
905
                        // Show a nicer error message if it's because a symlink
3✔
906
                        // is linked to a directory that does not exist
3✔
907
                        // (probably because it's not mounted).
×
908
                        if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
×
909
                                link, lerr := os.Readlink(e.Path)
×
910
                                if lerr == nil {
×
911
                                        str := "is symlink %s -> %s mounted?"
×
912
                                        err = fmt.Errorf(str, e.Path, link)
×
913
                                }
×
914
                        }
×
915

×
916
                        str := "Failed to create lnd directory '%s': %v"
917
                        return mkErr(str, dir, err)
918
                }
×
919

×
920
                return nil
921
        }
922

3✔
923
        // IsSet returns true if an option has been set in either the config
924
        // file or by a flag.
925
        isSet := func(field string) (bool, error) {
926
                fieldName, ok := reflect.TypeOf(Config{}).FieldByName(field)
927
                if !ok {
6✔
928
                        str := "could not find field %s"
3✔
929
                        return false, mkErr(str, field)
3✔
930
                }
×
931

×
932
                long, ok := fieldName.Tag.Lookup("long")
×
933
                if !ok {
934
                        str := "field %s does not have a long tag"
3✔
935
                        return false, mkErr(str, field)
3✔
936
                }
×
937

×
938
                // The user has the option to set the flag in either the config
×
939
                // file or as a command line flag. If any is set, we consider it
940
                // to be set, not applying any precedence rules here (since it
941
                // is a boolean the default is false anyway which would screw up
942
                // any precedence rules). Additionally, we need to also support
943
                // the use case where the config struct is embedded _within_
944
                // another struct with a prefix (as is the case with
945
                // lightning-terminal).
946
                fileOption := fileParser.FindOptionByLongName(long)
947
                fileOptionNested := fileParser.FindOptionByLongName(
948
                        "lnd." + long,
3✔
949
                )
3✔
950
                flagOption := flagParser.FindOptionByLongName(long)
3✔
951
                flagOptionNested := flagParser.FindOptionByLongName(
3✔
952
                        "lnd." + long,
3✔
953
                )
3✔
954

3✔
955
                return (fileOption != nil && fileOption.IsSet()) ||
3✔
956
                                (fileOptionNested != nil && fileOptionNested.IsSet()) ||
3✔
957
                                (flagOption != nil && flagOption.IsSet()) ||
3✔
958
                                (flagOptionNested != nil && flagOptionNested.IsSet()),
3✔
959
                        nil
3✔
960
        }
3✔
961

3✔
962
        // As soon as we're done parsing configuration options, ensure all paths
963
        // to directories and files are cleaned and expanded before attempting
964
        // to use them later on.
965
        cfg.DataDir = CleanAndExpandPath(cfg.DataDir)
966
        cfg.TLSCertPath = CleanAndExpandPath(cfg.TLSCertPath)
967
        cfg.TLSKeyPath = CleanAndExpandPath(cfg.TLSKeyPath)
3✔
968
        cfg.LetsEncryptDir = CleanAndExpandPath(cfg.LetsEncryptDir)
3✔
969
        cfg.AdminMacPath = CleanAndExpandPath(cfg.AdminMacPath)
3✔
970
        cfg.ReadMacPath = CleanAndExpandPath(cfg.ReadMacPath)
3✔
971
        cfg.InvoiceMacPath = CleanAndExpandPath(cfg.InvoiceMacPath)
3✔
972
        cfg.LogDir = CleanAndExpandPath(cfg.LogDir)
3✔
973
        cfg.BtcdMode.Dir = CleanAndExpandPath(cfg.BtcdMode.Dir)
3✔
974
        cfg.BitcoindMode.Dir = CleanAndExpandPath(cfg.BitcoindMode.Dir)
3✔
975
        cfg.BitcoindMode.ConfigPath = CleanAndExpandPath(
3✔
976
                cfg.BitcoindMode.ConfigPath,
3✔
977
        )
3✔
978
        cfg.BitcoindMode.RPCCookie = CleanAndExpandPath(cfg.BitcoindMode.RPCCookie)
3✔
979
        cfg.Tor.PrivateKeyPath = CleanAndExpandPath(cfg.Tor.PrivateKeyPath)
3✔
980
        cfg.Tor.WatchtowerKeyPath = CleanAndExpandPath(cfg.Tor.WatchtowerKeyPath)
3✔
981
        cfg.Watchtower.TowerDir = CleanAndExpandPath(cfg.Watchtower.TowerDir)
3✔
982
        cfg.BackupFilePath = CleanAndExpandPath(cfg.BackupFilePath)
3✔
983
        cfg.WalletUnlockPasswordFile = CleanAndExpandPath(
3✔
984
                cfg.WalletUnlockPasswordFile,
3✔
985
        )
3✔
986

3✔
987
        // Ensure that the user didn't attempt to specify negative values for
3✔
988
        // any of the autopilot params.
3✔
989
        if cfg.Autopilot.MaxChannels < 0 {
3✔
990
                str := "autopilot.maxchannels must be non-negative"
3✔
991

3✔
992
                return nil, mkErr(str)
×
993
        }
×
994
        if cfg.Autopilot.Allocation < 0 {
×
995
                str := "autopilot.allocation must be non-negative"
×
996

3✔
997
                return nil, mkErr(str)
×
998
        }
×
999
        if cfg.Autopilot.MinChannelSize < 0 {
×
1000
                str := "autopilot.minchansize must be non-negative"
×
1001

3✔
1002
                return nil, mkErr(str)
×
1003
        }
×
1004
        if cfg.Autopilot.MaxChannelSize < 0 {
×
1005
                str := "autopilot.maxchansize must be non-negative"
×
1006

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

3✔
1012
                return nil, mkErr(str)
×
1013
        }
×
1014
        if cfg.Autopilot.ConfTarget < 1 {
×
1015
                str := "autopilot.conftarget must be positive"
×
1016

3✔
1017
                return nil, mkErr(str)
×
1018
        }
×
1019

×
1020
        // Ensure that the specified values for the min and max channel size
×
1021
        // are within the bounds of the normal chan size constraints.
1022
        if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
1023
                cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
1024
        }
3✔
1025
        if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
×
1026
                cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
×
1027
        }
3✔
1028

×
1029
        if _, err := validateAtplCfg(cfg.Autopilot); err != nil {
×
1030
                return nil, mkErr("error validating autopilot: %v", err)
1031
        }
3✔
1032

×
1033
        // Ensure that --maxchansize is properly handled when set by user.
×
1034
        // For non-Wumbo channels this limit remains 16777215 satoshis by default
1035
        // as specified in BOLT-02. For wumbo channels this limit is 1,000,000,000.
1036
        // satoshis (10 BTC). Always enforce --maxchansize explicitly set by user.
1037
        // If unset (marked by 0 value), then enforce proper default.
1038
        if cfg.MaxChanSize == 0 {
1039
                if cfg.ProtocolOptions.Wumbo() {
1040
                        cfg.MaxChanSize = int64(funding.MaxBtcFundingAmountWumbo)
6✔
1041
                } else {
6✔
1042
                        cfg.MaxChanSize = int64(funding.MaxBtcFundingAmount)
3✔
1043
                }
6✔
1044
        }
3✔
1045

3✔
1046
        // Ensure that the user specified values for the min and max channel
1047
        // size make sense.
1048
        if cfg.MaxChanSize < cfg.MinChanSize {
1049
                return nil, mkErr("invalid channel size parameters: "+
1050
                        "max channel size %v, must be no less than min chan "+
3✔
1051
                        "size %v", cfg.MaxChanSize, cfg.MinChanSize,
×
1052
                )
×
1053
        }
×
1054

×
1055
        // Don't allow superfluous --maxchansize greater than
×
1056
        // BOLT 02 soft-limit for non-wumbo channel
1057
        if !cfg.ProtocolOptions.Wumbo() &&
1058
                cfg.MaxChanSize > int64(MaxFundingAmount) {
1059

3✔
1060
                return nil, mkErr("invalid channel size parameters: "+
3✔
1061
                        "maximum channel size %v is greater than maximum "+
×
1062
                        "non-wumbo channel size %v", cfg.MaxChanSize,
×
1063
                        MaxFundingAmount,
×
1064
                )
×
1065
        }
×
1066

×
1067
        // Ensure that the amount data for revoked commitment transactions is
×
1068
        // stored if the watchtower client is active.
1069
        if cfg.DB.NoRevLogAmtData && cfg.WtClient.Active {
1070
                return nil, mkErr("revocation log amount data must be stored " +
1071
                        "if the watchtower client is active")
3✔
1072
        }
×
1073

×
1074
        // Ensure a valid max channel fee allocation was set.
×
1075
        if cfg.MaxChannelFeeAllocation <= 0 || cfg.MaxChannelFeeAllocation > 1 {
1076
                return nil, mkErr("invalid max channel fee allocation: %v, "+
1077
                        "must be within (0, 1]", cfg.MaxChannelFeeAllocation)
3✔
1078
        }
×
1079

×
1080
        if cfg.MaxCommitFeeRateAnchors < 1 {
×
1081
                return nil, mkErr("invalid max commit fee rate anchors: %v, "+
1082
                        "must be at least 1 sat/vByte",
3✔
1083
                        cfg.MaxCommitFeeRateAnchors)
×
1084
        }
×
1085

×
1086
        // Validate the Tor config parameters.
×
1087
        socks, err := lncfg.ParseAddressString(
1088
                cfg.Tor.SOCKS, strconv.Itoa(defaultTorSOCKSPort),
1089
                cfg.net.ResolveTCPAddr,
3✔
1090
        )
3✔
1091
        if err != nil {
3✔
1092
                return nil, err
3✔
1093
        }
3✔
1094
        cfg.Tor.SOCKS = socks.String()
×
1095

×
1096
        // We'll only attempt to normalize and resolve the DNS host if it hasn't
3✔
1097
        // changed, as it doesn't need to be done for the default.
3✔
1098
        if cfg.Tor.DNS != defaultTorDNS {
3✔
1099
                dns, err := lncfg.ParseAddressString(
3✔
1100
                        cfg.Tor.DNS, strconv.Itoa(defaultTorDNSPort),
3✔
1101
                        cfg.net.ResolveTCPAddr,
×
1102
                )
×
1103
                if err != nil {
×
1104
                        return nil, mkErr("error parsing tor dns: %v", err)
×
1105
                }
×
1106
                cfg.Tor.DNS = dns.String()
×
1107
        }
×
1108

×
1109
        control, err := lncfg.ParseAddressString(
1110
                cfg.Tor.Control, strconv.Itoa(defaultTorControlPort),
1111
                cfg.net.ResolveTCPAddr,
3✔
1112
        )
3✔
1113
        if err != nil {
3✔
1114
                return nil, mkErr("error parsing tor control address: %v", err)
3✔
1115
        }
3✔
1116
        cfg.Tor.Control = control.String()
×
1117

×
1118
        // Ensure that tor socks host:port is not equal to tor control
3✔
1119
        // host:port. This would lead to lnd not starting up properly.
3✔
1120
        if cfg.Tor.SOCKS == cfg.Tor.Control {
3✔
1121
                str := "tor.socks and tor.control can not us the same host:port"
3✔
1122

3✔
1123
                return nil, mkErr(str)
×
1124
        }
×
1125

×
1126
        switch {
×
1127
        case cfg.Tor.V2 && cfg.Tor.V3:
1128
                return nil, mkErr("either tor.v2 or tor.v3 can be set, " +
3✔
1129
                        "but not both")
×
1130
        case cfg.DisableListen && (cfg.Tor.V2 || cfg.Tor.V3):
×
1131
                return nil, mkErr("listening must be enabled when enabling " +
×
1132
                        "inbound connections over Tor")
×
1133
        }
×
1134

×
1135
        if cfg.Tor.PrivateKeyPath == "" {
1136
                switch {
1137
                case cfg.Tor.V2:
6✔
1138
                        cfg.Tor.PrivateKeyPath = filepath.Join(
3✔
1139
                                lndDir, defaultTorV2PrivateKeyFilename,
×
1140
                        )
×
1141
                case cfg.Tor.V3:
×
1142
                        cfg.Tor.PrivateKeyPath = filepath.Join(
×
1143
                                lndDir, defaultTorV3PrivateKeyFilename,
×
1144
                        )
×
1145
                }
×
1146
        }
×
1147

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

1163
        // Set up the network-related functions that will be used throughout
1164
        // the daemon. We use the standard Go "net" package functions by
1165
        // default. If we should be proxying all traffic through Tor, then
1166
        // we'll use the Tor proxy specific functions in order to avoid leaking
1167
        // our real information.
1168
        if cfg.Tor.Active {
1169
                cfg.net = &tor.ProxyNet{
1170
                        SOCKS:                       cfg.Tor.SOCKS,
3✔
1171
                        DNS:                         cfg.Tor.DNS,
×
1172
                        StreamIsolation:             cfg.Tor.StreamIsolation,
×
1173
                        SkipProxyForClearNetTargets: cfg.Tor.SkipProxyForClearNetTargets,
×
1174
                }
×
1175
        }
×
1176

×
1177
        if cfg.DisableListen && cfg.NAT {
×
1178
                return nil, mkErr("NAT traversal cannot be used when " +
1179
                        "listening is disabled")
3✔
1180
        }
×
1181
        if cfg.NAT && len(cfg.ExternalHosts) != 0 {
×
1182
                return nil, mkErr("NAT support and externalhosts are " +
×
1183
                        "mutually exclusive, only one should be selected")
3✔
1184
        }
×
1185

×
1186
        // Multiple networks can't be selected simultaneously.  Count
×
1187
        // number of network flags passed; assign active network params
1188
        // while we're at it.
1189
        numNets := 0
1190
        if cfg.Bitcoin.MainNet {
1191
                numNets++
3✔
1192
                cfg.ActiveNetParams = chainreg.BitcoinMainNetParams
3✔
1193
        }
×
1194
        if cfg.Bitcoin.TestNet3 {
×
1195
                numNets++
×
1196
                cfg.ActiveNetParams = chainreg.BitcoinTestNetParams
3✔
1197
        }
×
1198
        if cfg.Bitcoin.RegTest {
×
1199
                numNets++
×
1200
                cfg.ActiveNetParams = chainreg.BitcoinRegTestNetParams
6✔
1201
        }
3✔
1202
        if cfg.Bitcoin.SimNet {
3✔
1203
                numNets++
3✔
1204
                cfg.ActiveNetParams = chainreg.BitcoinSimNetParams
3✔
1205

×
1206
                // For simnet, the btcsuite chain params uses a
×
1207
                // cointype of 115. However, we override this in
×
1208
                // chainreg/chainparams.go, but the raw ChainParam
×
1209
                // field is used elsewhere. To ensure everything is
×
1210
                // consistent, we'll also override the cointype within
×
1211
                // the raw params.
×
1212
                targetCoinType := chainreg.BitcoinSigNetParams.CoinType
×
1213
                cfg.ActiveNetParams.Params.HDCoinType = targetCoinType
×
1214
        }
×
1215
        if cfg.Bitcoin.SigNet {
×
1216
                numNets++
×
1217
                cfg.ActiveNetParams = chainreg.BitcoinSigNetParams
3✔
1218

×
1219
                // Let the user overwrite the default signet parameters.
×
1220
                // The challenge defines the actual signet network to
×
1221
                // join and the seed nodes are needed for network
×
1222
                // discovery.
×
1223
                sigNetChallenge := chaincfg.DefaultSignetChallenge
×
1224
                sigNetSeeds := chaincfg.DefaultSignetDNSSeeds
×
1225
                if cfg.Bitcoin.SigNetChallenge != "" {
×
1226
                        challenge, err := hex.DecodeString(
×
1227
                                cfg.Bitcoin.SigNetChallenge,
×
1228
                        )
×
1229
                        if err != nil {
×
1230
                                return nil, mkErr("Invalid "+
×
1231
                                        "signet challenge, hex decode "+
×
1232
                                        "failed: %v", err)
×
1233
                        }
×
1234
                        sigNetChallenge = challenge
×
1235
                }
×
1236

×
1237
                if len(cfg.Bitcoin.SigNetSeedNode) > 0 {
1238
                        sigNetSeeds = make([]chaincfg.DNSSeed, len(
1239
                                cfg.Bitcoin.SigNetSeedNode,
×
1240
                        ))
×
1241
                        for idx, seed := range cfg.Bitcoin.SigNetSeedNode {
×
1242
                                sigNetSeeds[idx] = chaincfg.DNSSeed{
×
1243
                                        Host:         seed,
×
1244
                                        HasFiltering: false,
×
1245
                                }
×
1246
                        }
×
1247
                }
×
1248

×
1249
                chainParams := chaincfg.CustomSignetParams(
1250
                        sigNetChallenge, sigNetSeeds,
1251
                )
×
1252
                cfg.ActiveNetParams.Params = &chainParams
×
1253
        }
×
1254
        if numNets > 1 {
×
1255
                str := "The mainnet, testnet, regtest, simnet and signet " +
1256
                        "params can't be used together -- choose one " +
3✔
1257
                        "of the five"
×
1258

×
1259
                return nil, mkErr(str)
×
1260
        }
×
1261

×
1262
        // The target network must be provided, otherwise, we won't
×
1263
        // know how to initialize the daemon.
1264
        if numNets == 0 {
1265
                str := "either --bitcoin.mainnet, or bitcoin.testnet, " +
1266
                        "bitcoin.simnet, bitcoin.regtest or bitcoin.signet " +
3✔
1267
                        "must be specified"
×
1268

×
1269
                return nil, mkErr(str)
×
1270
        }
×
1271

×
1272
        err = cfg.Bitcoin.Validate(minTimeLockDelta, funding.MinBtcRemoteDelay)
×
1273
        if err != nil {
1274
                return nil, mkErr("error validating bitcoin params: %v", err)
3✔
1275
        }
3✔
1276

×
1277
        switch cfg.Bitcoin.Node {
×
1278
        case btcdBackendName:
1279
                err := parseRPCParams(
3✔
1280
                        cfg.Bitcoin, cfg.BtcdMode, cfg.ActiveNetParams,
1✔
1281
                )
1✔
1282
                if err != nil {
1✔
1283
                        return nil, mkErr("unable to load RPC "+
1✔
1284
                                "credentials for btcd: %v", err)
1✔
1285
                }
×
1286
        case bitcoindBackendName:
×
1287
                if cfg.Bitcoin.SimNet {
×
1288
                        return nil, mkErr("bitcoind does not " +
1✔
1289
                                "support simnet")
1✔
1290
                }
×
1291

×
1292
                err := parseRPCParams(
×
1293
                        cfg.Bitcoin, cfg.BitcoindMode, cfg.ActiveNetParams,
1294
                )
1✔
1295
                if err != nil {
1✔
1296
                        return nil, mkErr("unable to load RPC "+
1✔
1297
                                "credentials for bitcoind: %v", err)
1✔
1298
                }
×
1299
        case neutrinoBackendName:
×
1300
                // No need to get RPC parameters.
×
1301

1✔
1302
        case "nochainbackend":
1303
                // Nothing to configure, we're running without any chain
1304
                // backend whatsoever (pure signing mode).
×
1305

1306
        default:
1307
                str := "only btcd, bitcoind, and neutrino mode " +
1308
                        "supported for bitcoin at this time"
×
1309

×
1310
                return nil, mkErr(str)
×
1311
        }
×
1312

×
1313
        cfg.Bitcoin.ChainDir = filepath.Join(
1314
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
1315
        )
3✔
1316

3✔
1317
        // Ensure that the user didn't attempt to specify negative values for
3✔
1318
        // any of the autopilot params.
3✔
1319
        if cfg.Autopilot.MaxChannels < 0 {
3✔
1320
                str := "autopilot.maxchannels must be non-negative"
3✔
1321

3✔
1322
                return nil, mkErr(str)
×
1323
        }
×
1324
        if cfg.Autopilot.Allocation < 0 {
×
1325
                str := "autopilot.allocation must be non-negative"
×
1326

3✔
1327
                return nil, mkErr(str)
×
1328
        }
×
1329
        if cfg.Autopilot.MinChannelSize < 0 {
×
1330
                str := "autopilot.minchansize must be non-negative"
×
1331

3✔
1332
                return nil, mkErr(str)
×
1333
        }
×
1334
        if cfg.Autopilot.MaxChannelSize < 0 {
×
1335
                str := "autopilot.maxchansize must be non-negative"
×
1336

3✔
1337
                return nil, mkErr(str)
×
1338
        }
×
1339

×
1340
        // Ensure that the specified values for the min and max channel size
×
1341
        // don't are within the bounds of the normal chan size constraints.
1342
        if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
1343
                cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
1344
        }
3✔
1345
        if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
×
1346
                cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
×
1347
        }
3✔
1348

×
1349
        // We'll now construct the network directory which will be where we
×
1350
        // store all the data specific to this chain/network.
1351
        cfg.networkDir = filepath.Join(
1352
                cfg.DataDir, defaultChainSubDirname, BitcoinChainName,
1353
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1354
        )
3✔
1355

3✔
1356
        // If a custom macaroon directory wasn't specified and the data
3✔
1357
        // directory has changed from the default path, then we'll also update
3✔
1358
        // the path for the macaroons to be generated.
3✔
1359
        if cfg.AdminMacPath == "" {
3✔
1360
                cfg.AdminMacPath = filepath.Join(
3✔
1361
                        cfg.networkDir, defaultAdminMacFilename,
3✔
1362
                )
×
1363
        }
×
1364
        if cfg.ReadMacPath == "" {
×
1365
                cfg.ReadMacPath = filepath.Join(
×
1366
                        cfg.networkDir, defaultReadMacFilename,
3✔
1367
                )
×
1368
        }
×
1369
        if cfg.InvoiceMacPath == "" {
×
1370
                cfg.InvoiceMacPath = filepath.Join(
×
1371
                        cfg.networkDir, defaultInvoiceMacFilename,
3✔
1372
                )
×
1373
        }
×
1374

×
1375
        towerDir := filepath.Join(
×
1376
                cfg.Watchtower.TowerDir, BitcoinChainName,
1377
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1378
        )
3✔
1379

3✔
1380
        // Create the lnd directory and all other sub-directories if they don't
3✔
1381
        // already exist. This makes sure that directory trees are also created
3✔
1382
        // for files that point to outside the lnddir.
3✔
1383
        dirs := []string{
3✔
1384
                lndDir, cfg.DataDir, cfg.networkDir,
3✔
1385
                cfg.LetsEncryptDir, towerDir, cfg.graphDatabaseDir(),
3✔
1386
                filepath.Dir(cfg.TLSCertPath), filepath.Dir(cfg.TLSKeyPath),
3✔
1387
                filepath.Dir(cfg.AdminMacPath), filepath.Dir(cfg.ReadMacPath),
3✔
1388
                filepath.Dir(cfg.InvoiceMacPath),
3✔
1389
                filepath.Dir(cfg.Tor.PrivateKeyPath),
3✔
1390
                filepath.Dir(cfg.Tor.WatchtowerKeyPath),
3✔
1391
        }
3✔
1392
        for _, dir := range dirs {
3✔
1393
                if err := makeDirectory(dir); err != nil {
3✔
1394
                        return nil, err
6✔
1395
                }
3✔
1396
        }
×
1397

×
1398
        // Similarly, if a custom back up file path wasn't specified, then
1399
        // we'll update the file location to match our set network directory.
1400
        if cfg.BackupFilePath == "" {
1401
                cfg.BackupFilePath = filepath.Join(
1402
                        cfg.networkDir, chanbackup.DefaultBackupFileName,
6✔
1403
                )
3✔
1404
        }
3✔
1405

3✔
1406
        // Append the network type to the log directory so it is "namespaced"
3✔
1407
        // per network in the same fashion as the data directory.
1408
        cfg.LogDir = filepath.Join(
1409
                cfg.LogDir, BitcoinChainName,
1410
                lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1411
        )
3✔
1412

3✔
1413
        if err := cfg.LogConfig.Validate(); err != nil {
3✔
1414
                return nil, mkErr("error validating logging config: %w", err)
3✔
1415
        }
3✔
1416

×
1417
        cfg.SubLogMgr = build.NewSubLoggerManager(build.NewDefaultLogHandlers(
×
1418
                cfg.LogConfig, cfg.LogRotator,
1419
        )...)
3✔
1420

3✔
1421
        // Initialize logging at the default logging level.
3✔
1422
        SetupLoggers(cfg.SubLogMgr, interceptor)
3✔
1423

3✔
1424
        if cfg.MaxLogFiles != 0 {
3✔
1425
                if cfg.LogConfig.File.MaxLogFiles !=
3✔
1426
                        build.DefaultMaxLogFiles {
3✔
1427

×
1428
                        return nil, mkErr("cannot set both maxlogfiles and "+
×
1429
                                "logging.file.max-files", err)
×
1430
                }
×
1431

×
1432
                cfg.LogConfig.File.MaxLogFiles = cfg.MaxLogFiles
×
1433
        }
1434
        if cfg.MaxLogFileSize != 0 {
×
1435
                if cfg.LogConfig.File.MaxLogFileSize !=
1436
                        build.DefaultMaxLogFileSize {
3✔
1437

×
1438
                        return nil, mkErr("cannot set both maxlogfilesize and "+
×
1439
                                "logging.file.max-file-size", err)
×
1440
                }
×
1441

×
1442
                cfg.LogConfig.File.MaxLogFileSize = cfg.MaxLogFileSize
×
1443
        }
1444

×
1445
        err = cfg.LogRotator.InitLogRotator(
1446
                cfg.LogConfig.File,
1447
                filepath.Join(cfg.LogDir, defaultLogFilename),
3✔
1448
        )
3✔
1449
        if err != nil {
3✔
1450
                str := "log rotation setup failed: %v"
3✔
1451
                return nil, mkErr(str, err)
3✔
1452
        }
×
1453

×
1454
        // Parse, validate, and set debug log level(s).
×
1455
        err = build.ParseAndSetDebugLevels(cfg.DebugLevel, cfg.SubLogMgr)
1456
        if err != nil {
1457
                str := "error parsing debug level: %v"
3✔
1458
                return nil, &lncfg.UsageError{Err: mkErr(str, err)}
3✔
1459
        }
×
1460

×
1461
        // At least one RPCListener is required. So listen on localhost per
×
1462
        // default.
1463
        if len(cfg.RawRPCListeners) == 0 {
1464
                addr := fmt.Sprintf("localhost:%d", defaultRPCPort)
1465
                cfg.RawRPCListeners = append(cfg.RawRPCListeners, addr)
3✔
1466
        }
×
1467

×
1468
        // Listen on localhost if no REST listeners were specified.
×
1469
        if len(cfg.RawRESTListeners) == 0 {
1470
                addr := fmt.Sprintf("localhost:%d", defaultRESTPort)
1471
                cfg.RawRESTListeners = append(cfg.RawRESTListeners, addr)
3✔
1472
        }
×
1473

×
1474
        // Listen on the default interface/port if no listeners were specified.
×
1475
        // An empty address string means default interface/address, which on
1476
        // most unix systems is the same as 0.0.0.0. If Tor is active, we
1477
        // default to only listening on localhost for hidden service
1478
        // connections.
1479
        if len(cfg.RawListeners) == 0 {
1480
                addr := fmt.Sprintf(":%d", defaultPeerPort)
1481
                if cfg.Tor.Active && !cfg.Tor.SkipProxyForClearNetTargets {
3✔
1482
                        addr = fmt.Sprintf("localhost:%d", defaultPeerPort)
×
1483
                }
×
1484
                cfg.RawListeners = append(cfg.RawListeners, addr)
×
1485
        }
×
1486

×
1487
        // Add default port to all RPC listener addresses if needed and remove
1488
        // duplicate addresses.
1489
        cfg.RPCListeners, err = lncfg.NormalizeAddresses(
1490
                cfg.RawRPCListeners, strconv.Itoa(defaultRPCPort),
1491
                cfg.net.ResolveTCPAddr,
3✔
1492
        )
3✔
1493
        if err != nil {
3✔
1494
                return nil, mkErr("error normalizing RPC listen addrs: %v", err)
3✔
1495
        }
3✔
1496

×
1497
        // Add default port to all REST listener addresses if needed and remove
×
1498
        // duplicate addresses.
1499
        cfg.RESTListeners, err = lncfg.NormalizeAddresses(
1500
                cfg.RawRESTListeners, strconv.Itoa(defaultRESTPort),
1501
                cfg.net.ResolveTCPAddr,
3✔
1502
        )
3✔
1503
        if err != nil {
3✔
1504
                return nil, mkErr("error normalizing REST listen addrs: %v", err)
3✔
1505
        }
3✔
1506

×
1507
        switch {
×
1508
        // The no seed backup and auto unlock are mutually exclusive.
1509
        case cfg.NoSeedBackup && cfg.WalletUnlockPasswordFile != "":
3✔
1510
                return nil, mkErr("cannot set noseedbackup and " +
1511
                        "wallet-unlock-password-file at the same time")
×
1512

×
1513
        // The "allow-create" flag cannot be set without the auto unlock file.
×
1514
        case cfg.WalletUnlockAllowCreate && cfg.WalletUnlockPasswordFile == "":
1515
                return nil, mkErr("cannot set wallet-unlock-allow-create " +
1516
                        "without wallet-unlock-password-file")
×
1517

×
1518
        // If a password file was specified, we need it to exist.
×
1519
        case cfg.WalletUnlockPasswordFile != "" &&
1520
                !lnrpc.FileExists(cfg.WalletUnlockPasswordFile):
1521

1522
                return nil, mkErr("wallet unlock password file %s does "+
×
1523
                        "not exist", cfg.WalletUnlockPasswordFile)
×
1524
        }
×
1525

×
1526
        // For each of the RPC listeners (REST+gRPC), we'll ensure that users
1527
        // have specified a safe combo for authentication. If not, we'll bail
1528
        // out with an error. Since we don't allow disabling TLS for gRPC
1529
        // connections we pass in tlsActive=true.
1530
        err = lncfg.EnforceSafeAuthentication(
1531
                cfg.RPCListeners, !cfg.NoMacaroons, true,
1532
        )
3✔
1533
        if err != nil {
3✔
1534
                return nil, mkErr("error enforcing safe authentication on "+
3✔
1535
                        "RPC ports: %v", err)
3✔
1536
        }
×
1537

×
1538
        if cfg.DisableRest {
×
1539
                ltndLog.Infof("REST API is disabled!")
1540
                cfg.RESTListeners = nil
3✔
1541
        } else {
×
1542
                err = lncfg.EnforceSafeAuthentication(
×
1543
                        cfg.RESTListeners, !cfg.NoMacaroons, !cfg.DisableRestTLS,
3✔
1544
                )
3✔
1545
                if err != nil {
3✔
1546
                        return nil, mkErr("error enforcing safe "+
3✔
1547
                                "authentication on REST ports: %v", err)
3✔
1548
                }
×
1549
        }
×
1550

×
1551
        // Remove the listening addresses specified if listening is disabled.
1552
        if cfg.DisableListen {
1553
                ltndLog.Infof("Listening on the p2p interface is disabled!")
1554
                cfg.Listeners = nil
6✔
1555
                cfg.ExternalIPs = nil
3✔
1556
        } else {
3✔
1557

3✔
1558
                // Add default port to all listener addresses if needed and remove
6✔
1559
                // duplicate addresses.
3✔
1560
                cfg.Listeners, err = lncfg.NormalizeAddresses(
3✔
1561
                        cfg.RawListeners, strconv.Itoa(defaultPeerPort),
3✔
1562
                        cfg.net.ResolveTCPAddr,
3✔
1563
                )
3✔
1564
                if err != nil {
3✔
1565
                        return nil, mkErr("error normalizing p2p listen "+
3✔
1566
                                "addrs: %v", err)
3✔
1567
                }
×
1568

×
1569
                // Add default port to all external IP addresses if needed and remove
×
1570
                // duplicate addresses.
1571
                cfg.ExternalIPs, err = lncfg.NormalizeAddresses(
1572
                        cfg.RawExternalIPs, strconv.Itoa(defaultPeerPort),
1573
                        cfg.net.ResolveTCPAddr,
3✔
1574
                )
3✔
1575
                if err != nil {
3✔
1576
                        return nil, err
3✔
1577
                }
3✔
1578

×
1579
                // For the p2p port it makes no sense to listen to an Unix socket.
×
1580
                // Also, we would need to refactor the brontide listener to support
1581
                // that.
1582
                for _, p2pListener := range cfg.Listeners {
1583
                        if lncfg.IsUnix(p2pListener) {
1584
                                return nil, mkErr("unix socket addresses "+
6✔
1585
                                        "cannot be used for the p2p "+
3✔
1586
                                        "connection listener: %s", p2pListener)
×
1587
                        }
×
1588
                }
×
1589
        }
×
1590

1591
        // Ensure that the specified minimum backoff is below or equal to the
1592
        // maximum backoff.
1593
        if cfg.MinBackoff > cfg.MaxBackoff {
1594
                return nil, mkErr("maxbackoff must be greater than minbackoff")
1595
        }
3✔
1596

×
1597
        // Newer versions of lnd added a new sub-config for bolt-specific
×
1598
        // parameters. However, we want to also allow existing users to use the
1599
        // value on the top-level config. If the outer config value is set,
1600
        // then we'll use that directly.
1601
        flagSet, err := isSet("SyncFreelist")
1602
        if err != nil {
1603
                return nil, mkErr("error parsing freelist sync flag: %v", err)
3✔
1604
        }
3✔
1605
        if flagSet {
×
1606
                cfg.DB.Bolt.NoFreelistSync = !cfg.SyncFreelist
×
1607
        }
3✔
1608

×
1609
        // Parse any extra sqlite pragma options that may have been provided
×
1610
        // to determine if they override any of the defaults that we will
1611
        // otherwise add.
1612
        var (
1613
                defaultSynchronous = true
1614
                defaultAutoVacuum  = true
3✔
1615
                defaultFullfsync   = true
3✔
1616
        )
3✔
1617
        for _, option := range cfg.DB.Sqlite.PragmaOptions {
3✔
1618
                switch {
3✔
1619
                case strings.HasPrefix(option, "synchronous="):
3✔
1620
                        defaultSynchronous = false
×
1621

×
1622
                case strings.HasPrefix(option, "auto_vacuum="):
×
1623
                        defaultAutoVacuum = false
1624

×
1625
                case strings.HasPrefix(option, "fullfsync="):
×
1626
                        defaultFullfsync = false
1627

×
1628
                default:
×
1629
                }
1630
        }
×
1631

1632
        if defaultSynchronous {
1633
                cfg.DB.Sqlite.PragmaOptions = append(
1634
                        cfg.DB.Sqlite.PragmaOptions, "synchronous=full",
6✔
1635
                )
3✔
1636
        }
3✔
1637

3✔
1638
        if defaultAutoVacuum {
3✔
1639
                cfg.DB.Sqlite.PragmaOptions = append(
1640
                        cfg.DB.Sqlite.PragmaOptions, "auto_vacuum=incremental",
6✔
1641
                )
3✔
1642
        }
3✔
1643

3✔
1644
        if defaultFullfsync {
3✔
1645
                cfg.DB.Sqlite.PragmaOptions = append(
1646
                        cfg.DB.Sqlite.PragmaOptions, "fullfsync=true",
6✔
1647
                )
3✔
1648
        }
3✔
1649

3✔
1650
        // Ensure that the user hasn't chosen a remote-max-htlc value greater
3✔
1651
        // than the protocol maximum.
1652
        maxRemoteHtlcs := uint16(input.MaxHTLCNumber / 2)
1653
        if cfg.DefaultRemoteMaxHtlcs > maxRemoteHtlcs {
1654
                return nil, mkErr("default-remote-max-htlcs (%v) must be "+
3✔
1655
                        "less than %v", cfg.DefaultRemoteMaxHtlcs,
3✔
1656
                        maxRemoteHtlcs)
×
1657
        }
×
1658

×
1659
        // Clamp the ChannelCommitInterval so that commitment updates can still
×
1660
        // happen in a reasonable timeframe.
1661
        if cfg.ChannelCommitInterval > maxChannelCommitInterval {
1662
                return nil, mkErr("channel-commit-interval (%v) must be less "+
1663
                        "than %v", cfg.ChannelCommitInterval,
3✔
1664
                        maxChannelCommitInterval)
×
1665
        }
×
1666

×
1667
        // Limit PendingCommitInterval so we don't wait too long for the remote
×
1668
        // party to send back a revoke.
1669
        if cfg.PendingCommitInterval > maxPendingCommitInterval {
1670
                return nil, mkErr("pending-commit-interval (%v) must be less "+
1671
                        "than %v", cfg.PendingCommitInterval,
3✔
1672
                        maxPendingCommitInterval)
×
1673
        }
×
1674

×
1675
        if err := cfg.Gossip.Parse(); err != nil {
×
1676
                return nil, mkErr("error parsing gossip syncer: %v", err)
1677
        }
3✔
1678

×
1679
        // If the experimental protocol options specify any protocol messages
×
1680
        // that we want to handle as custom messages, set them now.
1681
        customMsg := cfg.ProtocolOptions.CustomMessageOverrides()
1682

1683
        // We can safely set our custom override values during startup because
3✔
1684
        // startup is blocked on config parsing.
3✔
1685
        if err := lnwire.SetCustomOverrides(customMsg); err != nil {
3✔
1686
                return nil, mkErr("custom-message: %v", err)
3✔
1687
        }
3✔
1688

×
1689
        // Map old pprof flags to new pprof group flags.
×
1690
        //
1691
        // NOTE: This is a temporary measure to ensure compatibility with old
1692
        // flags.
1693
        if cfg.CPUProfile != "" {
1694
                if cfg.Pprof.CPUProfile != "" {
1695
                        return nil, mkErr("cpuprofile and pprof.cpuprofile " +
3✔
1696
                                "are mutually exclusive")
×
1697
                }
×
1698
                cfg.Pprof.CPUProfile = cfg.CPUProfile
×
1699
        }
×
1700
        if cfg.Profile != "" {
×
1701
                if cfg.Pprof.Profile != "" {
1702
                        return nil, mkErr("profile and pprof.profile " +
3✔
1703
                                "are mutually exclusive")
×
1704
                }
×
1705
                cfg.Pprof.Profile = cfg.Profile
×
1706
        }
×
1707
        if cfg.BlockingProfile != 0 {
×
1708
                if cfg.Pprof.BlockingProfile != 0 {
1709
                        return nil, mkErr("blockingprofile and " +
3✔
1710
                                "pprof.blockingprofile are mutually exclusive")
×
1711
                }
×
1712
                cfg.Pprof.BlockingProfile = cfg.BlockingProfile
×
1713
        }
×
1714
        if cfg.MutexProfile != 0 {
×
1715
                if cfg.Pprof.MutexProfile != 0 {
1716
                        return nil, mkErr("mutexprofile and " +
3✔
1717
                                "pprof.mutexprofile are mutually exclusive")
×
1718
                }
×
1719
                cfg.Pprof.MutexProfile = cfg.MutexProfile
×
1720
        }
×
1721

×
1722
        // Don't allow both the old dust-threshold and the new
1723
        // channel-max-fee-exposure to be set.
1724
        if cfg.DustThreshold != 0 && cfg.MaxFeeExposure != 0 {
1725
                return nil, mkErr("cannot set both dust-threshold and " +
1726
                        "channel-max-fee-exposure")
3✔
1727
        }
×
1728

×
1729
        switch {
×
1730
        // Use the old dust-threshold as the max fee exposure if it is set and
1731
        // the new option is not.
3✔
1732
        case cfg.DustThreshold != 0:
1733
                cfg.MaxFeeExposure = cfg.DustThreshold
1734

×
1735
        // Use the default max fee exposure if the new option is not set and
×
1736
        // the old one is not set either.
1737
        case cfg.MaxFeeExposure == 0:
1738
                cfg.MaxFeeExposure = uint64(
1739
                        htlcswitch.DefaultMaxFeeExposure.ToSatoshis(),
3✔
1740
                )
3✔
1741
        }
3✔
1742

3✔
1743
        // Validate the subconfigs for workers, caches, and the tower client.
1744
        err = lncfg.Validate(
1745
                cfg.Workers,
1746
                cfg.Caches,
3✔
1747
                cfg.WtClient,
3✔
1748
                cfg.DB,
3✔
1749
                cfg.Cluster,
3✔
1750
                cfg.HealthChecks,
3✔
1751
                cfg.RPCMiddleware,
3✔
1752
                cfg.RemoteSigner,
3✔
1753
                cfg.Sweeper,
3✔
1754
                cfg.Htlcswitch,
3✔
1755
                cfg.Invoices,
3✔
1756
                cfg.Routing,
3✔
1757
                cfg.Pprof,
3✔
1758
                cfg.Gossip,
3✔
1759
        )
3✔
1760
        if err != nil {
3✔
1761
                return nil, err
3✔
1762
        }
3✔
1763

×
1764
        // Finally, ensure that the user's color is correctly formatted,
×
1765
        // otherwise the server will not be able to start after the unlocking
1766
        // the wallet.
1767
        _, err = lncfg.ParseHexColor(cfg.Color)
1768
        if err != nil {
1769
                return nil, mkErr("unable to parse node color: %v", err)
3✔
1770
        }
3✔
1771

×
1772
        // All good, return the sanitized result.
×
1773
        return &cfg, nil
1774
}
1775

3✔
1776
// graphDatabaseDir returns the default directory where the local bolt graph db
1777
// files are stored.
1778
func (c *Config) graphDatabaseDir() string {
1779
        return filepath.Join(
1780
                c.DataDir, defaultGraphSubDirname,
3✔
1781
                lncfg.NormalizeNetwork(c.ActiveNetParams.Name),
3✔
1782
        )
3✔
1783
}
3✔
1784

3✔
1785
// ImplementationConfig returns the configuration of what actual implementations
3✔
1786
// should be used when creating the main lnd instance.
1787
func (c *Config) ImplementationConfig(
1788
        interceptor signal.Interceptor) *ImplementationCfg {
1789

1790
        // If we're using a remote signer, we still need the base wallet as a
3✔
1791
        // watch-only source of chain and address data. But we don't need any
3✔
1792
        // private key material in that btcwallet base wallet.
3✔
1793
        if c.RemoteSigner.Enable {
3✔
1794
                rpcImpl := NewRPCSignerWalletImpl(
3✔
1795
                        c, ltndLog, interceptor,
6✔
1796
                        c.RemoteSigner.MigrateWatchOnly,
3✔
1797
                )
3✔
1798
                return &ImplementationCfg{
3✔
1799
                        GrpcRegistrar:     rpcImpl,
3✔
1800
                        RestRegistrar:     rpcImpl,
3✔
1801
                        ExternalValidator: rpcImpl,
3✔
1802
                        DatabaseBuilder: NewDefaultDatabaseBuilder(
3✔
1803
                                c, ltndLog,
3✔
1804
                        ),
3✔
1805
                        WalletConfigBuilder: rpcImpl,
3✔
1806
                        ChainControlBuilder: rpcImpl,
3✔
1807
                }
3✔
1808
        }
3✔
1809

3✔
1810
        defaultImpl := NewDefaultWalletImpl(c, ltndLog, interceptor, false)
3✔
1811
        return &ImplementationCfg{
1812
                GrpcRegistrar:       defaultImpl,
3✔
1813
                RestRegistrar:       defaultImpl,
3✔
1814
                ExternalValidator:   defaultImpl,
3✔
1815
                DatabaseBuilder:     NewDefaultDatabaseBuilder(c, ltndLog),
3✔
1816
                WalletConfigBuilder: defaultImpl,
3✔
1817
                ChainControlBuilder: defaultImpl,
3✔
1818
        }
3✔
1819
}
3✔
1820

3✔
1821
// CleanAndExpandPath expands environment variables and leading ~ in the
1822
// passed path, cleans the result, and returns it.
1823
// This function is taken from https://github.com/btcsuite/btcd
1824
func CleanAndExpandPath(path string) string {
1825
        if path == "" {
1826
                return ""
3✔
1827
        }
6✔
1828

3✔
1829
        // Expand initial ~ to OS specific home directory.
3✔
1830
        if strings.HasPrefix(path, "~") {
1831
                var homeDir string
1832
                u, err := user.Current()
3✔
1833
                if err == nil {
×
1834
                        homeDir = u.HomeDir
×
1835
                } else {
×
1836
                        homeDir = os.Getenv("HOME")
×
1837
                }
×
1838

×
1839
                path = strings.Replace(path, "~", homeDir, 1)
×
1840
        }
1841

×
1842
        // NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
1843
        // but the variables can still be expanded via POSIX-style $VARIABLE.
1844
        return filepath.Clean(os.ExpandEnv(path))
1845
}
1846

3✔
1847
func parseRPCParams(cConfig *lncfg.Chain, nodeConfig interface{},
1848
        netParams chainreg.BitcoinNetParams) error {
1849

1850
        // First, we'll check our node config to make sure the RPC parameters
2✔
1851
        // were set correctly. We'll also determine the path to the conf file
2✔
1852
        // depending on the backend node.
2✔
1853
        var daemonName, confDir, confFile, confFileBase string
2✔
1854
        switch conf := nodeConfig.(type) {
2✔
1855
        case *lncfg.Btcd:
2✔
1856
                // Resolves environment variable references in RPCUser and
2✔
1857
                // RPCPass fields.
1✔
1858
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
1✔
1859
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
1✔
1860

1✔
1861
                // If both RPCUser and RPCPass are set, we assume those
1✔
1862
                // credentials are good to use.
1✔
1863
                if conf.RPCUser != "" && conf.RPCPass != "" {
1✔
1864
                        return nil
1✔
1865
                }
2✔
1866

1✔
1867
                // Set the daemon name for displaying proper errors.
1✔
1868
                daemonName = btcdBackendName
1869
                confDir = conf.Dir
1870
                confFileBase = btcdBackendName
×
1871

×
1872
                // If only ONE of RPCUser or RPCPass is set, we assume the
×
1873
                // user did that unintentionally.
×
1874
                if conf.RPCUser != "" || conf.RPCPass != "" {
×
1875
                        return fmt.Errorf("please set both or neither of "+
×
1876
                                "%[1]v.rpcuser, %[1]v.rpcpass", daemonName)
×
1877
                }
×
1878

×
1879
        case *lncfg.Bitcoind:
×
1880
                // Ensure that if the ZMQ options are set, that they are not
1881
                // equal.
1✔
1882
                if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
1✔
1883
                        err := checkZMQOptions(
1✔
1884
                                conf.ZMQPubRawBlock, conf.ZMQPubRawTx,
2✔
1885
                        )
1✔
1886
                        if err != nil {
1✔
1887
                                return err
1✔
1888
                        }
1✔
1889
                }
×
1890

×
1891
                // Ensure that if the estimate mode is set, that it is a legal
1892
                // value.
1893
                if conf.EstimateMode != "" {
1894
                        err := checkEstimateMode(conf.EstimateMode)
1895
                        if err != nil {
2✔
1896
                                return err
1✔
1897
                        }
1✔
1898
                }
×
1899

×
1900
                // Set the daemon name for displaying proper errors.
1901
                daemonName = bitcoindBackendName
1902
                confDir = conf.Dir
1903
                confFile = conf.ConfigPath
1✔
1904
                confFileBase = BitcoinChainName
1✔
1905

1✔
1906
                // Resolves environment variable references in RPCUser
1✔
1907
                // and RPCPass fields.
1✔
1908
                conf.RPCUser = supplyEnvValue(conf.RPCUser)
1✔
1909
                conf.RPCPass = supplyEnvValue(conf.RPCPass)
1✔
1910

1✔
1911
                // Check that cookie and credentials don't contradict each
1✔
1912
                // other.
1✔
1913
                if (conf.RPCUser != "" || conf.RPCPass != "") &&
1✔
1914
                        conf.RPCCookie != "" {
1✔
1915

1✔
1916
                        return fmt.Errorf("please only provide either "+
1✔
1917
                                "%[1]v.rpccookie or %[1]v.rpcuser and "+
×
1918
                                "%[1]v.rpcpass", daemonName)
×
1919
                }
×
1920

×
1921
                // We convert the cookie into a user name and password.
×
1922
                if conf.RPCCookie != "" {
1923
                        cookie, err := os.ReadFile(conf.RPCCookie)
1924
                        if err != nil {
1✔
1925
                                return fmt.Errorf("cannot read cookie file: %w",
×
1926
                                        err)
×
1927
                        }
×
1928

×
1929
                        splitCookie := strings.Split(string(cookie), ":")
×
1930
                        if len(splitCookie) != 2 {
1931
                                return fmt.Errorf("cookie file has a wrong " +
×
1932
                                        "format")
×
1933
                        }
×
1934
                        conf.RPCUser = splitCookie[0]
×
1935
                        conf.RPCPass = splitCookie[1]
×
1936
                }
×
1937

×
1938
                if conf.RPCUser != "" && conf.RPCPass != "" {
1939
                        // If all of RPCUser, RPCPass, ZMQBlockHost, and
1940
                        // ZMQTxHost are set, we assume those parameters are
2✔
1941
                        // good to use.
1✔
1942
                        if conf.ZMQPubRawBlock != "" && conf.ZMQPubRawTx != "" {
1✔
1943
                                return nil
1✔
1944
                        }
2✔
1945

1✔
1946
                        // If RPCUser and RPCPass are set and RPCPolling is
1✔
1947
                        // enabled, we assume the parameters are good to use.
1948
                        if conf.RPCPolling {
1949
                                return nil
1950
                        }
×
1951
                }
×
1952

×
1953
                // If not all of the parameters are set, we'll assume the user
1954
                // did this unintentionally.
1955
                if conf.RPCUser != "" || conf.RPCPass != "" ||
1956
                        conf.ZMQPubRawBlock != "" || conf.ZMQPubRawTx != "" {
1957

×
1958
                        return fmt.Errorf("please set %[1]v.rpcuser and "+
×
1959
                                "%[1]v.rpcpass (or %[1]v.rpccookie) together "+
×
1960
                                "with %[1]v.zmqpubrawblock, %[1]v.zmqpubrawtx",
×
1961
                                daemonName)
×
1962
                }
×
1963
        }
×
1964

×
1965
        // If we're in simnet mode, then the running btcd instance won't read
1966
        // the RPC credentials from the configuration. So if lnd wasn't
1967
        // specified the parameters, then we won't be able to start.
1968
        if cConfig.SimNet {
1969
                return fmt.Errorf("rpcuser and rpcpass must be set to your " +
1970
                        "btcd node's RPC parameters for simnet mode")
×
1971
        }
×
1972

×
1973
        fmt.Println("Attempting automatic RPC configuration to " + daemonName)
×
1974

1975
        if confFile == "" {
×
1976
                confFile = filepath.Join(confDir, fmt.Sprintf("%v.conf",
×
1977
                        confFileBase))
×
1978
        }
×
1979
        switch cConfig.Node {
×
1980
        case btcdBackendName:
×
1981
                nConf := nodeConfig.(*lncfg.Btcd)
×
1982
                rpcUser, rpcPass, err := extractBtcdRPCParams(confFile)
×
1983
                if err != nil {
×
1984
                        return fmt.Errorf("unable to extract RPC credentials: "+
×
1985
                                "%v, cannot start w/o RPC connection", err)
×
1986
                }
×
1987
                nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
×
1988

×
1989
        case bitcoindBackendName:
×
1990
                nConf := nodeConfig.(*lncfg.Bitcoind)
1991
                rpcUser, rpcPass, zmqBlockHost, zmqTxHost, err :=
×
1992
                        extractBitcoindRPCParams(netParams.Params.Name,
×
1993
                                nConf.Dir, confFile, nConf.RPCCookie)
×
1994
                if err != nil {
×
1995
                        return fmt.Errorf("unable to extract RPC credentials: "+
×
1996
                                "%v, cannot start w/o RPC connection", err)
×
1997
                }
×
1998
                nConf.RPCUser, nConf.RPCPass = rpcUser, rpcPass
×
1999
                nConf.ZMQPubRawBlock, nConf.ZMQPubRawTx = zmqBlockHost, zmqTxHost
×
2000
        }
×
2001

×
2002
        fmt.Printf("Automatically obtained %v's RPC credentials\n", daemonName)
2003
        return nil
2004
}
×
2005

×
2006
// supplyEnvValue supplies the value of an environment variable from a string.
2007
// It supports the following formats:
2008
// 1) $ENV_VAR
2009
// 2) ${ENV_VAR}
2010
// 3) ${ENV_VAR:-DEFAULT}
2011
//
2012
// Standard environment variable naming conventions:
2013
// - ENV_VAR contains letters, digits, and underscores, and does
2014
// not start with a digit.
2015
// - DEFAULT follows the rule that it can contain any characters except
2016
// whitespace.
2017
//
2018
// Parameters:
2019
// - value: The input string containing references to environment variables
2020
// (if any).
2021
//
2022
// Returns:
2023
// - string: The value of the specified environment variable, the default
2024
// value if provided, or the original input string if no matching variable is
2025
// found or set.
2026
func supplyEnvValue(value string) string {
2027
        // Regex for $ENV_VAR format.
2028
        var reEnvVar = regexp.MustCompile(`^\$([a-zA-Z_][a-zA-Z0-9_]*)$`)
2✔
2029

2✔
2030
        // Regex for ${ENV_VAR} format.
2✔
2031
        var reEnvVarWithBrackets = regexp.MustCompile(
2✔
2032
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$`,
2✔
2033
        )
2✔
2034

2✔
2035
        // Regex for ${ENV_VAR:-DEFAULT} format.
2✔
2036
        var reEnvVarWithDefault = regexp.MustCompile(
2✔
2037
                `^\$\{([a-zA-Z_][a-zA-Z0-9_]*):-([\S]+)\}$`,
2✔
2038
        )
2✔
2039

2✔
2040
        // Match against supported formats.
2✔
2041
        switch {
2✔
2042
        case reEnvVarWithDefault.MatchString(value):
2✔
2043
                matches := reEnvVarWithDefault.FindStringSubmatch(value)
2✔
2044
                envVariable := matches[1]
×
2045
                defaultValue := matches[2]
×
2046
                if envValue := os.Getenv(envVariable); envValue != "" {
×
2047
                        return envValue
×
2048
                }
×
2049

×
2050
                return defaultValue
×
2051

2052
        case reEnvVarWithBrackets.MatchString(value):
×
2053
                matches := reEnvVarWithBrackets.FindStringSubmatch(value)
2054
                envVariable := matches[1]
×
2055
                envValue := os.Getenv(envVariable)
×
2056

×
2057
                return envValue
×
2058

×
2059
        case reEnvVar.MatchString(value):
×
2060
                matches := reEnvVar.FindStringSubmatch(value)
2061
                envVariable := matches[1]
×
2062
                envValue := os.Getenv(envVariable)
×
2063

×
2064
                return envValue
×
2065
        }
×
2066

×
2067
        return value
2068
}
2069

2✔
2070
// extractBtcdRPCParams attempts to extract the RPC credentials for an existing
2071
// btcd instance. The passed path is expected to be the location of btcd's
2072
// application data directory on the target system.
2073
func extractBtcdRPCParams(btcdConfigPath string) (string, string, error) {
2074
        // First, we'll open up the btcd configuration file found at the target
2075
        // destination.
×
2076
        btcdConfigFile, err := os.Open(btcdConfigPath)
×
2077
        if err != nil {
×
2078
                return "", "", err
×
2079
        }
×
2080
        defer func() { _ = btcdConfigFile.Close() }()
×
2081

×
2082
        // With the file open extract the contents of the configuration file so
×
2083
        // we can attempt to locate the RPC credentials.
2084
        configContents, err := io.ReadAll(btcdConfigFile)
2085
        if err != nil {
2086
                return "", "", err
×
2087
        }
×
2088

×
2089
        // Attempt to locate the RPC user using a regular expression. If we
×
2090
        // don't have a match for our regular expression then we'll exit with
2091
        // an error.
2092
        rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
2093
        if err != nil {
2094
                return "", "", err
×
2095
        }
×
2096
        userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
×
2097
        if userSubmatches == nil {
×
2098
                return "", "", fmt.Errorf("unable to find rpcuser in config")
×
2099
        }
×
2100

×
2101
        // Similarly, we'll use another regular expression to find the set
×
2102
        // rpcpass (if any). If we can't find the pass, then we'll exit with an
2103
        // error.
2104
        rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpass\s*=\s*([^\s]+)`)
2105
        if err != nil {
2106
                return "", "", err
×
2107
        }
×
2108
        passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
×
2109
        if passSubmatches == nil {
×
2110
                return "", "", fmt.Errorf("unable to find rpcuser in config")
×
2111
        }
×
2112

×
2113
        return supplyEnvValue(string(userSubmatches[1])),
×
2114
                supplyEnvValue(string(passSubmatches[1])), nil
2115
}
×
2116

×
2117
// extractBitcoindRPCParams attempts to extract the RPC credentials for an
2118
// existing bitcoind node instance. The routine looks for a cookie first,
2119
// optionally following the datadir configuration option in the bitcoin.conf. If
2120
// it doesn't find one, it looks for rpcuser/rpcpassword.
2121
func extractBitcoindRPCParams(networkName, bitcoindDataDir, bitcoindConfigPath,
2122
        rpcCookiePath string) (string, string, string, string, error) {
2123

2124
        // First, we'll open up the bitcoind configuration file found at the
×
2125
        // target destination.
×
2126
        bitcoindConfigFile, err := os.Open(bitcoindConfigPath)
×
2127
        if err != nil {
×
2128
                return "", "", "", "", err
×
2129
        }
×
2130
        defer func() { _ = bitcoindConfigFile.Close() }()
×
2131

×
2132
        // With the file open extract the contents of the configuration file so
×
2133
        // we can attempt to locate the RPC credentials.
2134
        configContents, err := io.ReadAll(bitcoindConfigFile)
2135
        if err != nil {
2136
                return "", "", "", "", err
×
2137
        }
×
2138

×
2139
        // First, we'll look for the ZMQ hosts providing raw block and raw
×
2140
        // transaction notifications.
2141
        zmqBlockHostRE, err := regexp.Compile(
2142
                `(?m)^\s*zmqpubrawblock\s*=\s*([^\s]+)`,
2143
        )
×
2144
        if err != nil {
×
2145
                return "", "", "", "", err
×
2146
        }
×
2147
        zmqBlockHostSubmatches := zmqBlockHostRE.FindSubmatch(configContents)
×
2148
        if len(zmqBlockHostSubmatches) < 2 {
×
2149
                return "", "", "", "", fmt.Errorf("unable to find " +
×
2150
                        "zmqpubrawblock in config")
×
2151
        }
×
2152
        zmqTxHostRE, err := regexp.Compile(`(?m)^\s*zmqpubrawtx\s*=\s*([^\s]+)`)
×
2153
        if err != nil {
×
2154
                return "", "", "", "", err
×
2155
        }
×
2156
        zmqTxHostSubmatches := zmqTxHostRE.FindSubmatch(configContents)
×
2157
        if len(zmqTxHostSubmatches) < 2 {
×
2158
                return "", "", "", "", errors.New("unable to find zmqpubrawtx " +
×
2159
                        "in config")
×
2160
        }
×
2161
        zmqBlockHost := string(zmqBlockHostSubmatches[1])
×
2162
        zmqTxHost := string(zmqTxHostSubmatches[1])
×
2163
        if err := checkZMQOptions(zmqBlockHost, zmqTxHost); err != nil {
×
2164
                return "", "", "", "", err
×
2165
        }
×
2166

×
2167
        // Next, we'll try to find an auth cookie. We need to detect the chain
×
2168
        // by seeing if one is specified in the configuration file.
2169
        dataDir := filepath.Dir(bitcoindConfigPath)
2170
        if bitcoindDataDir != "" {
2171
                dataDir = bitcoindDataDir
×
2172
        }
×
2173
        dataDirRE, err := regexp.Compile(`(?m)^\s*datadir\s*=\s*([^\s]+)`)
×
2174
        if err != nil {
×
2175
                return "", "", "", "", err
×
2176
        }
×
2177
        dataDirSubmatches := dataDirRE.FindSubmatch(configContents)
×
2178
        if dataDirSubmatches != nil {
×
2179
                dataDir = string(dataDirSubmatches[1])
×
2180
        }
×
2181

×
2182
        var chainDir string
×
2183
        switch networkName {
2184
        case "mainnet":
×
2185
                chainDir = ""
×
2186
        case "regtest", "testnet3", "signet":
×
2187
                chainDir = networkName
×
2188
        default:
×
2189
                return "", "", "", "", fmt.Errorf("unexpected networkname %v", networkName)
×
2190
        }
×
2191

×
2192
        cookiePath := filepath.Join(dataDir, chainDir, ".cookie")
2193
        if rpcCookiePath != "" {
2194
                cookiePath = rpcCookiePath
×
2195
        }
×
2196
        cookie, err := os.ReadFile(cookiePath)
×
2197
        if err == nil {
×
2198
                splitCookie := strings.Split(string(cookie), ":")
×
2199
                if len(splitCookie) == 2 {
×
2200
                        return splitCookie[0], splitCookie[1], zmqBlockHost,
×
2201
                                zmqTxHost, nil
×
2202
                }
×
2203
        }
×
2204

×
2205
        // We didn't find a cookie, so we attempt to locate the RPC user using
2206
        // a regular expression. If we  don't have a match for our regular
2207
        // expression then we'll exit with an error.
2208
        rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser\s*=\s*([^\s]+)`)
2209
        if err != nil {
2210
                return "", "", "", "", err
×
2211
        }
×
2212
        userSubmatches := rpcUserRegexp.FindSubmatch(configContents)
×
2213

×
2214
        // Similarly, we'll use another regular expression to find the set
×
2215
        // rpcpass (if any). If we can't find the pass, then we'll exit with an
×
2216
        // error.
×
2217
        rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpassword\s*=\s*([^\s]+)`)
×
2218
        if err != nil {
×
2219
                return "", "", "", "", err
×
2220
        }
×
2221
        passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
×
2222

×
2223
        // Exit with an error if the cookie file, is defined in config, and
×
2224
        // can not be found, with both rpcuser and rpcpassword undefined.
×
2225
        if rpcCookiePath != "" && userSubmatches == nil && passSubmatches == nil {
×
2226
                return "", "", "", "", fmt.Errorf("unable to open cookie file (%v)",
×
2227
                        rpcCookiePath)
×
2228
        }
×
2229

×
2230
        if userSubmatches == nil {
×
2231
                return "", "", "", "", fmt.Errorf("unable to find rpcuser in " +
2232
                        "config")
×
2233
        }
×
2234
        if passSubmatches == nil {
×
2235
                return "", "", "", "", fmt.Errorf("unable to find rpcpassword " +
×
2236
                        "in config")
×
2237
        }
×
2238

×
2239
        return supplyEnvValue(string(userSubmatches[1])),
×
2240
                supplyEnvValue(string(passSubmatches[1])),
2241
                zmqBlockHost, zmqTxHost, nil
×
2242
}
×
2243

×
2244
// checkZMQOptions ensures that the provided addresses to use as the hosts for
2245
// ZMQ rawblock and rawtx notifications are different.
2246
func checkZMQOptions(zmqBlockHost, zmqTxHost string) error {
2247
        if zmqBlockHost == zmqTxHost {
2248
                return errors.New("zmqpubrawblock and zmqpubrawtx must be set " +
1✔
2249
                        "to different addresses")
1✔
2250
        }
×
2251

×
2252
        return nil
×
2253
}
2254

1✔
2255
// checkEstimateMode ensures that the provided estimate mode is legal.
2256
func checkEstimateMode(estimateMode string) error {
2257
        for _, mode := range bitcoindEstimateModes {
2258
                if estimateMode == mode {
1✔
2259
                        return nil
2✔
2260
                }
2✔
2261
        }
1✔
2262

1✔
2263
        return fmt.Errorf("estimatemode must be one of the following: %v",
2264
                bitcoindEstimateModes[:])
2265
}
×
2266

×
2267
// configToFlatMap converts the given config struct into a flat map of
2268
// key/value pairs using the dot notation we are used to from the config file
2269
// or command line flags. It also returns a map containing deprecated config
2270
// options.
2271
func configToFlatMap(cfg Config) (map[string]string,
2272
        map[string]struct{}, error) {
2273

2274
        result := make(map[string]string)
3✔
2275

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

3✔
2281
        // redact is the helper function that redacts sensitive values like
3✔
2282
        // passwords.
3✔
2283
        redact := func(key, value string) string {
3✔
2284
                sensitiveKeySuffixes := []string{
3✔
2285
                        "pass",
6✔
2286
                        "password",
3✔
2287
                        "dsn",
3✔
2288
                }
3✔
2289
                for _, suffix := range sensitiveKeySuffixes {
3✔
2290
                        if strings.HasSuffix(key, suffix) {
3✔
2291
                                return "[redacted]"
6✔
2292
                        }
6✔
2293
                }
3✔
2294

3✔
2295
                return value
2296
        }
2297

3✔
2298
        // printConfig is the helper function that goes into nested structs
2299
        // recursively. Because we call it recursively, we need to declare it
2300
        // before we define it.
2301
        var printConfig func(reflect.Value, string)
2302
        printConfig = func(obj reflect.Value, prefix string) {
2303
                // Turn struct pointers into the actual struct, so we can
3✔
2304
                // iterate over the fields as we would with a struct value.
6✔
2305
                if obj.Kind() == reflect.Ptr {
3✔
2306
                        obj = obj.Elem()
3✔
2307
                }
6✔
2308

3✔
2309
                // Abort on nil values.
3✔
2310
                if !obj.IsValid() {
2311
                        return
2312
                }
3✔
2313

×
2314
                // Loop over all fields of the struct and inspect the type.
×
2315
                for i := 0; i < obj.NumField(); i++ {
2316
                        field := obj.Field(i)
2317
                        fieldType := obj.Type().Field(i)
6✔
2318

3✔
2319
                        longName := fieldType.Tag.Get("long")
3✔
2320
                        namespace := fieldType.Tag.Get("namespace")
3✔
2321
                        group := fieldType.Tag.Get("group")
3✔
2322
                        hidden := fieldType.Tag.Get("hidden")
3✔
2323

3✔
2324
                        switch {
3✔
2325
                        // We have a long name defined, this is a config value.
3✔
2326
                        case longName != "":
3✔
2327
                                key := longName
2328
                                if prefix != "" {
3✔
2329
                                        key = prefix + "." + key
3✔
2330
                                }
6✔
2331

3✔
2332
                                // Add the value directly to the flattened map.
3✔
2333
                                result[key] = redact(key, fmt.Sprintf(
2334
                                        "%v", field.Interface(),
2335
                                ))
3✔
2336

3✔
2337
                                // If there's a hidden flag, it's deprecated.
3✔
2338
                                if hidden == "true" && !field.IsZero() {
3✔
2339
                                        deprecated[key] = struct{}{}
3✔
2340
                                }
3✔
2341

×
2342
                        // We have no long name but a namespace, this is a
×
2343
                        // nested struct.
2344
                        case longName == "" && namespace != "":
2345
                                key := namespace
2346
                                if prefix != "" {
3✔
2347
                                        key = prefix + "." + key
3✔
2348
                                }
6✔
2349

3✔
2350
                                printConfig(field, key)
3✔
2351

2352
                        // Just a group means this is a dummy struct to house
3✔
2353
                        // multiple config values, the group name doesn't go
2354
                        // into the final field name.
2355
                        case longName == "" && group != "":
2356
                                printConfig(field, prefix)
2357

3✔
2358
                        // Anonymous means embedded struct. We need to recurse
3✔
2359
                        // into it but without adding anything to the prefix.
2360
                        case fieldType.Anonymous:
2361
                                printConfig(field, prefix)
2362

3✔
2363
                        default:
3✔
2364
                                continue
2365
                        }
3✔
2366
                }
3✔
2367
        }
2368

2369
        // Turn the whole config struct into a flat map.
2370
        printConfig(reflect.ValueOf(cfg), "")
2371

2372
        return result, deprecated, nil
3✔
2373
}
3✔
2374

3✔
2375
// logWarningsForDeprecation logs a warning if a deprecated config option is
2376
// set.
2377
func logWarningsForDeprecation(cfg Config) {
2378
        _, deprecated, err := configToFlatMap(cfg)
2379
        if err != nil {
3✔
2380
                ltndLog.Errorf("Convert configs to map: %v", err)
3✔
2381
        }
3✔
2382

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