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

lightningnetwork / lnd / 16937581283

13 Aug 2025 12:43PM UTC coverage: 66.901% (-0.03%) from 66.929%
16937581283

Pull #10148

github

web-flow
Merge b1deddec4 into c6a9116e3
Pull Request #10148: graph/db+sqldb: different defaults for SQLite and Postgres query options

11 of 81 new or added lines in 7 files covered. (13.58%)

88 existing lines in 25 files now uncovered.

135834 of 203036 relevant lines covered (66.9%)

21598.84 hits per line

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

60.93
/config_builder.go
1
package lnd
2

3
import (
4
        "bytes"
5
        "context"
6
        "database/sql"
7
        "errors"
8
        "fmt"
9
        "net"
10
        "os"
11
        "path/filepath"
12
        "sort"
13
        "strconv"
14
        "strings"
15
        "sync/atomic"
16
        "time"
17

18
        "github.com/btcsuite/btcd/chaincfg"
19
        "github.com/btcsuite/btcd/chaincfg/chainhash"
20
        "github.com/btcsuite/btcd/wire"
21
        "github.com/btcsuite/btclog/v2"
22
        "github.com/btcsuite/btcwallet/chain"
23
        "github.com/btcsuite/btcwallet/waddrmgr"
24
        "github.com/btcsuite/btcwallet/wallet"
25
        "github.com/btcsuite/btcwallet/walletdb"
26
        proxy "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
27
        "github.com/lightninglabs/neutrino"
28
        "github.com/lightninglabs/neutrino/blockntfns"
29
        "github.com/lightninglabs/neutrino/headerfs"
30
        "github.com/lightninglabs/neutrino/pushtx"
31
        "github.com/lightningnetwork/lnd/blockcache"
32
        "github.com/lightningnetwork/lnd/chainntnfs"
33
        "github.com/lightningnetwork/lnd/chainreg"
34
        "github.com/lightningnetwork/lnd/channeldb"
35
        "github.com/lightningnetwork/lnd/clock"
36
        "github.com/lightningnetwork/lnd/fn/v2"
37
        "github.com/lightningnetwork/lnd/funding"
38
        graphdb "github.com/lightningnetwork/lnd/graph/db"
39
        "github.com/lightningnetwork/lnd/htlcswitch"
40
        "github.com/lightningnetwork/lnd/invoices"
41
        "github.com/lightningnetwork/lnd/keychain"
42
        "github.com/lightningnetwork/lnd/kvdb"
43
        "github.com/lightningnetwork/lnd/lncfg"
44
        "github.com/lightningnetwork/lnd/lnrpc"
45
        "github.com/lightningnetwork/lnd/lnwallet"
46
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
47
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
48
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
49
        "github.com/lightningnetwork/lnd/macaroons"
50
        "github.com/lightningnetwork/lnd/msgmux"
51
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
52
        "github.com/lightningnetwork/lnd/rpcperms"
53
        "github.com/lightningnetwork/lnd/signal"
54
        "github.com/lightningnetwork/lnd/sqldb"
55
        "github.com/lightningnetwork/lnd/sqldb/sqlc"
56
        "github.com/lightningnetwork/lnd/sweep"
57
        "github.com/lightningnetwork/lnd/walletunlocker"
58
        "github.com/lightningnetwork/lnd/watchtower"
59
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
60
        "github.com/lightningnetwork/lnd/watchtower/wtdb"
61
        "google.golang.org/grpc"
62
        "gopkg.in/macaroon-bakery.v2/bakery"
63
)
64

65
const (
66
        // invoiceMigrationBatchSize is the number of invoices that will be
67
        // migrated in a single batch.
68
        invoiceMigrationBatchSize = 1000
69

70
        // invoiceMigration is the version of the migration that will be used to
71
        // migrate invoices from the kvdb to the sql database.
72
        invoiceMigration = 7
73
)
74

75
// GrpcRegistrar is an interface that must be satisfied by an external subserver
76
// that wants to be able to register its own gRPC server onto lnd's main
77
// grpc.Server instance.
78
type GrpcRegistrar interface {
79
        // RegisterGrpcSubserver is called for each net.Listener on which lnd
80
        // creates a grpc.Server instance. External subservers implementing this
81
        // method can then register their own gRPC server structs to the main
82
        // server instance.
83
        RegisterGrpcSubserver(*grpc.Server) error
84
}
85

86
// RestRegistrar is an interface that must be satisfied by an external subserver
87
// that wants to be able to register its own REST mux onto lnd's main
88
// proxy.ServeMux instance.
89
type RestRegistrar interface {
90
        // RegisterRestSubserver is called after lnd creates the main
91
        // proxy.ServeMux instance. External subservers implementing this method
92
        // can then register their own REST proxy stubs to the main server
93
        // instance.
94
        RegisterRestSubserver(context.Context, *proxy.ServeMux, string,
95
                []grpc.DialOption) error
96
}
97

98
// ExternalValidator is an interface that must be satisfied by an external
99
// macaroon validator.
100
type ExternalValidator interface {
101
        macaroons.MacaroonValidator
102

103
        // Permissions returns the permissions that the external validator is
104
        // validating. It is a map between the full HTTP URI of each RPC and its
105
        // required macaroon permissions. If multiple action/entity tuples are
106
        // specified per URI, they are all required. See rpcserver.go for a list
107
        // of valid action and entity values.
108
        Permissions() map[string][]bakery.Op
109
}
110

111
// DatabaseBuilder is an interface that must be satisfied by the implementation
112
// that provides lnd's main database backend instances.
113
type DatabaseBuilder interface {
114
        // BuildDatabase extracts the current databases that we'll use for
115
        // normal operation in the daemon. A function closure that closes all
116
        // opened databases is also returned.
117
        BuildDatabase(ctx context.Context) (*DatabaseInstances, func(), error)
118
}
119

120
// WalletConfigBuilder is an interface that must be satisfied by a custom wallet
121
// implementation.
122
type WalletConfigBuilder interface {
123
        // BuildWalletConfig is responsible for creating or unlocking and then
124
        // fully initializing a wallet.
125
        BuildWalletConfig(context.Context, *DatabaseInstances, *AuxComponents,
126
                *rpcperms.InterceptorChain,
127
                []*ListenerWithSignal) (*chainreg.PartialChainControl,
128
                *btcwallet.Config, func(), error)
129
}
130

131
// ChainControlBuilder is an interface that must be satisfied by a custom wallet
132
// implementation.
133
type ChainControlBuilder interface {
134
        // BuildChainControl is responsible for creating a fully populated chain
135
        // control instance from a wallet.
136
        BuildChainControl(*chainreg.PartialChainControl,
137
                *btcwallet.Config) (*chainreg.ChainControl, func(), error)
138
}
139

140
// ImplementationCfg is a struct that holds all configuration items for
141
// components that can be implemented outside lnd itself.
142
type ImplementationCfg struct {
143
        // GrpcRegistrar is a type that can register additional gRPC subservers
144
        // before the main gRPC server is started.
145
        GrpcRegistrar
146

147
        // RestRegistrar is a type that can register additional REST subservers
148
        // before the main REST proxy is started.
149
        RestRegistrar
150

151
        // ExternalValidator is a type that can provide external macaroon
152
        // validation.
153
        ExternalValidator
154

155
        // DatabaseBuilder is a type that can provide lnd's main database
156
        // backend instances.
157
        DatabaseBuilder
158

159
        // WalletConfigBuilder is a type that can provide a wallet configuration
160
        // with a fully loaded and unlocked wallet.
161
        WalletConfigBuilder
162

163
        // ChainControlBuilder is a type that can provide a custom wallet
164
        // implementation.
165
        ChainControlBuilder
166

167
        // AuxComponents is a set of auxiliary components that can be used by
168
        // lnd for certain custom channel types.
169
        AuxComponents
170
}
171

172
// AuxComponents is a set of auxiliary components that can be used by lnd for
173
// certain custom channel types.
174
type AuxComponents struct {
175
        // AuxLeafStore is an optional data source that can be used by custom
176
        // channels to fetch+store various data.
177
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
178

179
        // TrafficShaper is an optional traffic shaper that can be used to
180
        // control the outgoing channel of a payment.
181
        TrafficShaper fn.Option[htlcswitch.AuxTrafficShaper]
182

183
        // MsgRouter is an optional message router that if set will be used in
184
        // place of a new blank default message router.
185
        MsgRouter fn.Option[msgmux.Router]
186

187
        // AuxFundingController is an optional controller that can be used to
188
        // modify the way we handle certain custom channel types. It's also
189
        // able to automatically handle new custom protocol messages related to
190
        // the funding process.
191
        AuxFundingController fn.Option[funding.AuxFundingController]
192

193
        // AuxSigner is an optional signer that can be used to sign auxiliary
194
        // leaves for certain custom channel types.
195
        AuxSigner fn.Option[lnwallet.AuxSigner]
196

197
        // AuxDataParser is an optional data parser that can be used to parse
198
        // auxiliary data for certain custom channel types.
199
        AuxDataParser fn.Option[AuxDataParser]
200

201
        // AuxChanCloser is an optional channel closer that can be used to
202
        // modify the way a coop-close transaction is constructed.
203
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
204

205
        // AuxSweeper is an optional interface that can be used to modify the
206
        // way sweep transaction are generated.
207
        AuxSweeper fn.Option[sweep.AuxSweeper]
208

209
        // AuxContractResolver is an optional interface that can be used to
210
        // modify the way contracts are resolved.
211
        AuxContractResolver fn.Option[lnwallet.AuxContractResolver]
212
}
213

214
// DefaultWalletImpl is the default implementation of our normal, btcwallet
215
// backed configuration.
216
type DefaultWalletImpl struct {
217
        cfg         *Config
218
        logger      btclog.Logger
219
        interceptor signal.Interceptor
220

221
        watchOnly        bool
222
        migrateWatchOnly bool
223
        pwService        *walletunlocker.UnlockerService
224
}
225

226
// NewDefaultWalletImpl creates a new default wallet implementation.
227
func NewDefaultWalletImpl(cfg *Config, logger btclog.Logger,
228
        interceptor signal.Interceptor, watchOnly bool) *DefaultWalletImpl {
3✔
229

3✔
230
        return &DefaultWalletImpl{
3✔
231
                cfg:         cfg,
3✔
232
                logger:      logger,
3✔
233
                interceptor: interceptor,
3✔
234
                watchOnly:   watchOnly,
3✔
235
                pwService:   createWalletUnlockerService(cfg),
3✔
236
        }
3✔
237
}
3✔
238

239
// RegisterRestSubserver is called after lnd creates the main proxy.ServeMux
240
// instance. External subservers implementing this method can then register
241
// their own REST proxy stubs to the main server instance.
242
//
243
// NOTE: This is part of the GrpcRegistrar interface.
244
func (d *DefaultWalletImpl) RegisterRestSubserver(ctx context.Context,
245
        mux *proxy.ServeMux, restProxyDest string,
246
        restDialOpts []grpc.DialOption) error {
3✔
247

3✔
248
        return lnrpc.RegisterWalletUnlockerHandlerFromEndpoint(
3✔
249
                ctx, mux, restProxyDest, restDialOpts,
3✔
250
        )
3✔
251
}
3✔
252

253
// RegisterGrpcSubserver is called for each net.Listener on which lnd creates a
254
// grpc.Server instance. External subservers implementing this method can then
255
// register their own gRPC server structs to the main server instance.
256
//
257
// NOTE: This is part of the GrpcRegistrar interface.
258
func (d *DefaultWalletImpl) RegisterGrpcSubserver(s *grpc.Server) error {
3✔
259
        lnrpc.RegisterWalletUnlockerServer(s, d.pwService)
3✔
260

3✔
261
        return nil
3✔
262
}
3✔
263

264
// ValidateMacaroon extracts the macaroon from the context's gRPC metadata,
265
// checks its signature, makes sure all specified permissions for the called
266
// method are contained within and finally ensures all caveat conditions are
267
// met. A non-nil error is returned if any of the checks fail.
268
//
269
// NOTE: This is part of the ExternalValidator interface.
270
func (d *DefaultWalletImpl) ValidateMacaroon(ctx context.Context,
271
        requiredPermissions []bakery.Op, fullMethod string) error {
×
272

×
273
        // Because the default implementation does not return any permissions,
×
274
        // we shouldn't be registered as an external validator at all and this
×
275
        // should never be invoked.
×
276
        return fmt.Errorf("default implementation does not support external " +
×
277
                "macaroon validation")
×
278
}
×
279

280
// Permissions returns the permissions that the external validator is
281
// validating. It is a map between the full HTTP URI of each RPC and its
282
// required macaroon permissions. If multiple action/entity tuples are specified
283
// per URI, they are all required. See rpcserver.go for a list of valid action
284
// and entity values.
285
//
286
// NOTE: This is part of the ExternalValidator interface.
287
func (d *DefaultWalletImpl) Permissions() map[string][]bakery.Op {
3✔
288
        return nil
3✔
289
}
3✔
290

291
// BuildWalletConfig is responsible for creating or unlocking and then
292
// fully initializing a wallet.
293
//
294
// NOTE: This is part of the WalletConfigBuilder interface.
295
func (d *DefaultWalletImpl) BuildWalletConfig(ctx context.Context,
296
        dbs *DatabaseInstances, aux *AuxComponents,
297
        interceptorChain *rpcperms.InterceptorChain,
298
        grpcListeners []*ListenerWithSignal) (*chainreg.PartialChainControl,
299
        *btcwallet.Config, func(), error) {
3✔
300

3✔
301
        // Keep track of our various cleanup functions. We use a defer function
3✔
302
        // as well to not repeat ourselves with every return statement.
3✔
303
        var (
3✔
304
                cleanUpTasks []func()
3✔
305
                earlyExit    = true
3✔
306
                cleanUp      = func() {
6✔
307
                        for _, fn := range cleanUpTasks {
6✔
308
                                if fn == nil {
3✔
309
                                        continue
×
310
                                }
311

312
                                fn()
3✔
313
                        }
314
                }
315
        )
316
        defer func() {
6✔
317
                if earlyExit {
3✔
318
                        cleanUp()
×
319
                }
×
320
        }()
321

322
        // Initialize a new block cache.
323
        blockCache := blockcache.NewBlockCache(d.cfg.BlockCacheSize)
3✔
324

3✔
325
        // Before starting the wallet, we'll create and start our Neutrino
3✔
326
        // light client instance, if enabled, in order to allow it to sync
3✔
327
        // while the rest of the daemon continues startup.
3✔
328
        mainChain := d.cfg.Bitcoin
3✔
329
        var neutrinoCS *neutrino.ChainService
3✔
330
        if mainChain.Node == "neutrino" {
4✔
331
                neutrinoBackend, neutrinoCleanUp, err := initNeutrinoBackend(
1✔
332
                        ctx, d.cfg, mainChain.ChainDir, blockCache,
1✔
333
                )
1✔
334
                if err != nil {
1✔
335
                        err := fmt.Errorf("unable to initialize neutrino "+
×
336
                                "backend: %v", err)
×
337
                        d.logger.Error(err)
×
338
                        return nil, nil, nil, err
×
339
                }
×
340
                cleanUpTasks = append(cleanUpTasks, neutrinoCleanUp)
1✔
341
                neutrinoCS = neutrinoBackend
1✔
342
        }
343

344
        var (
3✔
345
                walletInitParams = walletunlocker.WalletUnlockParams{
3✔
346
                        // In case we do auto-unlock, we need to be able to send
3✔
347
                        // into the channel without blocking so we buffer it.
3✔
348
                        MacResponseChan: make(chan []byte, 1),
3✔
349
                }
3✔
350
                privateWalletPw = lnwallet.DefaultPrivatePassphrase
3✔
351
                publicWalletPw  = lnwallet.DefaultPublicPassphrase
3✔
352
        )
3✔
353

3✔
354
        // If the user didn't request a seed, then we'll manually assume a
3✔
355
        // wallet birthday of now, as otherwise the seed would've specified
3✔
356
        // this information.
3✔
357
        walletInitParams.Birthday = time.Now()
3✔
358

3✔
359
        d.pwService.SetLoaderOpts([]btcwallet.LoaderOption{dbs.WalletDB})
3✔
360
        d.pwService.SetMacaroonDB(dbs.MacaroonDB)
3✔
361
        walletExists, err := d.pwService.WalletExists()
3✔
362
        if err != nil {
3✔
363
                return nil, nil, nil, err
×
364
        }
×
365

366
        if !walletExists {
6✔
367
                interceptorChain.SetWalletNotCreated()
3✔
368
        } else {
6✔
369
                interceptorChain.SetWalletLocked()
3✔
370
        }
3✔
371

372
        // If we've started in auto unlock mode, then a wallet should already
373
        // exist because we don't want to enable the RPC unlocker in that case
374
        // for security reasons (an attacker could inject their seed since the
375
        // RPC is unauthenticated). Only if the user explicitly wants to allow
376
        // wallet creation we don't error out here.
377
        if d.cfg.WalletUnlockPasswordFile != "" && !walletExists &&
3✔
378
                !d.cfg.WalletUnlockAllowCreate {
3✔
379

×
380
                return nil, nil, nil, fmt.Errorf("wallet unlock password file " +
×
381
                        "was specified but wallet does not exist; initialize " +
×
382
                        "the wallet before using auto unlocking")
×
383
        }
×
384

385
        // What wallet mode are we running in? We've already made sure the no
386
        // seed backup and auto unlock aren't both set during config parsing.
387
        switch {
3✔
388
        // No seed backup means we're also using the default password.
389
        case d.cfg.NoSeedBackup:
3✔
390
                // We continue normally, the default password has already been
391
                // set above.
392

393
        // A password for unlocking is provided in a file.
394
        case d.cfg.WalletUnlockPasswordFile != "" && walletExists:
×
395
                d.logger.Infof("Attempting automatic wallet unlock with " +
×
396
                        "password provided in file")
×
397
                pwBytes, err := os.ReadFile(d.cfg.WalletUnlockPasswordFile)
×
398
                if err != nil {
×
399
                        return nil, nil, nil, fmt.Errorf("error reading "+
×
400
                                "password from file %s: %v",
×
401
                                d.cfg.WalletUnlockPasswordFile, err)
×
402
                }
×
403

404
                // Remove any newlines at the end of the file. The lndinit tool
405
                // won't ever write a newline but maybe the file was provisioned
406
                // by another process or user.
407
                pwBytes = bytes.TrimRight(pwBytes, "\r\n")
×
408

×
409
                // We have the password now, we can ask the unlocker service to
×
410
                // do the unlock for us.
×
411
                unlockedWallet, unloadWalletFn, err := d.pwService.LoadAndUnlock(
×
412
                        pwBytes, 0,
×
413
                )
×
414
                if err != nil {
×
415
                        return nil, nil, nil, fmt.Errorf("error unlocking "+
×
416
                                "wallet with password from file: %v", err)
×
417
                }
×
418

419
                cleanUpTasks = append(cleanUpTasks, func() {
×
420
                        if err := unloadWalletFn(); err != nil {
×
421
                                d.logger.Errorf("Could not unload wallet: %v",
×
422
                                        err)
×
423
                        }
×
424
                })
425

426
                privateWalletPw = pwBytes
×
427
                publicWalletPw = pwBytes
×
428
                walletInitParams.Wallet = unlockedWallet
×
429
                walletInitParams.UnloadWallet = unloadWalletFn
×
430

431
        // If none of the automatic startup options are selected, we fall back
432
        // to the default behavior of waiting for the wallet creation/unlocking
433
        // over RPC.
434
        default:
3✔
435
                if err := d.interceptor.Notifier.NotifyReady(false); err != nil {
3✔
436
                        return nil, nil, nil, err
×
437
                }
×
438

439
                params, err := waitForWalletPassword(
3✔
440
                        d.cfg, d.pwService, []btcwallet.LoaderOption{dbs.WalletDB},
3✔
441
                        d.interceptor.ShutdownChannel(),
3✔
442
                )
3✔
443
                if err != nil {
3✔
444
                        err := fmt.Errorf("unable to set up wallet password "+
×
445
                                "listeners: %v", err)
×
446
                        d.logger.Error(err)
×
447
                        return nil, nil, nil, err
×
448
                }
×
449

450
                walletInitParams = *params
3✔
451
                privateWalletPw = walletInitParams.Password
3✔
452
                publicWalletPw = walletInitParams.Password
3✔
453
                cleanUpTasks = append(cleanUpTasks, func() {
6✔
454
                        if err := walletInitParams.UnloadWallet(); err != nil {
3✔
455
                                d.logger.Errorf("Could not unload wallet: %v",
×
456
                                        err)
×
457
                        }
×
458
                })
459

460
                if walletInitParams.RecoveryWindow > 0 {
6✔
461
                        d.logger.Infof("Wallet recovery mode enabled with "+
3✔
462
                                "address lookahead of %d addresses",
3✔
463
                                walletInitParams.RecoveryWindow)
3✔
464
                }
3✔
465
        }
466

467
        var macaroonService *macaroons.Service
3✔
468
        if !d.cfg.NoMacaroons {
6✔
469
                // Create the macaroon authentication/authorization service.
3✔
470
                rootKeyStore, err := macaroons.NewRootKeyStorage(dbs.MacaroonDB)
3✔
471
                if err != nil {
3✔
472
                        return nil, nil, nil, err
×
473
                }
×
474
                macaroonService, err = macaroons.NewService(
3✔
475
                        rootKeyStore, "lnd", walletInitParams.StatelessInit,
3✔
476
                        macaroons.IPLockChecker, macaroons.IPRangeLockChecker,
3✔
477
                        macaroons.CustomChecker(interceptorChain),
3✔
478
                )
3✔
479
                if err != nil {
3✔
480
                        err := fmt.Errorf("unable to set up macaroon "+
×
481
                                "authentication: %v", err)
×
482
                        d.logger.Error(err)
×
483
                        return nil, nil, nil, err
×
484
                }
×
485
                cleanUpTasks = append(cleanUpTasks, func() {
6✔
486
                        if err := macaroonService.Close(); err != nil {
3✔
487
                                d.logger.Errorf("Could not close macaroon "+
×
488
                                        "service: %v", err)
×
489
                        }
×
490
                })
491

492
                // Try to unlock the macaroon store with the private password.
493
                // Ignore ErrAlreadyUnlocked since it could be unlocked by the
494
                // wallet unlocker.
495
                err = macaroonService.CreateUnlock(&privateWalletPw)
3✔
496
                if err != nil && err != macaroons.ErrAlreadyUnlocked {
3✔
497
                        err := fmt.Errorf("unable to unlock macaroons: %w", err)
×
498
                        d.logger.Error(err)
×
499
                        return nil, nil, nil, err
×
500
                }
×
501

502
                // If we have a macaroon root key from the init wallet params,
503
                // set the root key before baking any macaroons.
504
                if len(walletInitParams.MacRootKey) > 0 {
3✔
505
                        err := macaroonService.SetRootKey(
×
506
                                walletInitParams.MacRootKey,
×
507
                        )
×
508
                        if err != nil {
×
509
                                return nil, nil, nil, err
×
510
                        }
×
511
                }
512

513
                // Send an admin macaroon to all our listeners that requested
514
                // one by setting a non-nil macaroon channel.
515
                adminMacBytes, err := bakeMacaroon(
3✔
516
                        ctx, macaroonService, adminPermissions(),
3✔
517
                )
3✔
518
                if err != nil {
3✔
519
                        return nil, nil, nil, err
×
520
                }
×
521
                for _, lis := range grpcListeners {
6✔
522
                        if lis.MacChan != nil {
3✔
523
                                lis.MacChan <- adminMacBytes
×
524
                        }
×
525
                }
526

527
                // In case we actually needed to unlock the wallet, we now need
528
                // to create an instance of the admin macaroon and send it to
529
                // the unlocker so it can forward it to the user. In no seed
530
                // backup mode, there's nobody listening on the channel and we'd
531
                // block here forever.
532
                if !d.cfg.NoSeedBackup {
6✔
533
                        // The channel is buffered by one element so writing
3✔
534
                        // should not block here.
3✔
535
                        walletInitParams.MacResponseChan <- adminMacBytes
3✔
536
                }
3✔
537

538
                // If the user requested a stateless initialization, no macaroon
539
                // files should be created.
540
                if !walletInitParams.StatelessInit {
6✔
541
                        // Create default macaroon files for lncli to use if
3✔
542
                        // they don't exist.
3✔
543
                        err = genDefaultMacaroons(
3✔
544
                                ctx, macaroonService, d.cfg.AdminMacPath,
3✔
545
                                d.cfg.ReadMacPath, d.cfg.InvoiceMacPath,
3✔
546
                        )
3✔
547
                        if err != nil {
3✔
548
                                err := fmt.Errorf("unable to create macaroons "+
×
549
                                        "%v", err)
×
550
                                d.logger.Error(err)
×
551
                                return nil, nil, nil, err
×
552
                        }
×
553
                }
554

555
                // As a security service to the user, if they requested
556
                // stateless initialization and there are macaroon files on disk
557
                // we log a warning.
558
                if walletInitParams.StatelessInit {
6✔
559
                        msg := "Found %s macaroon on disk (%s) even though " +
3✔
560
                                "--stateless_init was requested. Unencrypted " +
3✔
561
                                "state is accessible by the host system. You " +
3✔
562
                                "should change the password and use " +
3✔
563
                                "--new_mac_root_key with --stateless_init to " +
3✔
564
                                "clean up and invalidate old macaroons."
3✔
565

3✔
566
                        if lnrpc.FileExists(d.cfg.AdminMacPath) {
3✔
567
                                d.logger.Warnf(msg, "admin", d.cfg.AdminMacPath)
×
568
                        }
×
569
                        if lnrpc.FileExists(d.cfg.ReadMacPath) {
3✔
570
                                d.logger.Warnf(msg, "readonly", d.cfg.ReadMacPath)
×
571
                        }
×
572
                        if lnrpc.FileExists(d.cfg.InvoiceMacPath) {
3✔
573
                                d.logger.Warnf(msg, "invoice", d.cfg.InvoiceMacPath)
×
574
                        }
×
575
                }
576

577
                // We add the macaroon service to our RPC interceptor. This
578
                // will start checking macaroons against permissions on every
579
                // RPC invocation.
580
                interceptorChain.AddMacaroonService(macaroonService)
3✔
581
        }
582

583
        // Now that the wallet password has been provided, transition the RPC
584
        // state into Unlocked.
585
        interceptorChain.SetWalletUnlocked()
3✔
586

3✔
587
        // Since calls to the WalletUnlocker service wait for a response on the
3✔
588
        // macaroon channel, we close it here to make sure they return in case
3✔
589
        // we did not return the admin macaroon above. This will be the case if
3✔
590
        // --no-macaroons is used.
3✔
591
        close(walletInitParams.MacResponseChan)
3✔
592

3✔
593
        // We'll also close all the macaroon channels since lnd is done sending
3✔
594
        // macaroon data over it.
3✔
595
        for _, lis := range grpcListeners {
6✔
596
                if lis.MacChan != nil {
3✔
597
                        close(lis.MacChan)
×
598
                }
×
599
        }
600

601
        // With the information parsed from the configuration, create valid
602
        // instances of the pertinent interfaces required to operate the
603
        // Lightning Network Daemon.
604
        //
605
        // When we create the chain control, we need storage for the height
606
        // hints and also the wallet itself, for these two we want them to be
607
        // replicated, so we'll pass in the remote channel DB instance.
608
        chainControlCfg := &chainreg.Config{
3✔
609
                Bitcoin:                     d.cfg.Bitcoin,
3✔
610
                HeightHintCacheQueryDisable: d.cfg.HeightHintCacheQueryDisable,
3✔
611
                NeutrinoMode:                d.cfg.NeutrinoMode,
3✔
612
                BitcoindMode:                d.cfg.BitcoindMode,
3✔
613
                BtcdMode:                    d.cfg.BtcdMode,
3✔
614
                HeightHintDB:                dbs.HeightHintDB,
3✔
615
                ChanStateDB:                 dbs.ChanStateDB.ChannelStateDB(),
3✔
616
                NeutrinoCS:                  neutrinoCS,
3✔
617
                AuxLeafStore:                aux.AuxLeafStore,
3✔
618
                AuxSigner:                   aux.AuxSigner,
3✔
619
                ActiveNetParams:             d.cfg.ActiveNetParams,
3✔
620
                FeeURL:                      d.cfg.FeeURL,
3✔
621
                Fee: &lncfg.Fee{
3✔
622
                        URL:              d.cfg.Fee.URL,
3✔
623
                        MinUpdateTimeout: d.cfg.Fee.MinUpdateTimeout,
3✔
624
                        MaxUpdateTimeout: d.cfg.Fee.MaxUpdateTimeout,
3✔
625
                },
3✔
626
                Dialer: func(addr string) (net.Conn, error) {
3✔
627
                        return d.cfg.net.Dial(
×
628
                                "tcp", addr, d.cfg.ConnectionTimeout,
×
629
                        )
×
630
                },
×
631
                BlockCache:         blockCache,
632
                WalletUnlockParams: &walletInitParams,
633
        }
634

635
        // Let's go ahead and create the partial chain control now that is only
636
        // dependent on our configuration and doesn't require any wallet
637
        // specific information.
638
        partialChainControl, pccCleanup, err := chainreg.NewPartialChainControl(
3✔
639
                chainControlCfg,
3✔
640
        )
3✔
641
        cleanUpTasks = append(cleanUpTasks, pccCleanup)
3✔
642
        if err != nil {
3✔
643
                err := fmt.Errorf("unable to create partial chain control: %w",
×
644
                        err)
×
645
                d.logger.Error(err)
×
646
                return nil, nil, nil, err
×
647
        }
×
648

649
        walletConfig := &btcwallet.Config{
3✔
650
                PrivatePass:      privateWalletPw,
3✔
651
                PublicPass:       publicWalletPw,
3✔
652
                Birthday:         walletInitParams.Birthday,
3✔
653
                RecoveryWindow:   walletInitParams.RecoveryWindow,
3✔
654
                NetParams:        d.cfg.ActiveNetParams.Params,
3✔
655
                CoinType:         d.cfg.ActiveNetParams.CoinType,
3✔
656
                Wallet:           walletInitParams.Wallet,
3✔
657
                LoaderOptions:    []btcwallet.LoaderOption{dbs.WalletDB},
3✔
658
                ChainSource:      partialChainControl.ChainSource,
3✔
659
                WatchOnly:        d.watchOnly,
3✔
660
                MigrateWatchOnly: d.migrateWatchOnly,
3✔
661
        }
3✔
662

3✔
663
        // Parse coin selection strategy.
3✔
664
        switch d.cfg.CoinSelectionStrategy {
3✔
665
        case "largest":
3✔
666
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionLargest
3✔
667

668
        case "random":
×
669
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionRandom
×
670

671
        default:
×
672
                return nil, nil, nil, fmt.Errorf("unknown coin selection "+
×
673
                        "strategy %v", d.cfg.CoinSelectionStrategy)
×
674
        }
675

676
        earlyExit = false
3✔
677
        return partialChainControl, walletConfig, cleanUp, nil
3✔
678
}
679

680
// proxyBlockEpoch proxies a block epoch subsections to the underlying neutrino
681
// rebroadcaster client.
682
func proxyBlockEpoch(
683
        notifier chainntnfs.ChainNotifier) func() (*blockntfns.Subscription,
684
        error) {
2✔
685

2✔
686
        return func() (*blockntfns.Subscription, error) {
4✔
687
                blockEpoch, err := notifier.RegisterBlockEpochNtfn(
2✔
688
                        nil,
2✔
689
                )
2✔
690
                if err != nil {
2✔
691
                        return nil, err
×
692
                }
×
693

694
                sub := blockntfns.Subscription{
2✔
695
                        Notifications: make(chan blockntfns.BlockNtfn, 6),
2✔
696
                        Cancel:        blockEpoch.Cancel,
2✔
697
                }
2✔
698
                go func() {
4✔
699
                        for blk := range blockEpoch.Epochs {
4✔
700
                                ntfn := blockntfns.NewBlockConnected(
2✔
701
                                        *blk.BlockHeader,
2✔
702
                                        uint32(blk.Height),
2✔
703
                                )
2✔
704

2✔
705
                                sub.Notifications <- ntfn
2✔
706
                        }
2✔
707
                }()
708

709
                return &sub, nil
2✔
710
        }
711
}
712

713
// walletReBroadcaster is a simple wrapper around the pushtx.Broadcaster
714
// interface to adhere to the expanded lnwallet.Rebroadcaster interface.
715
type walletReBroadcaster struct {
716
        started atomic.Bool
717

718
        *pushtx.Broadcaster
719
}
720

721
// newWalletReBroadcaster creates a new instance of the walletReBroadcaster.
722
func newWalletReBroadcaster(
723
        broadcaster *pushtx.Broadcaster) *walletReBroadcaster {
2✔
724

2✔
725
        return &walletReBroadcaster{
2✔
726
                Broadcaster: broadcaster,
2✔
727
        }
2✔
728
}
2✔
729

730
// Start launches all goroutines the rebroadcaster needs to operate.
731
func (w *walletReBroadcaster) Start() error {
2✔
732
        defer w.started.Store(true)
2✔
733

2✔
734
        return w.Broadcaster.Start()
2✔
735
}
2✔
736

737
// Started returns true if the broadcaster is already active.
738
func (w *walletReBroadcaster) Started() bool {
2✔
739
        return w.started.Load()
2✔
740
}
2✔
741

742
// BuildChainControl is responsible for creating a fully populated chain
743
// control instance from a wallet.
744
//
745
// NOTE: This is part of the ChainControlBuilder interface.
746
func (d *DefaultWalletImpl) BuildChainControl(
747
        partialChainControl *chainreg.PartialChainControl,
748
        walletConfig *btcwallet.Config) (*chainreg.ChainControl, func(), error) {
3✔
749

3✔
750
        walletController, err := btcwallet.New(
3✔
751
                *walletConfig, partialChainControl.Cfg.BlockCache,
3✔
752
        )
3✔
753
        if err != nil {
3✔
754
                err := fmt.Errorf("unable to create wallet controller: %w", err)
×
755
                d.logger.Error(err)
×
756
                return nil, nil, err
×
757
        }
×
758

759
        keyRing := keychain.NewBtcWalletKeyRing(
3✔
760
                walletController.InternalWallet(), walletConfig.CoinType,
3✔
761
        )
3✔
762

3✔
763
        // Create, and start the lnwallet, which handles the core payment
3✔
764
        // channel logic, and exposes control via proxy state machines.
3✔
765
        lnWalletConfig := lnwallet.Config{
3✔
766
                Database:              partialChainControl.Cfg.ChanStateDB,
3✔
767
                Notifier:              partialChainControl.ChainNotifier,
3✔
768
                WalletController:      walletController,
3✔
769
                Signer:                walletController,
3✔
770
                FeeEstimator:          partialChainControl.FeeEstimator,
3✔
771
                SecretKeyRing:         keyRing,
3✔
772
                ChainIO:               walletController,
3✔
773
                NetParams:             *walletConfig.NetParams,
3✔
774
                CoinSelectionStrategy: walletConfig.CoinSelectionStrategy,
3✔
775
                AuxLeafStore:          partialChainControl.Cfg.AuxLeafStore,
3✔
776
                AuxSigner:             partialChainControl.Cfg.AuxSigner,
3✔
777
        }
3✔
778

3✔
779
        // The broadcast is already always active for neutrino nodes, so we
3✔
780
        // don't want to create a rebroadcast loop.
3✔
781
        if partialChainControl.Cfg.NeutrinoCS == nil {
5✔
782
                cs := partialChainControl.ChainSource
2✔
783
                broadcastCfg := pushtx.Config{
2✔
784
                        Broadcast: func(tx *wire.MsgTx) error {
4✔
785
                                _, err := cs.SendRawTransaction(
2✔
786
                                        tx, true,
2✔
787
                                )
2✔
788

2✔
789
                                return err
2✔
790
                        },
2✔
791
                        SubscribeBlocks: proxyBlockEpoch(
792
                                partialChainControl.ChainNotifier,
793
                        ),
794
                        RebroadcastInterval: pushtx.DefaultRebroadcastInterval,
795
                        // In case the backend is different from neutrino we
796
                        // make sure that broadcast backend errors are mapped
797
                        // to the neutrino broadcastErr.
798
                        MapCustomBroadcastError: func(err error) error {
2✔
799
                                rpcErr := cs.MapRPCErr(err)
2✔
800
                                return broadcastErrorMapper(rpcErr)
2✔
801
                        },
2✔
802
                }
803

804
                lnWalletConfig.Rebroadcaster = newWalletReBroadcaster(
2✔
805
                        pushtx.NewBroadcaster(&broadcastCfg),
2✔
806
                )
2✔
807
        }
808

809
        // We've created the wallet configuration now, so we can finish
810
        // initializing the main chain control.
811
        activeChainControl, cleanUp, err := chainreg.NewChainControl(
3✔
812
                lnWalletConfig, walletController, partialChainControl,
3✔
813
        )
3✔
814
        if err != nil {
3✔
815
                err := fmt.Errorf("unable to create chain control: %w", err)
×
816
                d.logger.Error(err)
×
817
                return nil, nil, err
×
818
        }
×
819

820
        return activeChainControl, cleanUp, nil
3✔
821
}
822

823
// RPCSignerWalletImpl is a wallet implementation that uses a remote signer over
824
// an RPC interface.
825
type RPCSignerWalletImpl struct {
826
        // DefaultWalletImpl is the embedded instance of the default
827
        // implementation that the remote signer uses as its watch-only wallet
828
        // for keeping track of addresses and UTXOs.
829
        *DefaultWalletImpl
830
}
831

832
// NewRPCSignerWalletImpl creates a new instance of the remote signing wallet
833
// implementation.
834
func NewRPCSignerWalletImpl(cfg *Config, logger btclog.Logger,
835
        interceptor signal.Interceptor,
836
        migrateWatchOnly bool) *RPCSignerWalletImpl {
3✔
837

3✔
838
        return &RPCSignerWalletImpl{
3✔
839
                DefaultWalletImpl: &DefaultWalletImpl{
3✔
840
                        cfg:              cfg,
3✔
841
                        logger:           logger,
3✔
842
                        interceptor:      interceptor,
3✔
843
                        watchOnly:        true,
3✔
844
                        migrateWatchOnly: migrateWatchOnly,
3✔
845
                        pwService:        createWalletUnlockerService(cfg),
3✔
846
                },
3✔
847
        }
3✔
848
}
3✔
849

850
// BuildChainControl is responsible for creating or unlocking and then fully
851
// initializing a wallet and returning it as part of a fully populated chain
852
// control instance.
853
//
854
// NOTE: This is part of the ChainControlBuilder interface.
855
func (d *RPCSignerWalletImpl) BuildChainControl(
856
        partialChainControl *chainreg.PartialChainControl,
857
        walletConfig *btcwallet.Config) (*chainreg.ChainControl, func(), error) {
3✔
858

3✔
859
        walletController, err := btcwallet.New(
3✔
860
                *walletConfig, partialChainControl.Cfg.BlockCache,
3✔
861
        )
3✔
862
        if err != nil {
3✔
863
                err := fmt.Errorf("unable to create wallet controller: %w", err)
×
864
                d.logger.Error(err)
×
865
                return nil, nil, err
×
866
        }
×
867

868
        baseKeyRing := keychain.NewBtcWalletKeyRing(
3✔
869
                walletController.InternalWallet(), walletConfig.CoinType,
3✔
870
        )
3✔
871

3✔
872
        rpcKeyRing, err := rpcwallet.NewRPCKeyRing(
3✔
873
                baseKeyRing, walletController,
3✔
874
                d.DefaultWalletImpl.cfg.RemoteSigner, walletConfig.NetParams,
3✔
875
        )
3✔
876
        if err != nil {
3✔
877
                err := fmt.Errorf("unable to create RPC remote signing wallet "+
×
878
                        "%v", err)
×
879
                d.logger.Error(err)
×
880
                return nil, nil, err
×
881
        }
×
882

883
        // Create, and start the lnwallet, which handles the core payment
884
        // channel logic, and exposes control via proxy state machines.
885
        lnWalletConfig := lnwallet.Config{
3✔
886
                Database:              partialChainControl.Cfg.ChanStateDB,
3✔
887
                Notifier:              partialChainControl.ChainNotifier,
3✔
888
                WalletController:      rpcKeyRing,
3✔
889
                Signer:                rpcKeyRing,
3✔
890
                FeeEstimator:          partialChainControl.FeeEstimator,
3✔
891
                SecretKeyRing:         rpcKeyRing,
3✔
892
                ChainIO:               walletController,
3✔
893
                NetParams:             *walletConfig.NetParams,
3✔
894
                CoinSelectionStrategy: walletConfig.CoinSelectionStrategy,
3✔
895
        }
3✔
896

3✔
897
        // We've created the wallet configuration now, so we can finish
3✔
898
        // initializing the main chain control.
3✔
899
        activeChainControl, cleanUp, err := chainreg.NewChainControl(
3✔
900
                lnWalletConfig, rpcKeyRing, partialChainControl,
3✔
901
        )
3✔
902
        if err != nil {
3✔
903
                err := fmt.Errorf("unable to create chain control: %w", err)
×
904
                d.logger.Error(err)
×
905
                return nil, nil, err
×
906
        }
×
907

908
        return activeChainControl, cleanUp, nil
3✔
909
}
910

911
// DatabaseInstances is a struct that holds all instances to the actual
912
// databases that are used in lnd.
913
type DatabaseInstances struct {
914
        // GraphDB is the database that stores the channel graph used for path
915
        // finding.
916
        GraphDB *graphdb.ChannelGraph
917

918
        // ChanStateDB is the database that stores all of our node's channel
919
        // state.
920
        ChanStateDB *channeldb.DB
921

922
        // HeightHintDB is the database that stores height hints for spends.
923
        HeightHintDB kvdb.Backend
924

925
        // InvoiceDB is the database that stores information about invoices.
926
        InvoiceDB invoices.InvoiceDB
927

928
        // KVPaymentsDB is the database that stores all payment related
929
        // information.
930
        KVPaymentsDB *channeldb.KVPaymentsDB
931

932
        // MacaroonDB is the database that stores macaroon root keys.
933
        MacaroonDB kvdb.Backend
934

935
        // DecayedLogDB is the database that stores p2p related encryption
936
        // information.
937
        DecayedLogDB kvdb.Backend
938

939
        // TowerClientDB is the database that stores the watchtower client's
940
        // configuration.
941
        TowerClientDB wtclient.DB
942

943
        // TowerServerDB is the database that stores the watchtower server's
944
        // configuration.
945
        TowerServerDB watchtower.DB
946

947
        // WalletDB is the configuration for loading the wallet database using
948
        // the btcwallet's loader.
949
        WalletDB btcwallet.LoaderOption
950

951
        // NativeSQLStore holds a reference to the native SQL store that can
952
        // be used for native SQL queries for tables that already support it.
953
        // This may be nil if the use-native-sql flag was not set.
954
        NativeSQLStore sqldb.DB
955
}
956

957
// DefaultDatabaseBuilder is a type that builds the default database backends
958
// for lnd, using the given configuration to decide what actual implementation
959
// to use.
960
type DefaultDatabaseBuilder struct {
961
        cfg    *Config
962
        logger btclog.Logger
963
}
964

965
// NewDefaultDatabaseBuilder returns a new instance of the default database
966
// builder.
967
func NewDefaultDatabaseBuilder(cfg *Config,
968
        logger btclog.Logger) *DefaultDatabaseBuilder {
3✔
969

3✔
970
        return &DefaultDatabaseBuilder{
3✔
971
                cfg:    cfg,
3✔
972
                logger: logger,
3✔
973
        }
3✔
974
}
3✔
975

976
// BuildDatabase extracts the current databases that we'll use for normal
977
// operation in the daemon. A function closure that closes all opened databases
978
// is also returned.
979
func (d *DefaultDatabaseBuilder) BuildDatabase(
980
        ctx context.Context) (*DatabaseInstances, func(), error) {
3✔
981

3✔
982
        d.logger.Infof("Opening the main database, this might take a few " +
3✔
983
                "minutes...")
3✔
984

3✔
985
        cfg := d.cfg
3✔
986
        if cfg.DB.Backend == lncfg.BoltBackend {
6✔
987
                d.logger.Infof("Opening bbolt database, sync_freelist=%v, "+
3✔
988
                        "auto_compact=%v", !cfg.DB.Bolt.NoFreelistSync,
3✔
989
                        cfg.DB.Bolt.AutoCompact)
3✔
990
        }
3✔
991

992
        startOpenTime := time.Now()
3✔
993

3✔
994
        databaseBackends, err := cfg.DB.GetBackends(
3✔
995
                ctx, cfg.graphDatabaseDir(), cfg.networkDir, filepath.Join(
3✔
996
                        cfg.Watchtower.TowerDir, BitcoinChainName,
3✔
997
                        lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
998
                ), cfg.WtClient.Active, cfg.Watchtower.Active, d.logger,
3✔
999
        )
3✔
1000
        if err != nil {
3✔
1001
                return nil, nil, fmt.Errorf("unable to obtain database "+
×
1002
                        "backends: %v", err)
×
1003
        }
×
1004

1005
        // With the full remote mode we made sure both the graph and channel
1006
        // state DB point to the same local or remote DB and the same namespace
1007
        // within that DB.
1008
        dbs := &DatabaseInstances{
3✔
1009
                HeightHintDB:   databaseBackends.HeightHintDB,
3✔
1010
                MacaroonDB:     databaseBackends.MacaroonDB,
3✔
1011
                DecayedLogDB:   databaseBackends.DecayedLogDB,
3✔
1012
                WalletDB:       databaseBackends.WalletDB,
3✔
1013
                NativeSQLStore: databaseBackends.NativeSQLStore,
3✔
1014
        }
3✔
1015
        cleanUp := func() {
6✔
1016
                // We can just close the returned close functions directly. Even
3✔
1017
                // if we decorate the channel DB with an additional struct, its
3✔
1018
                // close function still just points to the kvdb backend.
3✔
1019
                for name, closeFunc := range databaseBackends.CloseFuncs {
6✔
1020
                        if err := closeFunc(); err != nil {
3✔
1021
                                d.logger.Errorf("Error closing %s "+
×
1022
                                        "database: %v", name, err)
×
1023
                        }
×
1024
                }
1025
        }
1026
        if databaseBackends.Remote {
3✔
1027
                d.logger.Infof("Using remote %v database! Creating "+
×
1028
                        "graph and channel state DB instances", cfg.DB.Backend)
×
1029
        } else {
3✔
1030
                d.logger.Infof("Creating local graph and channel state DB " +
3✔
1031
                        "instances")
3✔
1032
        }
3✔
1033

1034
        graphDBOptions := []graphdb.StoreOptionModifier{
3✔
1035
                graphdb.WithRejectCacheSize(cfg.Caches.RejectCacheSize),
3✔
1036
                graphdb.WithChannelCacheSize(cfg.Caches.ChannelCacheSize),
3✔
1037
                graphdb.WithBatchCommitInterval(cfg.DB.BatchCommitInterval),
3✔
1038
        }
3✔
1039

3✔
1040
        chanGraphOpts := []graphdb.ChanGraphOption{
3✔
1041
                graphdb.WithUseGraphCache(!cfg.DB.NoGraphCache),
3✔
1042
        }
3✔
1043

3✔
1044
        // We want to pre-allocate the channel graph cache according to what we
3✔
1045
        // expect for mainnet to speed up memory allocation.
3✔
1046
        if cfg.ActiveNetParams.Name == chaincfg.MainNetParams.Name {
3✔
1047
                chanGraphOpts = append(
×
1048
                        chanGraphOpts, graphdb.WithPreAllocCacheNumNodes(
×
1049
                                graphdb.DefaultPreAllocCacheNumNodes,
×
1050
                        ),
×
1051
                )
×
1052
        }
×
1053

1054
        dbOptions := []channeldb.OptionModifier{
3✔
1055
                channeldb.OptionDryRunMigration(cfg.DryRunMigration),
3✔
1056
                channeldb.OptionStoreFinalHtlcResolutions(
3✔
1057
                        cfg.StoreFinalHtlcResolutions,
3✔
1058
                ),
3✔
1059
                channeldb.OptionPruneRevocationLog(cfg.DB.PruneRevocation),
3✔
1060
                channeldb.OptionNoRevLogAmtData(cfg.DB.NoRevLogAmtData),
3✔
1061
                channeldb.OptionGcDecayedLog(cfg.DB.NoGcDecayedLog),
3✔
1062
                channeldb.OptionWithDecayedLogDB(dbs.DecayedLogDB),
3✔
1063
        }
3✔
1064

3✔
1065
        // Otherwise, we'll open two instances, one for the state we only need
3✔
1066
        // locally, and the other for things we want to ensure are replicated.
3✔
1067
        dbs.ChanStateDB, err = channeldb.CreateWithBackend(
3✔
1068
                databaseBackends.ChanStateDB, dbOptions...,
3✔
1069
        )
3✔
1070
        switch {
3✔
1071
        // Give the DB a chance to dry run the migration. Since we know that
1072
        // both the channel state and graph DBs are still always behind the same
1073
        // backend, we know this would be applied to both of those DBs.
1074
        case err == channeldb.ErrDryRunMigrationOK:
×
1075
                d.logger.Infof("Channel DB dry run migration successful")
×
1076
                return nil, nil, err
×
1077

1078
        case err != nil:
×
1079
                cleanUp()
×
1080

×
1081
                err = fmt.Errorf("unable to open graph DB: %w", err)
×
1082
                d.logger.Error(err)
×
1083
                return nil, nil, err
×
1084
        }
1085

1086
        // The graph store implementation we will use depends on whether
1087
        // native SQL is enabled or not.
1088
        var graphStore graphdb.V1Store
3✔
1089

3✔
1090
        // Instantiate a native SQL store if the flag is set.
3✔
1091
        if d.cfg.DB.UseNativeSQL {
3✔
1092
                migrations := sqldb.GetMigrations()
×
1093

×
1094
                // If the user has not explicitly disabled the SQL invoice
×
1095
                // migration, attach the custom migration function to invoice
×
1096
                // migration (version 7). Even if this custom migration is
×
1097
                // disabled, the regular native SQL store migrations will still
×
1098
                // run. If the database version is already above this custom
×
1099
                // migration's version (7), it will be skipped permanently,
×
1100
                // regardless of the flag.
×
1101
                if !d.cfg.DB.SkipNativeSQLMigration {
×
1102
                        invoiceMig := func(tx *sqlc.Queries) error {
×
1103
                                err := invoices.MigrateInvoicesToSQL(
×
1104
                                        ctx, dbs.ChanStateDB.Backend,
×
1105
                                        dbs.ChanStateDB, tx,
×
1106
                                        invoiceMigrationBatchSize,
×
1107
                                )
×
1108
                                if err != nil {
×
1109
                                        return fmt.Errorf("failed to migrate "+
×
1110
                                                "invoices to SQL: %w", err)
×
1111
                                }
×
1112

1113
                                // Set the invoice bucket tombstone to indicate
1114
                                // that the migration has been completed.
1115
                                d.logger.Debugf("Setting invoice bucket " +
×
1116
                                        "tombstone")
×
1117

×
1118
                                return dbs.ChanStateDB.SetInvoiceBucketTombstone() //nolint:ll
×
1119
                        }
1120

1121
                        // Make sure we attach the custom migration function to
1122
                        // the correct migration version.
1123
                        for i := 0; i < len(migrations); i++ {
×
1124
                                version := migrations[i].Version
×
1125
                                if version == invoiceMigration {
×
1126
                                        migrations[i].MigrationFn = invoiceMig
×
1127

×
1128
                                        continue
×
1129
                                }
1130

1131
                                migFn, ok := d.getSQLMigration(
×
1132
                                        ctx, version, dbs.ChanStateDB.Backend,
×
NEW
1133
                                )
×
1134
                                if !ok {
×
1135
                                        continue
×
1136
                                }
1137

1138
                                migrations[i].MigrationFn = migFn
×
1139
                        }
1140
                }
1141

1142
                // We need to apply all migrations to the native SQL store
1143
                // before we can use it.
1144
                err = dbs.NativeSQLStore.ApplyAllMigrations(ctx, migrations)
×
1145
                if err != nil {
×
1146
                        cleanUp()
×
1147
                        err = fmt.Errorf("faild to run migrations for the "+
×
1148
                                "native SQL store: %w", err)
×
1149
                        d.logger.Error(err)
×
1150

×
1151
                        return nil, nil, err
×
1152
                }
×
1153

1154
                // With the DB ready and migrations applied, we can now create
1155
                // the base DB and transaction executor for the native SQL
1156
                // invoice store.
1157
                baseDB := dbs.NativeSQLStore.GetBaseDB()
×
1158
                invoiceExecutor := sqldb.NewTransactionExecutor(
×
1159
                        baseDB, func(tx *sql.Tx) invoices.SQLInvoiceQueries {
×
1160
                                return baseDB.WithTx(tx)
×
1161
                        },
×
1162
                )
1163

1164
                sqlInvoiceDB := invoices.NewSQLStore(
×
1165
                        invoiceExecutor, clock.NewDefaultClock(),
×
1166
                )
×
1167

×
1168
                dbs.InvoiceDB = sqlInvoiceDB
×
1169

×
1170
                graphStore, err = d.getGraphStore(
×
1171
                        baseDB, databaseBackends.GraphDB, graphDBOptions...,
×
1172
                )
×
1173
                if err != nil {
×
1174
                        err = fmt.Errorf("unable to get graph store: %w", err)
×
1175
                        d.logger.Error(err)
×
1176

×
1177
                        return nil, nil, err
×
1178
                }
×
1179
        } else {
3✔
1180
                // Check if the invoice bucket tombstone is set. If it is, we
3✔
1181
                // need to return and ask the user switch back to using the
3✔
1182
                // native SQL store.
3✔
1183
                ripInvoices, err := dbs.ChanStateDB.GetInvoiceBucketTombstone()
3✔
1184
                if err != nil {
3✔
1185
                        err = fmt.Errorf("unable to check invoice bucket "+
×
1186
                                "tombstone: %w", err)
×
1187
                        d.logger.Error(err)
×
1188

×
1189
                        return nil, nil, err
×
1190
                }
×
1191
                if ripInvoices {
3✔
1192
                        err = fmt.Errorf("invoices bucket tombstoned, please " +
×
1193
                                "switch back to native SQL")
×
1194
                        d.logger.Error(err)
×
1195

×
1196
                        return nil, nil, err
×
1197
                }
×
1198

1199
                dbs.InvoiceDB = dbs.ChanStateDB
3✔
1200

3✔
1201
                graphStore, err = graphdb.NewKVStore(
3✔
1202
                        databaseBackends.GraphDB, graphDBOptions...,
3✔
1203
                )
3✔
1204
                if err != nil {
3✔
1205
                        return nil, nil, err
×
1206
                }
×
1207
        }
1208

1209
        dbs.GraphDB, err = graphdb.NewChannelGraph(graphStore, chanGraphOpts...)
3✔
1210
        if err != nil {
3✔
1211
                cleanUp()
×
1212

×
1213
                err = fmt.Errorf("unable to open channel graph DB: %w", err)
×
1214
                d.logger.Error(err)
×
1215

×
1216
                return nil, nil, err
×
1217
        }
×
1218

1219
        // Mount the payments DB which is only KV for now.
1220
        //
1221
        // TODO(ziggie): Add support for SQL payments DB.
1222
        // Mount the payments DB for the KV store.
1223
        paymentsDBOptions := []paymentsdb.OptionModifier{
3✔
1224
                paymentsdb.WithKeepFailedPaymentAttempts(
3✔
1225
                        cfg.KeepFailedPaymentAttempts,
3✔
1226
                ),
3✔
1227
        }
3✔
1228
        kvPaymentsDB, err := channeldb.NewKVPaymentsDB(
3✔
1229
                dbs.ChanStateDB,
3✔
1230
                paymentsDBOptions...,
3✔
1231
        )
3✔
1232
        if err != nil {
3✔
1233
                cleanUp()
×
1234

×
1235
                err = fmt.Errorf("unable to open payments DB: %w", err)
×
1236
                d.logger.Error(err)
×
1237

×
1238
                return nil, nil, err
×
1239
        }
×
1240
        dbs.KVPaymentsDB = kvPaymentsDB
3✔
1241

3✔
1242
        // Wrap the watchtower client DB and make sure we clean up.
3✔
1243
        if cfg.WtClient.Active {
6✔
1244
                dbs.TowerClientDB, err = wtdb.OpenClientDB(
3✔
1245
                        databaseBackends.TowerClientDB,
3✔
1246
                )
3✔
1247
                if err != nil {
3✔
1248
                        cleanUp()
×
1249

×
1250
                        err = fmt.Errorf("unable to open %s database: %w",
×
1251
                                lncfg.NSTowerClientDB, err)
×
1252
                        d.logger.Error(err)
×
1253
                        return nil, nil, err
×
1254
                }
×
1255
        }
1256

1257
        // Wrap the watchtower server DB and make sure we clean up.
1258
        if cfg.Watchtower.Active {
6✔
1259
                dbs.TowerServerDB, err = wtdb.OpenTowerDB(
3✔
1260
                        databaseBackends.TowerServerDB,
3✔
1261
                )
3✔
1262
                if err != nil {
3✔
1263
                        cleanUp()
×
1264

×
1265
                        err = fmt.Errorf("unable to open %s database: %w",
×
1266
                                lncfg.NSTowerServerDB, err)
×
1267
                        d.logger.Error(err)
×
1268
                        return nil, nil, err
×
1269
                }
×
1270
        }
1271

1272
        openTime := time.Since(startOpenTime)
3✔
1273
        d.logger.Infof("Database(s) now open (time_to_open=%v)!", openTime)
3✔
1274

3✔
1275
        return dbs, cleanUp, nil
3✔
1276
}
1277

1278
// waitForWalletPassword blocks until a password is provided by the user to
1279
// this RPC server.
1280
func waitForWalletPassword(cfg *Config,
1281
        pwService *walletunlocker.UnlockerService,
1282
        loaderOpts []btcwallet.LoaderOption, shutdownChan <-chan struct{}) (
1283
        *walletunlocker.WalletUnlockParams, error) {
3✔
1284

3✔
1285
        // Wait for user to provide the password.
3✔
1286
        ltndLog.Infof("Waiting for wallet encryption password. Use `lncli " +
3✔
1287
                "create` to create a wallet, `lncli unlock` to unlock an " +
3✔
1288
                "existing wallet, or `lncli changepassword` to change the " +
3✔
1289
                "password of an existing wallet and unlock it.")
3✔
1290

3✔
1291
        // We currently don't distinguish between getting a password to be used
3✔
1292
        // for creation or unlocking, as a new wallet db will be created if
3✔
1293
        // none exists when creating the chain control.
3✔
1294
        select {
3✔
1295
        // The wallet is being created for the first time, we'll check to see
1296
        // if the user provided any entropy for seed creation. If so, then
1297
        // we'll create the wallet early to load the seed.
1298
        case initMsg := <-pwService.InitMsgs:
3✔
1299
                password := initMsg.Passphrase
3✔
1300
                cipherSeed := initMsg.WalletSeed
3✔
1301
                extendedKey := initMsg.WalletExtendedKey
3✔
1302
                watchOnlyAccounts := initMsg.WatchOnlyAccounts
3✔
1303
                recoveryWindow := initMsg.RecoveryWindow
3✔
1304

3✔
1305
                // Before we proceed, we'll check the internal version of the
3✔
1306
                // seed. If it's greater than the current key derivation
3✔
1307
                // version, then we'll return an error as we don't understand
3✔
1308
                // this.
3✔
1309
                if cipherSeed != nil &&
3✔
1310
                        !keychain.IsKnownVersion(cipherSeed.InternalVersion) {
3✔
1311

×
1312
                        return nil, fmt.Errorf("invalid internal "+
×
1313
                                "seed version %v, current max version is %v",
×
1314
                                cipherSeed.InternalVersion,
×
1315
                                keychain.CurrentKeyDerivationVersion)
×
1316
                }
×
1317

1318
                loader, err := btcwallet.NewWalletLoader(
3✔
1319
                        cfg.ActiveNetParams.Params, recoveryWindow,
3✔
1320
                        loaderOpts...,
3✔
1321
                )
3✔
1322
                if err != nil {
3✔
1323
                        return nil, err
×
1324
                }
×
1325

1326
                // With the seed, we can now use the wallet loader to create
1327
                // the wallet, then pass it back to avoid unlocking it again.
1328
                var (
3✔
1329
                        birthday  time.Time
3✔
1330
                        newWallet *wallet.Wallet
3✔
1331
                )
3✔
1332
                switch {
3✔
1333
                // A normal cipher seed was given, use the birthday encoded in
1334
                // it and create the wallet from that.
1335
                case cipherSeed != nil:
3✔
1336
                        birthday = cipherSeed.BirthdayTime()
3✔
1337
                        newWallet, err = loader.CreateNewWallet(
3✔
1338
                                password, password, cipherSeed.Entropy[:],
3✔
1339
                                birthday,
3✔
1340
                        )
3✔
1341

1342
                // No seed was given, we're importing a wallet from its extended
1343
                // private key.
1344
                case extendedKey != nil:
3✔
1345
                        birthday = initMsg.ExtendedKeyBirthday
3✔
1346
                        newWallet, err = loader.CreateNewWalletExtendedKey(
3✔
1347
                                password, password, extendedKey, birthday,
3✔
1348
                        )
3✔
1349

1350
                // Neither seed nor extended private key was given, so maybe the
1351
                // third option was chosen, the watch-only initialization. In
1352
                // this case we need to import each of the xpubs individually.
1353
                case watchOnlyAccounts != nil:
3✔
1354
                        if !cfg.RemoteSigner.Enable {
3✔
1355
                                return nil, fmt.Errorf("cannot initialize " +
×
1356
                                        "watch only wallet with remote " +
×
1357
                                        "signer config disabled")
×
1358
                        }
×
1359

1360
                        birthday = initMsg.WatchOnlyBirthday
3✔
1361
                        newWallet, err = loader.CreateNewWatchingOnlyWallet(
3✔
1362
                                password, birthday,
3✔
1363
                        )
3✔
1364
                        if err != nil {
3✔
1365
                                break
×
1366
                        }
1367

1368
                        err = importWatchOnlyAccounts(newWallet, initMsg)
3✔
1369

1370
                default:
×
1371
                        // The unlocker service made sure either the cipher seed
×
1372
                        // or the extended key is set so, we shouldn't get here.
×
1373
                        // The default case is just here for readability and
×
1374
                        // completeness.
×
1375
                        err = fmt.Errorf("cannot create wallet, neither seed " +
×
1376
                                "nor extended key was given")
×
1377
                }
1378
                if err != nil {
3✔
1379
                        // Don't leave the file open in case the new wallet
×
1380
                        // could not be created for whatever reason.
×
1381
                        if err := loader.UnloadWallet(); err != nil {
×
1382
                                ltndLog.Errorf("Could not unload new "+
×
1383
                                        "wallet: %v", err)
×
1384
                        }
×
1385
                        return nil, err
×
1386
                }
1387

1388
                // For new wallets, the ResetWalletTransactions flag is a no-op.
1389
                if cfg.ResetWalletTransactions {
6✔
1390
                        ltndLog.Warnf("Ignoring reset-wallet-transactions " +
3✔
1391
                                "flag for new wallet as it has no effect")
3✔
1392
                }
3✔
1393

1394
                return &walletunlocker.WalletUnlockParams{
3✔
1395
                        Password:        password,
3✔
1396
                        Birthday:        birthday,
3✔
1397
                        RecoveryWindow:  recoveryWindow,
3✔
1398
                        Wallet:          newWallet,
3✔
1399
                        ChansToRestore:  initMsg.ChanBackups,
3✔
1400
                        UnloadWallet:    loader.UnloadWallet,
3✔
1401
                        StatelessInit:   initMsg.StatelessInit,
3✔
1402
                        MacResponseChan: pwService.MacResponseChan,
3✔
1403
                        MacRootKey:      initMsg.MacRootKey,
3✔
1404
                }, nil
3✔
1405

1406
        // The wallet has already been created in the past, and is simply being
1407
        // unlocked. So we'll just return these passphrases.
1408
        case unlockMsg := <-pwService.UnlockMsgs:
3✔
1409
                // Resetting the transactions is something the user likely only
3✔
1410
                // wants to do once so we add a prominent warning to the log to
3✔
1411
                // remind the user to turn off the setting again after
3✔
1412
                // successful completion.
3✔
1413
                if cfg.ResetWalletTransactions {
6✔
1414
                        ltndLog.Warnf("Dropped all transaction history from " +
3✔
1415
                                "on-chain wallet. Remember to disable " +
3✔
1416
                                "reset-wallet-transactions flag for next " +
3✔
1417
                                "start of lnd")
3✔
1418
                }
3✔
1419

1420
                return &walletunlocker.WalletUnlockParams{
3✔
1421
                        Password:        unlockMsg.Passphrase,
3✔
1422
                        RecoveryWindow:  unlockMsg.RecoveryWindow,
3✔
1423
                        Wallet:          unlockMsg.Wallet,
3✔
1424
                        ChansToRestore:  unlockMsg.ChanBackups,
3✔
1425
                        UnloadWallet:    unlockMsg.UnloadWallet,
3✔
1426
                        StatelessInit:   unlockMsg.StatelessInit,
3✔
1427
                        MacResponseChan: pwService.MacResponseChan,
3✔
1428
                }, nil
3✔
1429

1430
        // If we got a shutdown signal we just return with an error immediately
1431
        case <-shutdownChan:
×
1432
                return nil, fmt.Errorf("shutting down")
×
1433
        }
1434
}
1435

1436
// importWatchOnlyAccounts imports all individual account xpubs into our wallet
1437
// which we created as watch-only.
1438
func importWatchOnlyAccounts(wallet *wallet.Wallet,
1439
        initMsg *walletunlocker.WalletInitMsg) error {
3✔
1440

3✔
1441
        scopes := make([]waddrmgr.ScopedIndex, 0, len(initMsg.WatchOnlyAccounts))
3✔
1442
        for scope := range initMsg.WatchOnlyAccounts {
6✔
1443
                scopes = append(scopes, scope)
3✔
1444
        }
3✔
1445

1446
        // We need to import the accounts in the correct order, otherwise the
1447
        // indices will be incorrect.
1448
        sort.Slice(scopes, func(i, j int) bool {
6✔
1449
                return scopes[i].Scope.Purpose < scopes[j].Scope.Purpose ||
3✔
1450
                        scopes[i].Index < scopes[j].Index
3✔
1451
        })
3✔
1452

1453
        for _, scope := range scopes {
6✔
1454
                addrSchema := waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0084]
3✔
1455

3✔
1456
                // We want witness pubkey hash by default, except for BIP49
3✔
1457
                // where we want mixed and BIP86 where we want taproot address
3✔
1458
                // formats.
3✔
1459
                switch scope.Scope.Purpose {
3✔
1460
                case waddrmgr.KeyScopeBIP0049Plus.Purpose,
1461
                        waddrmgr.KeyScopeBIP0086.Purpose:
3✔
1462

3✔
1463
                        addrSchema = waddrmgr.ScopeAddrMap[scope.Scope]
3✔
1464
                }
1465

1466
                // We want a human-readable account name. But for the default
1467
                // on-chain wallet we actually need to call it "default" to make
1468
                // sure everything works correctly.
1469
                name := fmt.Sprintf("%s/%d'", scope.Scope.String(), scope.Index)
3✔
1470
                if scope.Index == 0 {
6✔
1471
                        name = "default"
3✔
1472
                }
3✔
1473

1474
                _, err := wallet.ImportAccountWithScope(
3✔
1475
                        name, initMsg.WatchOnlyAccounts[scope],
3✔
1476
                        initMsg.WatchOnlyMasterFingerprint, scope.Scope,
3✔
1477
                        addrSchema,
3✔
1478
                )
3✔
1479
                if err != nil {
3✔
1480
                        return fmt.Errorf("could not import account %v: %w",
×
1481
                                name, err)
×
1482
                }
×
1483
        }
1484

1485
        return nil
3✔
1486
}
1487

1488
// handleNeutrinoPostgresDBMigration handles the migration of the neutrino db
1489
// to postgres. Initially we kept the neutrino db in the bolt db when running
1490
// with kvdb postgres backend. Now now move it to postgres as well. However we
1491
// need to make a distinction whether the user migrated the neutrino db to
1492
// postgres via lndinit or not. Currently if the db is not migrated we start
1493
// with a fresh db in postgres.
1494
//
1495
// TODO(ziggie): Also migrate the db to postgres in case it is still not
1496
// migrated ?
1497
func handleNeutrinoPostgresDBMigration(dbName, dbPath string,
1498
        cfg *Config) error {
×
1499

×
1500
        if !lnrpc.FileExists(dbName) {
×
1501
                return nil
×
1502
        }
×
1503

1504
        // Open bolt db to check if it is tombstoned. If it is we assume that
1505
        // the neutrino db was successfully migrated to postgres. We open it
1506
        // in read-only mode to avoid long db open times.
1507
        boltDB, err := kvdb.Open(
×
1508
                kvdb.BoltBackendName, dbName, true,
×
1509
                cfg.DB.Bolt.DBTimeout, true,
×
1510
        )
×
1511
        if err != nil {
×
1512
                return fmt.Errorf("failed to open bolt db: %w", err)
×
1513
        }
×
1514
        defer boltDB.Close()
×
1515

×
1516
        isTombstoned := false
×
1517
        err = boltDB.View(func(tx kvdb.RTx) error {
×
1518
                _, err = channeldb.CheckMarkerPresent(
×
1519
                        tx, channeldb.TombstoneKey,
×
1520
                )
×
1521

×
1522
                return err
×
1523
        }, func() {})
×
1524
        if err == nil {
×
1525
                isTombstoned = true
×
1526
        }
×
1527

1528
        if isTombstoned {
×
1529
                ltndLog.Infof("Neutrino Bolt DB is tombstoned, assuming " +
×
1530
                        "database was successfully migrated to postgres")
×
1531

×
1532
                return nil
×
1533
        }
×
1534

1535
        // If the db is not tombstoned, we remove the files and start fresh with
1536
        // postgres. This is the case when a user was running lnd with the
1537
        // postgres backend from the beginning without migrating from bolt.
1538
        ltndLog.Infof("Neutrino Bolt DB found but NOT tombstoned, removing " +
×
1539
                "it and starting fresh with postgres")
×
1540

×
1541
        filesToRemove := []string{
×
1542
                filepath.Join(dbPath, "block_headers.bin"),
×
1543
                filepath.Join(dbPath, "reg_filter_headers.bin"),
×
1544
                dbName,
×
1545
        }
×
1546

×
1547
        for _, file := range filesToRemove {
×
1548
                if err := os.Remove(file); err != nil {
×
1549
                        ltndLog.Warnf("Could not remove %s: %v", file, err)
×
1550
                }
×
1551
        }
1552

1553
        return nil
×
1554
}
1555

1556
// initNeutrinoBackend inits a new instance of the neutrino light client
1557
// backend given a target chain directory to store the chain state.
1558
func initNeutrinoBackend(ctx context.Context, cfg *Config, chainDir string,
1559
        blockCache *blockcache.BlockCache) (*neutrino.ChainService,
1560
        func(), error) {
1✔
1561

1✔
1562
        // Both channel validation flags are false by default but their meaning
1✔
1563
        // is the inverse of each other. Therefore both cannot be true. For
1✔
1564
        // every other case, the neutrino.validatechannels overwrites the
1✔
1565
        // routing.assumechanvalid value.
1✔
1566
        if cfg.NeutrinoMode.ValidateChannels && cfg.Routing.AssumeChannelValid {
1✔
1567
                return nil, nil, fmt.Errorf("can't set both " +
×
1568
                        "neutrino.validatechannels and routing." +
×
1569
                        "assumechanvalid to true at the same time")
×
1570
        }
×
1571
        cfg.Routing.AssumeChannelValid = !cfg.NeutrinoMode.ValidateChannels
1✔
1572

1✔
1573
        // First we'll open the database file for neutrino, creating the
1✔
1574
        // database if needed. We append the normalized network name here to
1✔
1575
        // match the behavior of btcwallet.
1✔
1576
        dbPath := filepath.Join(
1✔
1577
                chainDir, lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
1✔
1578
        )
1✔
1579

1✔
1580
        // Ensure that the neutrino db path exists.
1✔
1581
        if err := os.MkdirAll(dbPath, 0700); err != nil {
1✔
1582
                return nil, nil, err
×
1583
        }
×
1584

1585
        var (
1✔
1586
                db  walletdb.DB
1✔
1587
                err error
1✔
1588
        )
1✔
1589
        switch {
1✔
1590
        case cfg.DB.Backend == kvdb.SqliteBackendName:
×
1591
                sqliteConfig := lncfg.GetSqliteConfigKVDB(cfg.DB.Sqlite)
×
1592
                db, err = kvdb.Open(
×
1593
                        kvdb.SqliteBackendName, ctx, sqliteConfig, dbPath,
×
1594
                        lncfg.SqliteNeutrinoDBName, lncfg.NSNeutrinoDB,
×
1595
                )
×
1596

1597
        case cfg.DB.Backend == kvdb.PostgresBackendName:
×
1598
                dbName := filepath.Join(dbPath, lncfg.NeutrinoDBName)
×
1599

×
1600
                // This code needs to be in place because we did not start
×
1601
                // the postgres backend for neutrino at the beginning. Now we
×
1602
                // are also moving it into the postgres backend so we can phase
×
1603
                // out the bolt backend.
×
1604
                err = handleNeutrinoPostgresDBMigration(dbName, dbPath, cfg)
×
1605
                if err != nil {
×
1606
                        return nil, nil, err
×
1607
                }
×
1608

1609
                postgresConfig := lncfg.GetPostgresConfigKVDB(cfg.DB.Postgres)
×
1610
                db, err = kvdb.Open(
×
1611
                        kvdb.PostgresBackendName, ctx, postgresConfig,
×
1612
                        lncfg.NSNeutrinoDB,
×
1613
                )
×
1614

1615
        default:
1✔
1616
                dbName := filepath.Join(dbPath, lncfg.NeutrinoDBName)
1✔
1617
                db, err = walletdb.Create(
1✔
1618
                        kvdb.BoltBackendName, dbName, !cfg.SyncFreelist,
1✔
1619
                        cfg.DB.Bolt.DBTimeout, false,
1✔
1620
                )
1✔
1621
        }
1622
        if err != nil {
1✔
1623
                return nil, nil, fmt.Errorf("unable to create "+
×
1624
                        "neutrino database: %v", err)
×
1625
        }
×
1626

1627
        headerStateAssertion, err := parseHeaderStateAssertion(
1✔
1628
                cfg.NeutrinoMode.AssertFilterHeader,
1✔
1629
        )
1✔
1630
        if err != nil {
1✔
1631
                db.Close()
×
1632
                return nil, nil, err
×
1633
        }
×
1634

1635
        // With the database open, we can now create an instance of the
1636
        // neutrino light client. We pass in relevant configuration parameters
1637
        // required.
1638
        config := neutrino.Config{
1✔
1639
                DataDir:      dbPath,
1✔
1640
                Database:     db,
1✔
1641
                ChainParams:  *cfg.ActiveNetParams.Params,
1✔
1642
                AddPeers:     cfg.NeutrinoMode.AddPeers,
1✔
1643
                ConnectPeers: cfg.NeutrinoMode.ConnectPeers,
1✔
1644
                Dialer: func(addr net.Addr) (net.Conn, error) {
2✔
1645
                        return cfg.net.Dial(
1✔
1646
                                addr.Network(), addr.String(),
1✔
1647
                                cfg.ConnectionTimeout,
1✔
1648
                        )
1✔
1649
                },
1✔
1650
                NameResolver: func(host string) ([]net.IP, error) {
1✔
1651
                        addrs, err := cfg.net.LookupHost(host)
1✔
1652
                        if err != nil {
1✔
1653
                                return nil, err
×
1654
                        }
×
1655

1656
                        ips := make([]net.IP, 0, len(addrs))
1✔
1657
                        for _, strIP := range addrs {
2✔
1658
                                ip := net.ParseIP(strIP)
1✔
1659
                                if ip == nil {
1✔
1660
                                        continue
×
1661
                                }
1662

1663
                                ips = append(ips, ip)
1✔
1664
                        }
1665

1666
                        return ips, nil
1✔
1667
                },
1668
                AssertFilterHeader: headerStateAssertion,
1669
                BlockCache:         blockCache.Cache,
1670
                BroadcastTimeout:   cfg.NeutrinoMode.BroadcastTimeout,
1671
                PersistToDisk:      cfg.NeutrinoMode.PersistFilters,
1672
        }
1673

1674
        if cfg.NeutrinoMode.MaxPeers <= 0 {
1✔
1675
                return nil, nil, fmt.Errorf("a non-zero number must be set " +
×
1676
                        "for neutrino max peers")
×
1677
        }
×
1678
        neutrino.MaxPeers = cfg.NeutrinoMode.MaxPeers
1✔
1679
        neutrino.BanDuration = time.Hour * 48
1✔
1680
        neutrino.UserAgentName = cfg.NeutrinoMode.UserAgentName
1✔
1681
        neutrino.UserAgentVersion = cfg.NeutrinoMode.UserAgentVersion
1✔
1682

1✔
1683
        neutrinoCS, err := neutrino.NewChainService(config)
1✔
1684
        if err != nil {
1✔
1685
                db.Close()
×
1686
                return nil, nil, fmt.Errorf("unable to create neutrino light "+
×
1687
                        "client: %v", err)
×
1688
        }
×
1689

1690
        if err := neutrinoCS.Start(); err != nil {
1✔
1691
                db.Close()
×
1692
                return nil, nil, err
×
1693
        }
×
1694

1695
        cleanUp := func() {
2✔
1696
                if err := neutrinoCS.Stop(); err != nil {
1✔
1697
                        ltndLog.Infof("Unable to stop neutrino light client: "+
×
1698
                                "%v", err)
×
1699
                }
×
1700
                db.Close()
1✔
1701
        }
1702

1703
        return neutrinoCS, cleanUp, nil
1✔
1704
}
1705

1706
// parseHeaderStateAssertion parses the user-specified neutrino header state
1707
// into a headerfs.FilterHeader.
1708
func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) {
1✔
1709
        if len(state) == 0 {
2✔
1710
                return nil, nil
1✔
1711
        }
1✔
1712

1713
        split := strings.Split(state, ":")
×
1714
        if len(split) != 2 {
×
1715
                return nil, fmt.Errorf("header state assertion %v in "+
×
1716
                        "unexpected format, expected format height:hash", state)
×
1717
        }
×
1718

1719
        height, err := strconv.ParseUint(split[0], 10, 32)
×
1720
        if err != nil {
×
1721
                return nil, fmt.Errorf("invalid filter header height: %w", err)
×
1722
        }
×
1723

1724
        hash, err := chainhash.NewHashFromStr(split[1])
×
1725
        if err != nil {
×
1726
                return nil, fmt.Errorf("invalid filter header hash: %w", err)
×
1727
        }
×
1728

1729
        return &headerfs.FilterHeader{
×
1730
                Height:     uint32(height),
×
1731
                FilterHash: *hash,
×
1732
        }, nil
×
1733
}
1734

1735
// broadcastErrorMapper maps errors from bitcoin backends other than neutrino to
1736
// the neutrino BroadcastError which allows the Rebroadcaster which currently
1737
// resides in the neutrino package to use all of its functionalities.
1738
func broadcastErrorMapper(err error) error {
2✔
1739
        var returnErr error
2✔
1740

2✔
1741
        // We only filter for specific backend errors which are relevant for the
2✔
1742
        // Rebroadcaster.
2✔
1743
        switch {
2✔
1744
        // This makes sure the tx is removed from the rebroadcaster once it is
1745
        // confirmed.
1746
        case errors.Is(err, chain.ErrTxAlreadyKnown),
1747
                errors.Is(err, chain.ErrTxAlreadyConfirmed):
1✔
1748

1✔
1749
                returnErr = &pushtx.BroadcastError{
1✔
1750
                        Code:   pushtx.Confirmed,
1✔
1751
                        Reason: err.Error(),
1✔
1752
                }
1✔
1753

1754
        // Transactions which are still in mempool but might fall out because
1755
        // of low fees are rebroadcasted despite of their backend error.
1756
        case errors.Is(err, chain.ErrTxAlreadyInMempool):
×
1757
                returnErr = &pushtx.BroadcastError{
×
1758
                        Code:   pushtx.Mempool,
×
1759
                        Reason: err.Error(),
×
1760
                }
×
1761

1762
        // Transactions which are not accepted into mempool because of low fees
1763
        // in the first place are rebroadcasted despite of their backend error.
1764
        // Mempool conditions change over time so it makes sense to retry
1765
        // publishing the transaction. Moreover we log the detailed error so the
1766
        // user can intervene and increase the size of his mempool.
1767
        case errors.Is(err, chain.ErrMempoolMinFeeNotMet):
×
1768
                ltndLog.Warnf("Error while broadcasting transaction: %v", err)
×
1769

×
1770
                returnErr = &pushtx.BroadcastError{
×
1771
                        Code:   pushtx.Mempool,
×
1772
                        Reason: err.Error(),
×
1773
                }
×
1774
        }
1775

1776
        return returnErr
2✔
1777
}
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