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

lightningnetwork / lnd / 14000719599

21 Mar 2025 08:54PM UTC coverage: 58.717% (-10.3%) from 68.989%
14000719599

Pull #8754

github

web-flow
Merge 29f363f18 into 5235f3b24
Pull Request #8754: Add `Outbound` Remote Signer implementation

1562 of 2088 new or added lines in 41 files covered. (74.81%)

28126 existing lines in 464 files now uncovered.

97953 of 166822 relevant lines covered (58.72%)

1.82 hits per line

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

65.93
/config_builder.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
260
        return nil
3✔
261
}
3✔
262

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

717
        *pushtx.Broadcaster
718
}
719

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
858
        // Keeps track of both the remote signer and the chain control clean up
3✔
859
        // functions.
3✔
860
        var (
3✔
861
                cleanUpTasks []func()
3✔
862
                cleanUp      = func() {
6✔
863
                        for _, fn := range cleanUpTasks {
6✔
864
                                fn()
3✔
865
                        }
3✔
866
                }
867
        )
868

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

878
        remoteSignerConnBuilder := rpcwallet.NewRemoteSignerConnectionBuilder(
3✔
879
                d.DefaultWalletImpl.cfg.RemoteSigner,
3✔
880
        )
3✔
881

3✔
882
        // Create the remote signer connection instance.
3✔
883
        remoteSignerConn, err := remoteSignerConnBuilder.Build(
3✔
884
                context.Background(),
3✔
885
        )
3✔
886
        if err != nil {
3✔
NEW
887
                err := fmt.Errorf("unable to set up remote signer: %w", err)
×
NEW
888
                d.logger.Error(err)
×
NEW
889

×
NEW
890
                return nil, cleanUp, err
×
NEW
891
        }
×
892

893
        cleanUpTasks = append(cleanUpTasks, remoteSignerConn.Stop)
3✔
894

3✔
895
        baseKeyRing := keychain.NewBtcWalletKeyRing(
3✔
896
                walletController.InternalWallet(), walletConfig.CoinType,
3✔
897
        )
3✔
898

3✔
899
        rpcKeyRing, err := rpcwallet.NewRPCKeyRing(
3✔
900
                baseKeyRing, walletController,
3✔
901
                remoteSignerConn, walletConfig.NetParams,
3✔
902
        )
3✔
903
        if err != nil {
3✔
904
                err := fmt.Errorf("unable to create RPC remote signing wallet "+
×
905
                        "%v", err)
×
906
                d.logger.Error(err)
×
NEW
907

×
NEW
908
                return nil, cleanUp, err
×
UNCOV
909
        }
×
910

911
        // Create, and start the lnwallet, which handles the core payment
912
        // channel logic, and exposes control via proxy state machines.
913
        lnWalletConfig := lnwallet.Config{
3✔
914
                Database:              partialChainControl.Cfg.ChanStateDB,
3✔
915
                Notifier:              partialChainControl.ChainNotifier,
3✔
916
                WalletController:      rpcKeyRing,
3✔
917
                Signer:                rpcKeyRing,
3✔
918
                FeeEstimator:          partialChainControl.FeeEstimator,
3✔
919
                SecretKeyRing:         rpcKeyRing,
3✔
920
                ChainIO:               walletController,
3✔
921
                NetParams:             *walletConfig.NetParams,
3✔
922
                CoinSelectionStrategy: walletConfig.CoinSelectionStrategy,
3✔
923
        }
3✔
924

3✔
925
        // We've created the wallet configuration now, so we can finish
3✔
926
        // initializing the main chain control.
3✔
927
        activeChainControl, ccCleanUp, err := chainreg.NewChainControl(
3✔
928
                lnWalletConfig, rpcKeyRing, partialChainControl,
3✔
929
        )
3✔
930
        if err != nil {
3✔
931
                err := fmt.Errorf("unable to create chain control: %w", err)
×
932
                d.logger.Error(err)
×
NEW
933

×
NEW
934
                return nil, cleanUp, err
×
UNCOV
935
        }
×
936

937
        cleanUpTasks = append(cleanUpTasks, ccCleanUp)
3✔
938

3✔
939
        return activeChainControl, cleanUp, nil
3✔
940
}
941

942
// DatabaseInstances is a struct that holds all instances to the actual
943
// databases that are used in lnd.
944
type DatabaseInstances struct {
945
        // GraphDB is the database that stores the channel graph used for path
946
        // finding.
947
        GraphDB *graphdb.ChannelGraph
948

949
        // ChanStateDB is the database that stores all of our node's channel
950
        // state.
951
        ChanStateDB *channeldb.DB
952

953
        // HeightHintDB is the database that stores height hints for spends.
954
        HeightHintDB kvdb.Backend
955

956
        // InvoiceDB is the database that stores information about invoices.
957
        InvoiceDB invoices.InvoiceDB
958

959
        // MacaroonDB is the database that stores macaroon root keys.
960
        MacaroonDB kvdb.Backend
961

962
        // DecayedLogDB is the database that stores p2p related encryption
963
        // information.
964
        DecayedLogDB kvdb.Backend
965

966
        // TowerClientDB is the database that stores the watchtower client's
967
        // configuration.
968
        TowerClientDB wtclient.DB
969

970
        // TowerServerDB is the database that stores the watchtower server's
971
        // configuration.
972
        TowerServerDB watchtower.DB
973

974
        // WalletDB is the configuration for loading the wallet database using
975
        // the btcwallet's loader.
976
        WalletDB btcwallet.LoaderOption
977

978
        // NativeSQLStore holds a reference to the native SQL store that can
979
        // be used for native SQL queries for tables that already support it.
980
        // This may be nil if the use-native-sql flag was not set.
981
        NativeSQLStore sqldb.DB
982
}
983

984
// DefaultDatabaseBuilder is a type that builds the default database backends
985
// for lnd, using the given configuration to decide what actual implementation
986
// to use.
987
type DefaultDatabaseBuilder struct {
988
        cfg    *Config
989
        logger btclog.Logger
990
}
991

992
// NewDefaultDatabaseBuilder returns a new instance of the default database
993
// builder.
994
func NewDefaultDatabaseBuilder(cfg *Config,
995
        logger btclog.Logger) *DefaultDatabaseBuilder {
3✔
996

3✔
997
        return &DefaultDatabaseBuilder{
3✔
998
                cfg:    cfg,
3✔
999
                logger: logger,
3✔
1000
        }
3✔
1001
}
3✔
1002

1003
// BuildDatabase extracts the current databases that we'll use for normal
1004
// operation in the daemon. A function closure that closes all opened databases
1005
// is also returned.
1006
func (d *DefaultDatabaseBuilder) BuildDatabase(
1007
        ctx context.Context) (*DatabaseInstances, func(), error) {
3✔
1008

3✔
1009
        d.logger.Infof("Opening the main database, this might take a few " +
3✔
1010
                "minutes...")
3✔
1011

3✔
1012
        cfg := d.cfg
3✔
1013
        if cfg.DB.Backend == lncfg.BoltBackend {
6✔
1014
                d.logger.Infof("Opening bbolt database, sync_freelist=%v, "+
3✔
1015
                        "auto_compact=%v", !cfg.DB.Bolt.NoFreelistSync,
3✔
1016
                        cfg.DB.Bolt.AutoCompact)
3✔
1017
        }
3✔
1018

1019
        startOpenTime := time.Now()
3✔
1020

3✔
1021
        databaseBackends, err := cfg.DB.GetBackends(
3✔
1022
                ctx, cfg.graphDatabaseDir(), cfg.networkDir, filepath.Join(
3✔
1023
                        cfg.Watchtower.TowerDir, BitcoinChainName,
3✔
1024
                        lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
3✔
1025
                ), cfg.WtClient.Active, cfg.Watchtower.Active, d.logger,
3✔
1026
        )
3✔
1027
        if err != nil {
3✔
1028
                return nil, nil, fmt.Errorf("unable to obtain database "+
×
1029
                        "backends: %v", err)
×
1030
        }
×
1031

1032
        // With the full remote mode we made sure both the graph and channel
1033
        // state DB point to the same local or remote DB and the same namespace
1034
        // within that DB.
1035
        dbs := &DatabaseInstances{
3✔
1036
                HeightHintDB:   databaseBackends.HeightHintDB,
3✔
1037
                MacaroonDB:     databaseBackends.MacaroonDB,
3✔
1038
                DecayedLogDB:   databaseBackends.DecayedLogDB,
3✔
1039
                WalletDB:       databaseBackends.WalletDB,
3✔
1040
                NativeSQLStore: databaseBackends.NativeSQLStore,
3✔
1041
        }
3✔
1042
        cleanUp := func() {
6✔
1043
                // We can just close the returned close functions directly. Even
3✔
1044
                // if we decorate the channel DB with an additional struct, its
3✔
1045
                // close function still just points to the kvdb backend.
3✔
1046
                for name, closeFunc := range databaseBackends.CloseFuncs {
6✔
1047
                        if err := closeFunc(); err != nil {
3✔
1048
                                d.logger.Errorf("Error closing %s "+
×
1049
                                        "database: %v", name, err)
×
1050
                        }
×
1051
                }
1052
        }
1053
        if databaseBackends.Remote {
3✔
1054
                d.logger.Infof("Using remote %v database! Creating "+
×
1055
                        "graph and channel state DB instances", cfg.DB.Backend)
×
1056
        } else {
3✔
1057
                d.logger.Infof("Creating local graph and channel state DB " +
3✔
1058
                        "instances")
3✔
1059
        }
3✔
1060

1061
        graphDBOptions := []graphdb.OptionModifier{
3✔
1062
                graphdb.WithRejectCacheSize(cfg.Caches.RejectCacheSize),
3✔
1063
                graphdb.WithChannelCacheSize(cfg.Caches.ChannelCacheSize),
3✔
1064
                graphdb.WithBatchCommitInterval(cfg.DB.BatchCommitInterval),
3✔
1065
                graphdb.WithUseGraphCache(!cfg.DB.NoGraphCache),
3✔
1066
        }
3✔
1067

3✔
1068
        // We want to pre-allocate the channel graph cache according to what we
3✔
1069
        // expect for mainnet to speed up memory allocation.
3✔
1070
        if cfg.ActiveNetParams.Name == chaincfg.MainNetParams.Name {
3✔
1071
                graphDBOptions = append(
×
1072
                        graphDBOptions, graphdb.WithPreAllocCacheNumNodes(
×
1073
                                graphdb.DefaultPreAllocCacheNumNodes,
×
1074
                        ),
×
1075
                )
×
1076
        }
×
1077

1078
        dbs.GraphDB, err = graphdb.NewChannelGraph(
3✔
1079
                databaseBackends.GraphDB, graphDBOptions...,
3✔
1080
        )
3✔
1081
        if err != nil {
3✔
1082
                cleanUp()
×
1083

×
1084
                err = fmt.Errorf("unable to open graph DB: %w", err)
×
1085
                d.logger.Error(err)
×
1086

×
1087
                return nil, nil, err
×
1088
        }
×
1089

1090
        dbOptions := []channeldb.OptionModifier{
3✔
1091
                channeldb.OptionDryRunMigration(cfg.DryRunMigration),
3✔
1092
                channeldb.OptionKeepFailedPaymentAttempts(
3✔
1093
                        cfg.KeepFailedPaymentAttempts,
3✔
1094
                ),
3✔
1095
                channeldb.OptionStoreFinalHtlcResolutions(
3✔
1096
                        cfg.StoreFinalHtlcResolutions,
3✔
1097
                ),
3✔
1098
                channeldb.OptionPruneRevocationLog(cfg.DB.PruneRevocation),
3✔
1099
                channeldb.OptionNoRevLogAmtData(cfg.DB.NoRevLogAmtData),
3✔
1100
        }
3✔
1101

3✔
1102
        // Otherwise, we'll open two instances, one for the state we only need
3✔
1103
        // locally, and the other for things we want to ensure are replicated.
3✔
1104
        dbs.ChanStateDB, err = channeldb.CreateWithBackend(
3✔
1105
                databaseBackends.ChanStateDB, dbOptions...,
3✔
1106
        )
3✔
1107
        switch {
3✔
1108
        // Give the DB a chance to dry run the migration. Since we know that
1109
        // both the channel state and graph DBs are still always behind the same
1110
        // backend, we know this would be applied to both of those DBs.
1111
        case err == channeldb.ErrDryRunMigrationOK:
×
1112
                d.logger.Infof("Channel DB dry run migration successful")
×
1113
                return nil, nil, err
×
1114

1115
        case err != nil:
×
1116
                cleanUp()
×
1117

×
1118
                err = fmt.Errorf("unable to open graph DB: %w", err)
×
1119
                d.logger.Error(err)
×
1120
                return nil, nil, err
×
1121
        }
1122

1123
        // Instantiate a native SQL store if the flag is set.
1124
        if d.cfg.DB.UseNativeSQL {
3✔
1125
                migrations := sqldb.GetMigrations()
×
1126

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

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

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

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

1161
                                migrations[i].MigrationFn = migrationFn
×
1162
                        }
1163
                }
1164

1165
                // We need to apply all migrations to the native SQL store
1166
                // before we can use it.
1167
                err = dbs.NativeSQLStore.ApplyAllMigrations(ctx, migrations)
×
1168
                if err != nil {
×
1169
                        cleanUp()
×
1170
                        err = fmt.Errorf("faild to run migrations for the "+
×
1171
                                "native SQL store: %w", err)
×
1172
                        d.logger.Error(err)
×
1173

×
1174
                        return nil, nil, err
×
1175
                }
×
1176

1177
                // With the DB ready and migrations applied, we can now create
1178
                // the base DB and transaction executor for the native SQL
1179
                // invoice store.
1180
                baseDB := dbs.NativeSQLStore.GetBaseDB()
×
1181
                executor := sqldb.NewTransactionExecutor(
×
1182
                        baseDB, func(tx *sql.Tx) invoices.SQLInvoiceQueries {
×
1183
                                return baseDB.WithTx(tx)
×
1184
                        },
×
1185
                )
1186

1187
                sqlInvoiceDB := invoices.NewSQLStore(
×
1188
                        executor, clock.NewDefaultClock(),
×
1189
                )
×
1190

×
1191
                dbs.InvoiceDB = sqlInvoiceDB
×
1192
        } else {
3✔
1193
                // Check if the invoice bucket tombstone is set. If it is, we
3✔
1194
                // need to return and ask the user switch back to using the
3✔
1195
                // native SQL store.
3✔
1196
                ripInvoices, err := dbs.ChanStateDB.GetInvoiceBucketTombstone()
3✔
1197
                d.logger.Debugf("Invoice bucket tombstone set to: %v",
3✔
1198
                        ripInvoices)
3✔
1199

3✔
1200
                if err != nil {
3✔
1201
                        err = fmt.Errorf("unable to check invoice bucket "+
×
1202
                                "tombstone: %w", err)
×
1203
                        d.logger.Error(err)
×
1204

×
1205
                        return nil, nil, err
×
1206
                }
×
1207
                if ripInvoices {
3✔
1208
                        err = fmt.Errorf("invoices bucket tombstoned, please " +
×
1209
                                "switch back to native SQL")
×
1210
                        d.logger.Error(err)
×
1211

×
1212
                        return nil, nil, err
×
1213
                }
×
1214

1215
                dbs.InvoiceDB = dbs.ChanStateDB
3✔
1216
        }
1217

1218
        // Wrap the watchtower client DB and make sure we clean up.
1219
        if cfg.WtClient.Active {
6✔
1220
                dbs.TowerClientDB, err = wtdb.OpenClientDB(
3✔
1221
                        databaseBackends.TowerClientDB,
3✔
1222
                )
3✔
1223
                if err != nil {
3✔
1224
                        cleanUp()
×
1225

×
1226
                        err = fmt.Errorf("unable to open %s database: %w",
×
1227
                                lncfg.NSTowerClientDB, err)
×
1228
                        d.logger.Error(err)
×
1229
                        return nil, nil, err
×
1230
                }
×
1231
        }
1232

1233
        // Wrap the watchtower server DB and make sure we clean up.
1234
        if cfg.Watchtower.Active {
6✔
1235
                dbs.TowerServerDB, err = wtdb.OpenTowerDB(
3✔
1236
                        databaseBackends.TowerServerDB,
3✔
1237
                )
3✔
1238
                if err != nil {
3✔
1239
                        cleanUp()
×
1240

×
1241
                        err = fmt.Errorf("unable to open %s database: %w",
×
1242
                                lncfg.NSTowerServerDB, err)
×
1243
                        d.logger.Error(err)
×
1244
                        return nil, nil, err
×
1245
                }
×
1246
        }
1247

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

3✔
1251
        return dbs, cleanUp, nil
3✔
1252
}
1253

1254
// waitForWalletPassword blocks until a password is provided by the user to
1255
// this RPC server.
1256
func waitForWalletPassword(cfg *Config,
1257
        pwService *walletunlocker.UnlockerService,
1258
        loaderOpts []btcwallet.LoaderOption, shutdownChan <-chan struct{}) (
1259
        *walletunlocker.WalletUnlockParams, error) {
3✔
1260

3✔
1261
        // Wait for user to provide the password.
3✔
1262
        ltndLog.Infof("Waiting for wallet encryption password. Use `lncli " +
3✔
1263
                "create` to create a wallet, `lncli unlock` to unlock an " +
3✔
1264
                "existing wallet, or `lncli changepassword` to change the " +
3✔
1265
                "password of an existing wallet and unlock it.")
3✔
1266

3✔
1267
        // We currently don't distinguish between getting a password to be used
3✔
1268
        // for creation or unlocking, as a new wallet db will be created if
3✔
1269
        // none exists when creating the chain control.
3✔
1270
        select {
3✔
1271
        // The wallet is being created for the first time, we'll check to see
1272
        // if the user provided any entropy for seed creation. If so, then
1273
        // we'll create the wallet early to load the seed.
1274
        case initMsg := <-pwService.InitMsgs:
3✔
1275
                password := initMsg.Passphrase
3✔
1276
                cipherSeed := initMsg.WalletSeed
3✔
1277
                extendedKey := initMsg.WalletExtendedKey
3✔
1278
                watchOnlyAccounts := initMsg.WatchOnlyAccounts
3✔
1279
                recoveryWindow := initMsg.RecoveryWindow
3✔
1280

3✔
1281
                // Before we proceed, we'll check the internal version of the
3✔
1282
                // seed. If it's greater than the current key derivation
3✔
1283
                // version, then we'll return an error as we don't understand
3✔
1284
                // this.
3✔
1285
                if cipherSeed != nil &&
3✔
1286
                        !keychain.IsKnownVersion(cipherSeed.InternalVersion) {
3✔
1287

×
1288
                        return nil, fmt.Errorf("invalid internal "+
×
1289
                                "seed version %v, current max version is %v",
×
1290
                                cipherSeed.InternalVersion,
×
1291
                                keychain.CurrentKeyDerivationVersion)
×
1292
                }
×
1293

1294
                loader, err := btcwallet.NewWalletLoader(
3✔
1295
                        cfg.ActiveNetParams.Params, recoveryWindow,
3✔
1296
                        loaderOpts...,
3✔
1297
                )
3✔
1298
                if err != nil {
3✔
1299
                        return nil, err
×
1300
                }
×
1301

1302
                // With the seed, we can now use the wallet loader to create
1303
                // the wallet, then pass it back to avoid unlocking it again.
1304
                var (
3✔
1305
                        birthday  time.Time
3✔
1306
                        newWallet *wallet.Wallet
3✔
1307
                )
3✔
1308
                switch {
3✔
1309
                // A normal cipher seed was given, use the birthday encoded in
1310
                // it and create the wallet from that.
1311
                case cipherSeed != nil:
3✔
1312
                        birthday = cipherSeed.BirthdayTime()
3✔
1313
                        newWallet, err = loader.CreateNewWallet(
3✔
1314
                                password, password, cipherSeed.Entropy[:],
3✔
1315
                                birthday,
3✔
1316
                        )
3✔
1317

1318
                // No seed was given, we're importing a wallet from its extended
1319
                // private key.
1320
                case extendedKey != nil:
3✔
1321
                        birthday = initMsg.ExtendedKeyBirthday
3✔
1322
                        newWallet, err = loader.CreateNewWalletExtendedKey(
3✔
1323
                                password, password, extendedKey, birthday,
3✔
1324
                        )
3✔
1325

1326
                // Neither seed nor extended private key was given, so maybe the
1327
                // third option was chosen, the watch-only initialization. In
1328
                // this case we need to import each of the xpubs individually.
1329
                case watchOnlyAccounts != nil:
3✔
1330
                        if !cfg.RemoteSigner.Enable {
3✔
1331
                                return nil, fmt.Errorf("cannot initialize " +
×
1332
                                        "watch only wallet with remote " +
×
1333
                                        "signer config disabled")
×
1334
                        }
×
1335

1336
                        birthday = initMsg.WatchOnlyBirthday
3✔
1337
                        newWallet, err = loader.CreateNewWatchingOnlyWallet(
3✔
1338
                                password, birthday,
3✔
1339
                        )
3✔
1340
                        if err != nil {
3✔
1341
                                break
×
1342
                        }
1343

1344
                        err = importWatchOnlyAccounts(newWallet, initMsg)
3✔
1345

1346
                default:
×
1347
                        // The unlocker service made sure either the cipher seed
×
1348
                        // or the extended key is set so, we shouldn't get here.
×
1349
                        // The default case is just here for readability and
×
1350
                        // completeness.
×
1351
                        err = fmt.Errorf("cannot create wallet, neither seed " +
×
1352
                                "nor extended key was given")
×
1353
                }
1354
                if err != nil {
3✔
1355
                        // Don't leave the file open in case the new wallet
×
1356
                        // could not be created for whatever reason.
×
1357
                        if err := loader.UnloadWallet(); err != nil {
×
1358
                                ltndLog.Errorf("Could not unload new "+
×
1359
                                        "wallet: %v", err)
×
1360
                        }
×
1361
                        return nil, err
×
1362
                }
1363

1364
                // For new wallets, the ResetWalletTransactions flag is a no-op.
1365
                if cfg.ResetWalletTransactions {
6✔
1366
                        ltndLog.Warnf("Ignoring reset-wallet-transactions " +
3✔
1367
                                "flag for new wallet as it has no effect")
3✔
1368
                }
3✔
1369

1370
                return &walletunlocker.WalletUnlockParams{
3✔
1371
                        Password:        password,
3✔
1372
                        Birthday:        birthday,
3✔
1373
                        RecoveryWindow:  recoveryWindow,
3✔
1374
                        Wallet:          newWallet,
3✔
1375
                        ChansToRestore:  initMsg.ChanBackups,
3✔
1376
                        UnloadWallet:    loader.UnloadWallet,
3✔
1377
                        StatelessInit:   initMsg.StatelessInit,
3✔
1378
                        MacResponseChan: pwService.MacResponseChan,
3✔
1379
                        MacRootKey:      initMsg.MacRootKey,
3✔
1380
                }, nil
3✔
1381

1382
        // The wallet has already been created in the past, and is simply being
1383
        // unlocked. So we'll just return these passphrases.
1384
        case unlockMsg := <-pwService.UnlockMsgs:
3✔
1385
                // Resetting the transactions is something the user likely only
3✔
1386
                // wants to do once so we add a prominent warning to the log to
3✔
1387
                // remind the user to turn off the setting again after
3✔
1388
                // successful completion.
3✔
1389
                if cfg.ResetWalletTransactions {
6✔
1390
                        ltndLog.Warnf("Dropped all transaction history from " +
3✔
1391
                                "on-chain wallet. Remember to disable " +
3✔
1392
                                "reset-wallet-transactions flag for next " +
3✔
1393
                                "start of lnd")
3✔
1394
                }
3✔
1395

1396
                return &walletunlocker.WalletUnlockParams{
3✔
1397
                        Password:        unlockMsg.Passphrase,
3✔
1398
                        RecoveryWindow:  unlockMsg.RecoveryWindow,
3✔
1399
                        Wallet:          unlockMsg.Wallet,
3✔
1400
                        ChansToRestore:  unlockMsg.ChanBackups,
3✔
1401
                        UnloadWallet:    unlockMsg.UnloadWallet,
3✔
1402
                        StatelessInit:   unlockMsg.StatelessInit,
3✔
1403
                        MacResponseChan: pwService.MacResponseChan,
3✔
1404
                }, nil
3✔
1405

1406
        // If we got a shutdown signal we just return with an error immediately
1407
        case <-shutdownChan:
×
1408
                return nil, fmt.Errorf("shutting down")
×
1409
        }
1410
}
1411

1412
// importWatchOnlyAccounts imports all individual account xpubs into our wallet
1413
// which we created as watch-only.
1414
func importWatchOnlyAccounts(wallet *wallet.Wallet,
1415
        initMsg *walletunlocker.WalletInitMsg) error {
3✔
1416

3✔
1417
        scopes := make([]waddrmgr.ScopedIndex, 0, len(initMsg.WatchOnlyAccounts))
3✔
1418
        for scope := range initMsg.WatchOnlyAccounts {
6✔
1419
                scopes = append(scopes, scope)
3✔
1420
        }
3✔
1421

1422
        // We need to import the accounts in the correct order, otherwise the
1423
        // indices will be incorrect.
1424
        sort.Slice(scopes, func(i, j int) bool {
6✔
1425
                return scopes[i].Scope.Purpose < scopes[j].Scope.Purpose ||
3✔
1426
                        scopes[i].Index < scopes[j].Index
3✔
1427
        })
3✔
1428

1429
        for _, scope := range scopes {
6✔
1430
                addrSchema := waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0084]
3✔
1431

3✔
1432
                // We want witness pubkey hash by default, except for BIP49
3✔
1433
                // where we want mixed and BIP86 where we want taproot address
3✔
1434
                // formats.
3✔
1435
                switch scope.Scope.Purpose {
3✔
1436
                case waddrmgr.KeyScopeBIP0049Plus.Purpose,
1437
                        waddrmgr.KeyScopeBIP0086.Purpose:
3✔
1438

3✔
1439
                        addrSchema = waddrmgr.ScopeAddrMap[scope.Scope]
3✔
1440
                }
1441

1442
                // We want a human-readable account name. But for the default
1443
                // on-chain wallet we actually need to call it "default" to make
1444
                // sure everything works correctly.
1445
                name := fmt.Sprintf("%s/%d'", scope.Scope.String(), scope.Index)
3✔
1446
                if scope.Index == 0 {
6✔
1447
                        name = "default"
3✔
1448
                }
3✔
1449

1450
                _, err := wallet.ImportAccountWithScope(
3✔
1451
                        name, initMsg.WatchOnlyAccounts[scope],
3✔
1452
                        initMsg.WatchOnlyMasterFingerprint, scope.Scope,
3✔
1453
                        addrSchema,
3✔
1454
                )
3✔
1455
                if err != nil {
3✔
1456
                        return fmt.Errorf("could not import account %v: %w",
×
1457
                                name, err)
×
1458
                }
×
1459
        }
1460

1461
        return nil
3✔
1462
}
1463

1464
// initNeutrinoBackend inits a new instance of the neutrino light client
1465
// backend given a target chain directory to store the chain state.
1466
func initNeutrinoBackend(ctx context.Context, cfg *Config, chainDir string,
1467
        blockCache *blockcache.BlockCache) (*neutrino.ChainService,
1468
        func(), error) {
1✔
1469

1✔
1470
        // Both channel validation flags are false by default but their meaning
1✔
1471
        // is the inverse of each other. Therefore both cannot be true. For
1✔
1472
        // every other case, the neutrino.validatechannels overwrites the
1✔
1473
        // routing.assumechanvalid value.
1✔
1474
        if cfg.NeutrinoMode.ValidateChannels && cfg.Routing.AssumeChannelValid {
1✔
1475
                return nil, nil, fmt.Errorf("can't set both " +
×
1476
                        "neutrino.validatechannels and routing." +
×
1477
                        "assumechanvalid to true at the same time")
×
1478
        }
×
1479
        cfg.Routing.AssumeChannelValid = !cfg.NeutrinoMode.ValidateChannels
1✔
1480

1✔
1481
        // First we'll open the database file for neutrino, creating the
1✔
1482
        // database if needed. We append the normalized network name here to
1✔
1483
        // match the behavior of btcwallet.
1✔
1484
        dbPath := filepath.Join(
1✔
1485
                chainDir, lncfg.NormalizeNetwork(cfg.ActiveNetParams.Name),
1✔
1486
        )
1✔
1487

1✔
1488
        // Ensure that the neutrino db path exists.
1✔
1489
        if err := os.MkdirAll(dbPath, 0700); err != nil {
1✔
1490
                return nil, nil, err
×
1491
        }
×
1492

1493
        var (
1✔
1494
                db  walletdb.DB
1✔
1495
                err error
1✔
1496
        )
1✔
1497
        switch {
1✔
1498
        case cfg.DB.Backend == kvdb.SqliteBackendName:
×
1499
                sqliteConfig := lncfg.GetSqliteConfigKVDB(cfg.DB.Sqlite)
×
1500
                db, err = kvdb.Open(
×
1501
                        kvdb.SqliteBackendName, ctx, sqliteConfig, dbPath,
×
1502
                        lncfg.SqliteNeutrinoDBName, lncfg.NSNeutrinoDB,
×
1503
                )
×
1504

1505
        default:
1✔
1506
                dbName := filepath.Join(dbPath, "neutrino.db")
1✔
1507
                db, err = walletdb.Create(
1✔
1508
                        "bdb", dbName, !cfg.SyncFreelist, cfg.DB.Bolt.DBTimeout,
1✔
1509
                )
1✔
1510
        }
1511
        if err != nil {
1✔
1512
                return nil, nil, fmt.Errorf("unable to create "+
×
1513
                        "neutrino database: %v", err)
×
1514
        }
×
1515

1516
        headerStateAssertion, err := parseHeaderStateAssertion(
1✔
1517
                cfg.NeutrinoMode.AssertFilterHeader,
1✔
1518
        )
1✔
1519
        if err != nil {
1✔
1520
                db.Close()
×
1521
                return nil, nil, err
×
1522
        }
×
1523

1524
        // With the database open, we can now create an instance of the
1525
        // neutrino light client. We pass in relevant configuration parameters
1526
        // required.
1527
        config := neutrino.Config{
1✔
1528
                DataDir:      dbPath,
1✔
1529
                Database:     db,
1✔
1530
                ChainParams:  *cfg.ActiveNetParams.Params,
1✔
1531
                AddPeers:     cfg.NeutrinoMode.AddPeers,
1✔
1532
                ConnectPeers: cfg.NeutrinoMode.ConnectPeers,
1✔
1533
                Dialer: func(addr net.Addr) (net.Conn, error) {
2✔
1534
                        return cfg.net.Dial(
1✔
1535
                                addr.Network(), addr.String(),
1✔
1536
                                cfg.ConnectionTimeout,
1✔
1537
                        )
1✔
1538
                },
1✔
1539
                NameResolver: func(host string) ([]net.IP, error) {
1✔
1540
                        addrs, err := cfg.net.LookupHost(host)
1✔
1541
                        if err != nil {
1✔
1542
                                return nil, err
×
1543
                        }
×
1544

1545
                        ips := make([]net.IP, 0, len(addrs))
1✔
1546
                        for _, strIP := range addrs {
2✔
1547
                                ip := net.ParseIP(strIP)
1✔
1548
                                if ip == nil {
1✔
1549
                                        continue
×
1550
                                }
1551

1552
                                ips = append(ips, ip)
1✔
1553
                        }
1554

1555
                        return ips, nil
1✔
1556
                },
1557
                AssertFilterHeader: headerStateAssertion,
1558
                BlockCache:         blockCache.Cache,
1559
                BroadcastTimeout:   cfg.NeutrinoMode.BroadcastTimeout,
1560
                PersistToDisk:      cfg.NeutrinoMode.PersistFilters,
1561
        }
1562

1563
        if cfg.NeutrinoMode.MaxPeers <= 0 {
1✔
1564
                return nil, nil, fmt.Errorf("a non-zero number must be set " +
×
1565
                        "for neutrino max peers")
×
1566
        }
×
1567
        neutrino.MaxPeers = cfg.NeutrinoMode.MaxPeers
1✔
1568
        neutrino.BanDuration = time.Hour * 48
1✔
1569
        neutrino.UserAgentName = cfg.NeutrinoMode.UserAgentName
1✔
1570
        neutrino.UserAgentVersion = cfg.NeutrinoMode.UserAgentVersion
1✔
1571

1✔
1572
        neutrinoCS, err := neutrino.NewChainService(config)
1✔
1573
        if err != nil {
1✔
1574
                db.Close()
×
1575
                return nil, nil, fmt.Errorf("unable to create neutrino light "+
×
1576
                        "client: %v", err)
×
1577
        }
×
1578

1579
        if err := neutrinoCS.Start(); err != nil {
1✔
1580
                db.Close()
×
1581
                return nil, nil, err
×
1582
        }
×
1583

1584
        cleanUp := func() {
2✔
1585
                if err := neutrinoCS.Stop(); err != nil {
1✔
1586
                        ltndLog.Infof("Unable to stop neutrino light client: "+
×
1587
                                "%v", err)
×
1588
                }
×
1589
                db.Close()
1✔
1590
        }
1591

1592
        return neutrinoCS, cleanUp, nil
1✔
1593
}
1594

1595
// parseHeaderStateAssertion parses the user-specified neutrino header state
1596
// into a headerfs.FilterHeader.
1597
func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) {
1✔
1598
        if len(state) == 0 {
2✔
1599
                return nil, nil
1✔
1600
        }
1✔
1601

1602
        split := strings.Split(state, ":")
×
1603
        if len(split) != 2 {
×
1604
                return nil, fmt.Errorf("header state assertion %v in "+
×
1605
                        "unexpected format, expected format height:hash", state)
×
1606
        }
×
1607

1608
        height, err := strconv.ParseUint(split[0], 10, 32)
×
1609
        if err != nil {
×
1610
                return nil, fmt.Errorf("invalid filter header height: %w", err)
×
1611
        }
×
1612

1613
        hash, err := chainhash.NewHashFromStr(split[1])
×
1614
        if err != nil {
×
1615
                return nil, fmt.Errorf("invalid filter header hash: %w", err)
×
1616
        }
×
1617

1618
        return &headerfs.FilterHeader{
×
1619
                Height:     uint32(height),
×
1620
                FilterHash: *hash,
×
1621
        }, nil
×
1622
}
1623

1624
// broadcastErrorMapper maps errors from bitcoin backends other than neutrino to
1625
// the neutrino BroadcastError which allows the Rebroadcaster which currently
1626
// resides in the neutrino package to use all of its functionalities.
1627
func broadcastErrorMapper(err error) error {
2✔
1628
        var returnErr error
2✔
1629

2✔
1630
        // We only filter for specific backend errors which are relevant for the
2✔
1631
        // Rebroadcaster.
2✔
1632
        switch {
2✔
1633
        // This makes sure the tx is removed from the rebroadcaster once it is
1634
        // confirmed.
1635
        case errors.Is(err, chain.ErrTxAlreadyKnown),
1636
                errors.Is(err, chain.ErrTxAlreadyConfirmed):
1✔
1637

1✔
1638
                returnErr = &pushtx.BroadcastError{
1✔
1639
                        Code:   pushtx.Confirmed,
1✔
1640
                        Reason: err.Error(),
1✔
1641
                }
1✔
1642

1643
        // Transactions which are still in mempool but might fall out because
1644
        // of low fees are rebroadcasted despite of their backend error.
1645
        case errors.Is(err, chain.ErrTxAlreadyInMempool):
×
1646
                returnErr = &pushtx.BroadcastError{
×
1647
                        Code:   pushtx.Mempool,
×
1648
                        Reason: err.Error(),
×
1649
                }
×
1650

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

×
1659
                returnErr = &pushtx.BroadcastError{
×
1660
                        Code:   pushtx.Mempool,
×
1661
                        Reason: err.Error(),
×
1662
                }
×
1663
        }
1664

1665
        return returnErr
2✔
1666
}
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