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

lightningnetwork / lnd / 19616403112

23 Nov 2025 07:49PM UTC coverage: 65.173% (-0.06%) from 65.229%
19616403112

Pull #10390

github

web-flow
Merge bf85a3dc9 into 8c8662c86
Pull Request #10390: Defer Channel Cleanup after a channel is closed to avoid kv-sql stress

53 of 206 new or added lines in 4 files covered. (25.73%)

127 existing lines in 27 files now uncovered.

137610 of 211145 relevant lines covered (65.17%)

20759.97 hits per line

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

58.98
/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
        graphdbmig1 "github.com/lightningnetwork/lnd/graph/db/migration1"
40
        graphmig1sqlc "github.com/lightningnetwork/lnd/graph/db/migration1/sqlc"
41
        "github.com/lightningnetwork/lnd/htlcswitch"
42
        "github.com/lightningnetwork/lnd/invoices"
43
        "github.com/lightningnetwork/lnd/keychain"
44
        "github.com/lightningnetwork/lnd/kvdb"
45
        "github.com/lightningnetwork/lnd/lncfg"
46
        "github.com/lightningnetwork/lnd/lnrpc"
47
        "github.com/lightningnetwork/lnd/lnwallet"
48
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
49
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
50
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
51
        "github.com/lightningnetwork/lnd/macaroons"
52
        "github.com/lightningnetwork/lnd/msgmux"
53
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
54
        "github.com/lightningnetwork/lnd/rpcperms"
55
        "github.com/lightningnetwork/lnd/signal"
56
        "github.com/lightningnetwork/lnd/sqldb"
57
        "github.com/lightningnetwork/lnd/sqldb/sqlc"
58
        "github.com/lightningnetwork/lnd/sweep"
59
        "github.com/lightningnetwork/lnd/walletunlocker"
60
        "github.com/lightningnetwork/lnd/watchtower"
61
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
62
        "github.com/lightningnetwork/lnd/watchtower/wtdb"
63
        "google.golang.org/grpc"
64
        "gopkg.in/macaroon-bakery.v2/bakery"
65
)
66

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

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

76
        // graphMigration is the version number for the graph migration
77
        // that migrates the KV graph to the native SQL schema.
78
        graphMigration = 10
79
)
80

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

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

104
// ExternalValidator is an interface that must be satisfied by an external
105
// macaroon validator.
106
type ExternalValidator interface {
107
        macaroons.MacaroonValidator
108

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

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

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

137
// ChainControlBuilder is an interface that must be satisfied by a custom wallet
138
// implementation.
139
type ChainControlBuilder interface {
140
        // BuildChainControl is responsible for creating a fully populated chain
141
        // control instance from a wallet.
142
        BuildChainControl(*chainreg.PartialChainControl,
143
                *btcwallet.Config) (*chainreg.ChainControl, func(), error)
144
}
145

146
// ImplementationCfg is a struct that holds all configuration items for
147
// components that can be implemented outside lnd itself.
148
type ImplementationCfg struct {
149
        // GrpcRegistrar is a type that can register additional gRPC subservers
150
        // before the main gRPC server is started.
151
        GrpcRegistrar
152

153
        // RestRegistrar is a type that can register additional REST subservers
154
        // before the main REST proxy is started.
155
        RestRegistrar
156

157
        // ExternalValidator is a type that can provide external macaroon
158
        // validation.
159
        ExternalValidator
160

161
        // DatabaseBuilder is a type that can provide lnd's main database
162
        // backend instances.
163
        DatabaseBuilder
164

165
        // WalletConfigBuilder is a type that can provide a wallet configuration
166
        // with a fully loaded and unlocked wallet.
167
        WalletConfigBuilder
168

169
        // ChainControlBuilder is a type that can provide a custom wallet
170
        // implementation.
171
        ChainControlBuilder
172

173
        // AuxComponents is a set of auxiliary components that can be used by
174
        // lnd for certain custom channel types.
175
        AuxComponents
176
}
177

178
// AuxComponents is a set of auxiliary components that can be used by lnd for
179
// certain custom channel types.
180
type AuxComponents struct {
181
        // AuxLeafStore is an optional data source that can be used by custom
182
        // channels to fetch+store various data.
183
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
184

185
        // TrafficShaper is an optional traffic shaper that can be used to
186
        // control the outgoing channel of a payment.
187
        TrafficShaper fn.Option[htlcswitch.AuxTrafficShaper]
188

189
        // MsgRouter is an optional message router that if set will be used in
190
        // place of a new blank default message router.
191
        MsgRouter fn.Option[msgmux.Router]
192

193
        // AuxFundingController is an optional controller that can be used to
194
        // modify the way we handle certain custom channel types. It's also
195
        // able to automatically handle new custom protocol messages related to
196
        // the funding process.
197
        AuxFundingController fn.Option[funding.AuxFundingController]
198

199
        // AuxSigner is an optional signer that can be used to sign auxiliary
200
        // leaves for certain custom channel types.
201
        AuxSigner fn.Option[lnwallet.AuxSigner]
202

203
        // AuxDataParser is an optional data parser that can be used to parse
204
        // auxiliary data for certain custom channel types.
205
        AuxDataParser fn.Option[AuxDataParser]
206

207
        // AuxChanCloser is an optional channel closer that can be used to
208
        // modify the way a coop-close transaction is constructed.
209
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
210

211
        // AuxSweeper is an optional interface that can be used to modify the
212
        // way sweep transaction are generated.
213
        AuxSweeper fn.Option[sweep.AuxSweeper]
214

215
        // AuxContractResolver is an optional interface that can be used to
216
        // modify the way contracts are resolved.
217
        AuxContractResolver fn.Option[lnwallet.AuxContractResolver]
218

219
        // AuxChannelNegotiator is an optional interface that allows aux channel
220
        // implementations to inject and process custom records over channel
221
        // related wire messages.
222
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
223
}
224

225
// DefaultWalletImpl is the default implementation of our normal, btcwallet
226
// backed configuration.
227
type DefaultWalletImpl struct {
228
        cfg         *Config
229
        logger      btclog.Logger
230
        interceptor signal.Interceptor
231

232
        watchOnly        bool
233
        migrateWatchOnly bool
234
        pwService        *walletunlocker.UnlockerService
235
}
236

237
// NewDefaultWalletImpl creates a new default wallet implementation.
238
func NewDefaultWalletImpl(cfg *Config, logger btclog.Logger,
239
        interceptor signal.Interceptor, watchOnly bool) *DefaultWalletImpl {
3✔
240

3✔
241
        return &DefaultWalletImpl{
3✔
242
                cfg:         cfg,
3✔
243
                logger:      logger,
3✔
244
                interceptor: interceptor,
3✔
245
                watchOnly:   watchOnly,
3✔
246
                pwService:   createWalletUnlockerService(cfg),
3✔
247
        }
3✔
248
}
3✔
249

250
// RegisterRestSubserver is called after lnd creates the main proxy.ServeMux
251
// instance. External subservers implementing this method can then register
252
// their own REST proxy stubs to the main server instance.
253
//
254
// NOTE: This is part of the GrpcRegistrar interface.
255
func (d *DefaultWalletImpl) RegisterRestSubserver(ctx context.Context,
256
        mux *proxy.ServeMux, restProxyDest string,
257
        restDialOpts []grpc.DialOption) error {
3✔
258

3✔
259
        return lnrpc.RegisterWalletUnlockerHandlerFromEndpoint(
3✔
260
                ctx, mux, restProxyDest, restDialOpts,
3✔
261
        )
3✔
262
}
3✔
263

264
// RegisterGrpcSubserver is called for each net.Listener on which lnd creates a
265
// grpc.Server instance. External subservers implementing this method can then
266
// register their own gRPC server structs to the main server instance.
267
//
268
// NOTE: This is part of the GrpcRegistrar interface.
269
func (d *DefaultWalletImpl) RegisterGrpcSubserver(s *grpc.Server) error {
3✔
270
        lnrpc.RegisterWalletUnlockerServer(s, d.pwService)
3✔
271

3✔
272
        return nil
3✔
273
}
3✔
274

275
// ValidateMacaroon extracts the macaroon from the context's gRPC metadata,
276
// checks its signature, makes sure all specified permissions for the called
277
// method are contained within and finally ensures all caveat conditions are
278
// met. A non-nil error is returned if any of the checks fail.
279
//
280
// NOTE: This is part of the ExternalValidator interface.
281
func (d *DefaultWalletImpl) ValidateMacaroon(ctx context.Context,
282
        requiredPermissions []bakery.Op, fullMethod string) error {
×
283

×
284
        // Because the default implementation does not return any permissions,
×
285
        // we shouldn't be registered as an external validator at all and this
×
286
        // should never be invoked.
×
287
        return fmt.Errorf("default implementation does not support external " +
×
288
                "macaroon validation")
×
289
}
×
290

291
// Permissions returns the permissions that the external validator is
292
// validating. It is a map between the full HTTP URI of each RPC and its
293
// required macaroon permissions. If multiple action/entity tuples are specified
294
// per URI, they are all required. See rpcserver.go for a list of valid action
295
// and entity values.
296
//
297
// NOTE: This is part of the ExternalValidator interface.
298
func (d *DefaultWalletImpl) Permissions() map[string][]bakery.Op {
3✔
299
        return nil
3✔
300
}
3✔
301

302
// BuildWalletConfig is responsible for creating or unlocking and then
303
// fully initializing a wallet.
304
//
305
// NOTE: This is part of the WalletConfigBuilder interface.
306
func (d *DefaultWalletImpl) BuildWalletConfig(ctx context.Context,
307
        dbs *DatabaseInstances, aux *AuxComponents,
308
        interceptorChain *rpcperms.InterceptorChain,
309
        grpcListeners []*ListenerWithSignal) (*chainreg.PartialChainControl,
310
        *btcwallet.Config, func(), error) {
3✔
311

3✔
312
        // Keep track of our various cleanup functions. We use a defer function
3✔
313
        // as well to not repeat ourselves with every return statement.
3✔
314
        var (
3✔
315
                cleanUpTasks []func()
3✔
316
                earlyExit    = true
3✔
317
                cleanUp      = func() {
6✔
318
                        for _, fn := range cleanUpTasks {
6✔
319
                                if fn == nil {
3✔
320
                                        continue
×
321
                                }
322

323
                                fn()
3✔
324
                        }
325
                }
326
        )
327
        defer func() {
6✔
328
                if earlyExit {
3✔
329
                        cleanUp()
×
330
                }
×
331
        }()
332

333
        // Initialize a new block cache.
334
        blockCache := blockcache.NewBlockCache(d.cfg.BlockCacheSize)
3✔
335

3✔
336
        // Before starting the wallet, we'll create and start our Neutrino
3✔
337
        // light client instance, if enabled, in order to allow it to sync
3✔
338
        // while the rest of the daemon continues startup.
3✔
339
        mainChain := d.cfg.Bitcoin
3✔
340
        var neutrinoCS *neutrino.ChainService
3✔
341
        if mainChain.Node == "neutrino" {
4✔
342
                neutrinoBackend, neutrinoCleanUp, err := initNeutrinoBackend(
1✔
343
                        ctx, d.cfg, mainChain.ChainDir, blockCache,
1✔
344
                )
1✔
345
                if err != nil {
1✔
346
                        err := fmt.Errorf("unable to initialize neutrino "+
×
347
                                "backend: %v", err)
×
348
                        d.logger.Error(err)
×
349
                        return nil, nil, nil, err
×
350
                }
×
351
                cleanUpTasks = append(cleanUpTasks, neutrinoCleanUp)
1✔
352
                neutrinoCS = neutrinoBackend
1✔
353
        }
354

355
        var (
3✔
356
                walletInitParams = walletunlocker.WalletUnlockParams{
3✔
357
                        // In case we do auto-unlock, we need to be able to send
3✔
358
                        // into the channel without blocking so we buffer it.
3✔
359
                        MacResponseChan: make(chan []byte, 1),
3✔
360
                }
3✔
361
                privateWalletPw = lnwallet.DefaultPrivatePassphrase
3✔
362
                publicWalletPw  = lnwallet.DefaultPublicPassphrase
3✔
363
        )
3✔
364

3✔
365
        // If the user didn't request a seed, then we'll manually assume a
3✔
366
        // wallet birthday of now, as otherwise the seed would've specified
3✔
367
        // this information.
3✔
368
        walletInitParams.Birthday = time.Now()
3✔
369

3✔
370
        d.pwService.SetLoaderOpts([]btcwallet.LoaderOption{dbs.WalletDB})
3✔
371
        d.pwService.SetMacaroonDB(dbs.MacaroonDB)
3✔
372
        walletExists, err := d.pwService.WalletExists()
3✔
373
        if err != nil {
3✔
374
                return nil, nil, nil, err
×
375
        }
×
376

377
        if !walletExists {
6✔
378
                interceptorChain.SetWalletNotCreated()
3✔
379
        } else {
6✔
380
                interceptorChain.SetWalletLocked()
3✔
381
        }
3✔
382

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

×
391
                return nil, nil, nil, fmt.Errorf("wallet unlock password file " +
×
392
                        "was specified but wallet does not exist; initialize " +
×
393
                        "the wallet before using auto unlocking")
×
394
        }
×
395

396
        // What wallet mode are we running in? We've already made sure the no
397
        // seed backup and auto unlock aren't both set during config parsing.
398
        switch {
3✔
399
        // No seed backup means we're also using the default password.
400
        case d.cfg.NoSeedBackup:
3✔
401
                // We continue normally, the default password has already been
402
                // set above.
403

404
        // A password for unlocking is provided in a file.
405
        case d.cfg.WalletUnlockPasswordFile != "" && walletExists:
×
406
                d.logger.Infof("Attempting automatic wallet unlock with " +
×
407
                        "password provided in file")
×
408
                pwBytes, err := os.ReadFile(d.cfg.WalletUnlockPasswordFile)
×
409
                if err != nil {
×
410
                        return nil, nil, nil, fmt.Errorf("error reading "+
×
411
                                "password from file %s: %v",
×
412
                                d.cfg.WalletUnlockPasswordFile, err)
×
413
                }
×
414

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

×
420
                // We have the password now, we can ask the unlocker service to
×
421
                // do the unlock for us.
×
422
                unlockedWallet, unloadWalletFn, err := d.pwService.LoadAndUnlock(
×
423
                        pwBytes, 0,
×
424
                )
×
425
                if err != nil {
×
426
                        return nil, nil, nil, fmt.Errorf("error unlocking "+
×
427
                                "wallet with password from file: %v", err)
×
428
                }
×
429

430
                cleanUpTasks = append(cleanUpTasks, func() {
×
431
                        if err := unloadWalletFn(); err != nil {
×
432
                                d.logger.Errorf("Could not unload wallet: %v",
×
433
                                        err)
×
434
                        }
×
435
                })
436

437
                privateWalletPw = pwBytes
×
438
                publicWalletPw = pwBytes
×
439
                walletInitParams.Wallet = unlockedWallet
×
440
                walletInitParams.UnloadWallet = unloadWalletFn
×
441

442
        // If none of the automatic startup options are selected, we fall back
443
        // to the default behavior of waiting for the wallet creation/unlocking
444
        // over RPC.
445
        default:
3✔
446
                if err := d.interceptor.Notifier.NotifyReady(false); err != nil {
3✔
447
                        return nil, nil, nil, err
×
448
                }
×
449

450
                params, err := waitForWalletPassword(
3✔
451
                        d.cfg, d.pwService, []btcwallet.LoaderOption{dbs.WalletDB},
3✔
452
                        d.interceptor.ShutdownChannel(),
3✔
453
                )
3✔
454
                if err != nil {
3✔
455
                        err := fmt.Errorf("unable to set up wallet password "+
×
456
                                "listeners: %v", err)
×
457
                        d.logger.Error(err)
×
458
                        return nil, nil, nil, err
×
459
                }
×
460

461
                walletInitParams = *params
3✔
462
                privateWalletPw = walletInitParams.Password
3✔
463
                publicWalletPw = walletInitParams.Password
3✔
464
                cleanUpTasks = append(cleanUpTasks, func() {
6✔
465
                        if err := walletInitParams.UnloadWallet(); err != nil {
3✔
466
                                d.logger.Errorf("Could not unload wallet: %v",
×
467
                                        err)
×
468
                        }
×
469
                })
470

471
                if walletInitParams.RecoveryWindow > 0 {
6✔
472
                        d.logger.Infof("Wallet recovery mode enabled with "+
3✔
473
                                "address lookahead of %d addresses",
3✔
474
                                walletInitParams.RecoveryWindow)
3✔
475
                }
3✔
476
        }
477

478
        var macaroonService *macaroons.Service
3✔
479
        if !d.cfg.NoMacaroons {
6✔
480
                // Create the macaroon authentication/authorization service.
3✔
481
                rootKeyStore, err := macaroons.NewRootKeyStorage(dbs.MacaroonDB)
3✔
482
                if err != nil {
3✔
483
                        return nil, nil, nil, err
×
484
                }
×
485
                macaroonService, err = macaroons.NewService(
3✔
486
                        rootKeyStore, "lnd", walletInitParams.StatelessInit,
3✔
487
                        macaroons.IPLockChecker, macaroons.IPRangeLockChecker,
3✔
488
                        macaroons.CustomChecker(interceptorChain),
3✔
489
                )
3✔
490
                if err != nil {
3✔
491
                        err := fmt.Errorf("unable to set up macaroon "+
×
492
                                "authentication: %v", err)
×
493
                        d.logger.Error(err)
×
494
                        return nil, nil, nil, err
×
495
                }
×
496
                cleanUpTasks = append(cleanUpTasks, func() {
6✔
497
                        if err := macaroonService.Close(); err != nil {
3✔
498
                                d.logger.Errorf("Could not close macaroon "+
×
499
                                        "service: %v", err)
×
500
                        }
×
501
                })
502

503
                // Try to unlock the macaroon store with the private password.
504
                // Ignore ErrAlreadyUnlocked since it could be unlocked by the
505
                // wallet unlocker.
506
                err = macaroonService.CreateUnlock(&privateWalletPw)
3✔
507
                if err != nil && err != macaroons.ErrAlreadyUnlocked {
3✔
508
                        err := fmt.Errorf("unable to unlock macaroons: %w", err)
×
509
                        d.logger.Error(err)
×
510
                        return nil, nil, nil, err
×
511
                }
×
512

513
                // If we have a macaroon root key from the init wallet params,
514
                // set the root key before baking any macaroons.
515
                if len(walletInitParams.MacRootKey) > 0 {
3✔
516
                        err := macaroonService.SetRootKey(
×
517
                                walletInitParams.MacRootKey,
×
518
                        )
×
519
                        if err != nil {
×
520
                                return nil, nil, nil, err
×
521
                        }
×
522
                }
523

524
                // Send an admin macaroon to all our listeners that requested
525
                // one by setting a non-nil macaroon channel.
526
                adminMacBytes, err := bakeMacaroon(
3✔
527
                        ctx, macaroonService, adminPermissions(),
3✔
528
                )
3✔
529
                if err != nil {
3✔
530
                        return nil, nil, nil, err
×
531
                }
×
532
                for _, lis := range grpcListeners {
6✔
533
                        if lis.MacChan != nil {
3✔
534
                                lis.MacChan <- adminMacBytes
×
535
                        }
×
536
                }
537

538
                // In case we actually needed to unlock the wallet, we now need
539
                // to create an instance of the admin macaroon and send it to
540
                // the unlocker so it can forward it to the user. In no seed
541
                // backup mode, there's nobody listening on the channel and we'd
542
                // block here forever.
543
                if !d.cfg.NoSeedBackup {
6✔
544
                        // The channel is buffered by one element so writing
3✔
545
                        // should not block here.
3✔
546
                        walletInitParams.MacResponseChan <- adminMacBytes
3✔
547
                }
3✔
548

549
                // If the user requested a stateless initialization, no macaroon
550
                // files should be created.
551
                if !walletInitParams.StatelessInit {
6✔
552
                        // Create default macaroon files for lncli to use if
3✔
553
                        // they don't exist.
3✔
554
                        err = genDefaultMacaroons(
3✔
555
                                ctx, macaroonService, d.cfg.AdminMacPath,
3✔
556
                                d.cfg.ReadMacPath, d.cfg.InvoiceMacPath,
3✔
557
                        )
3✔
558
                        if err != nil {
3✔
559
                                err := fmt.Errorf("unable to create macaroons "+
×
560
                                        "%v", err)
×
561
                                d.logger.Error(err)
×
562
                                return nil, nil, nil, err
×
563
                        }
×
564
                }
565

566
                // As a security service to the user, if they requested
567
                // stateless initialization and there are macaroon files on disk
568
                // we log a warning.
569
                if walletInitParams.StatelessInit {
6✔
570
                        msg := "Found %s macaroon on disk (%s) even though " +
3✔
571
                                "--stateless_init was requested. Unencrypted " +
3✔
572
                                "state is accessible by the host system. You " +
3✔
573
                                "should change the password and use " +
3✔
574
                                "--new_mac_root_key with --stateless_init to " +
3✔
575
                                "clean up and invalidate old macaroons."
3✔
576

3✔
577
                        if lnrpc.FileExists(d.cfg.AdminMacPath) {
3✔
578
                                d.logger.Warnf(msg, "admin", d.cfg.AdminMacPath)
×
579
                        }
×
580
                        if lnrpc.FileExists(d.cfg.ReadMacPath) {
3✔
581
                                d.logger.Warnf(msg, "readonly", d.cfg.ReadMacPath)
×
582
                        }
×
583
                        if lnrpc.FileExists(d.cfg.InvoiceMacPath) {
3✔
584
                                d.logger.Warnf(msg, "invoice", d.cfg.InvoiceMacPath)
×
585
                        }
×
586
                }
587

588
                // We add the macaroon service to our RPC interceptor. This
589
                // will start checking macaroons against permissions on every
590
                // RPC invocation.
591
                interceptorChain.AddMacaroonService(macaroonService)
3✔
592
        }
593

594
        // Now that the wallet password has been provided, transition the RPC
595
        // state into Unlocked.
596
        interceptorChain.SetWalletUnlocked()
3✔
597

3✔
598
        // Since calls to the WalletUnlocker service wait for a response on the
3✔
599
        // macaroon channel, we close it here to make sure they return in case
3✔
600
        // we did not return the admin macaroon above. This will be the case if
3✔
601
        // --no-macaroons is used.
3✔
602
        close(walletInitParams.MacResponseChan)
3✔
603

3✔
604
        // We'll also close all the macaroon channels since lnd is done sending
3✔
605
        // macaroon data over it.
3✔
606
        for _, lis := range grpcListeners {
6✔
607
                if lis.MacChan != nil {
3✔
608
                        close(lis.MacChan)
×
609
                }
×
610
        }
611

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

646
        // Let's go ahead and create the partial chain control now that is only
647
        // dependent on our configuration and doesn't require any wallet
648
        // specific information.
649
        partialChainControl, pccCleanup, err := chainreg.NewPartialChainControl(
3✔
650
                chainControlCfg,
3✔
651
        )
3✔
652
        cleanUpTasks = append(cleanUpTasks, pccCleanup)
3✔
653
        if err != nil {
3✔
654
                err := fmt.Errorf("unable to create partial chain control: %w",
×
655
                        err)
×
656
                d.logger.Error(err)
×
657
                return nil, nil, nil, err
×
658
        }
×
659

660
        walletConfig := &btcwallet.Config{
3✔
661
                PrivatePass:      privateWalletPw,
3✔
662
                PublicPass:       publicWalletPw,
3✔
663
                Birthday:         walletInitParams.Birthday,
3✔
664
                RecoveryWindow:   walletInitParams.RecoveryWindow,
3✔
665
                NetParams:        d.cfg.ActiveNetParams.Params,
3✔
666
                CoinType:         d.cfg.ActiveNetParams.CoinType,
3✔
667
                Wallet:           walletInitParams.Wallet,
3✔
668
                LoaderOptions:    []btcwallet.LoaderOption{dbs.WalletDB},
3✔
669
                ChainSource:      partialChainControl.ChainSource,
3✔
670
                WatchOnly:        d.watchOnly,
3✔
671
                MigrateWatchOnly: d.migrateWatchOnly,
3✔
672
        }
3✔
673

3✔
674
        // Parse coin selection strategy.
3✔
675
        switch d.cfg.CoinSelectionStrategy {
3✔
676
        case "largest":
3✔
677
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionLargest
3✔
678

679
        case "random":
×
680
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionRandom
×
681

682
        default:
×
683
                return nil, nil, nil, fmt.Errorf("unknown coin selection "+
×
684
                        "strategy %v", d.cfg.CoinSelectionStrategy)
×
685
        }
686

687
        earlyExit = false
3✔
688
        return partialChainControl, walletConfig, cleanUp, nil
3✔
689
}
690

691
// proxyBlockEpoch proxies a block epoch subsections to the underlying neutrino
692
// rebroadcaster client.
693
func proxyBlockEpoch(
694
        notifier chainntnfs.ChainNotifier) func() (*blockntfns.Subscription,
695
        error) {
2✔
696

2✔
697
        return func() (*blockntfns.Subscription, error) {
4✔
698
                blockEpoch, err := notifier.RegisterBlockEpochNtfn(
2✔
699
                        nil,
2✔
700
                )
2✔
701
                if err != nil {
2✔
702
                        return nil, err
×
703
                }
×
704

705
                sub := blockntfns.Subscription{
2✔
706
                        Notifications: make(chan blockntfns.BlockNtfn, 6),
2✔
707
                        Cancel:        blockEpoch.Cancel,
2✔
708
                }
2✔
709
                go func() {
4✔
710
                        for blk := range blockEpoch.Epochs {
4✔
711
                                ntfn := blockntfns.NewBlockConnected(
2✔
712
                                        *blk.BlockHeader,
2✔
713
                                        uint32(blk.Height),
2✔
714
                                )
2✔
715

2✔
716
                                sub.Notifications <- ntfn
2✔
717
                        }
2✔
718
                }()
719

720
                return &sub, nil
2✔
721
        }
722
}
723

724
// walletReBroadcaster is a simple wrapper around the pushtx.Broadcaster
725
// interface to adhere to the expanded lnwallet.Rebroadcaster interface.
726
type walletReBroadcaster struct {
727
        started atomic.Bool
728

729
        *pushtx.Broadcaster
730
}
731

732
// newWalletReBroadcaster creates a new instance of the walletReBroadcaster.
733
func newWalletReBroadcaster(
734
        broadcaster *pushtx.Broadcaster) *walletReBroadcaster {
2✔
735

2✔
736
        return &walletReBroadcaster{
2✔
737
                Broadcaster: broadcaster,
2✔
738
        }
2✔
739
}
2✔
740

741
// Start launches all goroutines the rebroadcaster needs to operate.
742
func (w *walletReBroadcaster) Start() error {
2✔
743
        defer w.started.Store(true)
2✔
744

2✔
745
        return w.Broadcaster.Start()
2✔
746
}
2✔
747

748
// Started returns true if the broadcaster is already active.
749
func (w *walletReBroadcaster) Started() bool {
2✔
750
        return w.started.Load()
2✔
751
}
2✔
752

753
// BuildChainControl is responsible for creating a fully populated chain
754
// control instance from a wallet.
755
//
756
// NOTE: This is part of the ChainControlBuilder interface.
757
func (d *DefaultWalletImpl) BuildChainControl(
758
        partialChainControl *chainreg.PartialChainControl,
759
        walletConfig *btcwallet.Config) (*chainreg.ChainControl, func(), error) {
3✔
760

3✔
761
        walletController, err := btcwallet.New(
3✔
762
                *walletConfig, partialChainControl.Cfg.BlockCache,
3✔
763
        )
3✔
764
        if err != nil {
3✔
765
                err := fmt.Errorf("unable to create wallet controller: %w", err)
×
766
                d.logger.Error(err)
×
767
                return nil, nil, err
×
768
        }
×
769

770
        keyRing := keychain.NewBtcWalletKeyRing(
3✔
771
                walletController.InternalWallet(), walletConfig.CoinType,
3✔
772
        )
3✔
773

3✔
774
        // Create, and start the lnwallet, which handles the core payment
3✔
775
        // channel logic, and exposes control via proxy state machines.
3✔
776
        lnWalletConfig := lnwallet.Config{
3✔
777
                Database:              partialChainControl.Cfg.ChanStateDB,
3✔
778
                Notifier:              partialChainControl.ChainNotifier,
3✔
779
                WalletController:      walletController,
3✔
780
                Signer:                walletController,
3✔
781
                FeeEstimator:          partialChainControl.FeeEstimator,
3✔
782
                SecretKeyRing:         keyRing,
3✔
783
                ChainIO:               walletController,
3✔
784
                NetParams:             *walletConfig.NetParams,
3✔
785
                CoinSelectionStrategy: walletConfig.CoinSelectionStrategy,
3✔
786
                AuxLeafStore:          partialChainControl.Cfg.AuxLeafStore,
3✔
787
                AuxSigner:             partialChainControl.Cfg.AuxSigner,
3✔
788
        }
3✔
789

3✔
790
        // The broadcast is already always active for neutrino nodes, so we
3✔
791
        // don't want to create a rebroadcast loop.
3✔
792
        if partialChainControl.Cfg.NeutrinoCS == nil {
5✔
793
                cs := partialChainControl.ChainSource
2✔
794
                broadcastCfg := pushtx.Config{
2✔
795
                        Broadcast: func(tx *wire.MsgTx) error {
4✔
796
                                _, err := cs.SendRawTransaction(
2✔
797
                                        tx, true,
2✔
798
                                )
2✔
799

2✔
800
                                return err
2✔
801
                        },
2✔
802
                        SubscribeBlocks: proxyBlockEpoch(
803
                                partialChainControl.ChainNotifier,
804
                        ),
805
                        RebroadcastInterval: pushtx.DefaultRebroadcastInterval,
806
                        // In case the backend is different from neutrino we
807
                        // make sure that broadcast backend errors are mapped
808
                        // to the neutrino broadcastErr.
809
                        MapCustomBroadcastError: func(err error) error {
2✔
810
                                rpcErr := cs.MapRPCErr(err)
2✔
811
                                return broadcastErrorMapper(rpcErr)
2✔
812
                        },
2✔
813
                }
814

815
                lnWalletConfig.Rebroadcaster = newWalletReBroadcaster(
2✔
816
                        pushtx.NewBroadcaster(&broadcastCfg),
2✔
817
                )
2✔
818
        }
819

820
        // We've created the wallet configuration now, so we can finish
821
        // initializing the main chain control.
822
        activeChainControl, cleanUp, err := chainreg.NewChainControl(
3✔
823
                lnWalletConfig, walletController, partialChainControl,
3✔
824
        )
3✔
825
        if err != nil {
3✔
826
                err := fmt.Errorf("unable to create chain control: %w", err)
×
827
                d.logger.Error(err)
×
828
                return nil, nil, err
×
829
        }
×
830

831
        return activeChainControl, cleanUp, nil
3✔
832
}
833

834
// RPCSignerWalletImpl is a wallet implementation that uses a remote signer over
835
// an RPC interface.
836
type RPCSignerWalletImpl struct {
837
        // DefaultWalletImpl is the embedded instance of the default
838
        // implementation that the remote signer uses as its watch-only wallet
839
        // for keeping track of addresses and UTXOs.
840
        *DefaultWalletImpl
841
}
842

843
// NewRPCSignerWalletImpl creates a new instance of the remote signing wallet
844
// implementation.
845
func NewRPCSignerWalletImpl(cfg *Config, logger btclog.Logger,
846
        interceptor signal.Interceptor,
847
        migrateWatchOnly bool) *RPCSignerWalletImpl {
3✔
848

3✔
849
        return &RPCSignerWalletImpl{
3✔
850
                DefaultWalletImpl: &DefaultWalletImpl{
3✔
851
                        cfg:              cfg,
3✔
852
                        logger:           logger,
3✔
853
                        interceptor:      interceptor,
3✔
854
                        watchOnly:        true,
3✔
855
                        migrateWatchOnly: migrateWatchOnly,
3✔
856
                        pwService:        createWalletUnlockerService(cfg),
3✔
857
                },
3✔
858
        }
3✔
859
}
3✔
860

861
// BuildChainControl is responsible for creating or unlocking and then fully
862
// initializing a wallet and returning it as part of a fully populated chain
863
// control instance.
864
//
865
// NOTE: This is part of the ChainControlBuilder interface.
866
func (d *RPCSignerWalletImpl) BuildChainControl(
867
        partialChainControl *chainreg.PartialChainControl,
868
        walletConfig *btcwallet.Config) (*chainreg.ChainControl, func(), error) {
3✔
869

3✔
870
        walletController, err := btcwallet.New(
3✔
871
                *walletConfig, partialChainControl.Cfg.BlockCache,
3✔
872
        )
3✔
873
        if err != nil {
3✔
874
                err := fmt.Errorf("unable to create wallet controller: %w", err)
×
875
                d.logger.Error(err)
×
876
                return nil, nil, err
×
877
        }
×
878

879
        baseKeyRing := keychain.NewBtcWalletKeyRing(
3✔
880
                walletController.InternalWallet(), walletConfig.CoinType,
3✔
881
        )
3✔
882

3✔
883
        rpcKeyRing, err := rpcwallet.NewRPCKeyRing(
3✔
884
                baseKeyRing, walletController,
3✔
885
                d.DefaultWalletImpl.cfg.RemoteSigner, walletConfig.NetParams,
3✔
886
        )
3✔
887
        if err != nil {
3✔
888
                err := fmt.Errorf("unable to create RPC remote signing wallet "+
×
889
                        "%v", err)
×
890
                d.logger.Error(err)
×
891
                return nil, nil, err
×
892
        }
×
893

894
        // Create, and start the lnwallet, which handles the core payment
895
        // channel logic, and exposes control via proxy state machines.
896
        lnWalletConfig := lnwallet.Config{
3✔
897
                Database:              partialChainControl.Cfg.ChanStateDB,
3✔
898
                Notifier:              partialChainControl.ChainNotifier,
3✔
899
                WalletController:      rpcKeyRing,
3✔
900
                Signer:                rpcKeyRing,
3✔
901
                FeeEstimator:          partialChainControl.FeeEstimator,
3✔
902
                SecretKeyRing:         rpcKeyRing,
3✔
903
                ChainIO:               walletController,
3✔
904
                NetParams:             *walletConfig.NetParams,
3✔
905
                CoinSelectionStrategy: walletConfig.CoinSelectionStrategy,
3✔
906
        }
3✔
907

3✔
908
        // We've created the wallet configuration now, so we can finish
3✔
909
        // initializing the main chain control.
3✔
910
        activeChainControl, cleanUp, err := chainreg.NewChainControl(
3✔
911
                lnWalletConfig, rpcKeyRing, partialChainControl,
3✔
912
        )
3✔
913
        if err != nil {
3✔
914
                err := fmt.Errorf("unable to create chain control: %w", err)
×
915
                d.logger.Error(err)
×
916
                return nil, nil, err
×
917
        }
×
918

919
        return activeChainControl, cleanUp, nil
3✔
920
}
921

922
// DatabaseInstances is a struct that holds all instances to the actual
923
// databases that are used in lnd.
924
type DatabaseInstances struct {
925
        // GraphDB is the database that stores the channel graph used for path
926
        // finding.
927
        GraphDB *graphdb.ChannelGraph
928

929
        // ChanStateDB is the database that stores all of our node's channel
930
        // state.
931
        ChanStateDB *channeldb.DB
932

933
        // HeightHintDB is the database that stores height hints for spends.
934
        HeightHintDB kvdb.Backend
935

936
        // InvoiceDB is the database that stores information about invoices.
937
        InvoiceDB invoices.InvoiceDB
938

939
        // PaymentsDB is the database that stores all payment related
940
        // information.
941
        PaymentsDB paymentsdb.DB
942

943
        // MacaroonDB is the database that stores macaroon root keys.
944
        MacaroonDB kvdb.Backend
945

946
        // DecayedLogDB is the database that stores p2p related encryption
947
        // information.
948
        DecayedLogDB kvdb.Backend
949

950
        // TowerClientDB is the database that stores the watchtower client's
951
        // configuration.
952
        TowerClientDB wtclient.DB
953

954
        // TowerServerDB is the database that stores the watchtower server's
955
        // configuration.
956
        TowerServerDB watchtower.DB
957

958
        // WalletDB is the configuration for loading the wallet database using
959
        // the btcwallet's loader.
960
        WalletDB btcwallet.LoaderOption
961

962
        // NativeSQLStore holds a reference to the native SQL store that can
963
        // be used for native SQL queries for tables that already support it.
964
        // This may be nil if the use-native-sql flag was not set.
965
        NativeSQLStore sqldb.DB
966
}
967

968
// DefaultDatabaseBuilder is a type that builds the default database backends
969
// for lnd, using the given configuration to decide what actual implementation
970
// to use.
971
type DefaultDatabaseBuilder struct {
972
        cfg    *Config
973
        logger btclog.Logger
974
}
975

976
// NewDefaultDatabaseBuilder returns a new instance of the default database
977
// builder.
978
func NewDefaultDatabaseBuilder(cfg *Config,
979
        logger btclog.Logger) *DefaultDatabaseBuilder {
3✔
980

3✔
981
        return &DefaultDatabaseBuilder{
3✔
982
                cfg:    cfg,
3✔
983
                logger: logger,
3✔
984
        }
3✔
985
}
3✔
986

987
// BuildDatabase extracts the current databases that we'll use for normal
988
// operation in the daemon. A function closure that closes all opened databases
989
// is also returned.
990
func (d *DefaultDatabaseBuilder) BuildDatabase(
991
        ctx context.Context) (*DatabaseInstances, func(), error) {
3✔
992

3✔
993
        d.logger.Infof("Opening the main database, this might take a few " +
3✔
994
                "minutes...")
3✔
995

3✔
996
        cfg := d.cfg
3✔
997
        if cfg.DB.Backend == lncfg.BoltBackend {
6✔
998
                d.logger.Infof("Opening bbolt database, sync_freelist=%v, "+
3✔
999
                        "auto_compact=%v", !cfg.DB.Bolt.NoFreelistSync,
3✔
1000
                        cfg.DB.Bolt.AutoCompact)
3✔
1001
        }
3✔
1002

1003
        startOpenTime := time.Now()
3✔
1004

3✔
1005
        databaseBackends, err := cfg.DB.GetBackends(
3✔
1006
                ctx, cfg.graphDatabaseDir(), cfg.networkDir, filepath.Join(
3✔
1007
                        cfg.Watchtower.TowerDir, BitcoinChainName,
3✔
1008
                        lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1009
                ), cfg.WtClient.Active, cfg.Watchtower.Active, d.logger,
3✔
1010
        )
3✔
1011
        if err != nil {
3✔
1012
                return nil, nil, fmt.Errorf("unable to obtain database "+
×
1013
                        "backends: %v", err)
×
1014
        }
×
1015

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

1045
        graphDBOptions := []graphdb.StoreOptionModifier{
3✔
1046
                graphdb.WithRejectCacheSize(cfg.Caches.RejectCacheSize),
3✔
1047
                graphdb.WithChannelCacheSize(cfg.Caches.ChannelCacheSize),
3✔
1048
                graphdb.WithBatchCommitInterval(cfg.DB.BatchCommitInterval),
3✔
1049
        }
3✔
1050

3✔
1051
        chanGraphOpts := []graphdb.ChanGraphOption{
3✔
1052
                graphdb.WithUseGraphCache(!cfg.DB.NoGraphCache),
3✔
1053
        }
3✔
1054

3✔
1055
        // We want to pre-allocate the channel graph cache according to what we
3✔
1056
        // expect for mainnet to speed up memory allocation.
3✔
1057
        if cfg.ActiveNetParams.Name == chaincfg.MainNetParams.Name {
3✔
1058
                chanGraphOpts = append(
×
1059
                        chanGraphOpts, graphdb.WithPreAllocCacheNumNodes(
×
1060
                                graphdb.DefaultPreAllocCacheNumNodes,
×
1061
                        ),
×
1062
                )
×
1063
        }
×
1064

1065
        dbOptions := []channeldb.OptionModifier{
3✔
1066
                channeldb.OptionDryRunMigration(cfg.DryRunMigration),
3✔
1067
                channeldb.OptionStoreFinalHtlcResolutions(
3✔
1068
                        cfg.StoreFinalHtlcResolutions,
3✔
1069
                ),
3✔
1070
                channeldb.OptionPruneRevocationLog(cfg.DB.PruneRevocation),
3✔
1071
                channeldb.OptionNoRevLogAmtData(cfg.DB.NoRevLogAmtData),
3✔
1072
                channeldb.OptionGcDecayedLog(cfg.DB.NoGcDecayedLog),
3✔
1073
                channeldb.OptionWithDecayedLogDB(dbs.DecayedLogDB),
3✔
1074
        }
3✔
1075

3✔
1076
        // Otherwise, we'll open two instances, one for the state we only need
3✔
1077
        // locally, and the other for things we want to ensure are replicated.
3✔
1078
        dbs.ChanStateDB, err = channeldb.CreateWithBackend(
3✔
1079
                databaseBackends.ChanStateDB, dbOptions...,
3✔
1080
        )
3✔
1081
        switch {
3✔
1082
        // Give the DB a chance to dry run the migration. Since we know that
1083
        // both the channel state and graph DBs are still always behind the same
1084
        // backend, we know this would be applied to both of those DBs.
1085
        case err == channeldb.ErrDryRunMigrationOK:
×
1086
                d.logger.Infof("Channel DB dry run migration successful")
×
1087
                return nil, nil, err
×
1088

1089
        case err != nil:
×
1090
                cleanUp()
×
1091

×
1092
                err = fmt.Errorf("unable to open graph DB: %w", err)
×
1093
                d.logger.Error(err)
×
1094
                return nil, nil, err
×
1095
        }
1096

1097
        // Process any deferred channel cleanups. For postgres backends, heavy
1098
        // cleanup operations (deleting revocation logs, forwarding packages)
1099
        // are deferred to startup to avoid lock contention. For other backends
1100
        // (bbolt, sqlite), this is a no-op as they perform immediate cleanup.
1101
        if kvdb.ShouldDeferHeavyOperations(databaseBackends.ChanStateDB) {
3✔
NEW
1102
                err = dbs.ChanStateDB.ChannelStateDB().CleanupPendingCloses()
×
NEW
1103
                if err != nil {
×
NEW
1104
                        cleanUp()
×
NEW
1105

×
NEW
1106
                        err = fmt.Errorf("unable to cleanup pending "+
×
NEW
1107
                                "closes: %w", err)
×
NEW
1108
                        d.logger.Error(err)
×
NEW
1109
                        return nil, nil, err
×
NEW
1110
                }
×
1111
        }
1112

1113
        // The graph store implementation we will use depends on whether
1114
        // native SQL is enabled or not.
1115
        var graphStore graphdb.V1Store
3✔
1116

3✔
1117
        // Instantiate a native SQL store if the flag is set.
3✔
1118
        //nolint:nestif
3✔
1119
        if d.cfg.DB.UseNativeSQL {
3✔
1120
                migrations := sqldb.GetMigrations()
×
1121

×
1122
                queryCfg := &d.cfg.DB.Sqlite.QueryConfig
×
1123
                if d.cfg.DB.Backend == lncfg.PostgresBackend {
×
1124
                        queryCfg = &d.cfg.DB.Postgres.QueryConfig
×
1125
                }
×
1126

1127
                // If the user has not explicitly disabled the SQL invoice
1128
                // migration, attach the custom migration function to invoice
1129
                // migration (version 7). Even if this custom migration is
1130
                // disabled, the regular native SQL store migrations will still
1131
                // run. If the database version is already above this custom
1132
                // migration's version (7), it will be skipped permanently,
1133
                // regardless of the flag.
1134
                if !d.cfg.DB.SkipNativeSQLMigration {
×
1135
                        invoiceMig := func(tx *sqlc.Queries) error {
×
1136
                                err := invoices.MigrateInvoicesToSQL(
×
1137
                                        ctx, dbs.ChanStateDB.Backend,
×
1138
                                        dbs.ChanStateDB, tx,
×
1139
                                        invoiceMigrationBatchSize,
×
1140
                                )
×
1141
                                if err != nil {
×
1142
                                        return fmt.Errorf("failed to migrate "+
×
1143
                                                "invoices to SQL: %w", err)
×
1144
                                }
×
1145

1146
                                // Set the invoice bucket tombstone to indicate
1147
                                // that the migration has been completed.
1148
                                d.logger.Debugf("Setting invoice bucket " +
×
1149
                                        "tombstone")
×
1150

×
1151
                                //nolint:ll
×
1152
                                return dbs.ChanStateDB.SetInvoiceBucketTombstone()
×
1153
                        }
1154

1155
                        graphMig := func(tx *sqlc.Queries) error {
×
1156
                                cfg := &graphdbmig1.SQLStoreConfig{
×
1157
                                        //nolint:ll
×
1158
                                        ChainHash: *d.cfg.ActiveNetParams.GenesisHash,
×
1159
                                        QueryCfg:  queryCfg,
×
1160
                                }
×
1161
                                err := graphdbmig1.MigrateGraphToSQL(
×
1162
                                        ctx, cfg, dbs.ChanStateDB.Backend,
×
1163
                                        graphmig1sqlc.New(tx.GetTx()),
×
1164
                                )
×
1165
                                if err != nil {
×
1166
                                        return fmt.Errorf("failed to migrate "+
×
1167
                                                "graph to SQL: %w", err)
×
1168
                                }
×
1169

1170
                                return nil
×
1171
                        }
1172

1173
                        // Make sure we attach the custom migration function to
1174
                        // the correct migration version.
1175
                        for i := 0; i < len(migrations); i++ {
×
1176
                                version := migrations[i].Version
×
1177
                                switch version {
×
1178
                                case invoiceMigration:
×
1179
                                        migrations[i].MigrationFn = invoiceMig
×
1180

×
1181
                                        continue
×
1182
                                case graphMigration:
×
1183
                                        migrations[i].MigrationFn = graphMig
×
1184

×
1185
                                        continue
×
1186

1187
                                default:
×
1188
                                }
1189

1190
                                migFn, ok := d.getSQLMigration(
×
1191
                                        ctx, version, dbs.ChanStateDB.Backend,
×
1192
                                )
×
1193
                                if !ok {
×
1194
                                        continue
×
1195
                                }
1196

1197
                                migrations[i].MigrationFn = migFn
×
1198
                        }
1199
                }
1200

1201
                // We need to apply all migrations to the native SQL store
1202
                // before we can use it.
1203
                err = dbs.NativeSQLStore.ApplyAllMigrations(ctx, migrations)
×
1204
                if err != nil {
×
1205
                        cleanUp()
×
1206
                        err = fmt.Errorf("faild to run migrations for the "+
×
1207
                                "native SQL store: %w", err)
×
1208
                        d.logger.Error(err)
×
1209

×
1210
                        return nil, nil, err
×
1211
                }
×
1212

1213
                // With the DB ready and migrations applied, we can now create
1214
                // the base DB and transaction executor for the native SQL
1215
                // invoice store.
1216
                baseDB := dbs.NativeSQLStore.GetBaseDB()
×
1217
                invoiceExecutor := sqldb.NewTransactionExecutor(
×
1218
                        baseDB, func(tx *sql.Tx) invoices.SQLInvoiceQueries {
×
1219
                                return baseDB.WithTx(tx)
×
1220
                        },
×
1221
                )
1222

1223
                sqlInvoiceDB := invoices.NewSQLStore(
×
1224
                        invoiceExecutor, clock.NewDefaultClock(),
×
1225
                )
×
1226

×
1227
                dbs.InvoiceDB = sqlInvoiceDB
×
1228

×
1229
                graphExecutor := sqldb.NewTransactionExecutor(
×
1230
                        baseDB, func(tx *sql.Tx) graphdb.SQLQueries {
×
1231
                                return baseDB.WithTx(tx)
×
1232
                        },
×
1233
                )
1234

1235
                graphStore, err = graphdb.NewSQLStore(
×
1236
                        &graphdb.SQLStoreConfig{
×
1237
                                ChainHash: *d.cfg.ActiveNetParams.GenesisHash,
×
1238
                                QueryCfg:  queryCfg,
×
1239
                        },
×
1240
                        graphExecutor, graphDBOptions...,
×
1241
                )
×
1242
                if err != nil {
×
1243
                        err = fmt.Errorf("unable to get graph store: %w", err)
×
1244
                        d.logger.Error(err)
×
1245

×
1246
                        return nil, nil, err
×
1247
                }
×
1248
        } else {
3✔
1249
                // Check if the invoice bucket tombstone is set. If it is, we
3✔
1250
                // need to return and ask the user switch back to using the
3✔
1251
                // native SQL store.
3✔
1252
                ripInvoices, err := dbs.ChanStateDB.GetInvoiceBucketTombstone()
3✔
1253
                if err != nil {
3✔
1254
                        err = fmt.Errorf("unable to check invoice bucket "+
×
1255
                                "tombstone: %w", err)
×
1256
                        d.logger.Error(err)
×
1257

×
1258
                        return nil, nil, err
×
1259
                }
×
1260
                if ripInvoices {
3✔
1261
                        err = fmt.Errorf("invoices bucket tombstoned, please " +
×
1262
                                "switch back to native SQL")
×
1263
                        d.logger.Error(err)
×
1264

×
1265
                        return nil, nil, err
×
1266
                }
×
1267

1268
                dbs.InvoiceDB = dbs.ChanStateDB
3✔
1269

3✔
1270
                graphStore, err = graphdb.NewKVStore(
3✔
1271
                        databaseBackends.GraphDB, graphDBOptions...,
3✔
1272
                )
3✔
1273
                if err != nil {
3✔
1274
                        return nil, nil, err
×
1275
                }
×
1276
        }
1277

1278
        dbs.GraphDB, err = graphdb.NewChannelGraph(graphStore, chanGraphOpts...)
3✔
1279
        if err != nil {
3✔
1280
                cleanUp()
×
1281

×
1282
                err = fmt.Errorf("unable to open channel graph DB: %w", err)
×
1283
                d.logger.Error(err)
×
1284

×
1285
                return nil, nil, err
×
1286
        }
×
1287

1288
        // Mount the payments DB which is only KV for now.
1289
        //
1290
        // TODO(ziggie): Add support for SQL payments DB.
1291
        // Mount the payments DB for the KV store.
1292
        paymentsDBOptions := []paymentsdb.OptionModifier{
3✔
1293
                paymentsdb.WithKeepFailedPaymentAttempts(
3✔
1294
                        cfg.KeepFailedPaymentAttempts,
3✔
1295
                ),
3✔
1296
        }
3✔
1297
        kvPaymentsDB, err := paymentsdb.NewKVStore(
3✔
1298
                dbs.ChanStateDB,
3✔
1299
                paymentsDBOptions...,
3✔
1300
        )
3✔
1301
        if err != nil {
3✔
1302
                cleanUp()
×
1303

×
1304
                err = fmt.Errorf("unable to open payments DB: %w", err)
×
1305
                d.logger.Error(err)
×
1306

×
1307
                return nil, nil, err
×
1308
        }
×
1309
        dbs.PaymentsDB = kvPaymentsDB
3✔
1310

3✔
1311
        // Wrap the watchtower client DB and make sure we clean up.
3✔
1312
        if cfg.WtClient.Active {
6✔
1313
                dbs.TowerClientDB, err = wtdb.OpenClientDB(
3✔
1314
                        databaseBackends.TowerClientDB,
3✔
1315
                )
3✔
1316
                if err != nil {
3✔
1317
                        cleanUp()
×
1318

×
1319
                        err = fmt.Errorf("unable to open %s database: %w",
×
1320
                                lncfg.NSTowerClientDB, err)
×
1321
                        d.logger.Error(err)
×
1322
                        return nil, nil, err
×
1323
                }
×
1324
        }
1325

1326
        // Wrap the watchtower server DB and make sure we clean up.
1327
        if cfg.Watchtower.Active {
6✔
1328
                dbs.TowerServerDB, err = wtdb.OpenTowerDB(
3✔
1329
                        databaseBackends.TowerServerDB,
3✔
1330
                )
3✔
1331
                if err != nil {
3✔
1332
                        cleanUp()
×
1333

×
1334
                        err = fmt.Errorf("unable to open %s database: %w",
×
1335
                                lncfg.NSTowerServerDB, err)
×
1336
                        d.logger.Error(err)
×
1337
                        return nil, nil, err
×
1338
                }
×
1339
        }
1340

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

3✔
1344
        return dbs, cleanUp, nil
3✔
1345
}
1346

1347
// waitForWalletPassword blocks until a password is provided by the user to
1348
// this RPC server.
1349
func waitForWalletPassword(cfg *Config,
1350
        pwService *walletunlocker.UnlockerService,
1351
        loaderOpts []btcwallet.LoaderOption, shutdownChan <-chan struct{}) (
1352
        *walletunlocker.WalletUnlockParams, error) {
3✔
1353

3✔
1354
        // Wait for user to provide the password.
3✔
1355
        ltndLog.Infof("Waiting for wallet encryption password. Use `lncli " +
3✔
1356
                "create` to create a wallet, `lncli unlock` to unlock an " +
3✔
1357
                "existing wallet, or `lncli changepassword` to change the " +
3✔
1358
                "password of an existing wallet and unlock it.")
3✔
1359

3✔
1360
        // We currently don't distinguish between getting a password to be used
3✔
1361
        // for creation or unlocking, as a new wallet db will be created if
3✔
1362
        // none exists when creating the chain control.
3✔
1363
        select {
3✔
1364
        // The wallet is being created for the first time, we'll check to see
1365
        // if the user provided any entropy for seed creation. If so, then
1366
        // we'll create the wallet early to load the seed.
1367
        case initMsg := <-pwService.InitMsgs:
3✔
1368
                password := initMsg.Passphrase
3✔
1369
                cipherSeed := initMsg.WalletSeed
3✔
1370
                extendedKey := initMsg.WalletExtendedKey
3✔
1371
                watchOnlyAccounts := initMsg.WatchOnlyAccounts
3✔
1372
                recoveryWindow := initMsg.RecoveryWindow
3✔
1373

3✔
1374
                // Before we proceed, we'll check the internal version of the
3✔
1375
                // seed. If it's greater than the current key derivation
3✔
1376
                // version, then we'll return an error as we don't understand
3✔
1377
                // this.
3✔
1378
                if cipherSeed != nil &&
3✔
1379
                        !keychain.IsKnownVersion(cipherSeed.InternalVersion) {
3✔
1380

×
1381
                        return nil, fmt.Errorf("invalid internal "+
×
1382
                                "seed version %v, current max version is %v",
×
1383
                                cipherSeed.InternalVersion,
×
1384
                                keychain.CurrentKeyDerivationVersion)
×
1385
                }
×
1386

1387
                loader, err := btcwallet.NewWalletLoader(
3✔
1388
                        cfg.ActiveNetParams.Params, recoveryWindow,
3✔
1389
                        loaderOpts...,
3✔
1390
                )
3✔
1391
                if err != nil {
3✔
1392
                        return nil, err
×
1393
                }
×
1394

1395
                // With the seed, we can now use the wallet loader to create
1396
                // the wallet, then pass it back to avoid unlocking it again.
1397
                var (
3✔
1398
                        birthday  time.Time
3✔
1399
                        newWallet *wallet.Wallet
3✔
1400
                )
3✔
1401
                switch {
3✔
1402
                // A normal cipher seed was given, use the birthday encoded in
1403
                // it and create the wallet from that.
1404
                case cipherSeed != nil:
3✔
1405
                        birthday = cipherSeed.BirthdayTime()
3✔
1406
                        newWallet, err = loader.CreateNewWallet(
3✔
1407
                                password, password, cipherSeed.Entropy[:],
3✔
1408
                                birthday,
3✔
1409
                        )
3✔
1410

1411
                // No seed was given, we're importing a wallet from its extended
1412
                // private key.
1413
                case extendedKey != nil:
3✔
1414
                        birthday = initMsg.ExtendedKeyBirthday
3✔
1415
                        newWallet, err = loader.CreateNewWalletExtendedKey(
3✔
1416
                                password, password, extendedKey, birthday,
3✔
1417
                        )
3✔
1418

1419
                // Neither seed nor extended private key was given, so maybe the
1420
                // third option was chosen, the watch-only initialization. In
1421
                // this case we need to import each of the xpubs individually.
1422
                case watchOnlyAccounts != nil:
3✔
1423
                        if !cfg.RemoteSigner.Enable {
3✔
1424
                                return nil, fmt.Errorf("cannot initialize " +
×
1425
                                        "watch only wallet with remote " +
×
1426
                                        "signer config disabled")
×
1427
                        }
×
1428

1429
                        birthday = initMsg.WatchOnlyBirthday
3✔
1430
                        newWallet, err = loader.CreateNewWatchingOnlyWallet(
3✔
1431
                                password, birthday,
3✔
1432
                        )
3✔
1433
                        if err != nil {
3✔
1434
                                break
×
1435
                        }
1436

1437
                        err = importWatchOnlyAccounts(newWallet, initMsg)
3✔
1438

1439
                default:
×
1440
                        // The unlocker service made sure either the cipher seed
×
1441
                        // or the extended key is set so, we shouldn't get here.
×
1442
                        // The default case is just here for readability and
×
1443
                        // completeness.
×
1444
                        err = fmt.Errorf("cannot create wallet, neither seed " +
×
1445
                                "nor extended key was given")
×
1446
                }
1447
                if err != nil {
3✔
1448
                        // Don't leave the file open in case the new wallet
×
1449
                        // could not be created for whatever reason.
×
1450
                        if err := loader.UnloadWallet(); err != nil {
×
1451
                                ltndLog.Errorf("Could not unload new "+
×
1452
                                        "wallet: %v", err)
×
1453
                        }
×
1454
                        return nil, err
×
1455
                }
1456

1457
                // For new wallets, the ResetWalletTransactions flag is a no-op.
1458
                if cfg.ResetWalletTransactions {
6✔
1459
                        ltndLog.Warnf("Ignoring reset-wallet-transactions " +
3✔
1460
                                "flag for new wallet as it has no effect")
3✔
1461
                }
3✔
1462

1463
                return &walletunlocker.WalletUnlockParams{
3✔
1464
                        Password:        password,
3✔
1465
                        Birthday:        birthday,
3✔
1466
                        RecoveryWindow:  recoveryWindow,
3✔
1467
                        Wallet:          newWallet,
3✔
1468
                        ChansToRestore:  initMsg.ChanBackups,
3✔
1469
                        UnloadWallet:    loader.UnloadWallet,
3✔
1470
                        StatelessInit:   initMsg.StatelessInit,
3✔
1471
                        MacResponseChan: pwService.MacResponseChan,
3✔
1472
                        MacRootKey:      initMsg.MacRootKey,
3✔
1473
                }, nil
3✔
1474

1475
        // The wallet has already been created in the past, and is simply being
1476
        // unlocked. So we'll just return these passphrases.
1477
        case unlockMsg := <-pwService.UnlockMsgs:
3✔
1478
                // Resetting the transactions is something the user likely only
3✔
1479
                // wants to do once so we add a prominent warning to the log to
3✔
1480
                // remind the user to turn off the setting again after
3✔
1481
                // successful completion.
3✔
1482
                if cfg.ResetWalletTransactions {
6✔
1483
                        ltndLog.Warnf("Dropped all transaction history from " +
3✔
1484
                                "on-chain wallet. Remember to disable " +
3✔
1485
                                "reset-wallet-transactions flag for next " +
3✔
1486
                                "start of lnd")
3✔
1487
                }
3✔
1488

1489
                return &walletunlocker.WalletUnlockParams{
3✔
1490
                        Password:        unlockMsg.Passphrase,
3✔
1491
                        RecoveryWindow:  unlockMsg.RecoveryWindow,
3✔
1492
                        Wallet:          unlockMsg.Wallet,
3✔
1493
                        ChansToRestore:  unlockMsg.ChanBackups,
3✔
1494
                        UnloadWallet:    unlockMsg.UnloadWallet,
3✔
1495
                        StatelessInit:   unlockMsg.StatelessInit,
3✔
1496
                        MacResponseChan: pwService.MacResponseChan,
3✔
1497
                }, nil
3✔
1498

1499
        // If we got a shutdown signal we just return with an error immediately
1500
        case <-shutdownChan:
×
1501
                return nil, fmt.Errorf("shutting down")
×
1502
        }
1503
}
1504

1505
// importWatchOnlyAccounts imports all individual account xpubs into our wallet
1506
// which we created as watch-only.
1507
func importWatchOnlyAccounts(wallet *wallet.Wallet,
1508
        initMsg *walletunlocker.WalletInitMsg) error {
3✔
1509

3✔
1510
        scopes := make([]waddrmgr.ScopedIndex, 0, len(initMsg.WatchOnlyAccounts))
3✔
1511
        for scope := range initMsg.WatchOnlyAccounts {
6✔
1512
                scopes = append(scopes, scope)
3✔
1513
        }
3✔
1514

1515
        // We need to import the accounts in the correct order, otherwise the
1516
        // indices will be incorrect.
1517
        sort.Slice(scopes, func(i, j int) bool {
6✔
1518
                return scopes[i].Scope.Purpose < scopes[j].Scope.Purpose ||
3✔
1519
                        scopes[i].Index < scopes[j].Index
3✔
1520
        })
3✔
1521

1522
        for _, scope := range scopes {
6✔
1523
                addrSchema := waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0084]
3✔
1524

3✔
1525
                // We want witness pubkey hash by default, except for BIP49
3✔
1526
                // where we want mixed and BIP86 where we want taproot address
3✔
1527
                // formats.
3✔
1528
                switch scope.Scope.Purpose {
3✔
1529
                case waddrmgr.KeyScopeBIP0049Plus.Purpose,
1530
                        waddrmgr.KeyScopeBIP0086.Purpose:
3✔
1531

3✔
1532
                        addrSchema = waddrmgr.ScopeAddrMap[scope.Scope]
3✔
1533
                }
1534

1535
                // We want a human-readable account name. But for the default
1536
                // on-chain wallet we actually need to call it "default" to make
1537
                // sure everything works correctly.
1538
                name := fmt.Sprintf("%s/%d'", scope.Scope.String(), scope.Index)
3✔
1539
                if scope.Index == 0 {
6✔
1540
                        name = "default"
3✔
1541
                }
3✔
1542

1543
                _, err := wallet.ImportAccountWithScope(
3✔
1544
                        name, initMsg.WatchOnlyAccounts[scope],
3✔
1545
                        initMsg.WatchOnlyMasterFingerprint, scope.Scope,
3✔
1546
                        addrSchema,
3✔
1547
                )
3✔
1548
                if err != nil {
3✔
1549
                        return fmt.Errorf("could not import account %v: %w",
×
1550
                                name, err)
×
1551
                }
×
1552
        }
1553

1554
        return nil
3✔
1555
}
1556

1557
// handleNeutrinoPostgresDBMigration handles the migration of the neutrino db
1558
// to postgres. Initially we kept the neutrino db in the bolt db when running
1559
// with kvdb postgres backend. Now now move it to postgres as well. However we
1560
// need to make a distinction whether the user migrated the neutrino db to
1561
// postgres via lndinit or not. Currently if the db is not migrated we start
1562
// with a fresh db in postgres.
1563
//
1564
// TODO(ziggie): Also migrate the db to postgres in case it is still not
1565
// migrated ?
1566
func handleNeutrinoPostgresDBMigration(dbName, dbPath string,
1567
        cfg *Config) error {
×
1568

×
1569
        if !lnrpc.FileExists(dbName) {
×
1570
                return nil
×
1571
        }
×
1572

1573
        // Open bolt db to check if it is tombstoned. If it is we assume that
1574
        // the neutrino db was successfully migrated to postgres. We open it
1575
        // in read-only mode to avoid long db open times.
1576
        boltDB, err := kvdb.Open(
×
1577
                kvdb.BoltBackendName, dbName, true,
×
1578
                cfg.DB.Bolt.DBTimeout, true,
×
1579
        )
×
1580
        if err != nil {
×
1581
                return fmt.Errorf("failed to open bolt db: %w", err)
×
1582
        }
×
1583
        defer boltDB.Close()
×
1584

×
1585
        isTombstoned := false
×
1586
        err = boltDB.View(func(tx kvdb.RTx) error {
×
1587
                _, err = channeldb.CheckMarkerPresent(
×
1588
                        tx, channeldb.TombstoneKey,
×
1589
                )
×
1590

×
1591
                return err
×
1592
        }, func() {})
×
1593
        if err == nil {
×
1594
                isTombstoned = true
×
1595
        }
×
1596

1597
        if isTombstoned {
×
1598
                ltndLog.Infof("Neutrino Bolt DB is tombstoned, assuming " +
×
1599
                        "database was successfully migrated to postgres")
×
1600

×
1601
                return nil
×
1602
        }
×
1603

1604
        // If the db is not tombstoned, we remove the files and start fresh with
1605
        // postgres. This is the case when a user was running lnd with the
1606
        // postgres backend from the beginning without migrating from bolt.
1607
        ltndLog.Infof("Neutrino Bolt DB found but NOT tombstoned, removing " +
×
1608
                "it and starting fresh with postgres")
×
1609

×
1610
        filesToRemove := []string{
×
1611
                filepath.Join(dbPath, "block_headers.bin"),
×
1612
                filepath.Join(dbPath, "reg_filter_headers.bin"),
×
1613
                dbName,
×
1614
        }
×
1615

×
1616
        for _, file := range filesToRemove {
×
1617
                if err := os.Remove(file); err != nil {
×
1618
                        ltndLog.Warnf("Could not remove %s: %v", file, err)
×
1619
                }
×
1620
        }
1621

1622
        return nil
×
1623
}
1624

1625
// initNeutrinoBackend inits a new instance of the neutrino light client
1626
// backend given a target chain directory to store the chain state.
1627
func initNeutrinoBackend(ctx context.Context, cfg *Config, chainDir string,
1628
        blockCache *blockcache.BlockCache) (*neutrino.ChainService,
1629
        func(), error) {
1✔
1630

1✔
1631
        // Both channel validation flags are false by default but their meaning
1✔
1632
        // is the inverse of each other. Therefore both cannot be true. For
1✔
1633
        // every other case, the neutrino.validatechannels overwrites the
1✔
1634
        // routing.assumechanvalid value.
1✔
1635
        if cfg.NeutrinoMode.ValidateChannels && cfg.Routing.AssumeChannelValid {
1✔
1636
                return nil, nil, fmt.Errorf("can't set both " +
×
1637
                        "neutrino.validatechannels and routing." +
×
1638
                        "assumechanvalid to true at the same time")
×
1639
        }
×
1640
        cfg.Routing.AssumeChannelValid = !cfg.NeutrinoMode.ValidateChannels
1✔
1641

1✔
1642
        // First we'll open the database file for neutrino, creating the
1✔
1643
        // database if needed. We append the normalized network name here to
1✔
1644
        // match the behavior of btcwallet.
1✔
1645
        dbPath := filepath.Join(
1✔
1646
                chainDir, lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
1✔
1647
        )
1✔
1648

1✔
1649
        // Ensure that the neutrino db path exists.
1✔
1650
        if err := os.MkdirAll(dbPath, 0700); err != nil {
1✔
1651
                return nil, nil, err
×
1652
        }
×
1653

1654
        var (
1✔
1655
                db  walletdb.DB
1✔
1656
                err error
1✔
1657
        )
1✔
1658
        switch {
1✔
1659
        case cfg.DB.Backend == kvdb.SqliteBackendName:
×
1660
                sqliteConfig := lncfg.GetSqliteConfigKVDB(cfg.DB.Sqlite)
×
1661
                db, err = kvdb.Open(
×
1662
                        kvdb.SqliteBackendName, ctx, sqliteConfig, dbPath,
×
1663
                        lncfg.SqliteNeutrinoDBName, lncfg.NSNeutrinoDB,
×
1664
                )
×
1665

1666
        case cfg.DB.Backend == kvdb.PostgresBackendName:
×
1667
                dbName := filepath.Join(dbPath, lncfg.NeutrinoDBName)
×
1668

×
1669
                // This code needs to be in place because we did not start
×
1670
                // the postgres backend for neutrino at the beginning. Now we
×
1671
                // are also moving it into the postgres backend so we can phase
×
1672
                // out the bolt backend.
×
1673
                err = handleNeutrinoPostgresDBMigration(dbName, dbPath, cfg)
×
1674
                if err != nil {
×
1675
                        return nil, nil, err
×
1676
                }
×
1677

1678
                postgresConfig := lncfg.GetPostgresConfigKVDB(cfg.DB.Postgres)
×
1679
                db, err = kvdb.Open(
×
1680
                        kvdb.PostgresBackendName, ctx, postgresConfig,
×
1681
                        lncfg.NSNeutrinoDB,
×
1682
                )
×
1683

1684
        default:
1✔
1685
                dbName := filepath.Join(dbPath, lncfg.NeutrinoDBName)
1✔
1686
                db, err = walletdb.Create(
1✔
1687
                        kvdb.BoltBackendName, dbName, !cfg.SyncFreelist,
1✔
1688
                        cfg.DB.Bolt.DBTimeout, false,
1✔
1689
                )
1✔
1690
        }
1691
        if err != nil {
1✔
1692
                return nil, nil, fmt.Errorf("unable to create "+
×
1693
                        "neutrino database: %v", err)
×
1694
        }
×
1695

1696
        headerStateAssertion, err := parseHeaderStateAssertion(
1✔
1697
                cfg.NeutrinoMode.AssertFilterHeader,
1✔
1698
        )
1✔
1699
        if err != nil {
1✔
1700
                db.Close()
×
1701
                return nil, nil, err
×
1702
        }
×
1703

1704
        // With the database open, we can now create an instance of the
1705
        // neutrino light client. We pass in relevant configuration parameters
1706
        // required.
1707
        config := neutrino.Config{
1✔
1708
                DataDir:      dbPath,
1✔
1709
                Database:     db,
1✔
1710
                ChainParams:  *cfg.ActiveNetParams.Params,
1✔
1711
                AddPeers:     cfg.NeutrinoMode.AddPeers,
1✔
1712
                ConnectPeers: cfg.NeutrinoMode.ConnectPeers,
1✔
1713
                Dialer: func(addr net.Addr) (net.Conn, error) {
2✔
1714
                        return cfg.net.Dial(
1✔
1715
                                addr.Network(), addr.String(),
1✔
1716
                                cfg.ConnectionTimeout,
1✔
1717
                        )
1✔
1718
                },
1✔
1719
                NameResolver: func(host string) ([]net.IP, error) {
1✔
1720
                        addrs, err := cfg.net.LookupHost(host)
1✔
1721
                        if err != nil {
1✔
1722
                                return nil, err
×
1723
                        }
×
1724

1725
                        ips := make([]net.IP, 0, len(addrs))
1✔
1726
                        for _, strIP := range addrs {
2✔
1727
                                ip := net.ParseIP(strIP)
1✔
1728
                                if ip == nil {
1✔
1729
                                        continue
×
1730
                                }
1731

1732
                                ips = append(ips, ip)
1✔
1733
                        }
1734

1735
                        return ips, nil
1✔
1736
                },
1737
                AssertFilterHeader: headerStateAssertion,
1738
                BlockCache:         blockCache.Cache,
1739
                BroadcastTimeout:   cfg.NeutrinoMode.BroadcastTimeout,
1740
                PersistToDisk:      cfg.NeutrinoMode.PersistFilters,
1741
        }
1742

1743
        if cfg.NeutrinoMode.MaxPeers <= 0 {
1✔
1744
                return nil, nil, fmt.Errorf("a non-zero number must be set " +
×
1745
                        "for neutrino max peers")
×
1746
        }
×
1747
        neutrino.MaxPeers = cfg.NeutrinoMode.MaxPeers
1✔
1748
        neutrino.BanDuration = time.Hour * 48
1✔
1749
        neutrino.UserAgentName = cfg.NeutrinoMode.UserAgentName
1✔
1750
        neutrino.UserAgentVersion = cfg.NeutrinoMode.UserAgentVersion
1✔
1751

1✔
1752
        neutrinoCS, err := neutrino.NewChainService(config)
1✔
1753
        if err != nil {
1✔
1754
                db.Close()
×
1755
                return nil, nil, fmt.Errorf("unable to create neutrino light "+
×
1756
                        "client: %v", err)
×
1757
        }
×
1758

1759
        if err := neutrinoCS.Start(); err != nil {
1✔
1760
                db.Close()
×
1761
                return nil, nil, err
×
1762
        }
×
1763

1764
        cleanUp := func() {
2✔
1765
                if err := neutrinoCS.Stop(); err != nil {
1✔
1766
                        ltndLog.Infof("Unable to stop neutrino light client: "+
×
1767
                                "%v", err)
×
1768
                }
×
1769
                db.Close()
1✔
1770
        }
1771

1772
        return neutrinoCS, cleanUp, nil
1✔
1773
}
1774

1775
// parseHeaderStateAssertion parses the user-specified neutrino header state
1776
// into a headerfs.FilterHeader.
1777
func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) {
1✔
1778
        if len(state) == 0 {
2✔
1779
                return nil, nil
1✔
1780
        }
1✔
1781

1782
        split := strings.Split(state, ":")
×
1783
        if len(split) != 2 {
×
1784
                return nil, fmt.Errorf("header state assertion %v in "+
×
1785
                        "unexpected format, expected format height:hash", state)
×
1786
        }
×
1787

1788
        height, err := strconv.ParseUint(split[0], 10, 32)
×
1789
        if err != nil {
×
1790
                return nil, fmt.Errorf("invalid filter header height: %w", err)
×
1791
        }
×
1792

1793
        hash, err := chainhash.NewHashFromStr(split[1])
×
1794
        if err != nil {
×
1795
                return nil, fmt.Errorf("invalid filter header hash: %w", err)
×
1796
        }
×
1797

1798
        return &headerfs.FilterHeader{
×
1799
                Height:     uint32(height),
×
1800
                FilterHash: *hash,
×
1801
        }, nil
×
1802
}
1803

1804
// broadcastErrorMapper maps errors from bitcoin backends other than neutrino to
1805
// the neutrino BroadcastError which allows the Rebroadcaster which currently
1806
// resides in the neutrino package to use all of its functionalities.
1807
func broadcastErrorMapper(err error) error {
2✔
1808
        var returnErr error
2✔
1809

2✔
1810
        // We only filter for specific backend errors which are relevant for the
2✔
1811
        // Rebroadcaster.
2✔
1812
        switch {
2✔
1813
        // This makes sure the tx is removed from the rebroadcaster once it is
1814
        // confirmed.
1815
        case errors.Is(err, chain.ErrTxAlreadyKnown),
1816
                errors.Is(err, chain.ErrTxAlreadyConfirmed):
1✔
1817

1✔
1818
                returnErr = &pushtx.BroadcastError{
1✔
1819
                        Code:   pushtx.Confirmed,
1✔
1820
                        Reason: err.Error(),
1✔
1821
                }
1✔
1822

1823
        // Transactions which are still in mempool but might fall out because
1824
        // of low fees are rebroadcasted despite of their backend error.
1825
        case errors.Is(err, chain.ErrTxAlreadyInMempool):
×
1826
                returnErr = &pushtx.BroadcastError{
×
1827
                        Code:   pushtx.Mempool,
×
1828
                        Reason: err.Error(),
×
1829
                }
×
1830

1831
        // Transactions which are not accepted into mempool because of low fees
1832
        // in the first place are rebroadcasted despite of their backend error.
1833
        // Mempool conditions change over time so it makes sense to retry
1834
        // publishing the transaction. Moreover we log the detailed error so the
1835
        // user can intervene and increase the size of his mempool or increase
1836
        // his min relay fee configuration.
1837
        case errors.Is(err, chain.ErrMempoolMinFeeNotMet),
1838
                errors.Is(err, chain.ErrMinRelayFeeNotMet):
×
1839

×
1840
                ltndLog.Warnf("Error while broadcasting transaction: %v", err)
×
1841

×
1842
                returnErr = &pushtx.BroadcastError{
×
1843
                        Code:   pushtx.Mempool,
×
1844
                        Reason: err.Error(),
×
1845
                }
×
1846
        }
1847

1848
        return returnErr
2✔
1849
}
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