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

lightningnetwork / lnd / 18016273007

25 Sep 2025 05:55PM UTC coverage: 54.653% (-12.0%) from 66.622%
18016273007

Pull #10248

github

web-flow
Merge 128443298 into b09b20c69
Pull Request #10248: Enforce TLV when creating a Route

25 of 30 new or added lines in 4 files covered. (83.33%)

23906 existing lines in 281 files now uncovered.

109536 of 200421 relevant lines covered (54.65%)

21816.97 hits per line

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

0.0
/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
        // graphMigration is the version number for the graph migration
75
        // that migrates the KV graph to the native SQL schema.
76
        graphMigration = 10
77
)
78

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

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

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

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

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

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

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

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

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

155
        // ExternalValidator is a type that can provide external macaroon
156
        // validation.
157
        ExternalValidator
158

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

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

167
        // ChainControlBuilder is a type that can provide a custom wallet
168
        // implementation.
169
        ChainControlBuilder
170

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

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

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

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

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

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

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

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

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

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

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

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

230
        watchOnly        bool
231
        migrateWatchOnly bool
232
        pwService        *walletunlocker.UnlockerService
233
}
234

235
// NewDefaultWalletImpl creates a new default wallet implementation.
236
func NewDefaultWalletImpl(cfg *Config, logger btclog.Logger,
UNCOV
237
        interceptor signal.Interceptor, watchOnly bool) *DefaultWalletImpl {
×
UNCOV
238

×
UNCOV
239
        return &DefaultWalletImpl{
×
UNCOV
240
                cfg:         cfg,
×
UNCOV
241
                logger:      logger,
×
UNCOV
242
                interceptor: interceptor,
×
UNCOV
243
                watchOnly:   watchOnly,
×
UNCOV
244
                pwService:   createWalletUnlockerService(cfg),
×
UNCOV
245
        }
×
UNCOV
246
}
×
247

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

×
UNCOV
257
        return lnrpc.RegisterWalletUnlockerHandlerFromEndpoint(
×
UNCOV
258
                ctx, mux, restProxyDest, restDialOpts,
×
UNCOV
259
        )
×
UNCOV
260
}
×
261

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

×
UNCOV
270
        return nil
×
UNCOV
271
}
×
272

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

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

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

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

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

UNCOV
321
                                fn()
×
322
                        }
323
                }
324
        )
UNCOV
325
        defer func() {
×
UNCOV
326
                if earlyExit {
×
327
                        cleanUp()
×
328
                }
×
329
        }()
330

331
        // Initialize a new block cache.
UNCOV
332
        blockCache := blockcache.NewBlockCache(d.cfg.BlockCacheSize)
×
UNCOV
333

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

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

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

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

UNCOV
375
        if !walletExists {
×
UNCOV
376
                interceptorChain.SetWalletNotCreated()
×
UNCOV
377
        } else {
×
UNCOV
378
                interceptorChain.SetWalletLocked()
×
UNCOV
379
        }
×
380

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

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

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

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

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

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

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

435
                privateWalletPw = pwBytes
×
436
                publicWalletPw = pwBytes
×
437
                walletInitParams.Wallet = unlockedWallet
×
438
                walletInitParams.UnloadWallet = unloadWalletFn
×
439

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

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

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

UNCOV
469
                if walletInitParams.RecoveryWindow > 0 {
×
UNCOV
470
                        d.logger.Infof("Wallet recovery mode enabled with "+
×
UNCOV
471
                                "address lookahead of %d addresses",
×
UNCOV
472
                                walletInitParams.RecoveryWindow)
×
UNCOV
473
                }
×
474
        }
475

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

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

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

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

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

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

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

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

586
                // We add the macaroon service to our RPC interceptor. This
587
                // will start checking macaroons against permissions on every
588
                // RPC invocation.
UNCOV
589
                interceptorChain.AddMacaroonService(macaroonService)
×
590
        }
591

592
        // Now that the wallet password has been provided, transition the RPC
593
        // state into Unlocked.
UNCOV
594
        interceptorChain.SetWalletUnlocked()
×
UNCOV
595

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

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

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

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

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

×
UNCOV
672
        // Parse coin selection strategy.
×
UNCOV
673
        switch d.cfg.CoinSelectionStrategy {
×
UNCOV
674
        case "largest":
×
UNCOV
675
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionLargest
×
676

677
        case "random":
×
678
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionRandom
×
679

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

UNCOV
685
        earlyExit = false
×
UNCOV
686
        return partialChainControl, walletConfig, cleanUp, nil
×
687
}
688

689
// proxyBlockEpoch proxies a block epoch subsections to the underlying neutrino
690
// rebroadcaster client.
691
func proxyBlockEpoch(
692
        notifier chainntnfs.ChainNotifier) func() (*blockntfns.Subscription,
UNCOV
693
        error) {
×
UNCOV
694

×
UNCOV
695
        return func() (*blockntfns.Subscription, error) {
×
UNCOV
696
                blockEpoch, err := notifier.RegisterBlockEpochNtfn(
×
UNCOV
697
                        nil,
×
UNCOV
698
                )
×
UNCOV
699
                if err != nil {
×
700
                        return nil, err
×
701
                }
×
702

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

×
UNCOV
714
                                sub.Notifications <- ntfn
×
UNCOV
715
                        }
×
716
                }()
717

UNCOV
718
                return &sub, nil
×
719
        }
720
}
721

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

727
        *pushtx.Broadcaster
728
}
729

730
// newWalletReBroadcaster creates a new instance of the walletReBroadcaster.
731
func newWalletReBroadcaster(
UNCOV
732
        broadcaster *pushtx.Broadcaster) *walletReBroadcaster {
×
UNCOV
733

×
UNCOV
734
        return &walletReBroadcaster{
×
UNCOV
735
                Broadcaster: broadcaster,
×
UNCOV
736
        }
×
UNCOV
737
}
×
738

739
// Start launches all goroutines the rebroadcaster needs to operate.
UNCOV
740
func (w *walletReBroadcaster) Start() error {
×
UNCOV
741
        defer w.started.Store(true)
×
UNCOV
742

×
UNCOV
743
        return w.Broadcaster.Start()
×
UNCOV
744
}
×
745

746
// Started returns true if the broadcaster is already active.
UNCOV
747
func (w *walletReBroadcaster) Started() bool {
×
UNCOV
748
        return w.started.Load()
×
UNCOV
749
}
×
750

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

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

UNCOV
768
        keyRing := keychain.NewBtcWalletKeyRing(
×
UNCOV
769
                walletController.InternalWallet(), walletConfig.CoinType,
×
UNCOV
770
        )
×
UNCOV
771

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

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

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

UNCOV
813
                lnWalletConfig.Rebroadcaster = newWalletReBroadcaster(
×
UNCOV
814
                        pushtx.NewBroadcaster(&broadcastCfg),
×
UNCOV
815
                )
×
816
        }
817

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

UNCOV
829
        return activeChainControl, cleanUp, nil
×
830
}
831

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

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

×
UNCOV
847
        return &RPCSignerWalletImpl{
×
UNCOV
848
                DefaultWalletImpl: &DefaultWalletImpl{
×
UNCOV
849
                        cfg:              cfg,
×
UNCOV
850
                        logger:           logger,
×
UNCOV
851
                        interceptor:      interceptor,
×
UNCOV
852
                        watchOnly:        true,
×
UNCOV
853
                        migrateWatchOnly: migrateWatchOnly,
×
UNCOV
854
                        pwService:        createWalletUnlockerService(cfg),
×
UNCOV
855
                },
×
UNCOV
856
        }
×
UNCOV
857
}
×
858

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

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

UNCOV
877
        baseKeyRing := keychain.NewBtcWalletKeyRing(
×
UNCOV
878
                walletController.InternalWallet(), walletConfig.CoinType,
×
UNCOV
879
        )
×
UNCOV
880

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

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

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

UNCOV
917
        return activeChainControl, cleanUp, nil
×
918
}
919

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

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

931
        // HeightHintDB is the database that stores height hints for spends.
932
        HeightHintDB kvdb.Backend
933

934
        // InvoiceDB is the database that stores information about invoices.
935
        InvoiceDB invoices.InvoiceDB
936

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

941
        // MacaroonDB is the database that stores macaroon root keys.
942
        MacaroonDB kvdb.Backend
943

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

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

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

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

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

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

974
// NewDefaultDatabaseBuilder returns a new instance of the default database
975
// builder.
976
func NewDefaultDatabaseBuilder(cfg *Config,
UNCOV
977
        logger btclog.Logger) *DefaultDatabaseBuilder {
×
UNCOV
978

×
UNCOV
979
        return &DefaultDatabaseBuilder{
×
UNCOV
980
                cfg:    cfg,
×
UNCOV
981
                logger: logger,
×
UNCOV
982
        }
×
UNCOV
983
}
×
984

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

×
UNCOV
991
        d.logger.Infof("Opening the main database, this might take a few " +
×
UNCOV
992
                "minutes...")
×
UNCOV
993

×
UNCOV
994
        cfg := d.cfg
×
UNCOV
995
        if cfg.DB.Backend == lncfg.BoltBackend {
×
UNCOV
996
                d.logger.Infof("Opening bbolt database, sync_freelist=%v, "+
×
UNCOV
997
                        "auto_compact=%v", !cfg.DB.Bolt.NoFreelistSync,
×
UNCOV
998
                        cfg.DB.Bolt.AutoCompact)
×
UNCOV
999
        }
×
1000

UNCOV
1001
        startOpenTime := time.Now()
×
UNCOV
1002

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

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

UNCOV
1043
        graphDBOptions := []graphdb.StoreOptionModifier{
×
UNCOV
1044
                graphdb.WithRejectCacheSize(cfg.Caches.RejectCacheSize),
×
UNCOV
1045
                graphdb.WithChannelCacheSize(cfg.Caches.ChannelCacheSize),
×
UNCOV
1046
                graphdb.WithBatchCommitInterval(cfg.DB.BatchCommitInterval),
×
UNCOV
1047
        }
×
UNCOV
1048

×
UNCOV
1049
        chanGraphOpts := []graphdb.ChanGraphOption{
×
UNCOV
1050
                graphdb.WithUseGraphCache(!cfg.DB.NoGraphCache),
×
UNCOV
1051
        }
×
UNCOV
1052

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

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

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

1087
        case err != nil:
×
1088
                cleanUp()
×
1089

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

1095
        // The graph store implementation we will use depends on whether
1096
        // native SQL is enabled or not.
UNCOV
1097
        var graphStore graphdb.V1Store
×
UNCOV
1098

×
UNCOV
1099
        // Instantiate a native SQL store if the flag is set.
×
UNCOV
1100
        if d.cfg.DB.UseNativeSQL {
×
1101
                migrations := sqldb.GetMigrations()
×
1102

×
1103
                queryCfg := &d.cfg.DB.Sqlite.QueryConfig
×
1104
                if d.cfg.DB.Backend == lncfg.PostgresBackend {
×
1105
                        queryCfg = &d.cfg.DB.Postgres.QueryConfig
×
1106
                }
×
1107

1108
                // If the user has not explicitly disabled the SQL invoice
1109
                // migration, attach the custom migration function to invoice
1110
                // migration (version 7). Even if this custom migration is
1111
                // disabled, the regular native SQL store migrations will still
1112
                // run. If the database version is already above this custom
1113
                // migration's version (7), it will be skipped permanently,
1114
                // regardless of the flag.
1115
                if !d.cfg.DB.SkipNativeSQLMigration {
×
1116
                        invoiceMig := func(tx *sqlc.Queries) error {
×
1117
                                err := invoices.MigrateInvoicesToSQL(
×
1118
                                        ctx, dbs.ChanStateDB.Backend,
×
1119
                                        dbs.ChanStateDB, tx,
×
1120
                                        invoiceMigrationBatchSize,
×
1121
                                )
×
1122
                                if err != nil {
×
1123
                                        return fmt.Errorf("failed to migrate "+
×
1124
                                                "invoices to SQL: %w", err)
×
1125
                                }
×
1126

1127
                                // Set the invoice bucket tombstone to indicate
1128
                                // that the migration has been completed.
1129
                                d.logger.Debugf("Setting invoice bucket " +
×
1130
                                        "tombstone")
×
1131

×
1132
                                //nolint:ll
×
1133
                                return dbs.ChanStateDB.SetInvoiceBucketTombstone()
×
1134
                        }
1135

1136
                        graphMig := func(tx *sqlc.Queries) error {
×
1137
                                cfg := &graphdb.SQLStoreConfig{
×
1138
                                        //nolint:ll
×
1139
                                        ChainHash: *d.cfg.ActiveNetParams.GenesisHash,
×
1140
                                        QueryCfg:  queryCfg,
×
1141
                                }
×
1142
                                err := graphdb.MigrateGraphToSQL(
×
1143
                                        ctx, cfg, dbs.ChanStateDB.Backend, tx,
×
1144
                                )
×
1145
                                if err != nil {
×
1146
                                        return fmt.Errorf("failed to migrate "+
×
1147
                                                "graph to SQL: %w", err)
×
1148
                                }
×
1149

1150
                                return nil
×
1151
                        }
1152

1153
                        // Make sure we attach the custom migration function to
1154
                        // the correct migration version.
1155
                        for i := 0; i < len(migrations); i++ {
×
1156
                                version := migrations[i].Version
×
1157
                                switch version {
×
1158
                                case invoiceMigration:
×
1159
                                        migrations[i].MigrationFn = invoiceMig
×
1160

×
1161
                                        continue
×
1162
                                case graphMigration:
×
1163
                                        migrations[i].MigrationFn = graphMig
×
1164

×
1165
                                        continue
×
1166

1167
                                default:
×
1168
                                }
1169

1170
                                migFn, ok := d.getSQLMigration(
×
1171
                                        ctx, version, dbs.ChanStateDB.Backend,
×
1172
                                )
×
1173
                                if !ok {
×
1174
                                        continue
×
1175
                                }
1176

1177
                                migrations[i].MigrationFn = migFn
×
1178
                        }
1179
                }
1180

1181
                // We need to apply all migrations to the native SQL store
1182
                // before we can use it.
1183
                err = dbs.NativeSQLStore.ApplyAllMigrations(ctx, migrations)
×
1184
                if err != nil {
×
1185
                        cleanUp()
×
1186
                        err = fmt.Errorf("faild to run migrations for the "+
×
1187
                                "native SQL store: %w", err)
×
1188
                        d.logger.Error(err)
×
1189

×
1190
                        return nil, nil, err
×
1191
                }
×
1192

1193
                // With the DB ready and migrations applied, we can now create
1194
                // the base DB and transaction executor for the native SQL
1195
                // invoice store.
1196
                baseDB := dbs.NativeSQLStore.GetBaseDB()
×
1197
                invoiceExecutor := sqldb.NewTransactionExecutor(
×
1198
                        baseDB, func(tx *sql.Tx) invoices.SQLInvoiceQueries {
×
1199
                                return baseDB.WithTx(tx)
×
1200
                        },
×
1201
                )
1202

1203
                sqlInvoiceDB := invoices.NewSQLStore(
×
1204
                        invoiceExecutor, clock.NewDefaultClock(),
×
1205
                )
×
1206

×
1207
                dbs.InvoiceDB = sqlInvoiceDB
×
1208

×
1209
                graphExecutor := sqldb.NewTransactionExecutor(
×
1210
                        baseDB, func(tx *sql.Tx) graphdb.SQLQueries {
×
1211
                                return baseDB.WithTx(tx)
×
1212
                        },
×
1213
                )
1214

1215
                graphStore, err = graphdb.NewSQLStore(
×
1216
                        &graphdb.SQLStoreConfig{
×
1217
                                ChainHash: *d.cfg.ActiveNetParams.GenesisHash,
×
1218
                                QueryCfg:  queryCfg,
×
1219
                        },
×
1220
                        graphExecutor, graphDBOptions...,
×
1221
                )
×
1222
                if err != nil {
×
1223
                        err = fmt.Errorf("unable to get graph store: %w", err)
×
1224
                        d.logger.Error(err)
×
1225

×
1226
                        return nil, nil, err
×
1227
                }
×
UNCOV
1228
        } else {
×
UNCOV
1229
                // Check if the invoice bucket tombstone is set. If it is, we
×
UNCOV
1230
                // need to return and ask the user switch back to using the
×
UNCOV
1231
                // native SQL store.
×
UNCOV
1232
                ripInvoices, err := dbs.ChanStateDB.GetInvoiceBucketTombstone()
×
UNCOV
1233
                if err != nil {
×
1234
                        err = fmt.Errorf("unable to check invoice bucket "+
×
1235
                                "tombstone: %w", err)
×
1236
                        d.logger.Error(err)
×
1237

×
1238
                        return nil, nil, err
×
1239
                }
×
UNCOV
1240
                if ripInvoices {
×
1241
                        err = fmt.Errorf("invoices bucket tombstoned, please " +
×
1242
                                "switch back to native SQL")
×
1243
                        d.logger.Error(err)
×
1244

×
1245
                        return nil, nil, err
×
1246
                }
×
1247

UNCOV
1248
                dbs.InvoiceDB = dbs.ChanStateDB
×
UNCOV
1249

×
UNCOV
1250
                graphStore, err = graphdb.NewKVStore(
×
UNCOV
1251
                        databaseBackends.GraphDB, graphDBOptions...,
×
UNCOV
1252
                )
×
UNCOV
1253
                if err != nil {
×
1254
                        return nil, nil, err
×
1255
                }
×
1256
        }
1257

UNCOV
1258
        dbs.GraphDB, err = graphdb.NewChannelGraph(graphStore, chanGraphOpts...)
×
UNCOV
1259
        if err != nil {
×
1260
                cleanUp()
×
1261

×
1262
                err = fmt.Errorf("unable to open channel graph DB: %w", err)
×
1263
                d.logger.Error(err)
×
1264

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

1268
        // Mount the payments DB which is only KV for now.
1269
        //
1270
        // TODO(ziggie): Add support for SQL payments DB.
1271
        // Mount the payments DB for the KV store.
UNCOV
1272
        paymentsDBOptions := []paymentsdb.OptionModifier{
×
UNCOV
1273
                paymentsdb.WithKeepFailedPaymentAttempts(
×
UNCOV
1274
                        cfg.KeepFailedPaymentAttempts,
×
UNCOV
1275
                ),
×
UNCOV
1276
        }
×
UNCOV
1277
        kvPaymentsDB, err := paymentsdb.NewKVStore(
×
UNCOV
1278
                dbs.ChanStateDB,
×
UNCOV
1279
                paymentsDBOptions...,
×
UNCOV
1280
        )
×
UNCOV
1281
        if err != nil {
×
1282
                cleanUp()
×
1283

×
1284
                err = fmt.Errorf("unable to open payments DB: %w", err)
×
1285
                d.logger.Error(err)
×
1286

×
1287
                return nil, nil, err
×
1288
        }
×
UNCOV
1289
        dbs.PaymentsDB = kvPaymentsDB
×
UNCOV
1290

×
UNCOV
1291
        // Wrap the watchtower client DB and make sure we clean up.
×
UNCOV
1292
        if cfg.WtClient.Active {
×
UNCOV
1293
                dbs.TowerClientDB, err = wtdb.OpenClientDB(
×
UNCOV
1294
                        databaseBackends.TowerClientDB,
×
UNCOV
1295
                )
×
UNCOV
1296
                if err != nil {
×
1297
                        cleanUp()
×
1298

×
1299
                        err = fmt.Errorf("unable to open %s database: %w",
×
1300
                                lncfg.NSTowerClientDB, err)
×
1301
                        d.logger.Error(err)
×
1302
                        return nil, nil, err
×
1303
                }
×
1304
        }
1305

1306
        // Wrap the watchtower server DB and make sure we clean up.
UNCOV
1307
        if cfg.Watchtower.Active {
×
UNCOV
1308
                dbs.TowerServerDB, err = wtdb.OpenTowerDB(
×
UNCOV
1309
                        databaseBackends.TowerServerDB,
×
UNCOV
1310
                )
×
UNCOV
1311
                if err != nil {
×
1312
                        cleanUp()
×
1313

×
1314
                        err = fmt.Errorf("unable to open %s database: %w",
×
1315
                                lncfg.NSTowerServerDB, err)
×
1316
                        d.logger.Error(err)
×
1317
                        return nil, nil, err
×
1318
                }
×
1319
        }
1320

UNCOV
1321
        openTime := time.Since(startOpenTime)
×
UNCOV
1322
        d.logger.Infof("Database(s) now open (time_to_open=%v)!", openTime)
×
UNCOV
1323

×
UNCOV
1324
        return dbs, cleanUp, nil
×
1325
}
1326

1327
// waitForWalletPassword blocks until a password is provided by the user to
1328
// this RPC server.
1329
func waitForWalletPassword(cfg *Config,
1330
        pwService *walletunlocker.UnlockerService,
1331
        loaderOpts []btcwallet.LoaderOption, shutdownChan <-chan struct{}) (
UNCOV
1332
        *walletunlocker.WalletUnlockParams, error) {
×
UNCOV
1333

×
UNCOV
1334
        // Wait for user to provide the password.
×
UNCOV
1335
        ltndLog.Infof("Waiting for wallet encryption password. Use `lncli " +
×
UNCOV
1336
                "create` to create a wallet, `lncli unlock` to unlock an " +
×
UNCOV
1337
                "existing wallet, or `lncli changepassword` to change the " +
×
UNCOV
1338
                "password of an existing wallet and unlock it.")
×
UNCOV
1339

×
UNCOV
1340
        // We currently don't distinguish between getting a password to be used
×
UNCOV
1341
        // for creation or unlocking, as a new wallet db will be created if
×
UNCOV
1342
        // none exists when creating the chain control.
×
UNCOV
1343
        select {
×
1344
        // The wallet is being created for the first time, we'll check to see
1345
        // if the user provided any entropy for seed creation. If so, then
1346
        // we'll create the wallet early to load the seed.
UNCOV
1347
        case initMsg := <-pwService.InitMsgs:
×
UNCOV
1348
                password := initMsg.Passphrase
×
UNCOV
1349
                cipherSeed := initMsg.WalletSeed
×
UNCOV
1350
                extendedKey := initMsg.WalletExtendedKey
×
UNCOV
1351
                watchOnlyAccounts := initMsg.WatchOnlyAccounts
×
UNCOV
1352
                recoveryWindow := initMsg.RecoveryWindow
×
UNCOV
1353

×
UNCOV
1354
                // Before we proceed, we'll check the internal version of the
×
UNCOV
1355
                // seed. If it's greater than the current key derivation
×
UNCOV
1356
                // version, then we'll return an error as we don't understand
×
UNCOV
1357
                // this.
×
UNCOV
1358
                if cipherSeed != nil &&
×
UNCOV
1359
                        !keychain.IsKnownVersion(cipherSeed.InternalVersion) {
×
1360

×
1361
                        return nil, fmt.Errorf("invalid internal "+
×
1362
                                "seed version %v, current max version is %v",
×
1363
                                cipherSeed.InternalVersion,
×
1364
                                keychain.CurrentKeyDerivationVersion)
×
1365
                }
×
1366

UNCOV
1367
                loader, err := btcwallet.NewWalletLoader(
×
UNCOV
1368
                        cfg.ActiveNetParams.Params, recoveryWindow,
×
UNCOV
1369
                        loaderOpts...,
×
UNCOV
1370
                )
×
UNCOV
1371
                if err != nil {
×
1372
                        return nil, err
×
1373
                }
×
1374

1375
                // With the seed, we can now use the wallet loader to create
1376
                // the wallet, then pass it back to avoid unlocking it again.
UNCOV
1377
                var (
×
UNCOV
1378
                        birthday  time.Time
×
UNCOV
1379
                        newWallet *wallet.Wallet
×
UNCOV
1380
                )
×
UNCOV
1381
                switch {
×
1382
                // A normal cipher seed was given, use the birthday encoded in
1383
                // it and create the wallet from that.
UNCOV
1384
                case cipherSeed != nil:
×
UNCOV
1385
                        birthday = cipherSeed.BirthdayTime()
×
UNCOV
1386
                        newWallet, err = loader.CreateNewWallet(
×
UNCOV
1387
                                password, password, cipherSeed.Entropy[:],
×
UNCOV
1388
                                birthday,
×
UNCOV
1389
                        )
×
1390

1391
                // No seed was given, we're importing a wallet from its extended
1392
                // private key.
UNCOV
1393
                case extendedKey != nil:
×
UNCOV
1394
                        birthday = initMsg.ExtendedKeyBirthday
×
UNCOV
1395
                        newWallet, err = loader.CreateNewWalletExtendedKey(
×
UNCOV
1396
                                password, password, extendedKey, birthday,
×
UNCOV
1397
                        )
×
1398

1399
                // Neither seed nor extended private key was given, so maybe the
1400
                // third option was chosen, the watch-only initialization. In
1401
                // this case we need to import each of the xpubs individually.
UNCOV
1402
                case watchOnlyAccounts != nil:
×
UNCOV
1403
                        if !cfg.RemoteSigner.Enable {
×
1404
                                return nil, fmt.Errorf("cannot initialize " +
×
1405
                                        "watch only wallet with remote " +
×
1406
                                        "signer config disabled")
×
1407
                        }
×
1408

UNCOV
1409
                        birthday = initMsg.WatchOnlyBirthday
×
UNCOV
1410
                        newWallet, err = loader.CreateNewWatchingOnlyWallet(
×
UNCOV
1411
                                password, birthday,
×
UNCOV
1412
                        )
×
UNCOV
1413
                        if err != nil {
×
1414
                                break
×
1415
                        }
1416

UNCOV
1417
                        err = importWatchOnlyAccounts(newWallet, initMsg)
×
1418

1419
                default:
×
1420
                        // The unlocker service made sure either the cipher seed
×
1421
                        // or the extended key is set so, we shouldn't get here.
×
1422
                        // The default case is just here for readability and
×
1423
                        // completeness.
×
1424
                        err = fmt.Errorf("cannot create wallet, neither seed " +
×
1425
                                "nor extended key was given")
×
1426
                }
UNCOV
1427
                if err != nil {
×
1428
                        // Don't leave the file open in case the new wallet
×
1429
                        // could not be created for whatever reason.
×
1430
                        if err := loader.UnloadWallet(); err != nil {
×
1431
                                ltndLog.Errorf("Could not unload new "+
×
1432
                                        "wallet: %v", err)
×
1433
                        }
×
1434
                        return nil, err
×
1435
                }
1436

1437
                // For new wallets, the ResetWalletTransactions flag is a no-op.
UNCOV
1438
                if cfg.ResetWalletTransactions {
×
UNCOV
1439
                        ltndLog.Warnf("Ignoring reset-wallet-transactions " +
×
UNCOV
1440
                                "flag for new wallet as it has no effect")
×
UNCOV
1441
                }
×
1442

UNCOV
1443
                return &walletunlocker.WalletUnlockParams{
×
UNCOV
1444
                        Password:        password,
×
UNCOV
1445
                        Birthday:        birthday,
×
UNCOV
1446
                        RecoveryWindow:  recoveryWindow,
×
UNCOV
1447
                        Wallet:          newWallet,
×
UNCOV
1448
                        ChansToRestore:  initMsg.ChanBackups,
×
UNCOV
1449
                        UnloadWallet:    loader.UnloadWallet,
×
UNCOV
1450
                        StatelessInit:   initMsg.StatelessInit,
×
UNCOV
1451
                        MacResponseChan: pwService.MacResponseChan,
×
UNCOV
1452
                        MacRootKey:      initMsg.MacRootKey,
×
UNCOV
1453
                }, nil
×
1454

1455
        // The wallet has already been created in the past, and is simply being
1456
        // unlocked. So we'll just return these passphrases.
UNCOV
1457
        case unlockMsg := <-pwService.UnlockMsgs:
×
UNCOV
1458
                // Resetting the transactions is something the user likely only
×
UNCOV
1459
                // wants to do once so we add a prominent warning to the log to
×
UNCOV
1460
                // remind the user to turn off the setting again after
×
UNCOV
1461
                // successful completion.
×
UNCOV
1462
                if cfg.ResetWalletTransactions {
×
UNCOV
1463
                        ltndLog.Warnf("Dropped all transaction history from " +
×
UNCOV
1464
                                "on-chain wallet. Remember to disable " +
×
UNCOV
1465
                                "reset-wallet-transactions flag for next " +
×
UNCOV
1466
                                "start of lnd")
×
UNCOV
1467
                }
×
1468

UNCOV
1469
                return &walletunlocker.WalletUnlockParams{
×
UNCOV
1470
                        Password:        unlockMsg.Passphrase,
×
UNCOV
1471
                        RecoveryWindow:  unlockMsg.RecoveryWindow,
×
UNCOV
1472
                        Wallet:          unlockMsg.Wallet,
×
UNCOV
1473
                        ChansToRestore:  unlockMsg.ChanBackups,
×
UNCOV
1474
                        UnloadWallet:    unlockMsg.UnloadWallet,
×
UNCOV
1475
                        StatelessInit:   unlockMsg.StatelessInit,
×
UNCOV
1476
                        MacResponseChan: pwService.MacResponseChan,
×
UNCOV
1477
                }, nil
×
1478

1479
        // If we got a shutdown signal we just return with an error immediately
1480
        case <-shutdownChan:
×
1481
                return nil, fmt.Errorf("shutting down")
×
1482
        }
1483
}
1484

1485
// importWatchOnlyAccounts imports all individual account xpubs into our wallet
1486
// which we created as watch-only.
1487
func importWatchOnlyAccounts(wallet *wallet.Wallet,
UNCOV
1488
        initMsg *walletunlocker.WalletInitMsg) error {
×
UNCOV
1489

×
UNCOV
1490
        scopes := make([]waddrmgr.ScopedIndex, 0, len(initMsg.WatchOnlyAccounts))
×
UNCOV
1491
        for scope := range initMsg.WatchOnlyAccounts {
×
UNCOV
1492
                scopes = append(scopes, scope)
×
UNCOV
1493
        }
×
1494

1495
        // We need to import the accounts in the correct order, otherwise the
1496
        // indices will be incorrect.
UNCOV
1497
        sort.Slice(scopes, func(i, j int) bool {
×
UNCOV
1498
                return scopes[i].Scope.Purpose < scopes[j].Scope.Purpose ||
×
UNCOV
1499
                        scopes[i].Index < scopes[j].Index
×
UNCOV
1500
        })
×
1501

UNCOV
1502
        for _, scope := range scopes {
×
UNCOV
1503
                addrSchema := waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0084]
×
UNCOV
1504

×
UNCOV
1505
                // We want witness pubkey hash by default, except for BIP49
×
UNCOV
1506
                // where we want mixed and BIP86 where we want taproot address
×
UNCOV
1507
                // formats.
×
UNCOV
1508
                switch scope.Scope.Purpose {
×
1509
                case waddrmgr.KeyScopeBIP0049Plus.Purpose,
UNCOV
1510
                        waddrmgr.KeyScopeBIP0086.Purpose:
×
UNCOV
1511

×
UNCOV
1512
                        addrSchema = waddrmgr.ScopeAddrMap[scope.Scope]
×
1513
                }
1514

1515
                // We want a human-readable account name. But for the default
1516
                // on-chain wallet we actually need to call it "default" to make
1517
                // sure everything works correctly.
UNCOV
1518
                name := fmt.Sprintf("%s/%d'", scope.Scope.String(), scope.Index)
×
UNCOV
1519
                if scope.Index == 0 {
×
UNCOV
1520
                        name = "default"
×
UNCOV
1521
                }
×
1522

UNCOV
1523
                _, err := wallet.ImportAccountWithScope(
×
UNCOV
1524
                        name, initMsg.WatchOnlyAccounts[scope],
×
UNCOV
1525
                        initMsg.WatchOnlyMasterFingerprint, scope.Scope,
×
UNCOV
1526
                        addrSchema,
×
UNCOV
1527
                )
×
UNCOV
1528
                if err != nil {
×
1529
                        return fmt.Errorf("could not import account %v: %w",
×
1530
                                name, err)
×
1531
                }
×
1532
        }
1533

UNCOV
1534
        return nil
×
1535
}
1536

1537
// handleNeutrinoPostgresDBMigration handles the migration of the neutrino db
1538
// to postgres. Initially we kept the neutrino db in the bolt db when running
1539
// with kvdb postgres backend. Now now move it to postgres as well. However we
1540
// need to make a distinction whether the user migrated the neutrino db to
1541
// postgres via lndinit or not. Currently if the db is not migrated we start
1542
// with a fresh db in postgres.
1543
//
1544
// TODO(ziggie): Also migrate the db to postgres in case it is still not
1545
// migrated ?
1546
func handleNeutrinoPostgresDBMigration(dbName, dbPath string,
1547
        cfg *Config) error {
×
1548

×
1549
        if !lnrpc.FileExists(dbName) {
×
1550
                return nil
×
1551
        }
×
1552

1553
        // Open bolt db to check if it is tombstoned. If it is we assume that
1554
        // the neutrino db was successfully migrated to postgres. We open it
1555
        // in read-only mode to avoid long db open times.
1556
        boltDB, err := kvdb.Open(
×
1557
                kvdb.BoltBackendName, dbName, true,
×
1558
                cfg.DB.Bolt.DBTimeout, true,
×
1559
        )
×
1560
        if err != nil {
×
1561
                return fmt.Errorf("failed to open bolt db: %w", err)
×
1562
        }
×
1563
        defer boltDB.Close()
×
1564

×
1565
        isTombstoned := false
×
1566
        err = boltDB.View(func(tx kvdb.RTx) error {
×
1567
                _, err = channeldb.CheckMarkerPresent(
×
1568
                        tx, channeldb.TombstoneKey,
×
1569
                )
×
1570

×
1571
                return err
×
1572
        }, func() {})
×
1573
        if err == nil {
×
1574
                isTombstoned = true
×
1575
        }
×
1576

1577
        if isTombstoned {
×
1578
                ltndLog.Infof("Neutrino Bolt DB is tombstoned, assuming " +
×
1579
                        "database was successfully migrated to postgres")
×
1580

×
1581
                return nil
×
1582
        }
×
1583

1584
        // If the db is not tombstoned, we remove the files and start fresh with
1585
        // postgres. This is the case when a user was running lnd with the
1586
        // postgres backend from the beginning without migrating from bolt.
1587
        ltndLog.Infof("Neutrino Bolt DB found but NOT tombstoned, removing " +
×
1588
                "it and starting fresh with postgres")
×
1589

×
1590
        filesToRemove := []string{
×
1591
                filepath.Join(dbPath, "block_headers.bin"),
×
1592
                filepath.Join(dbPath, "reg_filter_headers.bin"),
×
1593
                dbName,
×
1594
        }
×
1595

×
1596
        for _, file := range filesToRemove {
×
1597
                if err := os.Remove(file); err != nil {
×
1598
                        ltndLog.Warnf("Could not remove %s: %v", file, err)
×
1599
                }
×
1600
        }
1601

1602
        return nil
×
1603
}
1604

1605
// initNeutrinoBackend inits a new instance of the neutrino light client
1606
// backend given a target chain directory to store the chain state.
1607
func initNeutrinoBackend(ctx context.Context, cfg *Config, chainDir string,
1608
        blockCache *blockcache.BlockCache) (*neutrino.ChainService,
UNCOV
1609
        func(), error) {
×
UNCOV
1610

×
UNCOV
1611
        // Both channel validation flags are false by default but their meaning
×
UNCOV
1612
        // is the inverse of each other. Therefore both cannot be true. For
×
UNCOV
1613
        // every other case, the neutrino.validatechannels overwrites the
×
UNCOV
1614
        // routing.assumechanvalid value.
×
UNCOV
1615
        if cfg.NeutrinoMode.ValidateChannels && cfg.Routing.AssumeChannelValid {
×
1616
                return nil, nil, fmt.Errorf("can't set both " +
×
1617
                        "neutrino.validatechannels and routing." +
×
1618
                        "assumechanvalid to true at the same time")
×
1619
        }
×
UNCOV
1620
        cfg.Routing.AssumeChannelValid = !cfg.NeutrinoMode.ValidateChannels
×
UNCOV
1621

×
UNCOV
1622
        // First we'll open the database file for neutrino, creating the
×
UNCOV
1623
        // database if needed. We append the normalized network name here to
×
UNCOV
1624
        // match the behavior of btcwallet.
×
UNCOV
1625
        dbPath := filepath.Join(
×
UNCOV
1626
                chainDir, lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
×
UNCOV
1627
        )
×
UNCOV
1628

×
UNCOV
1629
        // Ensure that the neutrino db path exists.
×
UNCOV
1630
        if err := os.MkdirAll(dbPath, 0700); err != nil {
×
1631
                return nil, nil, err
×
1632
        }
×
1633

UNCOV
1634
        var (
×
UNCOV
1635
                db  walletdb.DB
×
UNCOV
1636
                err error
×
UNCOV
1637
        )
×
UNCOV
1638
        switch {
×
1639
        case cfg.DB.Backend == kvdb.SqliteBackendName:
×
1640
                sqliteConfig := lncfg.GetSqliteConfigKVDB(cfg.DB.Sqlite)
×
1641
                db, err = kvdb.Open(
×
1642
                        kvdb.SqliteBackendName, ctx, sqliteConfig, dbPath,
×
1643
                        lncfg.SqliteNeutrinoDBName, lncfg.NSNeutrinoDB,
×
1644
                )
×
1645

1646
        case cfg.DB.Backend == kvdb.PostgresBackendName:
×
1647
                dbName := filepath.Join(dbPath, lncfg.NeutrinoDBName)
×
1648

×
1649
                // This code needs to be in place because we did not start
×
1650
                // the postgres backend for neutrino at the beginning. Now we
×
1651
                // are also moving it into the postgres backend so we can phase
×
1652
                // out the bolt backend.
×
1653
                err = handleNeutrinoPostgresDBMigration(dbName, dbPath, cfg)
×
1654
                if err != nil {
×
1655
                        return nil, nil, err
×
1656
                }
×
1657

1658
                postgresConfig := lncfg.GetPostgresConfigKVDB(cfg.DB.Postgres)
×
1659
                db, err = kvdb.Open(
×
1660
                        kvdb.PostgresBackendName, ctx, postgresConfig,
×
1661
                        lncfg.NSNeutrinoDB,
×
1662
                )
×
1663

UNCOV
1664
        default:
×
UNCOV
1665
                dbName := filepath.Join(dbPath, lncfg.NeutrinoDBName)
×
UNCOV
1666
                db, err = walletdb.Create(
×
UNCOV
1667
                        kvdb.BoltBackendName, dbName, !cfg.SyncFreelist,
×
UNCOV
1668
                        cfg.DB.Bolt.DBTimeout, false,
×
UNCOV
1669
                )
×
1670
        }
UNCOV
1671
        if err != nil {
×
1672
                return nil, nil, fmt.Errorf("unable to create "+
×
1673
                        "neutrino database: %v", err)
×
1674
        }
×
1675

UNCOV
1676
        headerStateAssertion, err := parseHeaderStateAssertion(
×
UNCOV
1677
                cfg.NeutrinoMode.AssertFilterHeader,
×
UNCOV
1678
        )
×
UNCOV
1679
        if err != nil {
×
1680
                db.Close()
×
1681
                return nil, nil, err
×
1682
        }
×
1683

1684
        // With the database open, we can now create an instance of the
1685
        // neutrino light client. We pass in relevant configuration parameters
1686
        // required.
UNCOV
1687
        config := neutrino.Config{
×
UNCOV
1688
                DataDir:      dbPath,
×
UNCOV
1689
                Database:     db,
×
UNCOV
1690
                ChainParams:  *cfg.ActiveNetParams.Params,
×
UNCOV
1691
                AddPeers:     cfg.NeutrinoMode.AddPeers,
×
UNCOV
1692
                ConnectPeers: cfg.NeutrinoMode.ConnectPeers,
×
UNCOV
1693
                Dialer: func(addr net.Addr) (net.Conn, error) {
×
UNCOV
1694
                        return cfg.net.Dial(
×
UNCOV
1695
                                addr.Network(), addr.String(),
×
UNCOV
1696
                                cfg.ConnectionTimeout,
×
UNCOV
1697
                        )
×
UNCOV
1698
                },
×
UNCOV
1699
                NameResolver: func(host string) ([]net.IP, error) {
×
UNCOV
1700
                        addrs, err := cfg.net.LookupHost(host)
×
UNCOV
1701
                        if err != nil {
×
1702
                                return nil, err
×
1703
                        }
×
1704

UNCOV
1705
                        ips := make([]net.IP, 0, len(addrs))
×
UNCOV
1706
                        for _, strIP := range addrs {
×
UNCOV
1707
                                ip := net.ParseIP(strIP)
×
UNCOV
1708
                                if ip == nil {
×
1709
                                        continue
×
1710
                                }
1711

UNCOV
1712
                                ips = append(ips, ip)
×
1713
                        }
1714

UNCOV
1715
                        return ips, nil
×
1716
                },
1717
                AssertFilterHeader: headerStateAssertion,
1718
                BlockCache:         blockCache.Cache,
1719
                BroadcastTimeout:   cfg.NeutrinoMode.BroadcastTimeout,
1720
                PersistToDisk:      cfg.NeutrinoMode.PersistFilters,
1721
        }
1722

UNCOV
1723
        if cfg.NeutrinoMode.MaxPeers <= 0 {
×
1724
                return nil, nil, fmt.Errorf("a non-zero number must be set " +
×
1725
                        "for neutrino max peers")
×
1726
        }
×
UNCOV
1727
        neutrino.MaxPeers = cfg.NeutrinoMode.MaxPeers
×
UNCOV
1728
        neutrino.BanDuration = time.Hour * 48
×
UNCOV
1729
        neutrino.UserAgentName = cfg.NeutrinoMode.UserAgentName
×
UNCOV
1730
        neutrino.UserAgentVersion = cfg.NeutrinoMode.UserAgentVersion
×
UNCOV
1731

×
UNCOV
1732
        neutrinoCS, err := neutrino.NewChainService(config)
×
UNCOV
1733
        if err != nil {
×
1734
                db.Close()
×
1735
                return nil, nil, fmt.Errorf("unable to create neutrino light "+
×
1736
                        "client: %v", err)
×
1737
        }
×
1738

UNCOV
1739
        if err := neutrinoCS.Start(); err != nil {
×
1740
                db.Close()
×
1741
                return nil, nil, err
×
1742
        }
×
1743

UNCOV
1744
        cleanUp := func() {
×
UNCOV
1745
                if err := neutrinoCS.Stop(); err != nil {
×
1746
                        ltndLog.Infof("Unable to stop neutrino light client: "+
×
1747
                                "%v", err)
×
1748
                }
×
UNCOV
1749
                db.Close()
×
1750
        }
1751

UNCOV
1752
        return neutrinoCS, cleanUp, nil
×
1753
}
1754

1755
// parseHeaderStateAssertion parses the user-specified neutrino header state
1756
// into a headerfs.FilterHeader.
UNCOV
1757
func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) {
×
UNCOV
1758
        if len(state) == 0 {
×
UNCOV
1759
                return nil, nil
×
UNCOV
1760
        }
×
1761

1762
        split := strings.Split(state, ":")
×
1763
        if len(split) != 2 {
×
1764
                return nil, fmt.Errorf("header state assertion %v in "+
×
1765
                        "unexpected format, expected format height:hash", state)
×
1766
        }
×
1767

1768
        height, err := strconv.ParseUint(split[0], 10, 32)
×
1769
        if err != nil {
×
1770
                return nil, fmt.Errorf("invalid filter header height: %w", err)
×
1771
        }
×
1772

1773
        hash, err := chainhash.NewHashFromStr(split[1])
×
1774
        if err != nil {
×
1775
                return nil, fmt.Errorf("invalid filter header hash: %w", err)
×
1776
        }
×
1777

1778
        return &headerfs.FilterHeader{
×
1779
                Height:     uint32(height),
×
1780
                FilterHash: *hash,
×
1781
        }, nil
×
1782
}
1783

1784
// broadcastErrorMapper maps errors from bitcoin backends other than neutrino to
1785
// the neutrino BroadcastError which allows the Rebroadcaster which currently
1786
// resides in the neutrino package to use all of its functionalities.
UNCOV
1787
func broadcastErrorMapper(err error) error {
×
UNCOV
1788
        var returnErr error
×
UNCOV
1789

×
UNCOV
1790
        // We only filter for specific backend errors which are relevant for the
×
UNCOV
1791
        // Rebroadcaster.
×
UNCOV
1792
        switch {
×
1793
        // This makes sure the tx is removed from the rebroadcaster once it is
1794
        // confirmed.
1795
        case errors.Is(err, chain.ErrTxAlreadyKnown),
UNCOV
1796
                errors.Is(err, chain.ErrTxAlreadyConfirmed):
×
UNCOV
1797

×
UNCOV
1798
                returnErr = &pushtx.BroadcastError{
×
UNCOV
1799
                        Code:   pushtx.Confirmed,
×
UNCOV
1800
                        Reason: err.Error(),
×
UNCOV
1801
                }
×
1802

1803
        // Transactions which are still in mempool but might fall out because
1804
        // of low fees are rebroadcasted despite of their backend error.
1805
        case errors.Is(err, chain.ErrTxAlreadyInMempool):
×
1806
                returnErr = &pushtx.BroadcastError{
×
1807
                        Code:   pushtx.Mempool,
×
1808
                        Reason: err.Error(),
×
1809
                }
×
1810

1811
        // Transactions which are not accepted into mempool because of low fees
1812
        // in the first place are rebroadcasted despite of their backend error.
1813
        // Mempool conditions change over time so it makes sense to retry
1814
        // publishing the transaction. Moreover we log the detailed error so the
1815
        // user can intervene and increase the size of his mempool or increase
1816
        // his min relay fee configuration.
1817
        case errors.Is(err, chain.ErrMempoolMinFeeNotMet),
1818
                errors.Is(err, chain.ErrMinRelayFeeNotMet):
×
1819

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

×
1822
                returnErr = &pushtx.BroadcastError{
×
1823
                        Code:   pushtx.Mempool,
×
1824
                        Reason: err.Error(),
×
1825
                }
×
1826
        }
1827

UNCOV
1828
        return returnErr
×
1829
}
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