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

lightningnetwork / lnd / 17830307614

18 Sep 2025 01:29PM UTC coverage: 54.617% (-12.0%) from 66.637%
17830307614

Pull #10200

github

web-flow
Merge 181a0a7bc into b34fc964b
Pull Request #10200: github: change to form-based issue template

109249 of 200028 relevant lines covered (54.62%)

21896.43 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

218
// DefaultWalletImpl is the default implementation of our normal, btcwallet
219
// backed configuration.
220
type DefaultWalletImpl struct {
221
        cfg         *Config
222
        logger      btclog.Logger
223
        interceptor signal.Interceptor
224

225
        watchOnly        bool
226
        migrateWatchOnly bool
227
        pwService        *walletunlocker.UnlockerService
228
}
229

230
// NewDefaultWalletImpl creates a new default wallet implementation.
231
func NewDefaultWalletImpl(cfg *Config, logger btclog.Logger,
232
        interceptor signal.Interceptor, watchOnly bool) *DefaultWalletImpl {
×
233

×
234
        return &DefaultWalletImpl{
×
235
                cfg:         cfg,
×
236
                logger:      logger,
×
237
                interceptor: interceptor,
×
238
                watchOnly:   watchOnly,
×
239
                pwService:   createWalletUnlockerService(cfg),
×
240
        }
×
241
}
×
242

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

×
252
        return lnrpc.RegisterWalletUnlockerHandlerFromEndpoint(
×
253
                ctx, mux, restProxyDest, restDialOpts,
×
254
        )
×
255
}
×
256

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

×
265
        return nil
×
266
}
×
267

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

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

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

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

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

316
                                fn()
×
317
                        }
318
                }
319
        )
320
        defer func() {
×
321
                if earlyExit {
×
322
                        cleanUp()
×
323
                }
×
324
        }()
325

326
        // Initialize a new block cache.
327
        blockCache := blockcache.NewBlockCache(d.cfg.BlockCacheSize)
×
328

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

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

×
358
        // If the user didn't request a seed, then we'll manually assume a
×
359
        // wallet birthday of now, as otherwise the seed would've specified
×
360
        // this information.
×
361
        walletInitParams.Birthday = time.Now()
×
362

×
363
        d.pwService.SetLoaderOpts([]btcwallet.LoaderOption{dbs.WalletDB})
×
364
        d.pwService.SetMacaroonDB(dbs.MacaroonDB)
×
365
        walletExists, err := d.pwService.WalletExists()
×
366
        if err != nil {
×
367
                return nil, nil, nil, err
×
368
        }
×
369

370
        if !walletExists {
×
371
                interceptorChain.SetWalletNotCreated()
×
372
        } else {
×
373
                interceptorChain.SetWalletLocked()
×
374
        }
×
375

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

×
384
                return nil, nil, nil, fmt.Errorf("wallet unlock password file " +
×
385
                        "was specified but wallet does not exist; initialize " +
×
386
                        "the wallet before using auto unlocking")
×
387
        }
×
388

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

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

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

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

423
                cleanUpTasks = append(cleanUpTasks, func() {
×
424
                        if err := unloadWalletFn(); err != nil {
×
425
                                d.logger.Errorf("Could not unload wallet: %v",
×
426
                                        err)
×
427
                        }
×
428
                })
429

430
                privateWalletPw = pwBytes
×
431
                publicWalletPw = pwBytes
×
432
                walletInitParams.Wallet = unlockedWallet
×
433
                walletInitParams.UnloadWallet = unloadWalletFn
×
434

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

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

454
                walletInitParams = *params
×
455
                privateWalletPw = walletInitParams.Password
×
456
                publicWalletPw = walletInitParams.Password
×
457
                cleanUpTasks = append(cleanUpTasks, func() {
×
458
                        if err := walletInitParams.UnloadWallet(); err != nil {
×
459
                                d.logger.Errorf("Could not unload wallet: %v",
×
460
                                        err)
×
461
                        }
×
462
                })
463

464
                if walletInitParams.RecoveryWindow > 0 {
×
465
                        d.logger.Infof("Wallet recovery mode enabled with "+
×
466
                                "address lookahead of %d addresses",
×
467
                                walletInitParams.RecoveryWindow)
×
468
                }
×
469
        }
470

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

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

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

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

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

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

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

×
570
                        if lnrpc.FileExists(d.cfg.AdminMacPath) {
×
571
                                d.logger.Warnf(msg, "admin", d.cfg.AdminMacPath)
×
572
                        }
×
573
                        if lnrpc.FileExists(d.cfg.ReadMacPath) {
×
574
                                d.logger.Warnf(msg, "readonly", d.cfg.ReadMacPath)
×
575
                        }
×
576
                        if lnrpc.FileExists(d.cfg.InvoiceMacPath) {
×
577
                                d.logger.Warnf(msg, "invoice", d.cfg.InvoiceMacPath)
×
578
                        }
×
579
                }
580

581
                // We add the macaroon service to our RPC interceptor. This
582
                // will start checking macaroons against permissions on every
583
                // RPC invocation.
584
                interceptorChain.AddMacaroonService(macaroonService)
×
585
        }
586

587
        // Now that the wallet password has been provided, transition the RPC
588
        // state into Unlocked.
589
        interceptorChain.SetWalletUnlocked()
×
590

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

×
597
        // We'll also close all the macaroon channels since lnd is done sending
×
598
        // macaroon data over it.
×
599
        for _, lis := range grpcListeners {
×
600
                if lis.MacChan != nil {
×
601
                        close(lis.MacChan)
×
602
                }
×
603
        }
604

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

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

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

×
667
        // Parse coin selection strategy.
×
668
        switch d.cfg.CoinSelectionStrategy {
×
669
        case "largest":
×
670
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionLargest
×
671

672
        case "random":
×
673
                walletConfig.CoinSelectionStrategy = wallet.CoinSelectionRandom
×
674

675
        default:
×
676
                return nil, nil, nil, fmt.Errorf("unknown coin selection "+
×
677
                        "strategy %v", d.cfg.CoinSelectionStrategy)
×
678
        }
679

680
        earlyExit = false
×
681
        return partialChainControl, walletConfig, cleanUp, nil
×
682
}
683

684
// proxyBlockEpoch proxies a block epoch subsections to the underlying neutrino
685
// rebroadcaster client.
686
func proxyBlockEpoch(
687
        notifier chainntnfs.ChainNotifier) func() (*blockntfns.Subscription,
688
        error) {
×
689

×
690
        return func() (*blockntfns.Subscription, error) {
×
691
                blockEpoch, err := notifier.RegisterBlockEpochNtfn(
×
692
                        nil,
×
693
                )
×
694
                if err != nil {
×
695
                        return nil, err
×
696
                }
×
697

698
                sub := blockntfns.Subscription{
×
699
                        Notifications: make(chan blockntfns.BlockNtfn, 6),
×
700
                        Cancel:        blockEpoch.Cancel,
×
701
                }
×
702
                go func() {
×
703
                        for blk := range blockEpoch.Epochs {
×
704
                                ntfn := blockntfns.NewBlockConnected(
×
705
                                        *blk.BlockHeader,
×
706
                                        uint32(blk.Height),
×
707
                                )
×
708

×
709
                                sub.Notifications <- ntfn
×
710
                        }
×
711
                }()
712

713
                return &sub, nil
×
714
        }
715
}
716

717
// walletReBroadcaster is a simple wrapper around the pushtx.Broadcaster
718
// interface to adhere to the expanded lnwallet.Rebroadcaster interface.
719
type walletReBroadcaster struct {
720
        started atomic.Bool
721

722
        *pushtx.Broadcaster
723
}
724

725
// newWalletReBroadcaster creates a new instance of the walletReBroadcaster.
726
func newWalletReBroadcaster(
727
        broadcaster *pushtx.Broadcaster) *walletReBroadcaster {
×
728

×
729
        return &walletReBroadcaster{
×
730
                Broadcaster: broadcaster,
×
731
        }
×
732
}
×
733

734
// Start launches all goroutines the rebroadcaster needs to operate.
735
func (w *walletReBroadcaster) Start() error {
×
736
        defer w.started.Store(true)
×
737

×
738
        return w.Broadcaster.Start()
×
739
}
×
740

741
// Started returns true if the broadcaster is already active.
742
func (w *walletReBroadcaster) Started() bool {
×
743
        return w.started.Load()
×
744
}
×
745

746
// BuildChainControl is responsible for creating a fully populated chain
747
// control instance from a wallet.
748
//
749
// NOTE: This is part of the ChainControlBuilder interface.
750
func (d *DefaultWalletImpl) BuildChainControl(
751
        partialChainControl *chainreg.PartialChainControl,
752
        walletConfig *btcwallet.Config) (*chainreg.ChainControl, func(), error) {
×
753

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

763
        keyRing := keychain.NewBtcWalletKeyRing(
×
764
                walletController.InternalWallet(), walletConfig.CoinType,
×
765
        )
×
766

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

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

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

808
                lnWalletConfig.Rebroadcaster = newWalletReBroadcaster(
×
809
                        pushtx.NewBroadcaster(&broadcastCfg),
×
810
                )
×
811
        }
812

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

824
        return activeChainControl, cleanUp, nil
×
825
}
826

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

836
// NewRPCSignerWalletImpl creates a new instance of the remote signing wallet
837
// implementation.
838
func NewRPCSignerWalletImpl(cfg *Config, logger btclog.Logger,
839
        interceptor signal.Interceptor,
840
        migrateWatchOnly bool) *RPCSignerWalletImpl {
×
841

×
842
        return &RPCSignerWalletImpl{
×
843
                DefaultWalletImpl: &DefaultWalletImpl{
×
844
                        cfg:              cfg,
×
845
                        logger:           logger,
×
846
                        interceptor:      interceptor,
×
847
                        watchOnly:        true,
×
848
                        migrateWatchOnly: migrateWatchOnly,
×
849
                        pwService:        createWalletUnlockerService(cfg),
×
850
                },
×
851
        }
×
852
}
×
853

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

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

872
        baseKeyRing := keychain.NewBtcWalletKeyRing(
×
873
                walletController.InternalWallet(), walletConfig.CoinType,
×
874
        )
×
875

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

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

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

912
        return activeChainControl, cleanUp, nil
×
913
}
914

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

922
        // ChanStateDB is the database that stores all of our node's channel
923
        // state.
924
        ChanStateDB *channeldb.DB
925

926
        // HeightHintDB is the database that stores height hints for spends.
927
        HeightHintDB kvdb.Backend
928

929
        // InvoiceDB is the database that stores information about invoices.
930
        InvoiceDB invoices.InvoiceDB
931

932
        // PaymentsDB is the database that stores all payment related
933
        // information.
934
        PaymentsDB paymentsdb.DB
935

936
        // MacaroonDB is the database that stores macaroon root keys.
937
        MacaroonDB kvdb.Backend
938

939
        // DecayedLogDB is the database that stores p2p related encryption
940
        // information.
941
        DecayedLogDB kvdb.Backend
942

943
        // TowerClientDB is the database that stores the watchtower client's
944
        // configuration.
945
        TowerClientDB wtclient.DB
946

947
        // TowerServerDB is the database that stores the watchtower server's
948
        // configuration.
949
        TowerServerDB watchtower.DB
950

951
        // WalletDB is the configuration for loading the wallet database using
952
        // the btcwallet's loader.
953
        WalletDB btcwallet.LoaderOption
954

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

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

969
// NewDefaultDatabaseBuilder returns a new instance of the default database
970
// builder.
971
func NewDefaultDatabaseBuilder(cfg *Config,
972
        logger btclog.Logger) *DefaultDatabaseBuilder {
×
973

×
974
        return &DefaultDatabaseBuilder{
×
975
                cfg:    cfg,
×
976
                logger: logger,
×
977
        }
×
978
}
×
979

980
// BuildDatabase extracts the current databases that we'll use for normal
981
// operation in the daemon. A function closure that closes all opened databases
982
// is also returned.
983
func (d *DefaultDatabaseBuilder) BuildDatabase(
984
        ctx context.Context) (*DatabaseInstances, func(), error) {
×
985

×
986
        d.logger.Infof("Opening the main database, this might take a few " +
×
987
                "minutes...")
×
988

×
989
        cfg := d.cfg
×
990
        if cfg.DB.Backend == lncfg.BoltBackend {
×
991
                d.logger.Infof("Opening bbolt database, sync_freelist=%v, "+
×
992
                        "auto_compact=%v", !cfg.DB.Bolt.NoFreelistSync,
×
993
                        cfg.DB.Bolt.AutoCompact)
×
994
        }
×
995

996
        startOpenTime := time.Now()
×
997

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

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

1038
        graphDBOptions := []graphdb.StoreOptionModifier{
×
1039
                graphdb.WithRejectCacheSize(cfg.Caches.RejectCacheSize),
×
1040
                graphdb.WithChannelCacheSize(cfg.Caches.ChannelCacheSize),
×
1041
                graphdb.WithBatchCommitInterval(cfg.DB.BatchCommitInterval),
×
1042
        }
×
1043

×
1044
        chanGraphOpts := []graphdb.ChanGraphOption{
×
1045
                graphdb.WithUseGraphCache(!cfg.DB.NoGraphCache),
×
1046
        }
×
1047

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

1058
        dbOptions := []channeldb.OptionModifier{
×
1059
                channeldb.OptionDryRunMigration(cfg.DryRunMigration),
×
1060
                channeldb.OptionStoreFinalHtlcResolutions(
×
1061
                        cfg.StoreFinalHtlcResolutions,
×
1062
                ),
×
1063
                channeldb.OptionPruneRevocationLog(cfg.DB.PruneRevocation),
×
1064
                channeldb.OptionNoRevLogAmtData(cfg.DB.NoRevLogAmtData),
×
1065
                channeldb.OptionGcDecayedLog(cfg.DB.NoGcDecayedLog),
×
1066
                channeldb.OptionWithDecayedLogDB(dbs.DecayedLogDB),
×
1067
        }
×
1068

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

1082
        case err != nil:
×
1083
                cleanUp()
×
1084

×
1085
                err = fmt.Errorf("unable to open graph DB: %w", err)
×
1086
                d.logger.Error(err)
×
1087
                return nil, nil, err
×
1088
        }
1089

1090
        // The graph store implementation we will use depends on whether
1091
        // native SQL is enabled or not.
1092
        var graphStore graphdb.V1Store
×
1093

×
1094
        // Instantiate a native SQL store if the flag is set.
×
1095
        if d.cfg.DB.UseNativeSQL {
×
1096
                migrations := sqldb.GetMigrations()
×
1097

×
1098
                queryCfg := &d.cfg.DB.Sqlite.QueryConfig
×
1099
                if d.cfg.DB.Backend == lncfg.PostgresBackend {
×
1100
                        queryCfg = &d.cfg.DB.Postgres.QueryConfig
×
1101
                }
×
1102

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

1122
                                // Set the invoice bucket tombstone to indicate
1123
                                // that the migration has been completed.
1124
                                d.logger.Debugf("Setting invoice bucket " +
×
1125
                                        "tombstone")
×
1126

×
1127
                                //nolint:ll
×
1128
                                return dbs.ChanStateDB.SetInvoiceBucketTombstone()
×
1129
                        }
1130

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

1145
                                return nil
×
1146
                        }
1147

1148
                        // Make sure we attach the custom migration function to
1149
                        // the correct migration version.
1150
                        for i := 0; i < len(migrations); i++ {
×
1151
                                version := migrations[i].Version
×
1152
                                switch version {
×
1153
                                case invoiceMigration:
×
1154
                                        migrations[i].MigrationFn = invoiceMig
×
1155

×
1156
                                        continue
×
1157
                                case graphMigration:
×
1158
                                        migrations[i].MigrationFn = graphMig
×
1159

×
1160
                                        continue
×
1161

1162
                                default:
×
1163
                                }
1164

1165
                                migFn, ok := d.getSQLMigration(
×
1166
                                        ctx, version, dbs.ChanStateDB.Backend,
×
1167
                                )
×
1168
                                if !ok {
×
1169
                                        continue
×
1170
                                }
1171

1172
                                migrations[i].MigrationFn = migFn
×
1173
                        }
1174
                }
1175

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

×
1185
                        return nil, nil, err
×
1186
                }
×
1187

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

1198
                sqlInvoiceDB := invoices.NewSQLStore(
×
1199
                        invoiceExecutor, clock.NewDefaultClock(),
×
1200
                )
×
1201

×
1202
                dbs.InvoiceDB = sqlInvoiceDB
×
1203

×
1204
                graphExecutor := sqldb.NewTransactionExecutor(
×
1205
                        baseDB, func(tx *sql.Tx) graphdb.SQLQueries {
×
1206
                                return baseDB.WithTx(tx)
×
1207
                        },
×
1208
                )
1209

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

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

×
1233
                        return nil, nil, err
×
1234
                }
×
1235
                if ripInvoices {
×
1236
                        err = fmt.Errorf("invoices bucket tombstoned, please " +
×
1237
                                "switch back to native SQL")
×
1238
                        d.logger.Error(err)
×
1239

×
1240
                        return nil, nil, err
×
1241
                }
×
1242

1243
                dbs.InvoiceDB = dbs.ChanStateDB
×
1244

×
1245
                graphStore, err = graphdb.NewKVStore(
×
1246
                        databaseBackends.GraphDB, graphDBOptions...,
×
1247
                )
×
1248
                if err != nil {
×
1249
                        return nil, nil, err
×
1250
                }
×
1251
        }
1252

1253
        dbs.GraphDB, err = graphdb.NewChannelGraph(graphStore, chanGraphOpts...)
×
1254
        if err != nil {
×
1255
                cleanUp()
×
1256

×
1257
                err = fmt.Errorf("unable to open channel graph DB: %w", err)
×
1258
                d.logger.Error(err)
×
1259

×
1260
                return nil, nil, err
×
1261
        }
×
1262

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

×
1279
                err = fmt.Errorf("unable to open payments DB: %w", err)
×
1280
                d.logger.Error(err)
×
1281

×
1282
                return nil, nil, err
×
1283
        }
×
1284
        dbs.PaymentsDB = kvPaymentsDB
×
1285

×
1286
        // Wrap the watchtower client DB and make sure we clean up.
×
1287
        if cfg.WtClient.Active {
×
1288
                dbs.TowerClientDB, err = wtdb.OpenClientDB(
×
1289
                        databaseBackends.TowerClientDB,
×
1290
                )
×
1291
                if err != nil {
×
1292
                        cleanUp()
×
1293

×
1294
                        err = fmt.Errorf("unable to open %s database: %w",
×
1295
                                lncfg.NSTowerClientDB, err)
×
1296
                        d.logger.Error(err)
×
1297
                        return nil, nil, err
×
1298
                }
×
1299
        }
1300

1301
        // Wrap the watchtower server DB and make sure we clean up.
1302
        if cfg.Watchtower.Active {
×
1303
                dbs.TowerServerDB, err = wtdb.OpenTowerDB(
×
1304
                        databaseBackends.TowerServerDB,
×
1305
                )
×
1306
                if err != nil {
×
1307
                        cleanUp()
×
1308

×
1309
                        err = fmt.Errorf("unable to open %s database: %w",
×
1310
                                lncfg.NSTowerServerDB, err)
×
1311
                        d.logger.Error(err)
×
1312
                        return nil, nil, err
×
1313
                }
×
1314
        }
1315

1316
        openTime := time.Since(startOpenTime)
×
1317
        d.logger.Infof("Database(s) now open (time_to_open=%v)!", openTime)
×
1318

×
1319
        return dbs, cleanUp, nil
×
1320
}
1321

1322
// waitForWalletPassword blocks until a password is provided by the user to
1323
// this RPC server.
1324
func waitForWalletPassword(cfg *Config,
1325
        pwService *walletunlocker.UnlockerService,
1326
        loaderOpts []btcwallet.LoaderOption, shutdownChan <-chan struct{}) (
1327
        *walletunlocker.WalletUnlockParams, error) {
×
1328

×
1329
        // Wait for user to provide the password.
×
1330
        ltndLog.Infof("Waiting for wallet encryption password. Use `lncli " +
×
1331
                "create` to create a wallet, `lncli unlock` to unlock an " +
×
1332
                "existing wallet, or `lncli changepassword` to change the " +
×
1333
                "password of an existing wallet and unlock it.")
×
1334

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

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

×
1356
                        return nil, fmt.Errorf("invalid internal "+
×
1357
                                "seed version %v, current max version is %v",
×
1358
                                cipherSeed.InternalVersion,
×
1359
                                keychain.CurrentKeyDerivationVersion)
×
1360
                }
×
1361

1362
                loader, err := btcwallet.NewWalletLoader(
×
1363
                        cfg.ActiveNetParams.Params, recoveryWindow,
×
1364
                        loaderOpts...,
×
1365
                )
×
1366
                if err != nil {
×
1367
                        return nil, err
×
1368
                }
×
1369

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

1386
                // No seed was given, we're importing a wallet from its extended
1387
                // private key.
1388
                case extendedKey != nil:
×
1389
                        birthday = initMsg.ExtendedKeyBirthday
×
1390
                        newWallet, err = loader.CreateNewWalletExtendedKey(
×
1391
                                password, password, extendedKey, birthday,
×
1392
                        )
×
1393

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

1404
                        birthday = initMsg.WatchOnlyBirthday
×
1405
                        newWallet, err = loader.CreateNewWatchingOnlyWallet(
×
1406
                                password, birthday,
×
1407
                        )
×
1408
                        if err != nil {
×
1409
                                break
×
1410
                        }
1411

1412
                        err = importWatchOnlyAccounts(newWallet, initMsg)
×
1413

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

1432
                // For new wallets, the ResetWalletTransactions flag is a no-op.
1433
                if cfg.ResetWalletTransactions {
×
1434
                        ltndLog.Warnf("Ignoring reset-wallet-transactions " +
×
1435
                                "flag for new wallet as it has no effect")
×
1436
                }
×
1437

1438
                return &walletunlocker.WalletUnlockParams{
×
1439
                        Password:        password,
×
1440
                        Birthday:        birthday,
×
1441
                        RecoveryWindow:  recoveryWindow,
×
1442
                        Wallet:          newWallet,
×
1443
                        ChansToRestore:  initMsg.ChanBackups,
×
1444
                        UnloadWallet:    loader.UnloadWallet,
×
1445
                        StatelessInit:   initMsg.StatelessInit,
×
1446
                        MacResponseChan: pwService.MacResponseChan,
×
1447
                        MacRootKey:      initMsg.MacRootKey,
×
1448
                }, nil
×
1449

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

1464
                return &walletunlocker.WalletUnlockParams{
×
1465
                        Password:        unlockMsg.Passphrase,
×
1466
                        RecoveryWindow:  unlockMsg.RecoveryWindow,
×
1467
                        Wallet:          unlockMsg.Wallet,
×
1468
                        ChansToRestore:  unlockMsg.ChanBackups,
×
1469
                        UnloadWallet:    unlockMsg.UnloadWallet,
×
1470
                        StatelessInit:   unlockMsg.StatelessInit,
×
1471
                        MacResponseChan: pwService.MacResponseChan,
×
1472
                }, nil
×
1473

1474
        // If we got a shutdown signal we just return with an error immediately
1475
        case <-shutdownChan:
×
1476
                return nil, fmt.Errorf("shutting down")
×
1477
        }
1478
}
1479

1480
// importWatchOnlyAccounts imports all individual account xpubs into our wallet
1481
// which we created as watch-only.
1482
func importWatchOnlyAccounts(wallet *wallet.Wallet,
1483
        initMsg *walletunlocker.WalletInitMsg) error {
×
1484

×
1485
        scopes := make([]waddrmgr.ScopedIndex, 0, len(initMsg.WatchOnlyAccounts))
×
1486
        for scope := range initMsg.WatchOnlyAccounts {
×
1487
                scopes = append(scopes, scope)
×
1488
        }
×
1489

1490
        // We need to import the accounts in the correct order, otherwise the
1491
        // indices will be incorrect.
1492
        sort.Slice(scopes, func(i, j int) bool {
×
1493
                return scopes[i].Scope.Purpose < scopes[j].Scope.Purpose ||
×
1494
                        scopes[i].Index < scopes[j].Index
×
1495
        })
×
1496

1497
        for _, scope := range scopes {
×
1498
                addrSchema := waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0084]
×
1499

×
1500
                // We want witness pubkey hash by default, except for BIP49
×
1501
                // where we want mixed and BIP86 where we want taproot address
×
1502
                // formats.
×
1503
                switch scope.Scope.Purpose {
×
1504
                case waddrmgr.KeyScopeBIP0049Plus.Purpose,
1505
                        waddrmgr.KeyScopeBIP0086.Purpose:
×
1506

×
1507
                        addrSchema = waddrmgr.ScopeAddrMap[scope.Scope]
×
1508
                }
1509

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

1518
                _, err := wallet.ImportAccountWithScope(
×
1519
                        name, initMsg.WatchOnlyAccounts[scope],
×
1520
                        initMsg.WatchOnlyMasterFingerprint, scope.Scope,
×
1521
                        addrSchema,
×
1522
                )
×
1523
                if err != nil {
×
1524
                        return fmt.Errorf("could not import account %v: %w",
×
1525
                                name, err)
×
1526
                }
×
1527
        }
1528

1529
        return nil
×
1530
}
1531

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

×
1544
        if !lnrpc.FileExists(dbName) {
×
1545
                return nil
×
1546
        }
×
1547

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

×
1560
        isTombstoned := false
×
1561
        err = boltDB.View(func(tx kvdb.RTx) error {
×
1562
                _, err = channeldb.CheckMarkerPresent(
×
1563
                        tx, channeldb.TombstoneKey,
×
1564
                )
×
1565

×
1566
                return err
×
1567
        }, func() {})
×
1568
        if err == nil {
×
1569
                isTombstoned = true
×
1570
        }
×
1571

1572
        if isTombstoned {
×
1573
                ltndLog.Infof("Neutrino Bolt DB is tombstoned, assuming " +
×
1574
                        "database was successfully migrated to postgres")
×
1575

×
1576
                return nil
×
1577
        }
×
1578

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

×
1585
        filesToRemove := []string{
×
1586
                filepath.Join(dbPath, "block_headers.bin"),
×
1587
                filepath.Join(dbPath, "reg_filter_headers.bin"),
×
1588
                dbName,
×
1589
        }
×
1590

×
1591
        for _, file := range filesToRemove {
×
1592
                if err := os.Remove(file); err != nil {
×
1593
                        ltndLog.Warnf("Could not remove %s: %v", file, err)
×
1594
                }
×
1595
        }
1596

1597
        return nil
×
1598
}
1599

1600
// initNeutrinoBackend inits a new instance of the neutrino light client
1601
// backend given a target chain directory to store the chain state.
1602
func initNeutrinoBackend(ctx context.Context, cfg *Config, chainDir string,
1603
        blockCache *blockcache.BlockCache) (*neutrino.ChainService,
1604
        func(), error) {
×
1605

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

×
1617
        // First we'll open the database file for neutrino, creating the
×
1618
        // database if needed. We append the normalized network name here to
×
1619
        // match the behavior of btcwallet.
×
1620
        dbPath := filepath.Join(
×
1621
                chainDir, lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
×
1622
        )
×
1623

×
1624
        // Ensure that the neutrino db path exists.
×
1625
        if err := os.MkdirAll(dbPath, 0700); err != nil {
×
1626
                return nil, nil, err
×
1627
        }
×
1628

1629
        var (
×
1630
                db  walletdb.DB
×
1631
                err error
×
1632
        )
×
1633
        switch {
×
1634
        case cfg.DB.Backend == kvdb.SqliteBackendName:
×
1635
                sqliteConfig := lncfg.GetSqliteConfigKVDB(cfg.DB.Sqlite)
×
1636
                db, err = kvdb.Open(
×
1637
                        kvdb.SqliteBackendName, ctx, sqliteConfig, dbPath,
×
1638
                        lncfg.SqliteNeutrinoDBName, lncfg.NSNeutrinoDB,
×
1639
                )
×
1640

1641
        case cfg.DB.Backend == kvdb.PostgresBackendName:
×
1642
                dbName := filepath.Join(dbPath, lncfg.NeutrinoDBName)
×
1643

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

1653
                postgresConfig := lncfg.GetPostgresConfigKVDB(cfg.DB.Postgres)
×
1654
                db, err = kvdb.Open(
×
1655
                        kvdb.PostgresBackendName, ctx, postgresConfig,
×
1656
                        lncfg.NSNeutrinoDB,
×
1657
                )
×
1658

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

1671
        headerStateAssertion, err := parseHeaderStateAssertion(
×
1672
                cfg.NeutrinoMode.AssertFilterHeader,
×
1673
        )
×
1674
        if err != nil {
×
1675
                db.Close()
×
1676
                return nil, nil, err
×
1677
        }
×
1678

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

1700
                        ips := make([]net.IP, 0, len(addrs))
×
1701
                        for _, strIP := range addrs {
×
1702
                                ip := net.ParseIP(strIP)
×
1703
                                if ip == nil {
×
1704
                                        continue
×
1705
                                }
1706

1707
                                ips = append(ips, ip)
×
1708
                        }
1709

1710
                        return ips, nil
×
1711
                },
1712
                AssertFilterHeader: headerStateAssertion,
1713
                BlockCache:         blockCache.Cache,
1714
                BroadcastTimeout:   cfg.NeutrinoMode.BroadcastTimeout,
1715
                PersistToDisk:      cfg.NeutrinoMode.PersistFilters,
1716
        }
1717

1718
        if cfg.NeutrinoMode.MaxPeers <= 0 {
×
1719
                return nil, nil, fmt.Errorf("a non-zero number must be set " +
×
1720
                        "for neutrino max peers")
×
1721
        }
×
1722
        neutrino.MaxPeers = cfg.NeutrinoMode.MaxPeers
×
1723
        neutrino.BanDuration = time.Hour * 48
×
1724
        neutrino.UserAgentName = cfg.NeutrinoMode.UserAgentName
×
1725
        neutrino.UserAgentVersion = cfg.NeutrinoMode.UserAgentVersion
×
1726

×
1727
        neutrinoCS, err := neutrino.NewChainService(config)
×
1728
        if err != nil {
×
1729
                db.Close()
×
1730
                return nil, nil, fmt.Errorf("unable to create neutrino light "+
×
1731
                        "client: %v", err)
×
1732
        }
×
1733

1734
        if err := neutrinoCS.Start(); err != nil {
×
1735
                db.Close()
×
1736
                return nil, nil, err
×
1737
        }
×
1738

1739
        cleanUp := func() {
×
1740
                if err := neutrinoCS.Stop(); err != nil {
×
1741
                        ltndLog.Infof("Unable to stop neutrino light client: "+
×
1742
                                "%v", err)
×
1743
                }
×
1744
                db.Close()
×
1745
        }
1746

1747
        return neutrinoCS, cleanUp, nil
×
1748
}
1749

1750
// parseHeaderStateAssertion parses the user-specified neutrino header state
1751
// into a headerfs.FilterHeader.
1752
func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) {
×
1753
        if len(state) == 0 {
×
1754
                return nil, nil
×
1755
        }
×
1756

1757
        split := strings.Split(state, ":")
×
1758
        if len(split) != 2 {
×
1759
                return nil, fmt.Errorf("header state assertion %v in "+
×
1760
                        "unexpected format, expected format height:hash", state)
×
1761
        }
×
1762

1763
        height, err := strconv.ParseUint(split[0], 10, 32)
×
1764
        if err != nil {
×
1765
                return nil, fmt.Errorf("invalid filter header height: %w", err)
×
1766
        }
×
1767

1768
        hash, err := chainhash.NewHashFromStr(split[1])
×
1769
        if err != nil {
×
1770
                return nil, fmt.Errorf("invalid filter header hash: %w", err)
×
1771
        }
×
1772

1773
        return &headerfs.FilterHeader{
×
1774
                Height:     uint32(height),
×
1775
                FilterHash: *hash,
×
1776
        }, nil
×
1777
}
1778

1779
// broadcastErrorMapper maps errors from bitcoin backends other than neutrino to
1780
// the neutrino BroadcastError which allows the Rebroadcaster which currently
1781
// resides in the neutrino package to use all of its functionalities.
1782
func broadcastErrorMapper(err error) error {
×
1783
        var returnErr error
×
1784

×
1785
        // We only filter for specific backend errors which are relevant for the
×
1786
        // Rebroadcaster.
×
1787
        switch {
×
1788
        // This makes sure the tx is removed from the rebroadcaster once it is
1789
        // confirmed.
1790
        case errors.Is(err, chain.ErrTxAlreadyKnown),
1791
                errors.Is(err, chain.ErrTxAlreadyConfirmed):
×
1792

×
1793
                returnErr = &pushtx.BroadcastError{
×
1794
                        Code:   pushtx.Confirmed,
×
1795
                        Reason: err.Error(),
×
1796
                }
×
1797

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

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

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

×
1817
                returnErr = &pushtx.BroadcastError{
×
1818
                        Code:   pushtx.Mempool,
×
1819
                        Reason: err.Error(),
×
1820
                }
×
1821
        }
1822

1823
        return returnErr
×
1824
}
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