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

lightningnetwork / lnd / 17101605539

20 Aug 2025 02:35PM UTC coverage: 57.321% (-9.4%) from 66.68%
17101605539

push

github

web-flow
Merge pull request #10102 from yyforyongyu/fix-UpdatesInHorizon

Catch bad gossip peer and fix `UpdatesInHorizon`

28 of 89 new or added lines in 4 files covered. (31.46%)

29163 existing lines in 459 files now uncovered.

99187 of 173038 relevant lines covered (57.32%)

1.78 hits per line

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

69.49
/server.go
1
package lnd
2

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/rand"
7
        "encoding/hex"
8
        "errors"
9
        "fmt"
10
        "math/big"
11
        prand "math/rand"
12
        "net"
13
        "strconv"
14
        "strings"
15
        "sync"
16
        "sync/atomic"
17
        "time"
18

19
        "github.com/btcsuite/btcd/btcec/v2"
20
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
21
        "github.com/btcsuite/btcd/btcutil"
22
        "github.com/btcsuite/btcd/chaincfg"
23
        "github.com/btcsuite/btcd/chaincfg/chainhash"
24
        "github.com/btcsuite/btcd/connmgr"
25
        "github.com/btcsuite/btcd/txscript"
26
        "github.com/btcsuite/btcd/wire"
27
        "github.com/btcsuite/btclog/v2"
28
        sphinx "github.com/lightningnetwork/lightning-onion"
29
        "github.com/lightningnetwork/lnd/aliasmgr"
30
        "github.com/lightningnetwork/lnd/autopilot"
31
        "github.com/lightningnetwork/lnd/brontide"
32
        "github.com/lightningnetwork/lnd/chainio"
33
        "github.com/lightningnetwork/lnd/chainreg"
34
        "github.com/lightningnetwork/lnd/chanacceptor"
35
        "github.com/lightningnetwork/lnd/chanbackup"
36
        "github.com/lightningnetwork/lnd/chanfitness"
37
        "github.com/lightningnetwork/lnd/channeldb"
38
        "github.com/lightningnetwork/lnd/channelnotifier"
39
        "github.com/lightningnetwork/lnd/clock"
40
        "github.com/lightningnetwork/lnd/cluster"
41
        "github.com/lightningnetwork/lnd/contractcourt"
42
        "github.com/lightningnetwork/lnd/discovery"
43
        "github.com/lightningnetwork/lnd/feature"
44
        "github.com/lightningnetwork/lnd/fn/v2"
45
        "github.com/lightningnetwork/lnd/funding"
46
        "github.com/lightningnetwork/lnd/graph"
47
        graphdb "github.com/lightningnetwork/lnd/graph/db"
48
        "github.com/lightningnetwork/lnd/graph/db/models"
49
        "github.com/lightningnetwork/lnd/healthcheck"
50
        "github.com/lightningnetwork/lnd/htlcswitch"
51
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
52
        "github.com/lightningnetwork/lnd/input"
53
        "github.com/lightningnetwork/lnd/invoices"
54
        "github.com/lightningnetwork/lnd/keychain"
55
        "github.com/lightningnetwork/lnd/lncfg"
56
        "github.com/lightningnetwork/lnd/lnencrypt"
57
        "github.com/lightningnetwork/lnd/lnpeer"
58
        "github.com/lightningnetwork/lnd/lnrpc"
59
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
60
        "github.com/lightningnetwork/lnd/lnutils"
61
        "github.com/lightningnetwork/lnd/lnwallet"
62
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
63
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
64
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
65
        "github.com/lightningnetwork/lnd/lnwire"
66
        "github.com/lightningnetwork/lnd/nat"
67
        "github.com/lightningnetwork/lnd/netann"
68
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
69
        "github.com/lightningnetwork/lnd/peer"
70
        "github.com/lightningnetwork/lnd/peernotifier"
71
        "github.com/lightningnetwork/lnd/pool"
72
        "github.com/lightningnetwork/lnd/queue"
73
        "github.com/lightningnetwork/lnd/routing"
74
        "github.com/lightningnetwork/lnd/routing/localchans"
75
        "github.com/lightningnetwork/lnd/routing/route"
76
        "github.com/lightningnetwork/lnd/subscribe"
77
        "github.com/lightningnetwork/lnd/sweep"
78
        "github.com/lightningnetwork/lnd/ticker"
79
        "github.com/lightningnetwork/lnd/tor"
80
        "github.com/lightningnetwork/lnd/walletunlocker"
81
        "github.com/lightningnetwork/lnd/watchtower/blob"
82
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
83
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
84
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
85
)
86

87
const (
88
        // defaultMinPeers is the minimum number of peers nodes should always be
89
        // connected to.
90
        defaultMinPeers = 3
91

92
        // defaultStableConnDuration is a floor under which all reconnection
93
        // attempts will apply exponential randomized backoff. Connections
94
        // durations exceeding this value will be eligible to have their
95
        // backoffs reduced.
96
        defaultStableConnDuration = 10 * time.Minute
97

98
        // numInstantInitReconnect specifies how many persistent peers we should
99
        // always attempt outbound connections to immediately. After this value
100
        // is surpassed, the remaining peers will be randomly delayed using
101
        // maxInitReconnectDelay.
102
        numInstantInitReconnect = 10
103

104
        // maxInitReconnectDelay specifies the maximum delay in seconds we will
105
        // apply in attempting to reconnect to persistent peers on startup. The
106
        // value used or a particular peer will be chosen between 0s and this
107
        // value.
108
        maxInitReconnectDelay = 30
109

110
        // multiAddrConnectionStagger is the number of seconds to wait between
111
        // attempting to a peer with each of its advertised addresses.
112
        multiAddrConnectionStagger = 10 * time.Second
113
)
114

115
var (
116
        // ErrPeerNotConnected signals that the server has no connection to the
117
        // given peer.
118
        ErrPeerNotConnected = errors.New("peer is not connected")
119

120
        // ErrServerNotActive indicates that the server has started but hasn't
121
        // fully finished the startup process.
122
        ErrServerNotActive = errors.New("server is still in the process of " +
123
                "starting")
124

125
        // ErrServerShuttingDown indicates that the server is in the process of
126
        // gracefully exiting.
127
        ErrServerShuttingDown = errors.New("server is shutting down")
128

129
        // MaxFundingAmount is a soft-limit of the maximum channel size
130
        // currently accepted within the Lightning Protocol. This is
131
        // defined in BOLT-0002, and serves as an initial precautionary limit
132
        // while implementations are battle tested in the real world.
133
        //
134
        // At the moment, this value depends on which chain is active. It is set
135
        // to the value under the Bitcoin chain as default.
136
        //
137
        // TODO(roasbeef): add command line param to modify.
138
        MaxFundingAmount = funding.MaxBtcFundingAmount
139

140
        // EndorsementExperimentEnd is the time after which nodes should stop
141
        // propagating experimental endorsement signals.
142
        //
143
        // Per blip04: January 1, 2026 12:00:00 AM UTC in unix seconds.
144
        EndorsementExperimentEnd = time.Unix(1767225600, 0)
145

146
        // ErrGossiperBan is one of the errors that can be returned when we
147
        // attempt to finalize a connection to a remote peer.
148
        ErrGossiperBan = errors.New("gossiper has banned remote's key")
149

150
        // ErrNoMoreRestrictedAccessSlots is one of the errors that can be
151
        // returned when we attempt to finalize a connection. It means that
152
        // this peer has no pending-open, open, or closed channels with us and
153
        // are already at our connection ceiling for a peer with this access
154
        // status.
155
        ErrNoMoreRestrictedAccessSlots = errors.New("no more restricted slots")
156

157
        // ErrNoPeerScore is returned when we expect to find a score in
158
        // peerScores, but one does not exist.
159
        ErrNoPeerScore = errors.New("peer score not found")
160

161
        // ErrNoPendingPeerInfo is returned when we couldn't find any pending
162
        // peer info.
163
        ErrNoPendingPeerInfo = errors.New("no pending peer info")
164
)
165

166
// errPeerAlreadyConnected is an error returned by the server when we're
167
// commanded to connect to a peer, but they're already connected.
168
type errPeerAlreadyConnected struct {
169
        peer *peer.Brontide
170
}
171

172
// Error returns the human readable version of this error type.
173
//
174
// NOTE: Part of the error interface.
175
func (e *errPeerAlreadyConnected) Error() string {
3✔
176
        return fmt.Sprintf("already connected to peer: %v", e.peer)
3✔
177
}
3✔
178

179
// peerAccessStatus denotes the p2p access status of a given peer. This will be
180
// used to assign peer ban scores that determine an action the server will
181
// take.
182
type peerAccessStatus int
183

184
const (
185
        // peerStatusRestricted indicates that the peer only has access to the
186
        // limited number of "free" reserved slots.
187
        peerStatusRestricted peerAccessStatus = iota
188

189
        // peerStatusTemporary indicates that the peer only has temporary p2p
190
        // access to the server.
191
        peerStatusTemporary
192

193
        // peerStatusProtected indicates that the peer has been granted
194
        // permanent p2p access to the server. The peer can still have its
195
        // access revoked.
196
        peerStatusProtected
197
)
198

199
// String returns a human-readable representation of the status code.
200
func (p peerAccessStatus) String() string {
3✔
201
        switch p {
3✔
202
        case peerStatusRestricted:
3✔
203
                return "restricted"
3✔
204

205
        case peerStatusTemporary:
3✔
206
                return "temporary"
3✔
207

208
        case peerStatusProtected:
3✔
209
                return "protected"
3✔
210

211
        default:
×
212
                return "unknown"
×
213
        }
214
}
215

216
// peerSlotStatus determines whether a peer gets access to one of our free
217
// slots or gets to bypass this safety mechanism.
218
type peerSlotStatus struct {
219
        // state determines which privileges the peer has with our server.
220
        state peerAccessStatus
221
}
222

223
// server is the main server of the Lightning Network Daemon. The server houses
224
// global state pertaining to the wallet, database, and the rpcserver.
225
// Additionally, the server is also used as a central messaging bus to interact
226
// with any of its companion objects.
227
type server struct {
228
        active   int32 // atomic
229
        stopping int32 // atomic
230

231
        start sync.Once
232
        stop  sync.Once
233

234
        cfg *Config
235

236
        implCfg *ImplementationCfg
237

238
        // identityECDH is an ECDH capable wrapper for the private key used
239
        // to authenticate any incoming connections.
240
        identityECDH keychain.SingleKeyECDH
241

242
        // identityKeyLoc is the key locator for the above wrapped identity key.
243
        identityKeyLoc keychain.KeyLocator
244

245
        // nodeSigner is an implementation of the MessageSigner implementation
246
        // that's backed by the identity private key of the running lnd node.
247
        nodeSigner *netann.NodeSigner
248

249
        chanStatusMgr *netann.ChanStatusManager
250

251
        // listenAddrs is the list of addresses the server is currently
252
        // listening on.
253
        listenAddrs []net.Addr
254

255
        // torController is a client that will communicate with a locally
256
        // running Tor server. This client will handle initiating and
257
        // authenticating the connection to the Tor server, automatically
258
        // creating and setting up onion services, etc.
259
        torController *tor.Controller
260

261
        // natTraversal is the specific NAT traversal technique used to
262
        // automatically set up port forwarding rules in order to advertise to
263
        // the network that the node is accepting inbound connections.
264
        natTraversal nat.Traversal
265

266
        // lastDetectedIP is the last IP detected by the NAT traversal technique
267
        // above. This IP will be watched periodically in a goroutine in order
268
        // to handle dynamic IP changes.
269
        lastDetectedIP net.IP
270

271
        mu sync.RWMutex
272

273
        // peersByPub is a map of the active peers.
274
        //
275
        // NOTE: The key used here is the raw bytes of the peer's public key to
276
        // string conversion, which means it cannot be printed using `%s` as it
277
        // will just print the binary.
278
        //
279
        // TODO(yy): Use the hex string instead.
280
        peersByPub map[string]*peer.Brontide
281

282
        inboundPeers  map[string]*peer.Brontide
283
        outboundPeers map[string]*peer.Brontide
284

285
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
286
        peerDisconnectedListeners map[string][]chan<- struct{}
287

288
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
289
        // will continue to send messages even if there are no active channels
290
        // and the value below is false. Once it's pruned, all its connections
291
        // will be closed, thus the Brontide.Start will return an error.
292
        persistentPeers        map[string]bool
293
        persistentPeersBackoff map[string]time.Duration
294
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
295
        persistentConnReqs     map[string][]*connmgr.ConnReq
296
        persistentRetryCancels map[string]chan struct{}
297

298
        // peerErrors keeps a set of peer error buffers for peers that have
299
        // disconnected from us. This allows us to track historic peer errors
300
        // over connections. The string of the peer's compressed pubkey is used
301
        // as a key for this map.
302
        peerErrors map[string]*queue.CircularBuffer
303

304
        // ignorePeerTermination tracks peers for which the server has initiated
305
        // a disconnect. Adding a peer to this map causes the peer termination
306
        // watcher to short circuit in the event that peers are purposefully
307
        // disconnected.
308
        ignorePeerTermination map[*peer.Brontide]struct{}
309

310
        // scheduledPeerConnection maps a pubkey string to a callback that
311
        // should be executed in the peerTerminationWatcher the prior peer with
312
        // the same pubkey exits.  This allows the server to wait until the
313
        // prior peer has cleaned up successfully, before adding the new peer
314
        // intended to replace it.
315
        scheduledPeerConnection map[string]func()
316

317
        // pongBuf is a shared pong reply buffer we'll use across all active
318
        // peer goroutines. We know the max size of a pong message
319
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
320
        // avoid allocations each time we need to send a pong message.
321
        pongBuf []byte
322

323
        cc *chainreg.ChainControl
324

325
        fundingMgr *funding.Manager
326

327
        graphDB *graphdb.ChannelGraph
328

329
        chanStateDB *channeldb.ChannelStateDB
330

331
        addrSource channeldb.AddrSource
332

333
        // miscDB is the DB that contains all "other" databases within the main
334
        // channel DB that haven't been separated out yet.
335
        miscDB *channeldb.DB
336

337
        invoicesDB invoices.InvoiceDB
338

339
        // paymentsDB is the DB that contains all functions for managing
340
        // payments.
341
        paymentsDB paymentsdb.DB
342

343
        aliasMgr *aliasmgr.Manager
344

345
        htlcSwitch *htlcswitch.Switch
346

347
        interceptableSwitch *htlcswitch.InterceptableSwitch
348

349
        invoices *invoices.InvoiceRegistry
350

351
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
352

353
        channelNotifier *channelnotifier.ChannelNotifier
354

355
        peerNotifier *peernotifier.PeerNotifier
356

357
        htlcNotifier *htlcswitch.HtlcNotifier
358

359
        witnessBeacon contractcourt.WitnessBeacon
360

361
        breachArbitrator *contractcourt.BreachArbitrator
362

363
        missionController *routing.MissionController
364
        defaultMC         *routing.MissionControl
365

366
        graphBuilder *graph.Builder
367

368
        chanRouter *routing.ChannelRouter
369

370
        controlTower routing.ControlTower
371

372
        authGossiper *discovery.AuthenticatedGossiper
373

374
        localChanMgr *localchans.Manager
375

376
        utxoNursery *contractcourt.UtxoNursery
377

378
        sweeper *sweep.UtxoSweeper
379

380
        chainArb *contractcourt.ChainArbitrator
381

382
        sphinx *hop.OnionProcessor
383

384
        towerClientMgr *wtclient.Manager
385

386
        connMgr *connmgr.ConnManager
387

388
        sigPool *lnwallet.SigPool
389

390
        writePool *pool.Write
391

392
        readPool *pool.Read
393

394
        tlsManager *TLSManager
395

396
        // featureMgr dispatches feature vectors for various contexts within the
397
        // daemon.
398
        featureMgr *feature.Manager
399

400
        // currentNodeAnn is the node announcement that has been broadcast to
401
        // the network upon startup, if the attributes of the node (us) has
402
        // changed since last start.
403
        currentNodeAnn *lnwire.NodeAnnouncement
404

405
        // chansToRestore is the set of channels that upon starting, the server
406
        // should attempt to restore/recover.
407
        chansToRestore walletunlocker.ChannelsToRecover
408

409
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
410
        // backups are consistent at all times. It interacts with the
411
        // channelNotifier to be notified of newly opened and closed channels.
412
        chanSubSwapper *chanbackup.SubSwapper
413

414
        // chanEventStore tracks the behaviour of channels and their remote peers to
415
        // provide insights into their health and performance.
416
        chanEventStore *chanfitness.ChannelEventStore
417

418
        hostAnn *netann.HostAnnouncer
419

420
        // livenessMonitor monitors that lnd has access to critical resources.
421
        livenessMonitor *healthcheck.Monitor
422

423
        customMessageServer *subscribe.Server
424

425
        // txPublisher is a publisher with fee-bumping capability.
426
        txPublisher *sweep.TxPublisher
427

428
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
429
        // of new blocks.
430
        blockbeatDispatcher *chainio.BlockbeatDispatcher
431

432
        // peerAccessMan implements peer access controls.
433
        peerAccessMan *accessMan
434

435
        quit chan struct{}
436

437
        wg sync.WaitGroup
438
}
439

440
// updatePersistentPeerAddrs subscribes to topology changes and stores
441
// advertised addresses for any NodeAnnouncements from our persisted peers.
442
func (s *server) updatePersistentPeerAddrs() error {
3✔
443
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
444
        if err != nil {
3✔
UNCOV
445
                return err
×
UNCOV
446
        }
×
447

448
        s.wg.Add(1)
3✔
449
        go func() {
6✔
450
                defer func() {
6✔
451
                        graphSub.Cancel()
3✔
452
                        s.wg.Done()
3✔
453
                }()
3✔
454

455
                for {
6✔
456
                        select {
3✔
457
                        case <-s.quit:
3✔
458
                                return
3✔
459

460
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
461
                                // If the router is shutting down, then we will
3✔
462
                                // as well.
3✔
463
                                if !ok {
3✔
UNCOV
464
                                        return
×
UNCOV
465
                                }
×
466

467
                                for _, update := range topChange.NodeUpdates {
6✔
468
                                        pubKeyStr := string(
3✔
469
                                                update.IdentityKey.
3✔
470
                                                        SerializeCompressed(),
3✔
471
                                        )
3✔
472

3✔
473
                                        // We only care about updates from
3✔
474
                                        // our persistentPeers.
3✔
475
                                        s.mu.RLock()
3✔
476
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
477
                                        s.mu.RUnlock()
3✔
478
                                        if !ok {
6✔
479
                                                continue
3✔
480
                                        }
481

482
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
483
                                                len(update.Addresses))
3✔
484

3✔
485
                                        for _, addr := range update.Addresses {
6✔
486
                                                addrs = append(addrs,
3✔
487
                                                        &lnwire.NetAddress{
3✔
488
                                                                IdentityKey: update.IdentityKey,
3✔
489
                                                                Address:     addr,
3✔
490
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
491
                                                        },
3✔
492
                                                )
3✔
493
                                        }
3✔
494

495
                                        s.mu.Lock()
3✔
496

3✔
497
                                        // Update the stored addresses for this
3✔
498
                                        // to peer to reflect the new set.
3✔
499
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
500

3✔
501
                                        // If there are no outstanding
3✔
502
                                        // connection requests for this peer
3✔
503
                                        // then our work is done since we are
3✔
504
                                        // not currently trying to connect to
3✔
505
                                        // them.
3✔
506
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
507
                                                s.mu.Unlock()
3✔
508
                                                continue
3✔
509
                                        }
510

511
                                        s.mu.Unlock()
3✔
512

3✔
513
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
514
                                }
515
                        }
516
                }
517
        }()
518

519
        return nil
3✔
520
}
521

522
// CustomMessage is a custom message that is received from a peer.
523
type CustomMessage struct {
524
        // Peer is the peer pubkey
525
        Peer [33]byte
526

527
        // Msg is the custom wire message.
528
        Msg *lnwire.Custom
529
}
530

531
// parseAddr parses an address from its string format to a net.Addr.
532
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
533
        var (
3✔
534
                host string
3✔
535
                port int
3✔
536
        )
3✔
537

3✔
538
        // Split the address into its host and port components.
3✔
539
        h, p, err := net.SplitHostPort(address)
3✔
540
        if err != nil {
3✔
UNCOV
541
                // If a port wasn't specified, we'll assume the address only
×
UNCOV
542
                // contains the host so we'll use the default port.
×
543
                host = address
×
544
                port = defaultPeerPort
×
545
        } else {
3✔
546
                // Otherwise, we'll note both the host and ports.
3✔
547
                host = h
3✔
548
                portNum, err := strconv.Atoi(p)
3✔
549
                if err != nil {
3✔
UNCOV
550
                        return nil, err
×
UNCOV
551
                }
×
552
                port = portNum
3✔
553
        }
554

555
        if tor.IsOnionHost(host) {
3✔
UNCOV
556
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
UNCOV
557
        }
×
558

559
        // If the host is part of a TCP address, we'll use the network
560
        // specific ResolveTCPAddr function in order to resolve these
561
        // addresses over Tor in order to prevent leaking your real IP
562
        // address.
563
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
564
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
565
}
566

567
// noiseDial is a factory function which creates a connmgr compliant dialing
568
// function by returning a closure which includes the server's identity key.
569
func noiseDial(idKey keychain.SingleKeyECDH,
570
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
3✔
571

3✔
572
        return func(a net.Addr) (net.Conn, error) {
6✔
573
                lnAddr := a.(*lnwire.NetAddress)
3✔
574
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
575
        }
3✔
576
}
577

578
// newServer creates a new instance of the server which is to listen using the
579
// passed listener address.
580
//
581
//nolint:funlen
582
func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
583
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
584
        nodeKeyDesc *keychain.KeyDescriptor,
585
        chansToRestore walletunlocker.ChannelsToRecover,
586
        chanPredicate chanacceptor.ChannelAcceptor,
587
        torController *tor.Controller, tlsManager *TLSManager,
588
        leaderElector cluster.LeaderElector,
589
        implCfg *ImplementationCfg) (*server, error) {
3✔
590

3✔
591
        var (
3✔
592
                err         error
3✔
593
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
594

3✔
595
                // We just derived the full descriptor, so we know the public
3✔
596
                // key is set on it.
3✔
597
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
598
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
599
                )
3✔
600
        )
3✔
601

3✔
602
        netParams := cfg.ActiveNetParams.Params
3✔
603

3✔
604
        // Initialize the sphinx router.
3✔
605
        replayLog := htlcswitch.NewDecayedLog(
3✔
606
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
607
        )
3✔
608
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
609

3✔
610
        writeBufferPool := pool.NewWriteBuffer(
3✔
611
                pool.DefaultWriteBufferGCInterval,
3✔
612
                pool.DefaultWriteBufferExpiryInterval,
3✔
613
        )
3✔
614

3✔
615
        writePool := pool.NewWrite(
3✔
616
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
617
        )
3✔
618

3✔
619
        readBufferPool := pool.NewReadBuffer(
3✔
620
                pool.DefaultReadBufferGCInterval,
3✔
621
                pool.DefaultReadBufferExpiryInterval,
3✔
622
        )
3✔
623

3✔
624
        readPool := pool.NewRead(
3✔
625
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
626
        )
3✔
627

3✔
628
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
629
        // controller, then we'll exit as this is incompatible.
3✔
630
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
631
                implCfg.AuxFundingController.IsNone() {
3✔
UNCOV
632

×
UNCOV
633
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
634
                        "overlay channels are not supported " +
×
635
                        "in a standalone lnd build")
×
636
        }
×
637

638
        //nolint:ll
639
        featureMgr, err := feature.NewManager(feature.Config{
3✔
640
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
641
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
642
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
643
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
644
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
645
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
646
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
647
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
648
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
649
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
650
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
651
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
652
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
653
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
654
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
655
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
656
        })
3✔
657
        if err != nil {
3✔
UNCOV
658
                return nil, err
×
UNCOV
659
        }
×
660

661
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
662
        registryConfig := invoices.RegistryConfig{
3✔
663
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
664
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
665
                Clock:                       clock.NewDefaultClock(),
3✔
666
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
667
                AcceptAMP:                   cfg.AcceptAMP,
3✔
668
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
669
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
670
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
671
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
672
        }
3✔
673

3✔
674
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
675

3✔
676
        s := &server{
3✔
677
                cfg:            cfg,
3✔
678
                implCfg:        implCfg,
3✔
679
                graphDB:        dbs.GraphDB,
3✔
680
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
681
                addrSource:     addrSource,
3✔
682
                miscDB:         dbs.ChanStateDB,
3✔
683
                invoicesDB:     dbs.InvoiceDB,
3✔
684
                paymentsDB:     dbs.PaymentsDB,
3✔
685
                cc:             cc,
3✔
686
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
687
                writePool:      writePool,
3✔
688
                readPool:       readPool,
3✔
689
                chansToRestore: chansToRestore,
3✔
690

3✔
691
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
692
                        cc.ChainNotifier,
3✔
693
                ),
3✔
694
                channelNotifier: channelnotifier.New(
3✔
695
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
696
                ),
3✔
697

3✔
698
                identityECDH:   nodeKeyECDH,
3✔
699
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
700
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
701

3✔
702
                listenAddrs: listenAddrs,
3✔
703

3✔
704
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
705
                // schedule
3✔
706
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
707

3✔
708
                torController: torController,
3✔
709

3✔
710
                persistentPeers:         make(map[string]bool),
3✔
711
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
712
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
713
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
714
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
715
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
716
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
717
                scheduledPeerConnection: make(map[string]func()),
3✔
718
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
719

3✔
720
                peersByPub:                make(map[string]*peer.Brontide),
3✔
721
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
722
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
723
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
724
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
725

3✔
726
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
727

3✔
728
                customMessageServer: subscribe.NewServer(),
3✔
729

3✔
730
                tlsManager: tlsManager,
3✔
731

3✔
732
                featureMgr: featureMgr,
3✔
733
                quit:       make(chan struct{}),
3✔
734
        }
3✔
735

3✔
736
        // Start the low-level services once they are initialized.
3✔
737
        //
3✔
738
        // TODO(yy): break the server startup into four steps,
3✔
739
        // 1. init the low-level services.
3✔
740
        // 2. start the low-level services.
3✔
741
        // 3. init the high-level services.
3✔
742
        // 4. start the high-level services.
3✔
743
        if err := s.startLowLevelServices(); err != nil {
3✔
UNCOV
744
                return nil, err
×
UNCOV
745
        }
×
746

747
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
748
        if err != nil {
3✔
UNCOV
749
                return nil, err
×
UNCOV
750
        }
×
751

752
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
753
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
754
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
755
        )
3✔
756
        s.invoices = invoices.NewRegistry(
3✔
757
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
758
        )
3✔
759

3✔
760
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
761

3✔
762
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
763
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
764

3✔
765
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
766
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
767
                if err != nil {
3✔
UNCOV
768
                        return err
×
UNCOV
769
                }
×
770

771
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
772

3✔
773
                return nil
3✔
774
        }
775

776
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
777
        if err != nil {
3✔
UNCOV
778
                return nil, err
×
UNCOV
779
        }
×
780

781
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
782
                DB:                   dbs.ChanStateDB,
3✔
783
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
784
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
785
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
786
                LocalChannelClose: func(pubKey []byte,
3✔
787
                        request *htlcswitch.ChanClose) {
6✔
788

3✔
789
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
790
                        if err != nil {
3✔
UNCOV
791
                                srvrLog.Errorf("unable to close channel, peer"+
×
UNCOV
792
                                        " with %v id can't be found: %v",
×
793
                                        pubKey, err,
×
794
                                )
×
795
                                return
×
796
                        }
×
797

798
                        peer.HandleLocalCloseChanReqs(request)
3✔
799
                },
800
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
801
                SwitchPackager:         channeldb.NewSwitchPackager(),
802
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
803
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
804
                Notifier:               s.cc.ChainNotifier,
805
                HtlcNotifier:           s.htlcNotifier,
806
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
807
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
808
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
809
                AllowCircularRoute:     cfg.AllowCircularRoute,
810
                RejectHTLC:             cfg.RejectHTLC,
811
                Clock:                  clock.NewDefaultClock(),
812
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
813
                MaxFeeExposure:         thresholdMSats,
814
                SignAliasUpdate:        s.signAliasUpdate,
815
                IsAlias:                aliasmgr.IsAlias,
816
        }, uint32(currentHeight))
817
        if err != nil {
3✔
UNCOV
818
                return nil, err
×
UNCOV
819
        }
×
820
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
821
                &htlcswitch.InterceptableSwitchConfig{
3✔
822
                        Switch:             s.htlcSwitch,
3✔
823
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
824
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
825
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
826
                        Notifier:           s.cc.ChainNotifier,
3✔
827
                },
3✔
828
        )
3✔
829
        if err != nil {
3✔
UNCOV
830
                return nil, err
×
UNCOV
831
        }
×
832

833
        s.witnessBeacon = newPreimageBeacon(
3✔
834
                dbs.ChanStateDB.NewWitnessCache(),
3✔
835
                s.interceptableSwitch.ForwardPacket,
3✔
836
        )
3✔
837

3✔
838
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
839
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
840
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
841
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
842
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
843
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
844
                MessageSigner:            s.nodeSigner,
3✔
845
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
846
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
847
                DB:                       s.chanStateDB,
3✔
848
                Graph:                    dbs.GraphDB,
3✔
849
        }
3✔
850

3✔
851
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
852
        if err != nil {
3✔
UNCOV
853
                return nil, err
×
UNCOV
854
        }
×
855
        s.chanStatusMgr = chanStatusMgr
3✔
856

3✔
857
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
858
        // port forwarding for users behind a NAT.
3✔
859
        if cfg.NAT {
3✔
UNCOV
860
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
UNCOV
861

×
862
                discoveryTimeout := time.Duration(10 * time.Second)
×
863

×
864
                ctx, cancel := context.WithTimeout(
×
865
                        context.Background(), discoveryTimeout,
×
866
                )
×
867
                defer cancel()
×
868
                upnp, err := nat.DiscoverUPnP(ctx)
×
869
                if err == nil {
×
870
                        s.natTraversal = upnp
×
871
                } else {
×
872
                        // If we were not able to discover a UPnP enabled device
×
873
                        // on the local network, we'll fall back to attempting
×
874
                        // to discover a NAT-PMP enabled device.
×
875
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
876
                                "device on the local network: %v", err)
×
877

×
878
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
879
                                "enabled device")
×
880

×
881
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
882
                        if err != nil {
×
883
                                err := fmt.Errorf("unable to discover a "+
×
884
                                        "NAT-PMP enabled device on the local "+
×
885
                                        "network: %v", err)
×
886
                                srvrLog.Error(err)
×
887
                                return nil, err
×
888
                        }
×
889

890
                        s.natTraversal = pmp
×
891
                }
892
        }
893

894
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
895
        // Set the self node which represents our node in the graph.
3✔
896
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
897
        if err != nil {
3✔
UNCOV
898
                return nil, err
×
UNCOV
899
        }
×
900

901
        // The router will get access to the payment ID sequencer, such that it
902
        // can generate unique payment IDs.
903
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
904
        if err != nil {
3✔
UNCOV
905
                return nil, err
×
UNCOV
906
        }
×
907

908
        // Instantiate mission control with config from the sub server.
909
        //
910
        // TODO(joostjager): When we are further in the process of moving to sub
911
        // servers, the mission control instance itself can be moved there too.
912
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
913

3✔
914
        // We only initialize a probability estimator if there's no custom one.
3✔
915
        var estimator routing.Estimator
3✔
916
        if cfg.Estimator != nil {
3✔
UNCOV
917
                estimator = cfg.Estimator
×
918
        } else {
3✔
919
                switch routingConfig.ProbabilityEstimatorType {
3✔
920
                case routing.AprioriEstimatorName:
3✔
921
                        aCfg := routingConfig.AprioriConfig
3✔
922
                        aprioriConfig := routing.AprioriConfig{
3✔
923
                                AprioriHopProbability: aCfg.HopProbability,
3✔
924
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
925
                                AprioriWeight:         aCfg.Weight,
3✔
926
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
927
                        }
3✔
928

3✔
929
                        estimator, err = routing.NewAprioriEstimator(
3✔
930
                                aprioriConfig,
3✔
931
                        )
3✔
932
                        if err != nil {
3✔
UNCOV
933
                                return nil, err
×
UNCOV
934
                        }
×
935

936
                case routing.BimodalEstimatorName:
×
UNCOV
937
                        bCfg := routingConfig.BimodalConfig
×
938
                        bimodalConfig := routing.BimodalConfig{
×
939
                                BimodalNodeWeight: bCfg.NodeWeight,
×
940
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
941
                                        bCfg.Scale,
×
942
                                ),
×
943
                                BimodalDecayTime: bCfg.DecayTime,
×
944
                        }
×
945

×
946
                        estimator, err = routing.NewBimodalEstimator(
×
947
                                bimodalConfig,
×
948
                        )
×
949
                        if err != nil {
×
950
                                return nil, err
×
951
                        }
×
952

953
                default:
×
UNCOV
954
                        return nil, fmt.Errorf("unknown estimator type %v",
×
955
                                routingConfig.ProbabilityEstimatorType)
×
956
                }
957
        }
958

959
        mcCfg := &routing.MissionControlConfig{
3✔
960
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
961
                Estimator:               estimator,
3✔
962
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
963
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
964
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
965
        }
3✔
966

3✔
967
        s.missionController, err = routing.NewMissionController(
3✔
968
                dbs.ChanStateDB, nodePubKey, mcCfg,
3✔
969
        )
3✔
970
        if err != nil {
3✔
UNCOV
971
                return nil, fmt.Errorf("can't create mission control "+
×
UNCOV
972
                        "manager: %w", err)
×
973
        }
×
974
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
975
                routing.DefaultMissionControlNamespace,
3✔
976
        )
3✔
977
        if err != nil {
3✔
UNCOV
978
                return nil, fmt.Errorf("can't create mission control in the "+
×
UNCOV
979
                        "default namespace: %w", err)
×
980
        }
×
981

982
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
983
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
984
                int64(routingConfig.AttemptCost),
3✔
985
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
986
                routingConfig.MinRouteProbability)
3✔
987

3✔
988
        pathFindingConfig := routing.PathFindingConfig{
3✔
989
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
990
                        routingConfig.AttemptCost,
3✔
991
                ),
3✔
992
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
993
                MinProbability: routingConfig.MinRouteProbability,
3✔
994
        }
3✔
995

3✔
996
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
997
        if err != nil {
3✔
UNCOV
998
                return nil, fmt.Errorf("error getting source node: %w", err)
×
UNCOV
999
        }
×
1000
        paymentSessionSource := &routing.SessionSource{
3✔
1001
                GraphSessionFactory: dbs.GraphDB,
3✔
1002
                SourceNode:          sourceNode,
3✔
1003
                MissionControl:      s.defaultMC,
3✔
1004
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1005
                PathFindingConfig:   pathFindingConfig,
3✔
1006
        }
3✔
1007

3✔
1008
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
1009

3✔
1010
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1011
                cfg.Routing.StrictZombiePruning
3✔
1012

3✔
1013
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1014
                SelfNode:            nodePubKey,
3✔
1015
                Graph:               dbs.GraphDB,
3✔
1016
                Chain:               cc.ChainIO,
3✔
1017
                ChainView:           cc.ChainView,
3✔
1018
                Notifier:            cc.ChainNotifier,
3✔
1019
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1020
                GraphPruneInterval:  time.Hour,
3✔
1021
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1022
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1023
                StrictZombiePruning: strictPruning,
3✔
1024
                IsAlias:             aliasmgr.IsAlias,
3✔
1025
        })
3✔
1026
        if err != nil {
3✔
UNCOV
1027
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
UNCOV
1028
        }
×
1029

1030
        s.chanRouter, err = routing.New(routing.Config{
3✔
1031
                SelfNode:           nodePubKey,
3✔
1032
                RoutingGraph:       dbs.GraphDB,
3✔
1033
                Chain:              cc.ChainIO,
3✔
1034
                Payer:              s.htlcSwitch,
3✔
1035
                Control:            s.controlTower,
3✔
1036
                MissionControl:     s.defaultMC,
3✔
1037
                SessionSource:      paymentSessionSource,
3✔
1038
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1039
                NextPaymentID:      sequencer.NextID,
3✔
1040
                PathFindingConfig:  pathFindingConfig,
3✔
1041
                Clock:              clock.NewDefaultClock(),
3✔
1042
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1043
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1044
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1045
        })
3✔
1046
        if err != nil {
3✔
UNCOV
1047
                return nil, fmt.Errorf("can't create router: %w", err)
×
UNCOV
1048
        }
×
1049

1050
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1051
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1052
        if err != nil {
3✔
UNCOV
1053
                return nil, err
×
UNCOV
1054
        }
×
1055
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1056
        if err != nil {
3✔
UNCOV
1057
                return nil, err
×
UNCOV
1058
        }
×
1059

1060
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1061

3✔
1062
        s.authGossiper = discovery.New(discovery.Config{
3✔
1063
                Graph:                 s.graphBuilder,
3✔
1064
                ChainIO:               s.cc.ChainIO,
3✔
1065
                Notifier:              s.cc.ChainNotifier,
3✔
1066
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1067
                Broadcast:             s.BroadcastMessage,
3✔
1068
                ChanSeries:            chanSeries,
3✔
1069
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1070
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1071
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1072
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1073
                        error) {
3✔
UNCOV
1074

×
UNCOV
1075
                        return s.genNodeAnnouncement(nil)
×
1076
                },
×
1077
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1078
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1079
                RetransmitTicker:        ticker.New(time.Minute * 30),
1080
                RebroadcastInterval:     time.Hour * 24,
1081
                WaitingProofStore:       waitingProofStore,
1082
                MessageStore:            gossipMessageStore,
1083
                AnnSigner:               s.nodeSigner,
1084
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1085
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1086
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1087
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1088
                MinimumBatchSize:        10,
1089
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1090
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1091
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1092
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1093
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1094
                IsAlias:                 aliasmgr.IsAlias,
1095
                SignAliasUpdate:         s.signAliasUpdate,
1096
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1097
                GetAlias:                s.aliasMgr.GetPeerAlias,
1098
                FindChannel:             s.findChannel,
1099
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1100
                ScidCloser:              scidCloserMan,
1101
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1102
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1103
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1104
                FilterConcurrency:       cfg.Gossip.FilterConcurrency,
1105
                BanThreshold:            cfg.Gossip.BanThreshold,
1106
        }, nodeKeyDesc)
1107

1108
        accessCfg := &accessManConfig{
3✔
1109
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1110
                        error) {
6✔
1111

3✔
1112
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1113
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1114
                                genesisHash[:],
3✔
1115
                        )
3✔
1116
                },
3✔
1117
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1118
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1119
        }
1120

1121
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1122
        if err != nil {
3✔
UNCOV
1123
                return nil, err
×
UNCOV
1124
        }
×
1125

1126
        s.peerAccessMan = peerAccessMan
3✔
1127

3✔
1128
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1129
        //nolint:ll
3✔
1130
        s.localChanMgr = &localchans.Manager{
3✔
1131
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1132
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1133
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1134
                        cb func(*models.ChannelEdgeInfo,
3✔
1135
                                *models.ChannelEdgePolicy) error,
3✔
1136
                        reset func()) error {
6✔
1137

3✔
1138
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1139
                                func(c *models.ChannelEdgeInfo,
3✔
1140
                                        e *models.ChannelEdgePolicy,
3✔
1141
                                        _ *models.ChannelEdgePolicy) error {
6✔
1142

3✔
1143
                                        // NOTE: The invoked callback here may
3✔
1144
                                        // receive a nil channel policy.
3✔
1145
                                        return cb(c, e)
3✔
1146
                                }, reset,
3✔
1147
                        )
1148
                },
1149
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1150
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1151
                FetchChannel:              s.chanStateDB.FetchChannel,
1152
                AddEdge: func(ctx context.Context,
UNCOV
1153
                        edge *models.ChannelEdgeInfo) error {
×
UNCOV
1154

×
1155
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1156
                },
×
1157
        }
1158

1159
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1160
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1161
        )
3✔
1162
        if err != nil {
3✔
UNCOV
1163
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
UNCOV
1164
                return nil, err
×
1165
        }
×
1166

1167
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1168
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1169
        )
3✔
1170
        if err != nil {
3✔
UNCOV
1171
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
UNCOV
1172
                return nil, err
×
1173
        }
×
1174

1175
        aggregator := sweep.NewBudgetAggregator(
3✔
1176
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1177
                s.implCfg.AuxSweeper,
3✔
1178
        )
3✔
1179

3✔
1180
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1181
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1182
                Wallet:     cc.Wallet,
3✔
1183
                Estimator:  cc.FeeEstimator,
3✔
1184
                Notifier:   cc.ChainNotifier,
3✔
1185
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1186
        })
3✔
1187

3✔
1188
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1189
                FeeEstimator: cc.FeeEstimator,
3✔
1190
                GenSweepScript: newSweepPkScriptGen(
3✔
1191
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1192
                ),
3✔
1193
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1194
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1195
                Mempool:              cc.MempoolNotifier,
3✔
1196
                Notifier:             cc.ChainNotifier,
3✔
1197
                Store:                sweeperStore,
3✔
1198
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1199
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1200
                Aggregator:           aggregator,
3✔
1201
                Publisher:            s.txPublisher,
3✔
1202
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1203
        })
3✔
1204

3✔
1205
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1206
                ChainIO:             cc.ChainIO,
3✔
1207
                ConfDepth:           1,
3✔
1208
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1209
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1210
                Notifier:            cc.ChainNotifier,
3✔
1211
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1212
                Store:               utxnStore,
3✔
1213
                SweepInput:          s.sweeper.SweepInput,
3✔
1214
                Budget:              s.cfg.Sweeper.Budget,
3✔
1215
        })
3✔
1216

3✔
1217
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1218
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1219
                closureType contractcourt.ChannelCloseType) {
6✔
1220
                // TODO(conner): Properly respect the update and error channels
3✔
1221
                // returned by CloseLink.
3✔
1222

3✔
1223
                // Instruct the switch to close the channel.  Provide no close out
3✔
1224
                // delivery script or target fee per kw because user input is not
3✔
1225
                // available when the remote peer closes the channel.
3✔
1226
                s.htlcSwitch.CloseLink(
3✔
1227
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1228
                )
3✔
1229
        }
3✔
1230

1231
        // We will use the following channel to reliably hand off contract
1232
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1233
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
3✔
1234

3✔
1235
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1236
                &contractcourt.BreachConfig{
3✔
1237
                        CloseLink: closeLink,
3✔
1238
                        DB:        s.chanStateDB,
3✔
1239
                        Estimator: s.cc.FeeEstimator,
3✔
1240
                        GenSweepScript: newSweepPkScriptGen(
3✔
1241
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1242
                        ),
3✔
1243
                        Notifier:           cc.ChainNotifier,
3✔
1244
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1245
                        ContractBreaches:   contractBreaches,
3✔
1246
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1247
                        Store: contractcourt.NewRetributionStore(
3✔
1248
                                dbs.ChanStateDB,
3✔
1249
                        ),
3✔
1250
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1251
                },
3✔
1252
        )
3✔
1253

3✔
1254
        //nolint:ll
3✔
1255
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1256
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1257
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1258
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1259
                NewSweepAddr: func() ([]byte, error) {
3✔
UNCOV
1260
                        addr, err := newSweepPkScriptGen(
×
UNCOV
1261
                                cc.Wallet, netParams,
×
1262
                        )().Unpack()
×
1263
                        if err != nil {
×
1264
                                return nil, err
×
1265
                        }
×
1266

1267
                        return addr.DeliveryAddress, nil
×
1268
                },
1269
                PublishTx: cc.Wallet.PublishTransaction,
1270
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1271
                        for _, msg := range msgs {
6✔
1272
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1273
                                if err != nil {
3✔
UNCOV
1274
                                        return err
×
UNCOV
1275
                                }
×
1276
                        }
1277
                        return nil
3✔
1278
                },
1279
                IncubateOutputs: func(chanPoint wire.OutPoint,
1280
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1281
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1282
                        broadcastHeight uint32,
1283
                        deadlineHeight fn.Option[int32]) error {
3✔
1284

3✔
1285
                        return s.utxoNursery.IncubateOutputs(
3✔
1286
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1287
                                broadcastHeight, deadlineHeight,
3✔
1288
                        )
3✔
1289
                },
3✔
1290
                PreimageDB:   s.witnessBeacon,
1291
                Notifier:     cc.ChainNotifier,
1292
                Mempool:      cc.MempoolNotifier,
1293
                Signer:       cc.Wallet.Cfg.Signer,
1294
                FeeEstimator: cc.FeeEstimator,
1295
                ChainIO:      cc.ChainIO,
1296
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1297
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1298
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1299
                        return nil
3✔
1300
                },
3✔
1301
                IsOurAddress: cc.Wallet.IsOurAddress,
1302
                ContractBreach: func(chanPoint wire.OutPoint,
1303
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1304

3✔
1305
                        // processACK will handle the BreachArbitrator ACKing
3✔
1306
                        // the event.
3✔
1307
                        finalErr := make(chan error, 1)
3✔
1308
                        processACK := func(brarErr error) {
6✔
1309
                                if brarErr != nil {
3✔
UNCOV
1310
                                        finalErr <- brarErr
×
UNCOV
1311
                                        return
×
1312
                                }
×
1313

1314
                                // If the BreachArbitrator successfully handled
1315
                                // the event, we can signal that the handoff
1316
                                // was successful.
1317
                                finalErr <- nil
3✔
1318
                        }
1319

1320
                        event := &contractcourt.ContractBreachEvent{
3✔
1321
                                ChanPoint:         chanPoint,
3✔
1322
                                ProcessACK:        processACK,
3✔
1323
                                BreachRetribution: breachRet,
3✔
1324
                        }
3✔
1325

3✔
1326
                        // Send the contract breach event to the
3✔
1327
                        // BreachArbitrator.
3✔
1328
                        select {
3✔
1329
                        case contractBreaches <- event:
3✔
UNCOV
1330
                        case <-s.quit:
×
UNCOV
1331
                                return ErrServerShuttingDown
×
1332
                        }
1333

1334
                        // We'll wait for a final error to be available from
1335
                        // the BreachArbitrator.
1336
                        select {
3✔
1337
                        case err := <-finalErr:
3✔
1338
                                return err
3✔
UNCOV
1339
                        case <-s.quit:
×
UNCOV
1340
                                return ErrServerShuttingDown
×
1341
                        }
1342
                },
1343
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1344
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1345
                },
3✔
1346
                Sweeper:                       s.sweeper,
1347
                Registry:                      s.invoices,
1348
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1349
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1350
                OnionProcessor:                s.sphinx,
1351
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1352
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1353
                Clock:                         clock.NewDefaultClock(),
1354
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1355
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1356
                HtlcNotifier:                  s.htlcNotifier,
1357
                Budget:                        *s.cfg.Sweeper.Budget,
1358

1359
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1360
                QueryIncomingCircuit: func(
1361
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1362

3✔
1363
                        // Get the circuit map.
3✔
1364
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1365

3✔
1366
                        // Lookup the outgoing circuit.
3✔
1367
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1368
                        if pc == nil {
5✔
1369
                                return nil
2✔
1370
                        }
2✔
1371

1372
                        return &pc.Incoming
3✔
1373
                },
1374
                AuxLeafStore: implCfg.AuxLeafStore,
1375
                AuxSigner:    implCfg.AuxSigner,
1376
                AuxResolver:  implCfg.AuxContractResolver,
1377
        }, dbs.ChanStateDB)
1378

1379
        // Select the configuration and funding parameters for Bitcoin.
1380
        chainCfg := cfg.Bitcoin
3✔
1381
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1382
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1383

3✔
1384
        var chanIDSeed [32]byte
3✔
1385
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
UNCOV
1386
                return nil, err
×
UNCOV
1387
        }
×
1388

1389
        // Wrap the DeleteChannelEdges method so that the funding manager can
1390
        // use it without depending on several layers of indirection.
1391
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1392
                *models.ChannelEdgePolicy, error) {
6✔
1393

3✔
1394
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1395
                        scid.ToUint64(),
3✔
1396
                )
3✔
1397
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
UNCOV
1398
                        // This is unlikely but there is a slim chance of this
×
UNCOV
1399
                        // being hit if lnd was killed via SIGKILL and the
×
1400
                        // funding manager was stepping through the delete
×
1401
                        // alias edge logic.
×
1402
                        return nil, nil
×
1403
                } else if err != nil {
3✔
1404
                        return nil, err
×
UNCOV
1405
                }
×
1406

1407
                // Grab our key to find our policy.
1408
                var ourKey [33]byte
3✔
1409
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1410

3✔
1411
                var ourPolicy *models.ChannelEdgePolicy
3✔
1412
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1413
                        ourPolicy = e1
3✔
1414
                } else {
6✔
1415
                        ourPolicy = e2
3✔
1416
                }
3✔
1417

1418
                if ourPolicy == nil {
3✔
UNCOV
1419
                        // Something is wrong, so return an error.
×
UNCOV
1420
                        return nil, fmt.Errorf("we don't have an edge")
×
1421
                }
×
1422

1423
                err = s.graphDB.DeleteChannelEdges(
3✔
1424
                        false, false, scid.ToUint64(),
3✔
1425
                )
3✔
1426
                return ourPolicy, err
3✔
1427
        }
1428

1429
        // For the reservationTimeout and the zombieSweeperInterval different
1430
        // values are set in case we are in a dev environment so enhance test
1431
        // capacilities.
1432
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1433
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1434

3✔
1435
        // Get the development config for funding manager. If we are not in
3✔
1436
        // development mode, this would be nil.
3✔
1437
        var devCfg *funding.DevConfig
3✔
1438
        if lncfg.IsDevBuild() {
6✔
1439
                devCfg = &funding.DevConfig{
3✔
1440
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1441
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1442
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1443
                }
3✔
1444

3✔
1445
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1446
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1447

3✔
1448
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1449
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1450
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1451
        }
3✔
1452

1453
        //nolint:ll
1454
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1455
                Dev:                devCfg,
3✔
1456
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1457
                IDKey:              nodeKeyDesc.PubKey,
3✔
1458
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1459
                Wallet:             cc.Wallet,
3✔
1460
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1461
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1462
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1463
                },
3✔
1464
                Notifier:     cc.ChainNotifier,
1465
                ChannelDB:    s.chanStateDB,
1466
                FeeEstimator: cc.FeeEstimator,
1467
                SignMessage:  cc.MsgSigner.SignMessage,
1468
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1469
                        error) {
3✔
1470

3✔
1471
                        return s.genNodeAnnouncement(nil)
3✔
1472
                },
3✔
1473
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1474
                NotifyWhenOnline:     s.NotifyWhenOnline,
1475
                TempChanIDSeed:       chanIDSeed,
1476
                FindChannel:          s.findChannel,
1477
                DefaultRoutingPolicy: cc.RoutingPolicy,
1478
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1479
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1480
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1481
                        // For large channels we increase the number
3✔
1482
                        // of confirmations we require for the
3✔
1483
                        // channel to be considered open. As it is
3✔
1484
                        // always the responder that gets to choose
3✔
1485
                        // value, the pushAmt is value being pushed
3✔
1486
                        // to us. This means we have more to lose
3✔
1487
                        // in the case this gets re-orged out, and
3✔
1488
                        // we will require more confirmations before
3✔
1489
                        // we consider it open.
3✔
1490

3✔
1491
                        // In case the user has explicitly specified
3✔
1492
                        // a default value for the number of
3✔
1493
                        // confirmations, we use it.
3✔
1494
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1495
                        if defaultConf != 0 {
6✔
1496
                                return defaultConf
3✔
1497
                        }
3✔
1498

UNCOV
1499
                        minConf := uint64(3)
×
UNCOV
1500
                        maxConf := uint64(6)
×
1501

×
1502
                        // If this is a wumbo channel, then we'll require the
×
1503
                        // max amount of confirmations.
×
1504
                        if chanAmt > MaxFundingAmount {
×
1505
                                return uint16(maxConf)
×
1506
                        }
×
1507

1508
                        // If not we return a value scaled linearly
1509
                        // between 3 and 6, depending on channel size.
1510
                        // TODO(halseth): Use 1 as minimum?
UNCOV
1511
                        maxChannelSize := uint64(
×
UNCOV
1512
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1513
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1514
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1515
                        if conf < minConf {
×
1516
                                conf = minConf
×
1517
                        }
×
1518
                        if conf > maxConf {
×
1519
                                conf = maxConf
×
1520
                        }
×
1521
                        return uint16(conf)
×
1522
                },
1523
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1524
                        // We scale the remote CSV delay (the time the
3✔
1525
                        // remote have to claim funds in case of a unilateral
3✔
1526
                        // close) linearly from minRemoteDelay blocks
3✔
1527
                        // for small channels, to maxRemoteDelay blocks
3✔
1528
                        // for channels of size MaxFundingAmount.
3✔
1529

3✔
1530
                        // In case the user has explicitly specified
3✔
1531
                        // a default value for the remote delay, we
3✔
1532
                        // use it.
3✔
1533
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1534
                        if defaultDelay > 0 {
6✔
1535
                                return defaultDelay
3✔
1536
                        }
3✔
1537

1538
                        // If this is a wumbo channel, then we'll require the
1539
                        // max value.
UNCOV
1540
                        if chanAmt > MaxFundingAmount {
×
UNCOV
1541
                                return maxRemoteDelay
×
1542
                        }
×
1543

1544
                        // If not we scale according to channel size.
UNCOV
1545
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
UNCOV
1546
                                chanAmt / MaxFundingAmount)
×
1547
                        if delay < minRemoteDelay {
×
1548
                                delay = minRemoteDelay
×
1549
                        }
×
1550
                        if delay > maxRemoteDelay {
×
1551
                                delay = maxRemoteDelay
×
1552
                        }
×
1553
                        return delay
×
1554
                },
1555
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1556
                        peerKey *btcec.PublicKey) error {
3✔
1557

3✔
1558
                        // First, we'll mark this new peer as a persistent peer
3✔
1559
                        // for re-connection purposes. If the peer is not yet
3✔
1560
                        // tracked or the user hasn't requested it to be perm,
3✔
1561
                        // we'll set false to prevent the server from continuing
3✔
1562
                        // to connect to this peer even if the number of
3✔
1563
                        // channels with this peer is zero.
3✔
1564
                        s.mu.Lock()
3✔
1565
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1566
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1567
                                s.persistentPeers[pubStr] = false
3✔
1568
                        }
3✔
1569
                        s.mu.Unlock()
3✔
1570

3✔
1571
                        // With that taken care of, we'll send this channel to
3✔
1572
                        // the chain arb so it can react to on-chain events.
3✔
1573
                        return s.chainArb.WatchNewChannel(channel)
3✔
1574
                },
1575
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1576
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1577
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1578
                },
3✔
1579
                RequiredRemoteChanReserve: func(chanAmt,
1580
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1581

3✔
1582
                        // By default, we'll require the remote peer to maintain
3✔
1583
                        // at least 1% of the total channel capacity at all
3✔
1584
                        // times. If this value ends up dipping below the dust
3✔
1585
                        // limit, then we'll use the dust limit itself as the
3✔
1586
                        // reserve as required by BOLT #2.
3✔
1587
                        reserve := chanAmt / 100
3✔
1588
                        if reserve < dustLimit {
6✔
1589
                                reserve = dustLimit
3✔
1590
                        }
3✔
1591

1592
                        return reserve
3✔
1593
                },
1594
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1595
                        // By default, we'll allow the remote peer to fully
3✔
1596
                        // utilize the full bandwidth of the channel, minus our
3✔
1597
                        // required reserve.
3✔
1598
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1599
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1600
                },
3✔
1601
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1602
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1603
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1604
                        }
3✔
1605

1606
                        // By default, we'll permit them to utilize the full
1607
                        // channel bandwidth.
UNCOV
1608
                        return uint16(input.MaxHTLCNumber / 2)
×
1609
                },
1610
                ZombieSweeperInterval:         zombieSweeperInterval,
1611
                ReservationTimeout:            reservationTimeout,
1612
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1613
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1614
                MaxPendingChannels:            cfg.MaxPendingChannels,
1615
                RejectPush:                    cfg.RejectPush,
1616
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1617
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1618
                OpenChannelPredicate:          chanPredicate,
1619
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1620
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1621
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1622
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1623
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1624
                DeleteAliasEdge:      deleteAliasEdge,
1625
                AliasManager:         s.aliasMgr,
1626
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1627
                AuxFundingController: implCfg.AuxFundingController,
1628
                AuxSigner:            implCfg.AuxSigner,
1629
                AuxResolver:          implCfg.AuxContractResolver,
1630
        })
1631
        if err != nil {
3✔
UNCOV
1632
                return nil, err
×
UNCOV
1633
        }
×
1634

1635
        // Next, we'll assemble the sub-system that will maintain an on-disk
1636
        // static backup of the latest channel state.
1637
        chanNotifier := &channelNotifier{
3✔
1638
                chanNotifier: s.channelNotifier,
3✔
1639
                addrs:        s.addrSource,
3✔
1640
        }
3✔
1641
        backupFile := chanbackup.NewMultiFile(
3✔
1642
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1643
        )
3✔
1644
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1645
                ctx, s.chanStateDB, s.addrSource,
3✔
1646
        )
3✔
1647
        if err != nil {
3✔
UNCOV
1648
                return nil, err
×
UNCOV
1649
        }
×
1650
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1651
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1652
        )
3✔
1653
        if err != nil {
3✔
UNCOV
1654
                return nil, err
×
UNCOV
1655
        }
×
1656

1657
        // Assemble a peer notifier which will provide clients with subscriptions
1658
        // to peer online and offline events.
1659
        s.peerNotifier = peernotifier.New()
3✔
1660

3✔
1661
        // Create a channel event store which monitors all open channels.
3✔
1662
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1663
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1664
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1665
                },
3✔
1666
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1667
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1668
                },
3✔
1669
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1670
                Clock:           clock.NewDefaultClock(),
1671
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1672
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1673
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1674
        })
1675

1676
        if cfg.WtClient.Active {
6✔
1677
                policy := wtpolicy.DefaultPolicy()
3✔
1678
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1679

3✔
1680
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1681
                // protocol operations on sat/kw.
3✔
1682
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1683
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1684
                )
3✔
1685

3✔
1686
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1687

3✔
1688
                if err := policy.Validate(); err != nil {
3✔
UNCOV
1689
                        return nil, err
×
UNCOV
1690
                }
×
1691

1692
                // authDial is the wrapper around the btrontide.Dial for the
1693
                // watchtower.
1694
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1695
                        netAddr *lnwire.NetAddress,
3✔
1696
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1697

3✔
1698
                        return brontide.Dial(
3✔
1699
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1700
                        )
3✔
1701
                }
3✔
1702

1703
                // buildBreachRetribution is a call-back that can be used to
1704
                // query the BreachRetribution info and channel type given a
1705
                // channel ID and commitment height.
1706
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1707
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1708
                        channeldb.ChannelType, error) {
6✔
1709

3✔
1710
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1711
                                nil, chanID,
3✔
1712
                        )
3✔
1713
                        if err != nil {
3✔
UNCOV
1714
                                return nil, 0, err
×
UNCOV
1715
                        }
×
1716

1717
                        br, err := lnwallet.NewBreachRetribution(
3✔
1718
                                channel, commitHeight, 0, nil,
3✔
1719
                                implCfg.AuxLeafStore,
3✔
1720
                                implCfg.AuxContractResolver,
3✔
1721
                        )
3✔
1722
                        if err != nil {
3✔
UNCOV
1723
                                return nil, 0, err
×
UNCOV
1724
                        }
×
1725

1726
                        return br, channel.ChanType, nil
3✔
1727
                }
1728

1729
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1730

3✔
1731
                // Copy the policy for legacy channels and set the blob flag
3✔
1732
                // signalling support for anchor channels.
3✔
1733
                anchorPolicy := policy
3✔
1734
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1735

3✔
1736
                // Copy the policy for legacy channels and set the blob flag
3✔
1737
                // signalling support for taproot channels.
3✔
1738
                taprootPolicy := policy
3✔
1739
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1740
                        blob.FlagTaprootChannel,
3✔
1741
                )
3✔
1742

3✔
1743
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1744
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1745
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1746
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1747
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1748
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1749
                                error) {
6✔
1750

3✔
1751
                                return s.channelNotifier.
3✔
1752
                                        SubscribeChannelEvents()
3✔
1753
                        },
3✔
1754
                        Signer: cc.Wallet.Cfg.Signer,
1755
                        NewAddress: func() ([]byte, error) {
3✔
1756
                                addr, err := newSweepPkScriptGen(
3✔
1757
                                        cc.Wallet, netParams,
3✔
1758
                                )().Unpack()
3✔
1759
                                if err != nil {
3✔
UNCOV
1760
                                        return nil, err
×
UNCOV
1761
                                }
×
1762

1763
                                return addr.DeliveryAddress, nil
3✔
1764
                        },
1765
                        SecretKeyRing:      s.cc.KeyRing,
1766
                        Dial:               cfg.net.Dial,
1767
                        AuthDial:           authDial,
1768
                        DB:                 dbs.TowerClientDB,
1769
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1770
                        MinBackoff:         10 * time.Second,
1771
                        MaxBackoff:         5 * time.Minute,
1772
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1773
                }, policy, anchorPolicy, taprootPolicy)
1774
                if err != nil {
3✔
UNCOV
1775
                        return nil, err
×
UNCOV
1776
                }
×
1777
        }
1778

1779
        if len(cfg.ExternalHosts) != 0 {
3✔
UNCOV
1780
                advertisedIPs := make(map[string]struct{})
×
UNCOV
1781
                for _, addr := range s.currentNodeAnn.Addresses {
×
1782
                        advertisedIPs[addr.String()] = struct{}{}
×
1783
                }
×
1784

1785
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
UNCOV
1786
                        Hosts:         cfg.ExternalHosts,
×
1787
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1788
                        LookupHost: func(host string) (net.Addr, error) {
×
1789
                                return lncfg.ParseAddressString(
×
1790
                                        host, strconv.Itoa(defaultPeerPort),
×
1791
                                        cfg.net.ResolveTCPAddr,
×
1792
                                )
×
1793
                        },
×
1794
                        AdvertisedIPs: advertisedIPs,
1795
                        AnnounceNewIPs: netann.IPAnnouncer(
1796
                                func(modifier ...netann.NodeAnnModifier) (
UNCOV
1797
                                        lnwire.NodeAnnouncement, error) {
×
UNCOV
1798

×
1799
                                        return s.genNodeAnnouncement(
×
1800
                                                nil, modifier...,
×
1801
                                        )
×
1802
                                }),
×
1803
                })
1804
        }
1805

1806
        // Create liveness monitor.
1807
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1808

3✔
1809
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1810
        for i, listenAddr := range listenAddrs {
6✔
1811
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1812
                // doesn't need to call the general lndResolveTCP function
3✔
1813
                // since we are resolving a local address.
3✔
1814

3✔
1815
                // RESOLVE: We are actually partially accepting inbound
3✔
1816
                // connection requests when we call NewListener.
3✔
1817
                listeners[i], err = brontide.NewListener(
3✔
1818
                        nodeKeyECDH, listenAddr.String(),
3✔
1819
                        // TODO(yy): remove this check and unify the inbound
3✔
1820
                        // connection check inside `InboundPeerConnected`.
3✔
1821
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1822
                )
3✔
1823
                if err != nil {
3✔
UNCOV
1824
                        return nil, err
×
UNCOV
1825
                }
×
1826
        }
1827

1828
        // Create the connection manager which will be responsible for
1829
        // maintaining persistent outbound connections and also accepting new
1830
        // incoming connections
1831
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1832
                Listeners:      listeners,
3✔
1833
                OnAccept:       s.InboundPeerConnected,
3✔
1834
                RetryDuration:  time.Second * 5,
3✔
1835
                TargetOutbound: 100,
3✔
1836
                Dial: noiseDial(
3✔
1837
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1838
                ),
3✔
1839
                OnConnection: s.OutboundPeerConnected,
3✔
1840
        })
3✔
1841
        if err != nil {
3✔
UNCOV
1842
                return nil, err
×
UNCOV
1843
        }
×
1844
        s.connMgr = cmgr
3✔
1845

3✔
1846
        // Finally, register the subsystems in blockbeat.
3✔
1847
        s.registerBlockConsumers()
3✔
1848

3✔
1849
        return s, nil
3✔
1850
}
1851

1852
// UpdateRoutingConfig is a callback function to update the routing config
1853
// values in the main cfg.
1854
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1855
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1856

3✔
1857
        switch c := cfg.Estimator.Config().(type) {
3✔
1858
        case routing.AprioriConfig:
3✔
1859
                routerCfg.ProbabilityEstimatorType =
3✔
1860
                        routing.AprioriEstimatorName
3✔
1861

3✔
1862
                targetCfg := routerCfg.AprioriConfig
3✔
1863
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1864
                targetCfg.Weight = c.AprioriWeight
3✔
1865
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1866
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1867

1868
        case routing.BimodalConfig:
3✔
1869
                routerCfg.ProbabilityEstimatorType =
3✔
1870
                        routing.BimodalEstimatorName
3✔
1871

3✔
1872
                targetCfg := routerCfg.BimodalConfig
3✔
1873
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1874
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1875
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1876
        }
1877

1878
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1879
}
1880

1881
// registerBlockConsumers registers the subsystems that consume block events.
1882
// By calling `RegisterQueue`, a list of subsystems are registered in the
1883
// blockbeat for block notifications. When a new block arrives, the subsystems
1884
// in the same queue are notified sequentially, and different queues are
1885
// notified concurrently.
1886
//
1887
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1888
// a new `RegisterQueue` call.
1889
func (s *server) registerBlockConsumers() {
3✔
1890
        // In this queue, when a new block arrives, it will be received and
3✔
1891
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1892
        consumers := []chainio.Consumer{
3✔
1893
                s.chainArb,
3✔
1894
                s.sweeper,
3✔
1895
                s.txPublisher,
3✔
1896
        }
3✔
1897
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1898
}
3✔
1899

1900
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1901
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1902
// may differ from what is on disk.
1903
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1904
        error) {
3✔
1905

3✔
1906
        data, err := u.DataToSign()
3✔
1907
        if err != nil {
3✔
UNCOV
1908
                return nil, err
×
UNCOV
1909
        }
×
1910

1911
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1912
}
1913

1914
// createLivenessMonitor creates a set of health checks using our configured
1915
// values and uses these checks to create a liveness monitor. Available
1916
// health checks,
1917
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1918
//   - diskCheck
1919
//   - tlsHealthCheck
1920
//   - torController, only created when tor is enabled.
1921
//
1922
// If a health check has been disabled by setting attempts to 0, our monitor
1923
// will not run it.
1924
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1925
        leaderElector cluster.LeaderElector) {
3✔
1926

3✔
1927
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1928
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
UNCOV
1929
                srvrLog.Info("Disabling chain backend checks for " +
×
UNCOV
1930
                        "nochainbackend mode")
×
1931

×
1932
                chainBackendAttempts = 0
×
1933
        }
×
1934

1935
        chainHealthCheck := healthcheck.NewObservation(
3✔
1936
                "chain backend",
3✔
1937
                cc.HealthCheck,
3✔
1938
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1939
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1940
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1941
                chainBackendAttempts,
3✔
1942
        )
3✔
1943

3✔
1944
        diskCheck := healthcheck.NewObservation(
3✔
1945
                "disk space",
3✔
1946
                func() error {
3✔
UNCOV
1947
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
UNCOV
1948
                                cfg.LndDir,
×
1949
                        )
×
1950
                        if err != nil {
×
1951
                                return err
×
1952
                        }
×
1953

1954
                        // If we have more free space than we require,
1955
                        // we return a nil error.
UNCOV
1956
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
UNCOV
1957
                                return nil
×
1958
                        }
×
1959

1960
                        return fmt.Errorf("require: %v free space, got: %v",
×
UNCOV
1961
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1962
                                free)
×
1963
                },
1964
                cfg.HealthChecks.DiskCheck.Interval,
1965
                cfg.HealthChecks.DiskCheck.Timeout,
1966
                cfg.HealthChecks.DiskCheck.Backoff,
1967
                cfg.HealthChecks.DiskCheck.Attempts,
1968
        )
1969

1970
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1971
                "tls",
3✔
1972
                func() error {
3✔
UNCOV
1973
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
UNCOV
1974
                                s.cc.KeyRing,
×
1975
                        )
×
1976
                        if err != nil {
×
1977
                                return err
×
1978
                        }
×
1979
                        if expired {
×
1980
                                return fmt.Errorf("TLS certificate is "+
×
1981
                                        "expired as of %v", expTime)
×
1982
                        }
×
1983

1984
                        // If the certificate is not outdated, no error needs
1985
                        // to be returned
UNCOV
1986
                        return nil
×
1987
                },
1988
                cfg.HealthChecks.TLSCheck.Interval,
1989
                cfg.HealthChecks.TLSCheck.Timeout,
1990
                cfg.HealthChecks.TLSCheck.Backoff,
1991
                cfg.HealthChecks.TLSCheck.Attempts,
1992
        )
1993

1994
        checks := []*healthcheck.Observation{
3✔
1995
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1996
        }
3✔
1997

3✔
1998
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1999
        if s.torController != nil {
3✔
UNCOV
2000
                torConnectionCheck := healthcheck.NewObservation(
×
UNCOV
2001
                        "tor connection",
×
2002
                        func() error {
×
2003
                                return healthcheck.CheckTorServiceStatus(
×
2004
                                        s.torController,
×
2005
                                        func() error {
×
2006
                                                return s.createNewHiddenService(
×
2007
                                                        context.TODO(),
×
2008
                                                )
×
2009
                                        },
×
2010
                                )
2011
                        },
2012
                        cfg.HealthChecks.TorConnection.Interval,
2013
                        cfg.HealthChecks.TorConnection.Timeout,
2014
                        cfg.HealthChecks.TorConnection.Backoff,
2015
                        cfg.HealthChecks.TorConnection.Attempts,
2016
                )
UNCOV
2017
                checks = append(checks, torConnectionCheck)
×
2018
        }
2019

2020
        // If remote signing is enabled, add the healthcheck for the remote
2021
        // signing RPC interface.
2022
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2023
                // Because we have two cascading timeouts here, we need to add
3✔
2024
                // some slack to the "outer" one of them in case the "inner"
3✔
2025
                // returns exactly on time.
3✔
2026
                overhead := time.Millisecond * 10
3✔
2027

3✔
2028
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2029
                        "remote signer connection",
3✔
2030
                        rpcwallet.HealthCheck(
3✔
2031
                                s.cfg.RemoteSigner,
3✔
2032

3✔
2033
                                // For the health check we might to be even
3✔
2034
                                // stricter than the initial/normal connect, so
3✔
2035
                                // we use the health check timeout here.
3✔
2036
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2037
                        ),
3✔
2038
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2039
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2040
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2041
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2042
                )
3✔
2043
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2044
        }
3✔
2045

2046
        // If we have a leader elector, we add a health check to ensure we are
2047
        // still the leader. During normal operation, we should always be the
2048
        // leader, but there are circumstances where this may change, such as
2049
        // when we lose network connectivity for long enough expiring out lease.
2050
        if leaderElector != nil {
3✔
UNCOV
2051
                leaderCheck := healthcheck.NewObservation(
×
UNCOV
2052
                        "leader status",
×
2053
                        func() error {
×
2054
                                // Check if we are still the leader. Note that
×
2055
                                // we don't need to use a timeout context here
×
2056
                                // as the healthcheck observer will handle the
×
2057
                                // timeout case for us.
×
2058
                                timeoutCtx, cancel := context.WithTimeout(
×
2059
                                        context.Background(),
×
2060
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2061
                                )
×
2062
                                defer cancel()
×
2063

×
2064
                                leader, err := leaderElector.IsLeader(
×
2065
                                        timeoutCtx,
×
2066
                                )
×
2067
                                if err != nil {
×
2068
                                        return fmt.Errorf("unable to check if "+
×
2069
                                                "still leader: %v", err)
×
2070
                                }
×
2071

2072
                                if !leader {
×
UNCOV
2073
                                        srvrLog.Debug("Not the current leader")
×
2074
                                        return fmt.Errorf("not the current " +
×
2075
                                                "leader")
×
2076
                                }
×
2077

2078
                                return nil
×
2079
                        },
2080
                        cfg.HealthChecks.LeaderCheck.Interval,
2081
                        cfg.HealthChecks.LeaderCheck.Timeout,
2082
                        cfg.HealthChecks.LeaderCheck.Backoff,
2083
                        cfg.HealthChecks.LeaderCheck.Attempts,
2084
                )
2085

UNCOV
2086
                checks = append(checks, leaderCheck)
×
2087
        }
2088

2089
        // If we have not disabled all of our health checks, we create a
2090
        // liveness monitor with our configured checks.
2091
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2092
                &healthcheck.Config{
3✔
2093
                        Checks:   checks,
3✔
2094
                        Shutdown: srvrLog.Criticalf,
3✔
2095
                },
3✔
2096
        )
3✔
2097
}
2098

2099
// Started returns true if the server has been started, and false otherwise.
2100
// NOTE: This function is safe for concurrent access.
2101
func (s *server) Started() bool {
3✔
2102
        return atomic.LoadInt32(&s.active) != 0
3✔
2103
}
3✔
2104

2105
// cleaner is used to aggregate "cleanup" functions during an operation that
2106
// starts several subsystems. In case one of the subsystem fails to start
2107
// and a proper resource cleanup is required, the "run" method achieves this
2108
// by running all these added "cleanup" functions.
2109
type cleaner []func() error
2110

2111
// add is used to add a cleanup function to be called when
2112
// the run function is executed.
2113
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2114
        return append(c, cleanup)
3✔
2115
}
3✔
2116

2117
// run is used to run all the previousely added cleanup functions.
UNCOV
2118
func (c cleaner) run() {
×
UNCOV
2119
        for i := len(c) - 1; i >= 0; i-- {
×
2120
                if err := c[i](); err != nil {
×
2121
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2122
                }
×
2123
        }
2124
}
2125

2126
// startLowLevelServices starts the low-level services of the server. These
2127
// services must be started successfully before running the main server. The
2128
// services are,
2129
// 1. the chain notifier.
2130
//
2131
// TODO(yy): identify and add more low-level services here.
2132
func (s *server) startLowLevelServices() error {
3✔
2133
        var startErr error
3✔
2134

3✔
2135
        cleanup := cleaner{}
3✔
2136

3✔
2137
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2138
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
UNCOV
2139
                startErr = err
×
UNCOV
2140
        }
×
2141

2142
        if startErr != nil {
3✔
UNCOV
2143
                cleanup.run()
×
UNCOV
2144
        }
×
2145

2146
        return startErr
3✔
2147
}
2148

2149
// Start starts the main daemon server, all requested listeners, and any helper
2150
// goroutines.
2151
// NOTE: This function is safe for concurrent access.
2152
//
2153
//nolint:funlen
2154
func (s *server) Start(ctx context.Context) error {
3✔
2155
        // Get the current blockbeat.
3✔
2156
        beat, err := s.getStartingBeat()
3✔
2157
        if err != nil {
3✔
UNCOV
2158
                return err
×
UNCOV
2159
        }
×
2160

2161
        var startErr error
3✔
2162

3✔
2163
        // If one sub system fails to start, the following code ensures that the
3✔
2164
        // previous started ones are stopped. It also ensures a proper wallet
3✔
2165
        // shutdown which is important for releasing its resources (boltdb, etc...)
3✔
2166
        cleanup := cleaner{}
3✔
2167

3✔
2168
        s.start.Do(func() {
6✔
2169
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2170
                if err := s.customMessageServer.Start(); err != nil {
3✔
UNCOV
2171
                        startErr = err
×
UNCOV
2172
                        return
×
2173
                }
×
2174

2175
                if s.hostAnn != nil {
3✔
UNCOV
2176
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
UNCOV
2177
                        if err := s.hostAnn.Start(); err != nil {
×
2178
                                startErr = err
×
2179
                                return
×
2180
                        }
×
2181
                }
2182

2183
                if s.livenessMonitor != nil {
6✔
2184
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2185
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
UNCOV
2186
                                startErr = err
×
UNCOV
2187
                                return
×
2188
                        }
×
2189
                }
2190

2191
                // Start the notification server. This is used so channel
2192
                // management goroutines can be notified when a funding
2193
                // transaction reaches a sufficient number of confirmations, or
2194
                // when the input for the funding transaction is spent in an
2195
                // attempt at an uncooperative close by the counterparty.
2196
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2197
                if err := s.sigPool.Start(); err != nil {
3✔
UNCOV
2198
                        startErr = err
×
UNCOV
2199
                        return
×
2200
                }
×
2201

2202
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2203
                if err := s.writePool.Start(); err != nil {
3✔
UNCOV
2204
                        startErr = err
×
UNCOV
2205
                        return
×
2206
                }
×
2207

2208
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2209
                if err := s.readPool.Start(); err != nil {
3✔
UNCOV
2210
                        startErr = err
×
UNCOV
2211
                        return
×
2212
                }
×
2213

2214
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2215
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
UNCOV
2216
                        startErr = err
×
UNCOV
2217
                        return
×
2218
                }
×
2219

2220
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
2221
                if err := s.channelNotifier.Start(); err != nil {
3✔
UNCOV
2222
                        startErr = err
×
UNCOV
2223
                        return
×
2224
                }
×
2225

2226
                cleanup = cleanup.add(func() error {
3✔
UNCOV
2227
                        return s.peerNotifier.Stop()
×
UNCOV
2228
                })
×
2229
                if err := s.peerNotifier.Start(); err != nil {
3✔
2230
                        startErr = err
×
UNCOV
2231
                        return
×
2232
                }
×
2233

2234
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2235
                if err := s.htlcNotifier.Start(); err != nil {
3✔
UNCOV
2236
                        startErr = err
×
UNCOV
2237
                        return
×
2238
                }
×
2239

2240
                if s.towerClientMgr != nil {
6✔
2241
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2242
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
UNCOV
2243
                                startErr = err
×
UNCOV
2244
                                return
×
2245
                        }
×
2246
                }
2247

2248
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2249
                if err := s.txPublisher.Start(beat); err != nil {
3✔
UNCOV
2250
                        startErr = err
×
UNCOV
2251
                        return
×
2252
                }
×
2253

2254
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2255
                if err := s.sweeper.Start(beat); err != nil {
3✔
UNCOV
2256
                        startErr = err
×
UNCOV
2257
                        return
×
2258
                }
×
2259

2260
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
2261
                if err := s.utxoNursery.Start(); err != nil {
3✔
UNCOV
2262
                        startErr = err
×
UNCOV
2263
                        return
×
2264
                }
×
2265

2266
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
2267
                if err := s.breachArbitrator.Start(); err != nil {
3✔
UNCOV
2268
                        startErr = err
×
UNCOV
2269
                        return
×
2270
                }
×
2271

2272
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2273
                if err := s.fundingMgr.Start(); err != nil {
3✔
UNCOV
2274
                        startErr = err
×
UNCOV
2275
                        return
×
2276
                }
×
2277

2278
                // htlcSwitch must be started before chainArb since the latter
2279
                // relies on htlcSwitch to deliver resolution message upon
2280
                // start.
2281
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2282
                if err := s.htlcSwitch.Start(); err != nil {
3✔
UNCOV
2283
                        startErr = err
×
UNCOV
2284
                        return
×
2285
                }
×
2286

2287
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
3✔
2288
                if err := s.interceptableSwitch.Start(); err != nil {
3✔
UNCOV
2289
                        startErr = err
×
UNCOV
2290
                        return
×
2291
                }
×
2292

2293
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
3✔
2294
                if err := s.invoiceHtlcModifier.Start(); err != nil {
3✔
UNCOV
2295
                        startErr = err
×
UNCOV
2296
                        return
×
2297
                }
×
2298

2299
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2300
                if err := s.chainArb.Start(beat); err != nil {
3✔
UNCOV
2301
                        startErr = err
×
UNCOV
2302
                        return
×
2303
                }
×
2304

2305
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2306
                if err := s.graphDB.Start(); err != nil {
3✔
UNCOV
2307
                        startErr = err
×
UNCOV
2308
                        return
×
2309
                }
×
2310

2311
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2312
                if err := s.graphBuilder.Start(); err != nil {
3✔
UNCOV
2313
                        startErr = err
×
UNCOV
2314
                        return
×
2315
                }
×
2316

2317
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2318
                if err := s.chanRouter.Start(); err != nil {
3✔
UNCOV
2319
                        startErr = err
×
UNCOV
2320
                        return
×
2321
                }
×
2322
                // The authGossiper depends on the chanRouter and therefore
2323
                // should be started after it.
2324
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2325
                if err := s.authGossiper.Start(); err != nil {
3✔
UNCOV
2326
                        startErr = err
×
UNCOV
2327
                        return
×
2328
                }
×
2329

2330
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2331
                if err := s.invoices.Start(); err != nil {
3✔
UNCOV
2332
                        startErr = err
×
UNCOV
2333
                        return
×
2334
                }
×
2335

2336
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2337
                if err := s.sphinx.Start(); err != nil {
3✔
UNCOV
2338
                        startErr = err
×
UNCOV
2339
                        return
×
2340
                }
×
2341

2342
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2343
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
UNCOV
2344
                        startErr = err
×
UNCOV
2345
                        return
×
2346
                }
×
2347

2348
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2349
                if err := s.chanEventStore.Start(); err != nil {
3✔
UNCOV
2350
                        startErr = err
×
UNCOV
2351
                        return
×
2352
                }
×
2353

2354
                cleanup.add(func() error {
3✔
UNCOV
2355
                        s.missionController.StopStoreTickers()
×
UNCOV
2356
                        return nil
×
2357
                })
×
2358
                s.missionController.RunStoreTickers()
3✔
2359

3✔
2360
                // Before we start the connMgr, we'll check to see if we have
3✔
2361
                // any backups to recover. We do this now as we want to ensure
3✔
2362
                // that have all the information we need to handle channel
3✔
2363
                // recovery _before_ we even accept connections from any peers.
3✔
2364
                chanRestorer := &chanDBRestorer{
3✔
2365
                        db:         s.chanStateDB,
3✔
2366
                        secretKeys: s.cc.KeyRing,
3✔
2367
                        chainArb:   s.chainArb,
3✔
2368
                }
3✔
2369
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
UNCOV
2370
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
UNCOV
2371
                                s.chansToRestore.PackedSingleChanBackups,
×
2372
                                s.cc.KeyRing, chanRestorer, s,
×
2373
                        )
×
2374
                        if err != nil {
×
2375
                                startErr = fmt.Errorf("unable to unpack single "+
×
2376
                                        "backups: %v", err)
×
2377
                                return
×
2378
                        }
×
2379
                }
2380
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2381
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2382
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2383
                                s.cc.KeyRing, chanRestorer, s,
3✔
2384
                        )
3✔
2385
                        if err != nil {
3✔
UNCOV
2386
                                startErr = fmt.Errorf("unable to unpack chan "+
×
UNCOV
2387
                                        "backup: %v", err)
×
2388
                                return
×
2389
                        }
×
2390
                }
2391

2392
                // chanSubSwapper must be started after the `channelNotifier`
2393
                // because it depends on channel events as a synchronization
2394
                // point.
2395
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2396
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
UNCOV
2397
                        startErr = err
×
UNCOV
2398
                        return
×
2399
                }
×
2400

2401
                if s.torController != nil {
3✔
UNCOV
2402
                        cleanup = cleanup.add(s.torController.Stop)
×
UNCOV
2403
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2404
                                startErr = err
×
2405
                                return
×
2406
                        }
×
2407
                }
2408

2409
                if s.natTraversal != nil {
3✔
UNCOV
2410
                        s.wg.Add(1)
×
UNCOV
2411
                        go s.watchExternalIP()
×
2412
                }
×
2413

2414
                // Start connmgr last to prevent connections before init.
2415
                cleanup = cleanup.add(func() error {
3✔
UNCOV
2416
                        s.connMgr.Stop()
×
UNCOV
2417
                        return nil
×
2418
                })
×
2419

2420
                // RESOLVE: s.connMgr.Start() is called here, but
2421
                // brontide.NewListener() is called in newServer. This means
2422
                // that we are actually listening and partially accepting
2423
                // inbound connections even before the connMgr starts.
2424
                //
2425
                // TODO(yy): move the log into the connMgr's `Start` method.
2426
                srvrLog.Info("connMgr starting...")
3✔
2427
                s.connMgr.Start()
3✔
2428
                srvrLog.Debug("connMgr started")
3✔
2429

3✔
2430
                // If peers are specified as a config option, we'll add those
3✔
2431
                // peers first.
3✔
2432
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2433
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2434
                                peerAddrCfg,
3✔
2435
                        )
3✔
2436
                        if err != nil {
3✔
UNCOV
2437
                                startErr = fmt.Errorf("unable to parse peer "+
×
UNCOV
2438
                                        "pubkey from config: %v", err)
×
2439
                                return
×
2440
                        }
×
2441
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2442
                        if err != nil {
3✔
UNCOV
2443
                                startErr = fmt.Errorf("unable to parse peer "+
×
UNCOV
2444
                                        "address provided as a config option: "+
×
2445
                                        "%v", err)
×
2446
                                return
×
2447
                        }
×
2448

2449
                        peerAddr := &lnwire.NetAddress{
3✔
2450
                                IdentityKey: parsedPubkey,
3✔
2451
                                Address:     addr,
3✔
2452
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2453
                        }
3✔
2454

3✔
2455
                        err = s.ConnectToPeer(
3✔
2456
                                peerAddr, true,
3✔
2457
                                s.cfg.ConnectionTimeout,
3✔
2458
                        )
3✔
2459
                        if err != nil {
3✔
UNCOV
2460
                                startErr = fmt.Errorf("unable to connect to "+
×
UNCOV
2461
                                        "peer address provided as a config "+
×
2462
                                        "option: %v", err)
×
2463
                                return
×
2464
                        }
×
2465
                }
2466

2467
                // Subscribe to NodeAnnouncements that advertise new addresses
2468
                // our persistent peers.
2469
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
UNCOV
2470
                        srvrLog.Errorf("Failed to update persistent peer "+
×
UNCOV
2471
                                "addr: %v", err)
×
2472

×
2473
                        startErr = err
×
2474
                        return
×
2475
                }
×
2476

2477
                // With all the relevant sub-systems started, we'll now attempt
2478
                // to establish persistent connections to our direct channel
2479
                // collaborators within the network. Before doing so however,
2480
                // we'll prune our set of link nodes found within the database
2481
                // to ensure we don't reconnect to any nodes we no longer have
2482
                // open channels with.
2483
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
UNCOV
2484
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
UNCOV
2485

×
2486
                        startErr = err
×
2487
                        return
×
2488
                }
×
2489

2490
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
UNCOV
2491
                        srvrLog.Errorf("Failed to establish persistent "+
×
UNCOV
2492
                                "connections: %v", err)
×
2493
                }
×
2494

2495
                // setSeedList is a helper function that turns multiple DNS seed
2496
                // server tuples from the command line or config file into the
2497
                // data structure we need and does a basic formal sanity check
2498
                // in the process.
2499
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
UNCOV
2500
                        if len(tuples) == 0 {
×
UNCOV
2501
                                return
×
2502
                        }
×
2503

2504
                        result := make([][2]string, len(tuples))
×
UNCOV
2505
                        for idx, tuple := range tuples {
×
2506
                                tuple = strings.TrimSpace(tuple)
×
2507
                                if len(tuple) == 0 {
×
2508
                                        return
×
2509
                                }
×
2510

2511
                                servers := strings.Split(tuple, ",")
×
UNCOV
2512
                                if len(servers) > 2 || len(servers) == 0 {
×
2513
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2514
                                                "seed tuple: %v", servers)
×
2515
                                        return
×
2516
                                }
×
2517

2518
                                copy(result[idx][:], servers)
×
2519
                        }
2520

UNCOV
2521
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2522
                }
2523

2524
                // Let users overwrite the DNS seed nodes. We only allow them
2525
                // for bitcoin mainnet/testnet/signet.
2526
                if s.cfg.Bitcoin.MainNet {
3✔
UNCOV
2527
                        setSeedList(
×
UNCOV
2528
                                s.cfg.Bitcoin.DNSSeeds,
×
2529
                                chainreg.BitcoinMainnetGenesis,
×
2530
                        )
×
2531
                }
×
2532
                if s.cfg.Bitcoin.TestNet3 {
3✔
2533
                        setSeedList(
×
UNCOV
2534
                                s.cfg.Bitcoin.DNSSeeds,
×
2535
                                chainreg.BitcoinTestnetGenesis,
×
2536
                        )
×
2537
                }
×
2538
                if s.cfg.Bitcoin.TestNet4 {
3✔
2539
                        setSeedList(
×
UNCOV
2540
                                s.cfg.Bitcoin.DNSSeeds,
×
2541
                                chainreg.BitcoinTestnet4Genesis,
×
2542
                        )
×
2543
                }
×
2544
                if s.cfg.Bitcoin.SigNet {
3✔
2545
                        setSeedList(
×
UNCOV
2546
                                s.cfg.Bitcoin.DNSSeeds,
×
2547
                                chainreg.BitcoinSignetGenesis,
×
2548
                        )
×
2549
                }
×
2550

2551
                // If network bootstrapping hasn't been disabled, then we'll
2552
                // configure the set of active bootstrappers, and launch a
2553
                // dedicated goroutine to maintain a set of persistent
2554
                // connections.
2555
                if !s.cfg.NoNetBootstrap {
6✔
2556
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2557
                        if err != nil {
3✔
UNCOV
2558
                                startErr = err
×
UNCOV
2559
                                return
×
2560
                        }
×
2561

2562
                        s.wg.Add(1)
3✔
2563
                        go s.peerBootstrapper(
3✔
2564
                                ctx, defaultMinPeers, bootstrappers,
3✔
2565
                        )
3✔
2566
                } else {
3✔
2567
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2568
                }
3✔
2569

2570
                // Start the blockbeat after all other subsystems have been
2571
                // started so they are ready to receive new blocks.
2572
                cleanup = cleanup.add(func() error {
3✔
UNCOV
2573
                        s.blockbeatDispatcher.Stop()
×
UNCOV
2574
                        return nil
×
2575
                })
×
2576
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2577
                        startErr = err
×
UNCOV
2578
                        return
×
2579
                }
×
2580

2581
                // Set the active flag now that we've completed the full
2582
                // startup.
2583
                atomic.StoreInt32(&s.active, 1)
3✔
2584
        })
2585

2586
        if startErr != nil {
3✔
UNCOV
2587
                cleanup.run()
×
UNCOV
2588
        }
×
2589
        return startErr
3✔
2590
}
2591

2592
// Stop gracefully shutsdown the main daemon server. This function will signal
2593
// any active goroutines, or helper objects to exit, then blocks until they've
2594
// all successfully exited. Additionally, any/all listeners are closed.
2595
// NOTE: This function is safe for concurrent access.
2596
func (s *server) Stop() error {
3✔
2597
        s.stop.Do(func() {
6✔
2598
                atomic.StoreInt32(&s.stopping, 1)
3✔
2599

3✔
2600
                ctx := context.Background()
3✔
2601

3✔
2602
                close(s.quit)
3✔
2603

3✔
2604
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2605
                s.connMgr.Stop()
3✔
2606

3✔
2607
                // Stop dispatching blocks to other systems immediately.
3✔
2608
                s.blockbeatDispatcher.Stop()
3✔
2609

3✔
2610
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2611
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
UNCOV
2612
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
UNCOV
2613
                }
×
2614
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2615
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
UNCOV
2616
                }
×
2617
                if err := s.sphinx.Stop(); err != nil {
3✔
2618
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
UNCOV
2619
                }
×
2620
                if err := s.invoices.Stop(); err != nil {
3✔
2621
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
UNCOV
2622
                }
×
2623
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2624
                        srvrLog.Warnf("failed to stop interceptable "+
×
UNCOV
2625
                                "switch: %v", err)
×
2626
                }
×
2627
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2628
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
UNCOV
2629
                                "modifier: %v", err)
×
2630
                }
×
2631
                if err := s.chanRouter.Stop(); err != nil {
3✔
2632
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
UNCOV
2633
                }
×
2634
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2635
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
UNCOV
2636
                }
×
2637
                if err := s.graphDB.Stop(); err != nil {
3✔
2638
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
UNCOV
2639
                }
×
2640
                if err := s.chainArb.Stop(); err != nil {
3✔
2641
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
UNCOV
2642
                }
×
2643
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2644
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
UNCOV
2645
                }
×
2646
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2647
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
UNCOV
2648
                                err)
×
2649
                }
×
2650
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2651
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
UNCOV
2652
                }
×
2653
                if err := s.authGossiper.Stop(); err != nil {
3✔
2654
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
UNCOV
2655
                }
×
2656
                if err := s.sweeper.Stop(); err != nil {
3✔
2657
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
UNCOV
2658
                }
×
2659
                if err := s.txPublisher.Stop(); err != nil {
3✔
2660
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
UNCOV
2661
                }
×
2662
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2663
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
UNCOV
2664
                }
×
2665
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2666
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
UNCOV
2667
                }
×
2668
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2669
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
UNCOV
2670
                }
×
2671

2672
                // Update channel.backup file. Make sure to do it before
2673
                // stopping chanSubSwapper.
2674
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2675
                        ctx, s.chanStateDB, s.addrSource,
3✔
2676
                )
3✔
2677
                if err != nil {
3✔
UNCOV
2678
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
UNCOV
2679
                                err)
×
2680
                } else {
3✔
2681
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2682
                        if err != nil {
6✔
2683
                                srvrLog.Warnf("Manual update of channel "+
3✔
2684
                                        "backup failed: %v", err)
3✔
2685
                        }
3✔
2686
                }
2687

2688
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
UNCOV
2689
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
UNCOV
2690
                }
×
2691
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2692
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
UNCOV
2693
                }
×
2694
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2695
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
UNCOV
2696
                                err)
×
2697
                }
×
2698
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2699
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
UNCOV
2700
                                err)
×
2701
                }
×
2702
                s.missionController.StopStoreTickers()
3✔
2703

3✔
2704
                // Disconnect from each active peers to ensure that
3✔
2705
                // peerTerminationWatchers signal completion to each peer.
3✔
2706
                for _, peer := range s.Peers() {
6✔
2707
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2708
                        if err != nil {
3✔
UNCOV
2709
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
UNCOV
2710
                                        "received error: %v", peer.IdentityKey(),
×
2711
                                        err,
×
2712
                                )
×
2713
                        }
×
2714
                }
2715

2716
                // Now that all connections have been torn down, stop the tower
2717
                // client which will reliably flush all queued states to the
2718
                // tower. If this is halted for any reason, the force quit timer
2719
                // will kick in and abort to allow this method to return.
2720
                if s.towerClientMgr != nil {
6✔
2721
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
UNCOV
2722
                                srvrLog.Warnf("Unable to shut down tower "+
×
UNCOV
2723
                                        "client manager: %v", err)
×
2724
                        }
×
2725
                }
2726

2727
                if s.hostAnn != nil {
3✔
UNCOV
2728
                        if err := s.hostAnn.Stop(); err != nil {
×
UNCOV
2729
                                srvrLog.Warnf("unable to shut down host "+
×
2730
                                        "annoucner: %v", err)
×
2731
                        }
×
2732
                }
2733

2734
                if s.livenessMonitor != nil {
6✔
2735
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
UNCOV
2736
                                srvrLog.Warnf("unable to shutdown liveness "+
×
UNCOV
2737
                                        "monitor: %v", err)
×
2738
                        }
×
2739
                }
2740

2741
                // Wait for all lingering goroutines to quit.
2742
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2743
                s.wg.Wait()
3✔
2744

3✔
2745
                srvrLog.Debug("Stopping buffer pools...")
3✔
2746
                s.sigPool.Stop()
3✔
2747
                s.writePool.Stop()
3✔
2748
                s.readPool.Stop()
3✔
2749
        })
2750

2751
        return nil
3✔
2752
}
2753

2754
// Stopped returns true if the server has been instructed to shutdown.
2755
// NOTE: This function is safe for concurrent access.
2756
func (s *server) Stopped() bool {
3✔
2757
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2758
}
3✔
2759

2760
// configurePortForwarding attempts to set up port forwarding for the different
2761
// ports that the server will be listening on.
2762
//
2763
// NOTE: This should only be used when using some kind of NAT traversal to
2764
// automatically set up forwarding rules.
UNCOV
2765
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
UNCOV
2766
        ip, err := s.natTraversal.ExternalIP()
×
2767
        if err != nil {
×
2768
                return nil, err
×
2769
        }
×
2770
        s.lastDetectedIP = ip
×
2771

×
2772
        externalIPs := make([]string, 0, len(ports))
×
2773
        for _, port := range ports {
×
2774
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2775
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2776
                        continue
×
2777
                }
2778

UNCOV
2779
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
UNCOV
2780
                externalIPs = append(externalIPs, hostIP)
×
2781
        }
2782

UNCOV
2783
        return externalIPs, nil
×
2784
}
2785

2786
// removePortForwarding attempts to clear the forwarding rules for the different
2787
// ports the server is currently listening on.
2788
//
2789
// NOTE: This should only be used when using some kind of NAT traversal to
2790
// automatically set up forwarding rules.
UNCOV
2791
func (s *server) removePortForwarding() {
×
UNCOV
2792
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2793
        for _, port := range forwardedPorts {
×
2794
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2795
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2796
                                "port %d: %v", port, err)
×
2797
                }
×
2798
        }
2799
}
2800

2801
// watchExternalIP continuously checks for an updated external IP address every
2802
// 15 minutes. Once a new IP address has been detected, it will automatically
2803
// handle port forwarding rules and send updated node announcements to the
2804
// currently connected peers.
2805
//
2806
// NOTE: This MUST be run as a goroutine.
UNCOV
2807
func (s *server) watchExternalIP() {
×
UNCOV
2808
        defer s.wg.Done()
×
2809

×
2810
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2811
        // up by the server.
×
2812
        defer s.removePortForwarding()
×
2813

×
2814
        // Keep track of the external IPs set by the user to avoid replacing
×
2815
        // them when detecting a new IP.
×
2816
        ipsSetByUser := make(map[string]struct{})
×
2817
        for _, ip := range s.cfg.ExternalIPs {
×
2818
                ipsSetByUser[ip.String()] = struct{}{}
×
2819
        }
×
2820

2821
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
UNCOV
2822

×
2823
        ticker := time.NewTicker(15 * time.Minute)
×
2824
        defer ticker.Stop()
×
2825
out:
×
2826
        for {
×
2827
                select {
×
2828
                case <-ticker.C:
×
2829
                        // We'll start off by making sure a new IP address has
×
2830
                        // been detected.
×
2831
                        ip, err := s.natTraversal.ExternalIP()
×
2832
                        if err != nil {
×
2833
                                srvrLog.Debugf("Unable to retrieve the "+
×
2834
                                        "external IP address: %v", err)
×
2835
                                continue
×
2836
                        }
2837

2838
                        // Periodically renew the NAT port forwarding.
UNCOV
2839
                        for _, port := range forwardedPorts {
×
UNCOV
2840
                                err := s.natTraversal.AddPortMapping(port)
×
2841
                                if err != nil {
×
2842
                                        srvrLog.Warnf("Unable to automatically "+
×
2843
                                                "re-create port forwarding using %s: %v",
×
2844
                                                s.natTraversal.Name(), err)
×
2845
                                } else {
×
2846
                                        srvrLog.Debugf("Automatically re-created "+
×
2847
                                                "forwarding for port %d using %s to "+
×
2848
                                                "advertise external IP",
×
2849
                                                port, s.natTraversal.Name())
×
2850
                                }
×
2851
                        }
2852

UNCOV
2853
                        if ip.Equal(s.lastDetectedIP) {
×
UNCOV
2854
                                continue
×
2855
                        }
2856

UNCOV
2857
                        srvrLog.Infof("Detected new external IP address %s", ip)
×
UNCOV
2858

×
2859
                        // Next, we'll craft the new addresses that will be
×
2860
                        // included in the new node announcement and advertised
×
2861
                        // to the network. Each address will consist of the new
×
2862
                        // IP detected and one of the currently advertised
×
2863
                        // ports.
×
2864
                        var newAddrs []net.Addr
×
2865
                        for _, port := range forwardedPorts {
×
2866
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2867
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2868
                                if err != nil {
×
2869
                                        srvrLog.Debugf("Unable to resolve "+
×
2870
                                                "host %v: %v", addr, err)
×
2871
                                        continue
×
2872
                                }
2873

UNCOV
2874
                                newAddrs = append(newAddrs, addr)
×
2875
                        }
2876

2877
                        // Skip the update if we weren't able to resolve any of
2878
                        // the new addresses.
UNCOV
2879
                        if len(newAddrs) == 0 {
×
UNCOV
2880
                                srvrLog.Debug("Skipping node announcement " +
×
2881
                                        "update due to not being able to " +
×
2882
                                        "resolve any new addresses")
×
2883
                                continue
×
2884
                        }
2885

2886
                        // Now, we'll need to update the addresses in our node's
2887
                        // announcement in order to propagate the update
2888
                        // throughout the network. We'll only include addresses
2889
                        // that have a different IP from the previous one, as
2890
                        // the previous IP is no longer valid.
UNCOV
2891
                        currentNodeAnn := s.getNodeAnnouncement()
×
UNCOV
2892

×
2893
                        for _, addr := range currentNodeAnn.Addresses {
×
2894
                                host, _, err := net.SplitHostPort(addr.String())
×
2895
                                if err != nil {
×
2896
                                        srvrLog.Debugf("Unable to determine "+
×
2897
                                                "host from address %v: %v",
×
2898
                                                addr, err)
×
2899
                                        continue
×
2900
                                }
2901

2902
                                // We'll also make sure to include external IPs
2903
                                // set manually by the user.
UNCOV
2904
                                _, setByUser := ipsSetByUser[addr.String()]
×
UNCOV
2905
                                if setByUser || host != s.lastDetectedIP.String() {
×
2906
                                        newAddrs = append(newAddrs, addr)
×
2907
                                }
×
2908
                        }
2909

2910
                        // Then, we'll generate a new timestamped node
2911
                        // announcement with the updated addresses and broadcast
2912
                        // it to our peers.
UNCOV
2913
                        newNodeAnn, err := s.genNodeAnnouncement(
×
UNCOV
2914
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2915
                        )
×
2916
                        if err != nil {
×
2917
                                srvrLog.Debugf("Unable to generate new node "+
×
2918
                                        "announcement: %v", err)
×
2919
                                continue
×
2920
                        }
2921

UNCOV
2922
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
2923
                        if err != nil {
×
2924
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2925
                                        "announcement to peers: %v", err)
×
2926
                                continue
×
2927
                        }
2928

2929
                        // Finally, update the last IP seen to the current one.
UNCOV
2930
                        s.lastDetectedIP = ip
×
UNCOV
2931
                case <-s.quit:
×
2932
                        break out
×
2933
                }
2934
        }
2935
}
2936

2937
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2938
// based on the server, and currently active bootstrap mechanisms as defined
2939
// within the current configuration.
2940
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2941
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2942

3✔
2943
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2944

3✔
2945
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2946
        // this can be used by default if we've already partially seeded the
3✔
2947
        // network.
3✔
2948
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2949
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2950
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2951
        )
3✔
2952
        if err != nil {
3✔
UNCOV
2953
                return nil, err
×
UNCOV
2954
        }
×
2955
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2956

3✔
2957
        // If this isn't using simnet or regtest mode, then one of our
3✔
2958
        // additional bootstrapping sources will be the set of running DNS
3✔
2959
        // seeds.
3✔
2960
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
UNCOV
2961
                //nolint:ll
×
UNCOV
2962
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2963

×
2964
                // If we have a set of DNS seeds for this chain, then we'll add
×
2965
                // it as an additional bootstrapping source.
×
2966
                if ok {
×
2967
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2968
                                "seeds: %v", dnsSeeds)
×
2969

×
2970
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2971
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2972
                        )
×
2973
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2974
                }
×
2975
        }
2976

2977
        return bootStrappers, nil
3✔
2978
}
2979

2980
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2981
// needs to ignore, which is made of three parts,
2982
//   - the node itself needs to be skipped as it doesn't make sense to connect
2983
//     to itself.
2984
//   - the peers that already have connections with, as in s.peersByPub.
2985
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2986
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
2987
        s.mu.RLock()
3✔
2988
        defer s.mu.RUnlock()
3✔
2989

3✔
2990
        ignore := make(map[autopilot.NodeID]struct{})
3✔
2991

3✔
2992
        // We should ignore ourselves from bootstrapping.
3✔
2993
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
2994
        ignore[selfKey] = struct{}{}
3✔
2995

3✔
2996
        // Ignore all connected peers.
3✔
2997
        for _, peer := range s.peersByPub {
3✔
UNCOV
2998
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
UNCOV
2999
                ignore[nID] = struct{}{}
×
3000
        }
×
3001

3002
        // Ignore all persistent peers as they have a dedicated reconnecting
3003
        // process.
3004
        for pubKeyStr := range s.persistentPeers {
3✔
UNCOV
3005
                var nID autopilot.NodeID
×
UNCOV
3006
                copy(nID[:], []byte(pubKeyStr))
×
3007
                ignore[nID] = struct{}{}
×
3008
        }
×
3009

3010
        return ignore
3✔
3011
}
3012

3013
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3014
// and maintain a target minimum number of outbound connections. With this
3015
// invariant, we ensure that our node is connected to a diverse set of peers
3016
// and that nodes newly joining the network receive an up to date network view
3017
// as soon as possible.
3018
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3019
        bootstrappers []discovery.NetworkPeerBootstrapper) {
3✔
3020

3✔
3021
        defer s.wg.Done()
3✔
3022

3✔
3023
        // Before we continue, init the ignore peers map.
3✔
3024
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3025

3✔
3026
        // We'll start off by aggressively attempting connections to peers in
3✔
3027
        // order to be a part of the network as soon as possible.
3✔
3028
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
3✔
3029

3✔
3030
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3031
        // peers.
3✔
3032
        //
3✔
3033
        // We'll use a 15 second backoff, and double the time every time an
3✔
3034
        // epoch fails up to a ceiling.
3✔
3035
        backOff := time.Second * 15
3✔
3036

3✔
3037
        // We'll create a new ticker to wake us up every 15 seconds so we can
3✔
3038
        // see if we've reached our minimum number of peers.
3✔
3039
        sampleTicker := time.NewTicker(backOff)
3✔
3040
        defer sampleTicker.Stop()
3✔
3041

3✔
3042
        // We'll use the number of attempts and errors to determine if we need
3✔
3043
        // to increase the time between discovery epochs.
3✔
3044
        var epochErrors uint32 // To be used atomically.
3✔
3045
        var epochAttempts uint32
3✔
3046

3✔
3047
        for {
6✔
3048
                select {
3✔
3049
                // The ticker has just woken us up, so we'll need to check if
3050
                // we need to attempt to connect our to any more peers.
UNCOV
3051
                case <-sampleTicker.C:
×
UNCOV
3052
                        // Obtain the current number of peers, so we can gauge
×
3053
                        // if we need to sample more peers or not.
×
3054
                        s.mu.RLock()
×
3055
                        numActivePeers := uint32(len(s.peersByPub))
×
3056
                        s.mu.RUnlock()
×
3057

×
3058
                        // If we have enough peers, then we can loop back
×
3059
                        // around to the next round as we're done here.
×
3060
                        if numActivePeers >= numTargetPeers {
×
3061
                                continue
×
3062
                        }
3063

3064
                        // If all of our attempts failed during this last back
3065
                        // off period, then will increase our backoff to 5
3066
                        // minute ceiling to avoid an excessive number of
3067
                        // queries
3068
                        //
3069
                        // TODO(roasbeef): add reverse policy too?
3070

UNCOV
3071
                        if epochAttempts > 0 &&
×
UNCOV
3072
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3073

×
3074
                                sampleTicker.Stop()
×
3075

×
3076
                                backOff *= 2
×
3077
                                if backOff > bootstrapBackOffCeiling {
×
3078
                                        backOff = bootstrapBackOffCeiling
×
3079
                                }
×
3080

3081
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
UNCOV
3082
                                        "%v", backOff)
×
3083
                                sampleTicker = time.NewTicker(backOff)
×
3084
                                continue
×
3085
                        }
3086

UNCOV
3087
                        atomic.StoreUint32(&epochErrors, 0)
×
UNCOV
3088
                        epochAttempts = 0
×
3089

×
3090
                        // Since we know need more peers, we'll compute the
×
3091
                        // exact number we need to reach our threshold.
×
3092
                        numNeeded := numTargetPeers - numActivePeers
×
3093

×
3094
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3095
                                "peers", numNeeded)
×
3096

×
3097
                        // With the number of peers we need calculated, we'll
×
3098
                        // query the network bootstrappers to sample a set of
×
3099
                        // random addrs for us.
×
3100
                        //
×
3101
                        // Before we continue, get a copy of the ignore peers
×
3102
                        // map.
×
3103
                        ignoreList = s.createBootstrapIgnorePeers()
×
3104

×
3105
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3106
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3107
                        )
×
3108
                        if err != nil {
×
3109
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3110
                                        "peers: %v", err)
×
3111
                                continue
×
3112
                        }
3113

3114
                        // Finally, we'll launch a new goroutine for each
3115
                        // prospective peer candidates.
UNCOV
3116
                        for _, addr := range peerAddrs {
×
UNCOV
3117
                                epochAttempts++
×
3118

×
3119
                                go func(a *lnwire.NetAddress) {
×
3120
                                        // TODO(roasbeef): can do AS, subnet,
×
3121
                                        // country diversity, etc
×
3122
                                        errChan := make(chan error, 1)
×
3123
                                        s.connectToPeer(
×
3124
                                                a, errChan,
×
3125
                                                s.cfg.ConnectionTimeout,
×
3126
                                        )
×
3127
                                        select {
×
3128
                                        case err := <-errChan:
×
3129
                                                if err == nil {
×
3130
                                                        return
×
3131
                                                }
×
3132

3133
                                                srvrLog.Errorf("Unable to "+
×
UNCOV
3134
                                                        "connect to %v: %v",
×
3135
                                                        a, err)
×
3136
                                                atomic.AddUint32(&epochErrors, 1)
×
3137
                                        case <-s.quit:
×
3138
                                        }
3139
                                }(addr)
3140
                        }
3141
                case <-s.quit:
3✔
3142
                        return
3✔
3143
                }
3144
        }
3145
}
3146

3147
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3148
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3149
// query back off each time we encounter a failure.
3150
const bootstrapBackOffCeiling = time.Minute * 5
3151

3152
// initialPeerBootstrap attempts to continuously connect to peers on startup
3153
// until the target number of peers has been reached. This ensures that nodes
3154
// receive an up to date network view as soon as possible.
3155
func (s *server) initialPeerBootstrap(ctx context.Context,
3156
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3157
        bootstrappers []discovery.NetworkPeerBootstrapper) {
3✔
3158

3✔
3159
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3160
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3161

3✔
3162
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3163
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3164
        var delaySignal <-chan time.Time
3✔
3165
        delayTime := time.Second * 2
3✔
3166

3✔
3167
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3168
        // then the main peer bootstrap logic.
3✔
3169
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3170

3✔
3171
        for attempts := 0; ; attempts++ {
6✔
3172
                // Check if the server has been requested to shut down in order
3✔
3173
                // to prevent blocking.
3✔
3174
                if s.Stopped() {
3✔
UNCOV
3175
                        return
×
UNCOV
3176
                }
×
3177

3178
                // We can exit our aggressive initial peer bootstrapping stage
3179
                // if we've reached out target number of peers.
3180
                s.mu.RLock()
3✔
3181
                numActivePeers := uint32(len(s.peersByPub))
3✔
3182
                s.mu.RUnlock()
3✔
3183

3✔
3184
                if numActivePeers >= numTargetPeers {
6✔
3185
                        return
3✔
3186
                }
3✔
3187

3188
                if attempts > 0 {
3✔
UNCOV
3189
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3190
                                "bootstrap peers (attempt #%v)", delayTime,
×
3191
                                attempts)
×
3192

×
3193
                        // We've completed at least one iterating and haven't
×
3194
                        // finished, so we'll start to insert a delay period
×
3195
                        // between each attempt.
×
3196
                        delaySignal = time.After(delayTime)
×
3197
                        select {
×
3198
                        case <-delaySignal:
×
3199
                        case <-s.quit:
×
3200
                                return
×
3201
                        }
3202

3203
                        // After our delay, we'll double the time we wait up to
3204
                        // the max back off period.
UNCOV
3205
                        delayTime *= 2
×
UNCOV
3206
                        if delayTime > backOffCeiling {
×
3207
                                delayTime = backOffCeiling
×
3208
                        }
×
3209
                }
3210

3211
                // Otherwise, we'll request for the remaining number of peers
3212
                // in order to reach our target.
3213
                peersNeeded := numTargetPeers - numActivePeers
3✔
3214
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3215
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3216
                )
3✔
3217
                if err != nil {
3✔
UNCOV
3218
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3219
                                "peers: %v", err)
×
3220
                        continue
×
3221
                }
3222

3223
                // Then, we'll attempt to establish a connection to the
3224
                // different peer addresses retrieved by our bootstrappers.
3225
                var wg sync.WaitGroup
3✔
3226
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3227
                        wg.Add(1)
3✔
3228
                        go func(addr *lnwire.NetAddress) {
6✔
3229
                                defer wg.Done()
3✔
3230

3✔
3231
                                errChan := make(chan error, 1)
3✔
3232
                                go s.connectToPeer(
3✔
3233
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3234
                                )
3✔
3235

3✔
3236
                                // We'll only allow this connection attempt to
3✔
3237
                                // take up to 3 seconds. This allows us to move
3✔
3238
                                // quickly by discarding peers that are slowing
3✔
3239
                                // us down.
3✔
3240
                                select {
3✔
3241
                                case err := <-errChan:
3✔
3242
                                        if err == nil {
6✔
3243
                                                return
3✔
3244
                                        }
3✔
UNCOV
3245
                                        srvrLog.Errorf("Unable to connect to "+
×
UNCOV
3246
                                                "%v: %v", addr, err)
×
3247
                                // TODO: tune timeout? 3 seconds might be *too*
3248
                                // aggressive but works well.
UNCOV
3249
                                case <-time.After(3 * time.Second):
×
UNCOV
3250
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3251
                                                "to not establishing a "+
×
3252
                                                "connection within 3 seconds",
×
3253
                                                addr)
×
3254
                                case <-s.quit:
×
3255
                                }
3256
                        }(bootstrapAddr)
3257
                }
3258

3259
                wg.Wait()
3✔
3260
        }
3261
}
3262

3263
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3264
// order to listen for inbound connections over Tor.
UNCOV
3265
func (s *server) createNewHiddenService(ctx context.Context) error {
×
UNCOV
3266
        // Determine the different ports the server is listening on. The onion
×
3267
        // service's virtual port will map to these ports and one will be picked
×
3268
        // at random when the onion service is being accessed.
×
3269
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3270
        for _, listenAddr := range s.listenAddrs {
×
3271
                port := listenAddr.(*net.TCPAddr).Port
×
3272
                listenPorts = append(listenPorts, port)
×
3273
        }
×
3274

3275
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
UNCOV
3276
        if err != nil {
×
3277
                return err
×
3278
        }
×
3279

3280
        // Once the port mapping has been set, we can go ahead and automatically
3281
        // create our onion service. The service's private key will be saved to
3282
        // disk in order to regain access to this service when restarting `lnd`.
UNCOV
3283
        onionCfg := tor.AddOnionConfig{
×
UNCOV
3284
                VirtualPort: defaultPeerPort,
×
3285
                TargetPorts: listenPorts,
×
3286
                Store: tor.NewOnionFile(
×
3287
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3288
                        encrypter,
×
3289
                ),
×
3290
        }
×
3291

×
3292
        switch {
×
3293
        case s.cfg.Tor.V2:
×
3294
                onionCfg.Type = tor.V2
×
3295
        case s.cfg.Tor.V3:
×
3296
                onionCfg.Type = tor.V3
×
3297
        }
3298

UNCOV
3299
        addr, err := s.torController.AddOnion(onionCfg)
×
UNCOV
3300
        if err != nil {
×
3301
                return err
×
3302
        }
×
3303

3304
        // Now that the onion service has been created, we'll add the onion
3305
        // address it can be reached at to our list of advertised addresses.
UNCOV
3306
        newNodeAnn, err := s.genNodeAnnouncement(
×
UNCOV
3307
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3308
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3309
                },
×
3310
        )
3311
        if err != nil {
×
UNCOV
3312
                return fmt.Errorf("unable to generate new node "+
×
3313
                        "announcement: %v", err)
×
3314
        }
×
3315

3316
        // Finally, we'll update the on-disk version of our announcement so it
3317
        // will eventually propagate to nodes in the network.
UNCOV
3318
        selfNode := &models.LightningNode{
×
UNCOV
3319
                HaveNodeAnnouncement: true,
×
3320
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3321
                Addresses:            newNodeAnn.Addresses,
×
3322
                Alias:                newNodeAnn.Alias.String(),
×
3323
                Features: lnwire.NewFeatureVector(
×
3324
                        newNodeAnn.Features, lnwire.Features,
×
3325
                ),
×
3326
                Color:        newNodeAnn.RGBColor,
×
3327
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3328
        }
×
3329
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3330
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3331
                return fmt.Errorf("can't set self node: %w", err)
×
3332
        }
×
3333

3334
        return nil
×
3335
}
3336

3337
// findChannel finds a channel given a public key and ChannelID. It is an
3338
// optimization that is quicker than seeking for a channel given only the
3339
// ChannelID.
3340
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3341
        *channeldb.OpenChannel, error) {
3✔
3342

3✔
3343
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3344
        if err != nil {
3✔
UNCOV
3345
                return nil, err
×
UNCOV
3346
        }
×
3347

3348
        for _, channel := range nodeChans {
6✔
3349
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3350
                        return channel, nil
3✔
3351
                }
3✔
3352
        }
3353

3354
        return nil, fmt.Errorf("unable to find channel")
3✔
3355
}
3356

3357
// getNodeAnnouncement fetches the current, fully signed node announcement.
3358
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3359
        s.mu.Lock()
3✔
3360
        defer s.mu.Unlock()
3✔
3361

3✔
3362
        return *s.currentNodeAnn
3✔
3363
}
3✔
3364

3365
// genNodeAnnouncement generates and returns the current fully signed node
3366
// announcement. The time stamp of the announcement will be updated in order
3367
// to ensure it propagates through the network.
3368
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3369
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3370

3✔
3371
        s.mu.Lock()
3✔
3372
        defer s.mu.Unlock()
3✔
3373

3✔
3374
        // Create a shallow copy of the current node announcement to work on.
3✔
3375
        // This ensures the original announcement remains unchanged
3✔
3376
        // until the new announcement is fully signed and valid.
3✔
3377
        newNodeAnn := *s.currentNodeAnn
3✔
3378

3✔
3379
        // First, try to update our feature manager with the updated set of
3✔
3380
        // features.
3✔
3381
        if features != nil {
6✔
3382
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3383
                        feature.SetNodeAnn: features,
3✔
3384
                }
3✔
3385
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3386
                if err != nil {
6✔
3387
                        return lnwire.NodeAnnouncement{}, err
3✔
3388
                }
3✔
3389

3390
                // If we could successfully update our feature manager, add
3391
                // an update modifier to include these new features to our
3392
                // set.
3393
                modifiers = append(
3✔
3394
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3395
                )
3✔
3396
        }
3397

3398
        // Always update the timestamp when refreshing to ensure the update
3399
        // propagates.
3400
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3401

3✔
3402
        // Apply the requested changes to the node announcement.
3✔
3403
        for _, modifier := range modifiers {
6✔
3404
                modifier(&newNodeAnn)
3✔
3405
        }
3✔
3406

3407
        // Sign a new update after applying all of the passed modifiers.
3408
        err := netann.SignNodeAnnouncement(
3✔
3409
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3410
        )
3✔
3411
        if err != nil {
3✔
UNCOV
3412
                return lnwire.NodeAnnouncement{}, err
×
UNCOV
3413
        }
×
3414

3415
        // If signing succeeds, update the current announcement.
3416
        *s.currentNodeAnn = newNodeAnn
3✔
3417

3✔
3418
        return *s.currentNodeAnn, nil
3✔
3419
}
3420

3421
// updateAndBroadcastSelfNode generates a new node announcement
3422
// applying the giving modifiers and updating the time stamp
3423
// to ensure it propagates through the network. Then it broadcasts
3424
// it to the network.
3425
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3426
        features *lnwire.RawFeatureVector,
3427
        modifiers ...netann.NodeAnnModifier) error {
3✔
3428

3✔
3429
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3430
        if err != nil {
6✔
3431
                return fmt.Errorf("unable to generate new node "+
3✔
3432
                        "announcement: %v", err)
3✔
3433
        }
3✔
3434

3435
        // Update the on-disk version of our announcement.
3436
        // Load and modify self node istead of creating anew instance so we
3437
        // don't risk overwriting any existing values.
3438
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3439
        if err != nil {
3✔
UNCOV
3440
                return fmt.Errorf("unable to get current source node: %w", err)
×
UNCOV
3441
        }
×
3442

3443
        selfNode.HaveNodeAnnouncement = true
3✔
3444
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3445
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3446
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3447
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3448
        selfNode.Color = newNodeAnn.RGBColor
3✔
3449
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3450

3✔
3451
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
3452

3✔
3453
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
UNCOV
3454
                return fmt.Errorf("can't set self node: %w", err)
×
UNCOV
3455
        }
×
3456

3457
        // Finally, propagate it to the nodes in the network.
3458
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3459
        if err != nil {
3✔
UNCOV
3460
                rpcsLog.Debugf("Unable to broadcast new node "+
×
UNCOV
3461
                        "announcement to peers: %v", err)
×
3462
                return err
×
3463
        }
×
3464

3465
        return nil
3✔
3466
}
3467

3468
type nodeAddresses struct {
3469
        pubKey    *btcec.PublicKey
3470
        addresses []net.Addr
3471
}
3472

3473
// establishPersistentConnections attempts to establish persistent connections
3474
// to all our direct channel collaborators. In order to promote liveness of our
3475
// active channels, we instruct the connection manager to attempt to establish
3476
// and maintain persistent connections to all our direct channel counterparties.
3477
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3478
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3479
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3480
        // since other PubKey forms can't be compared.
3✔
3481
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3482

3✔
3483
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3484
        // attempt to connect to based on our set of previous connections. Set
3✔
3485
        // the reconnection port to the default peer port.
3✔
3486
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3487
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
UNCOV
3488
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
UNCOV
3489
        }
×
3490

3491
        for _, node := range linkNodes {
6✔
3492
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3493
                nodeAddrs := &nodeAddresses{
3✔
3494
                        pubKey:    node.IdentityPub,
3✔
3495
                        addresses: node.Addresses,
3✔
3496
                }
3✔
3497
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3498
        }
3✔
3499

3500
        // After checking our previous connections for addresses to connect to,
3501
        // iterate through the nodes in our channel graph to find addresses
3502
        // that have been added via NodeAnnouncement messages.
3503
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3504
        // each of the nodes.
3505
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3506
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3507
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3508

3✔
3509
                // If the remote party has announced the channel to us, but we
3✔
3510
                // haven't yet, then we won't have a policy. However, we don't
3✔
3511
                // need this to connect to the peer, so we'll log it and move on.
3✔
3512
                if !havePolicy {
3✔
UNCOV
3513
                        srvrLog.Warnf("No channel policy found for "+
×
UNCOV
3514
                                "ChannelPoint(%v): ", chanPoint)
×
3515
                }
×
3516

3517
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3518

3✔
3519
                // Add all unique addresses from channel
3✔
3520
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3521
                // connect to for this peer.
3✔
3522
                addrSet := make(map[string]net.Addr)
3✔
3523
                for _, addr := range channelPeer.Addresses {
6✔
3524
                        switch addr.(type) {
3✔
3525
                        case *net.TCPAddr:
3✔
3526
                                addrSet[addr.String()] = addr
3✔
3527

3528
                        // We'll only attempt to connect to Tor addresses if Tor
3529
                        // outbound support is enabled.
UNCOV
3530
                        case *tor.OnionAddr:
×
UNCOV
3531
                                if s.cfg.Tor.Active {
×
3532
                                        addrSet[addr.String()] = addr
×
3533
                                }
×
3534
                        }
3535
                }
3536

3537
                // If this peer is also recorded as a link node, we'll add any
3538
                // additional addresses that have not already been selected.
3539
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3540
                if ok {
6✔
3541
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3542
                                switch lnAddress.(type) {
3✔
3543
                                case *net.TCPAddr:
3✔
3544
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3545

3546
                                // We'll only attempt to connect to Tor
3547
                                // addresses if Tor outbound support is enabled.
UNCOV
3548
                                case *tor.OnionAddr:
×
UNCOV
3549
                                        if s.cfg.Tor.Active {
×
3550
                                                //nolint:ll
×
3551
                                                addrSet[lnAddress.String()] = lnAddress
×
3552
                                        }
×
3553
                                }
3554
                        }
3555
                }
3556

3557
                // Construct a slice of the deduped addresses.
3558
                var addrs []net.Addr
3✔
3559
                for _, addr := range addrSet {
6✔
3560
                        addrs = append(addrs, addr)
3✔
3561
                }
3✔
3562

3563
                n := &nodeAddresses{
3✔
3564
                        addresses: addrs,
3✔
3565
                }
3✔
3566
                n.pubKey, err = channelPeer.PubKey()
3✔
3567
                if err != nil {
3✔
UNCOV
3568
                        return err
×
UNCOV
3569
                }
×
3570

3571
                graphAddrs[pubStr] = n
3✔
3572
                return nil
3✔
3573
        }
3574
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3575
                ctx, forEachSrcNodeChan, func() {
6✔
3576
                        clear(graphAddrs)
3✔
3577
                },
3✔
3578
        )
3579
        if err != nil {
3✔
UNCOV
3580
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
UNCOV
3581
                        "%v", err)
×
3582

×
3583
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3584
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3585

×
3586
                        return err
×
3587
                }
×
3588
        }
3589

3590
        // Combine the addresses from the link nodes and the channel graph.
3591
        for pubStr, nodeAddr := range graphAddrs {
6✔
3592
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3593
        }
3✔
3594

3595
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3596
                len(nodeAddrsMap))
3✔
3597

3✔
3598
        // Acquire and hold server lock until all persistent connection requests
3✔
3599
        // have been recorded and sent to the connection manager.
3✔
3600
        s.mu.Lock()
3✔
3601
        defer s.mu.Unlock()
3✔
3602

3✔
3603
        // Iterate through the combined list of addresses from prior links and
3✔
3604
        // node announcements and attempt to reconnect to each node.
3✔
3605
        var numOutboundConns int
3✔
3606
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3607
                // Add this peer to the set of peers we should maintain a
3✔
3608
                // persistent connection with. We set the value to false to
3✔
3609
                // indicate that we should not continue to reconnect if the
3✔
3610
                // number of channels returns to zero, since this peer has not
3✔
3611
                // been requested as perm by the user.
3✔
3612
                s.persistentPeers[pubStr] = false
3✔
3613
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3614
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3615
                }
3✔
3616

3617
                for _, address := range nodeAddr.addresses {
6✔
3618
                        // Create a wrapper address which couples the IP and
3✔
3619
                        // the pubkey so the brontide authenticated connection
3✔
3620
                        // can be established.
3✔
3621
                        lnAddr := &lnwire.NetAddress{
3✔
3622
                                IdentityKey: nodeAddr.pubKey,
3✔
3623
                                Address:     address,
3✔
3624
                        }
3✔
3625

3✔
3626
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3627
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3628
                }
3✔
3629

3630
                // We'll connect to the first 10 peers immediately, then
3631
                // randomly stagger any remaining connections if the
3632
                // stagger initial reconnect flag is set. This ensures
3633
                // that mobile nodes or nodes with a small number of
3634
                // channels obtain connectivity quickly, but larger
3635
                // nodes are able to disperse the costs of connecting to
3636
                // all peers at once.
3637
                if numOutboundConns < numInstantInitReconnect ||
3✔
3638
                        !s.cfg.StaggerInitialReconnect {
6✔
3639

3✔
3640
                        go s.connectToPersistentPeer(pubStr)
3✔
3641
                } else {
3✔
UNCOV
3642
                        go s.delayInitialReconnect(pubStr)
×
UNCOV
3643
                }
×
3644

3645
                numOutboundConns++
3✔
3646
        }
3647

3648
        return nil
3✔
3649
}
3650

3651
// delayInitialReconnect will attempt a reconnection to the given peer after
3652
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3653
//
3654
// NOTE: This method MUST be run as a goroutine.
UNCOV
3655
func (s *server) delayInitialReconnect(pubStr string) {
×
UNCOV
3656
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3657
        select {
×
3658
        case <-time.After(delay):
×
3659
                s.connectToPersistentPeer(pubStr)
×
3660
        case <-s.quit:
×
3661
        }
3662
}
3663

3664
// prunePersistentPeerConnection removes all internal state related to
3665
// persistent connections to a peer within the server. This is used to avoid
3666
// persistent connection retries to peers we do not have any open channels with.
3667
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
3✔
3668
        pubKeyStr := string(compressedPubKey[:])
3✔
3669

3✔
3670
        s.mu.Lock()
3✔
3671
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3672
                delete(s.persistentPeers, pubKeyStr)
3✔
3673
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3674
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3675
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3676
                s.mu.Unlock()
3✔
3677

3✔
3678
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3679
                        "peer has no open channels", compressedPubKey)
3✔
3680

3✔
3681
                return
3✔
3682
        }
3✔
3683
        s.mu.Unlock()
3✔
3684
}
3685

3686
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3687
// is instead used to remove persistent peer state for a peer that has been
3688
// disconnected for good cause by the server. Currently, a gossip ban from
3689
// sending garbage and the server running out of restricted-access
3690
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3691
// future, this function may expand when more ban criteria is added.
3692
//
3693
// NOTE: The server's write lock MUST be held when this is called.
UNCOV
3694
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
UNCOV
3695
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3696
                delete(s.persistentPeers, remotePub)
×
3697
                delete(s.persistentPeersBackoff, remotePub)
×
3698
                delete(s.persistentPeerAddrs, remotePub)
×
3699
                s.cancelConnReqs(remotePub, nil)
×
3700
        }
×
3701
}
3702

3703
// BroadcastMessage sends a request to the server to broadcast a set of
3704
// messages to all peers other than the one specified by the `skips` parameter.
3705
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3706
// the target peers.
3707
//
3708
// NOTE: This function is safe for concurrent access.
3709
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3710
        msgs ...lnwire.Message) error {
3✔
3711

3✔
3712
        // Filter out peers found in the skips map. We synchronize access to
3✔
3713
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3714
        // exact set of peers present at the time of invocation.
3✔
3715
        s.mu.RLock()
3✔
3716
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3717
        for pubStr, sPeer := range s.peersByPub {
6✔
3718
                if skips != nil {
6✔
3719
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3720
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3721
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3722
                                continue
3✔
3723
                        }
3724
                }
3725

3726
                peers = append(peers, sPeer)
3✔
3727
        }
3728
        s.mu.RUnlock()
3✔
3729

3✔
3730
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3731
        // all messages to each of peers.
3✔
3732
        var wg sync.WaitGroup
3✔
3733
        for _, sPeer := range peers {
6✔
3734
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3735
                        sPeer.PubKey())
3✔
3736

3✔
3737
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3738
                wg.Add(1)
3✔
3739
                s.wg.Add(1)
3✔
3740
                go func(p lnpeer.Peer) {
6✔
3741
                        defer s.wg.Done()
3✔
3742
                        defer wg.Done()
3✔
3743

3✔
3744
                        p.SendMessageLazy(false, msgs...)
3✔
3745
                }(sPeer)
3✔
3746
        }
3747

3748
        // Wait for all messages to have been dispatched before returning to
3749
        // caller.
3750
        wg.Wait()
3✔
3751

3✔
3752
        return nil
3✔
3753
}
3754

3755
// NotifyWhenOnline can be called by other subsystems to get notified when a
3756
// particular peer comes online. The peer itself is sent across the peerChan.
3757
//
3758
// NOTE: This function is safe for concurrent access.
3759
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3760
        peerChan chan<- lnpeer.Peer) {
3✔
3761

3✔
3762
        s.mu.Lock()
3✔
3763

3✔
3764
        // Compute the target peer's identifier.
3✔
3765
        pubStr := string(peerKey[:])
3✔
3766

3✔
3767
        // Check if peer is connected.
3✔
3768
        peer, ok := s.peersByPub[pubStr]
3✔
3769
        if ok {
6✔
3770
                // Unlock here so that the mutex isn't held while we are
3✔
3771
                // waiting for the peer to become active.
3✔
3772
                s.mu.Unlock()
3✔
3773

3✔
3774
                // Wait until the peer signals that it is actually active
3✔
3775
                // rather than only in the server's maps.
3✔
3776
                select {
3✔
3777
                case <-peer.ActiveSignal():
3✔
UNCOV
3778
                case <-peer.QuitSignal():
×
UNCOV
3779
                        // The peer quit, so we'll add the channel to the slice
×
3780
                        // and return.
×
3781
                        s.mu.Lock()
×
3782
                        s.peerConnectedListeners[pubStr] = append(
×
3783
                                s.peerConnectedListeners[pubStr], peerChan,
×
3784
                        )
×
3785
                        s.mu.Unlock()
×
3786
                        return
×
3787
                }
3788

3789
                // Connected, can return early.
3790
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3791

3✔
3792
                select {
3✔
3793
                case peerChan <- peer:
3✔
UNCOV
3794
                case <-s.quit:
×
3795
                }
3796

3797
                return
3✔
3798
        }
3799

3800
        // Not connected, store this listener such that it can be notified when
3801
        // the peer comes online.
3802
        s.peerConnectedListeners[pubStr] = append(
3✔
3803
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3804
        )
3✔
3805
        s.mu.Unlock()
3✔
3806
}
3807

3808
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3809
// the given public key has been disconnected. The notification is signaled by
3810
// closing the channel returned.
3811
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3812
        s.mu.Lock()
3✔
3813
        defer s.mu.Unlock()
3✔
3814

3✔
3815
        c := make(chan struct{})
3✔
3816

3✔
3817
        // If the peer is already offline, we can immediately trigger the
3✔
3818
        // notification.
3✔
3819
        peerPubKeyStr := string(peerPubKey[:])
3✔
3820
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
UNCOV
3821
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
UNCOV
3822
                close(c)
×
3823
                return c
×
3824
        }
×
3825

3826
        // Otherwise, the peer is online, so we'll keep track of the channel to
3827
        // trigger the notification once the server detects the peer
3828
        // disconnects.
3829
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3830
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3831
        )
3✔
3832

3✔
3833
        return c
3✔
3834
}
3835

3836
// FindPeer will return the peer that corresponds to the passed in public key.
3837
// This function is used by the funding manager, allowing it to update the
3838
// daemon's local representation of the remote peer.
3839
//
3840
// NOTE: This function is safe for concurrent access.
3841
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3842
        s.mu.RLock()
3✔
3843
        defer s.mu.RUnlock()
3✔
3844

3✔
3845
        pubStr := string(peerKey.SerializeCompressed())
3✔
3846

3✔
3847
        return s.findPeerByPubStr(pubStr)
3✔
3848
}
3✔
3849

3850
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3851
// which should be a string representation of the peer's serialized, compressed
3852
// public key.
3853
//
3854
// NOTE: This function is safe for concurrent access.
3855
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3856
        s.mu.RLock()
3✔
3857
        defer s.mu.RUnlock()
3✔
3858

3✔
3859
        return s.findPeerByPubStr(pubStr)
3✔
3860
}
3✔
3861

3862
// findPeerByPubStr is an internal method that retrieves the specified peer from
3863
// the server's internal state using.
3864
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3865
        peer, ok := s.peersByPub[pubStr]
3✔
3866
        if !ok {
6✔
3867
                return nil, ErrPeerNotConnected
3✔
3868
        }
3✔
3869

3870
        return peer, nil
3✔
3871
}
3872

3873
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3874
// exponential backoff. If no previous backoff was known, the default is
3875
// returned.
3876
func (s *server) nextPeerBackoff(pubStr string,
3877
        startTime time.Time) time.Duration {
3✔
3878

3✔
3879
        // Now, determine the appropriate backoff to use for the retry.
3✔
3880
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3881
        if !ok {
6✔
3882
                // If an existing backoff was unknown, use the default.
3✔
3883
                return s.cfg.MinBackoff
3✔
3884
        }
3✔
3885

3886
        // If the peer failed to start properly, we'll just use the previous
3887
        // backoff to compute the subsequent randomized exponential backoff
3888
        // duration. This will roughly double on average.
3889
        if startTime.IsZero() {
3✔
UNCOV
3890
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3891
        }
×
3892

3893
        // The peer succeeded in starting. If the connection didn't last long
3894
        // enough to be considered stable, we'll continue to back off retries
3895
        // with this peer.
3896
        connDuration := time.Since(startTime)
3✔
3897
        if connDuration < defaultStableConnDuration {
6✔
3898
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3899
        }
3✔
3900

3901
        // The peer succeed in starting and this was stable peer, so we'll
3902
        // reduce the timeout duration by the length of the connection after
3903
        // applying randomized exponential backoff. We'll only apply this in the
3904
        // case that:
3905
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
UNCOV
3906
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
UNCOV
3907
        if relaxedBackoff > s.cfg.MinBackoff {
×
3908
                return relaxedBackoff
×
3909
        }
×
3910

3911
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3912
        // the stable connection lasted much longer than our previous backoff.
3913
        // To reward such good behavior, we'll reconnect after the default
3914
        // timeout.
UNCOV
3915
        return s.cfg.MinBackoff
×
3916
}
3917

3918
// shouldDropLocalConnection determines if our local connection to a remote peer
3919
// should be dropped in the case of concurrent connection establishment. In
3920
// order to deterministically decide which connection should be dropped, we'll
3921
// utilize the ordering of the local and remote public key. If we didn't use
3922
// such a tie breaker, then we risk _both_ connections erroneously being
3923
// dropped.
UNCOV
3924
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
UNCOV
3925
        localPubBytes := local.SerializeCompressed()
×
3926
        remotePubPbytes := remote.SerializeCompressed()
×
3927

×
3928
        // The connection that comes from the node with a "smaller" pubkey
×
3929
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3930
        // should drop our established connection.
×
3931
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3932
}
×
3933

3934
// InboundPeerConnected initializes a new peer in response to a new inbound
3935
// connection.
3936
//
3937
// NOTE: This function is safe for concurrent access.
3938
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3939
        // Exit early if we have already been instructed to shutdown, this
3✔
3940
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3941
        if s.Stopped() {
3✔
UNCOV
3942
                return
×
UNCOV
3943
        }
×
3944

3945
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3946
        pubSer := nodePub.SerializeCompressed()
3✔
3947
        pubStr := string(pubSer)
3✔
3948

3✔
3949
        var pubBytes [33]byte
3✔
3950
        copy(pubBytes[:], pubSer)
3✔
3951

3✔
3952
        s.mu.Lock()
3✔
3953
        defer s.mu.Unlock()
3✔
3954

3✔
3955
        // If we already have an outbound connection to this peer, then ignore
3✔
3956
        // this new connection.
3✔
3957
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3958
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3959
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3960
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3961

3✔
3962
                conn.Close()
3✔
3963
                return
3✔
3964
        }
3✔
3965

3966
        // If we already have a valid connection that is scheduled to take
3967
        // precedence once the prior peer has finished disconnecting, we'll
3968
        // ignore this connection.
3969
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
UNCOV
3970
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
UNCOV
3971
                        "scheduled", conn.RemoteAddr(), p)
×
3972
                conn.Close()
×
3973
                return
×
3974
        }
×
3975

3976
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
3✔
3977

3✔
3978
        // Check to see if we already have a connection with this peer. If so,
3✔
3979
        // we may need to drop our existing connection. This prevents us from
3✔
3980
        // having duplicate connections to the same peer. We forgo adding a
3✔
3981
        // default case as we expect these to be the only error values returned
3✔
3982
        // from findPeerByPubStr.
3✔
3983
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3984
        switch err {
3✔
3985
        case ErrPeerNotConnected:
3✔
3986
                // We were unable to locate an existing connection with the
3✔
3987
                // target peer, proceed to connect.
3✔
3988
                s.cancelConnReqs(pubStr, nil)
3✔
3989
                s.peerConnected(conn, nil, true)
3✔
3990

3991
        case nil:
3✔
3992
                ctx := btclog.WithCtx(
3✔
3993
                        context.TODO(),
3✔
3994
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
3995
                )
3✔
3996

3✔
3997
                // We already have a connection with the incoming peer. If the
3✔
3998
                // connection we've already established should be kept and is
3✔
3999
                // not of the same type of the new connection (inbound), then
3✔
4000
                // we'll close out the new connection s.t there's only a single
3✔
4001
                // connection between us.
3✔
4002
                localPub := s.identityECDH.PubKey()
3✔
4003
                if !connectedPeer.Inbound() &&
3✔
4004
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
UNCOV
4005

×
UNCOV
4006
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4007
                                "peer, but already have outbound "+
×
4008
                                "connection, dropping conn",
×
4009
                                fmt.Errorf("already have outbound conn"))
×
4010
                        conn.Close()
×
4011
                        return
×
4012
                }
×
4013

4014
                // Otherwise, if we should drop the connection, then we'll
4015
                // disconnect our already connected peer.
4016
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4017

3✔
4018
                s.cancelConnReqs(pubStr, nil)
3✔
4019

3✔
4020
                // Remove the current peer from the server's internal state and
3✔
4021
                // signal that the peer termination watcher does not need to
3✔
4022
                // execute for this peer.
3✔
4023
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4024
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4025
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4026
                        s.peerConnected(conn, nil, true)
3✔
4027
                }
3✔
4028
        }
4029
}
4030

4031
// OutboundPeerConnected initializes a new peer in response to a new outbound
4032
// connection.
4033
// NOTE: This function is safe for concurrent access.
4034
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4035
        // Exit early if we have already been instructed to shutdown, this
3✔
4036
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4037
        if s.Stopped() {
3✔
UNCOV
4038
                return
×
UNCOV
4039
        }
×
4040

4041
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4042
        pubSer := nodePub.SerializeCompressed()
3✔
4043
        pubStr := string(pubSer)
3✔
4044

3✔
4045
        var pubBytes [33]byte
3✔
4046
        copy(pubBytes[:], pubSer)
3✔
4047

3✔
4048
        s.mu.Lock()
3✔
4049
        defer s.mu.Unlock()
3✔
4050

3✔
4051
        // If we already have an inbound connection to this peer, then ignore
3✔
4052
        // this new connection.
3✔
4053
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4054
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4055
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4056
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4057

3✔
4058
                if connReq != nil {
6✔
4059
                        s.connMgr.Remove(connReq.ID())
3✔
4060
                }
3✔
4061
                conn.Close()
3✔
4062
                return
3✔
4063
        }
4064
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
UNCOV
4065
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
UNCOV
4066
                s.connMgr.Remove(connReq.ID())
×
4067
                conn.Close()
×
4068
                return
×
4069
        }
×
4070

4071
        // If we already have a valid connection that is scheduled to take
4072
        // precedence once the prior peer has finished disconnecting, we'll
4073
        // ignore this connection.
4074
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
UNCOV
4075
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
UNCOV
4076

×
4077
                if connReq != nil {
×
4078
                        s.connMgr.Remove(connReq.ID())
×
4079
                }
×
4080

4081
                conn.Close()
×
UNCOV
4082
                return
×
4083
        }
4084

4085
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4086
                conn.RemoteAddr())
3✔
4087

3✔
4088
        if connReq != nil {
6✔
4089
                // A successful connection was returned by the connmgr.
3✔
4090
                // Immediately cancel all pending requests, excluding the
3✔
4091
                // outbound connection we just established.
3✔
4092
                ignore := connReq.ID()
3✔
4093
                s.cancelConnReqs(pubStr, &ignore)
3✔
4094
        } else {
6✔
4095
                // This was a successful connection made by some other
3✔
4096
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4097
                s.cancelConnReqs(pubStr, nil)
3✔
4098
        }
3✔
4099

4100
        // If we already have a connection with this peer, decide whether or not
4101
        // we need to drop the stale connection. We forgo adding a default case
4102
        // as we expect these to be the only error values returned from
4103
        // findPeerByPubStr.
4104
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4105
        switch err {
3✔
4106
        case ErrPeerNotConnected:
3✔
4107
                // We were unable to locate an existing connection with the
3✔
4108
                // target peer, proceed to connect.
3✔
4109
                s.peerConnected(conn, connReq, false)
3✔
4110

4111
        case nil:
3✔
4112
                ctx := btclog.WithCtx(
3✔
4113
                        context.TODO(),
3✔
4114
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4115
                )
3✔
4116

3✔
4117
                // We already have a connection with the incoming peer. If the
3✔
4118
                // connection we've already established should be kept and is
3✔
4119
                // not of the same type of the new connection (outbound), then
3✔
4120
                // we'll close out the new connection s.t there's only a single
3✔
4121
                // connection between us.
3✔
4122
                localPub := s.identityECDH.PubKey()
3✔
4123
                if connectedPeer.Inbound() &&
3✔
4124
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
UNCOV
4125

×
UNCOV
4126
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4127
                                "to peer, but already have inbound "+
×
4128
                                "connection, dropping conn",
×
4129
                                fmt.Errorf("already have inbound conn"))
×
4130
                        if connReq != nil {
×
4131
                                s.connMgr.Remove(connReq.ID())
×
4132
                        }
×
4133
                        conn.Close()
×
4134
                        return
×
4135
                }
4136

4137
                // Otherwise, _their_ connection should be dropped. So we'll
4138
                // disconnect the peer and send the now obsolete peer to the
4139
                // server for garbage collection.
4140
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4141

3✔
4142
                // Remove the current peer from the server's internal state and
3✔
4143
                // signal that the peer termination watcher does not need to
3✔
4144
                // execute for this peer.
3✔
4145
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4146
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4147
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4148
                        s.peerConnected(conn, connReq, false)
3✔
4149
                }
3✔
4150
        }
4151
}
4152

4153
// UnassignedConnID is the default connection ID that a request can have before
4154
// it actually is submitted to the connmgr.
4155
// TODO(conner): move into connmgr package, or better, add connmgr method for
4156
// generating atomic IDs
4157
const UnassignedConnID uint64 = 0
4158

4159
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4160
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4161
// Afterwards, each connection request removed from the connmgr. The caller can
4162
// optionally specify a connection ID to ignore, which prevents us from
4163
// canceling a successful request. All persistent connreqs for the provided
4164
// pubkey are discarded after the operationjw.
4165
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4166
        // First, cancel any lingering persistent retry attempts, which will
3✔
4167
        // prevent retries for any with backoffs that are still maturing.
3✔
4168
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4169
                close(cancelChan)
3✔
4170
                delete(s.persistentRetryCancels, pubStr)
3✔
4171
        }
3✔
4172

4173
        // Next, check to see if we have any outstanding persistent connection
4174
        // requests to this peer. If so, then we'll remove all of these
4175
        // connection requests, and also delete the entry from the map.
4176
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4177
        if !ok {
6✔
4178
                return
3✔
4179
        }
3✔
4180

4181
        for _, connReq := range connReqs {
6✔
4182
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4183

3✔
4184
                // Atomically capture the current request identifier.
3✔
4185
                connID := connReq.ID()
3✔
4186

3✔
4187
                // Skip any zero IDs, this indicates the request has not
3✔
4188
                // yet been schedule.
3✔
4189
                if connID == UnassignedConnID {
3✔
UNCOV
4190
                        continue
×
4191
                }
4192

4193
                // Skip a particular connection ID if instructed.
4194
                if skip != nil && connID == *skip {
6✔
4195
                        continue
3✔
4196
                }
4197

4198
                s.connMgr.Remove(connID)
3✔
4199
        }
4200

4201
        delete(s.persistentConnReqs, pubStr)
3✔
4202
}
4203

4204
// handleCustomMessage dispatches an incoming custom peers message to
4205
// subscribers.
4206
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4207
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4208
                peer, msg.Type)
3✔
4209

3✔
4210
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4211
                Peer: peer,
3✔
4212
                Msg:  msg,
3✔
4213
        })
3✔
4214
}
3✔
4215

4216
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4217
// messages.
4218
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4219
        return s.customMessageServer.Subscribe()
3✔
4220
}
3✔
4221

4222
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4223
// the channelNotifier's NotifyOpenChannelEvent.
4224
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4225
        remotePub *btcec.PublicKey) {
3✔
4226

3✔
4227
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4228
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4229
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
3✔
4230
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
3✔
4231
        }
3✔
4232

4233
        // Notify subscribers about this open channel event.
4234
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4235
}
4236

4237
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4238
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4239
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4240
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4241

3✔
4242
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4243
        // peer.
3✔
4244
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
UNCOV
4245
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4246
                        "channel[%v] pending open",
×
4247
                        remotePub.SerializeCompressed(), op)
×
4248
        }
×
4249

4250
        // Notify subscribers about this event.
4251
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4252
}
4253

4254
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4255
// calls the channelNotifier's NotifyFundingTimeout.
4256
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4257
        remotePub *btcec.PublicKey) {
3✔
4258

3✔
4259
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4260
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4261
        if err != nil {
3✔
UNCOV
4262
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4263
                        "channel[%v] pending close",
×
4264
                        remotePub.SerializeCompressed(), op)
×
4265
        }
×
4266

4267
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
UNCOV
4268
                // If we encounter an error while attempting to disconnect the
×
UNCOV
4269
                // peer, log the error.
×
4270
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4271
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4272
                }
×
4273
        }
4274

4275
        // Notify subscribers about this event.
4276
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4277
}
4278

4279
// peerConnected is a function that handles initialization a newly connected
4280
// peer by adding it to the server's global list of all active peers, and
4281
// starting all the goroutines the peer needs to function properly. The inbound
4282
// boolean should be true if the peer initiated the connection to us.
4283
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4284
        inbound bool) {
3✔
4285

3✔
4286
        brontideConn := conn.(*brontide.Conn)
3✔
4287
        addr := conn.RemoteAddr()
3✔
4288
        pubKey := brontideConn.RemotePub()
3✔
4289

3✔
4290
        // Only restrict access for inbound connections, which means if the
3✔
4291
        // remote node's public key is banned or the restricted slots are used
3✔
4292
        // up, we will drop the connection.
3✔
4293
        //
3✔
4294
        // TODO(yy): Consider perform this check in
3✔
4295
        // `peerAccessMan.addPeerAccess`.
3✔
4296
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4297
        if inbound && err != nil {
3✔
UNCOV
4298
                pubSer := pubKey.SerializeCompressed()
×
UNCOV
4299

×
4300
                // Clean up the persistent peer maps if we're dropping this
×
4301
                // connection.
×
4302
                s.bannedPersistentPeerConnection(string(pubSer))
×
4303

×
4304
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4305
                        "of restricted-access connection slots: %v.", pubSer,
×
4306
                        err)
×
4307

×
4308
                conn.Close()
×
4309

×
4310
                return
×
4311
        }
×
4312

4313
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4314
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4315

3✔
4316
        peerAddr := &lnwire.NetAddress{
3✔
4317
                IdentityKey: pubKey,
3✔
4318
                Address:     addr,
3✔
4319
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4320
        }
3✔
4321

3✔
4322
        // With the brontide connection established, we'll now craft the feature
3✔
4323
        // vectors to advertise to the remote node.
3✔
4324
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4325
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4326

3✔
4327
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4328
        // found, create a fresh buffer.
3✔
4329
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4330
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4331
        if !ok {
6✔
4332
                var err error
3✔
4333
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4334
                if err != nil {
3✔
UNCOV
4335
                        srvrLog.Errorf("unable to create peer %v", err)
×
UNCOV
4336
                        return
×
4337
                }
×
4338
        }
4339

4340
        // If we directly set the peer.Config TowerClient member to the
4341
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4342
        // the peer.Config's TowerClient member will not evaluate to nil even
4343
        // though the underlying value is nil. To avoid this gotcha which can
4344
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4345
        // TowerClient if needed.
4346
        var towerClient wtclient.ClientManager
3✔
4347
        if s.towerClientMgr != nil {
6✔
4348
                towerClient = s.towerClientMgr
3✔
4349
        }
3✔
4350

4351
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4352
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4353

3✔
4354
        // Now that we've established a connection, create a peer, and it to the
3✔
4355
        // set of currently active peers. Configure the peer with the incoming
3✔
4356
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4357
        // offered that would trigger channel closure. In case of outgoing
3✔
4358
        // htlcs, an extra block is added to prevent the channel from being
3✔
4359
        // closed when the htlc is outstanding and a new block comes in.
3✔
4360
        pCfg := peer.Config{
3✔
4361
                Conn:                    brontideConn,
3✔
4362
                ConnReq:                 connReq,
3✔
4363
                Addr:                    peerAddr,
3✔
4364
                Inbound:                 inbound,
3✔
4365
                Features:                initFeatures,
3✔
4366
                LegacyFeatures:          legacyFeatures,
3✔
4367
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4368
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4369
                ErrorBuffer:             errBuffer,
3✔
4370
                WritePool:               s.writePool,
3✔
4371
                ReadPool:                s.readPool,
3✔
4372
                Switch:                  s.htlcSwitch,
3✔
4373
                InterceptSwitch:         s.interceptableSwitch,
3✔
4374
                ChannelDB:               s.chanStateDB,
3✔
4375
                ChannelGraph:            s.graphDB,
3✔
4376
                ChainArb:                s.chainArb,
3✔
4377
                AuthGossiper:            s.authGossiper,
3✔
4378
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4379
                ChainIO:                 s.cc.ChainIO,
3✔
4380
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4381
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4382
                SigPool:                 s.sigPool,
3✔
4383
                Wallet:                  s.cc.Wallet,
3✔
4384
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4385
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4386
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4387
                Sphinx:                  s.sphinx,
3✔
4388
                WitnessBeacon:           s.witnessBeacon,
3✔
4389
                Invoices:                s.invoices,
3✔
4390
                ChannelNotifier:         s.channelNotifier,
3✔
4391
                HtlcNotifier:            s.htlcNotifier,
3✔
4392
                TowerClient:             towerClient,
3✔
4393
                DisconnectPeer:          s.DisconnectPeer,
3✔
4394
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4395
                        lnwire.NodeAnnouncement, error) {
6✔
4396

3✔
4397
                        return s.genNodeAnnouncement(nil)
3✔
4398
                },
3✔
4399

4400
                PongBuf: s.pongBuf,
4401

4402
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4403

4404
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4405

4406
                FundingManager: s.fundingMgr,
4407

4408
                Hodl:                    s.cfg.Hodl,
4409
                UnsafeReplay:            s.cfg.UnsafeReplay,
4410
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4411
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4412
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4413
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4414
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4415
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4416
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4417
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4418
                HandleCustomMessage:    s.handleCustomMessage,
4419
                GetAliases:             s.aliasMgr.GetAliases,
4420
                RequestAlias:           s.aliasMgr.RequestAlias,
4421
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4422
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4423
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4424
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4425
                MaxFeeExposure:         thresholdMSats,
4426
                Quit:                   s.quit,
4427
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4428
                AuxSigner:              s.implCfg.AuxSigner,
4429
                MsgRouter:              s.implCfg.MsgRouter,
4430
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4431
                AuxResolver:            s.implCfg.AuxContractResolver,
4432
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4433
                ShouldFwdExpEndorsement: func() bool {
3✔
4434
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4435
                                return false
3✔
4436
                        }
3✔
4437

4438
                        return clock.NewDefaultClock().Now().Before(
3✔
4439
                                EndorsementExperimentEnd,
3✔
4440
                        )
3✔
4441
                },
4442
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4443
        }
4444

4445
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4446
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4447

3✔
4448
        p := peer.NewBrontide(pCfg)
3✔
4449

3✔
4450
        // Update the access manager with the access permission for this peer.
3✔
4451
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4452

3✔
4453
        // TODO(roasbeef): update IP address for link-node
3✔
4454
        //  * also mark last-seen, do it one single transaction?
3✔
4455

3✔
4456
        s.addPeer(p)
3✔
4457

3✔
4458
        // Once we have successfully added the peer to the server, we can
3✔
4459
        // delete the previous error buffer from the server's map of error
3✔
4460
        // buffers.
3✔
4461
        delete(s.peerErrors, pkStr)
3✔
4462

3✔
4463
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4464
        // includes sending and receiving Init messages, which would be a DOS
3✔
4465
        // vector if we held the server's mutex throughout the procedure.
3✔
4466
        s.wg.Add(1)
3✔
4467
        go s.peerInitializer(p)
3✔
4468
}
4469

4470
// addPeer adds the passed peer to the server's global state of all active
4471
// peers.
4472
func (s *server) addPeer(p *peer.Brontide) {
3✔
4473
        if p == nil {
3✔
UNCOV
4474
                return
×
UNCOV
4475
        }
×
4476

4477
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4478

3✔
4479
        // Ignore new peers if we're shutting down.
3✔
4480
        if s.Stopped() {
3✔
UNCOV
4481
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
UNCOV
4482
                        pubBytes)
×
4483
                p.Disconnect(ErrServerShuttingDown)
×
4484

×
4485
                return
×
4486
        }
×
4487

4488
        // Track the new peer in our indexes so we can quickly look it up either
4489
        // according to its public key, or its peer ID.
4490
        // TODO(roasbeef): pipe all requests through to the
4491
        // queryHandler/peerManager
4492

4493
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4494
        // be human-readable.
4495
        pubStr := string(pubBytes)
3✔
4496

3✔
4497
        s.peersByPub[pubStr] = p
3✔
4498

3✔
4499
        if p.Inbound() {
6✔
4500
                s.inboundPeers[pubStr] = p
3✔
4501
        } else {
6✔
4502
                s.outboundPeers[pubStr] = p
3✔
4503
        }
3✔
4504

4505
        // Inform the peer notifier of a peer online event so that it can be reported
4506
        // to clients listening for peer events.
4507
        var pubKey [33]byte
3✔
4508
        copy(pubKey[:], pubBytes)
3✔
4509
}
4510

4511
// peerInitializer asynchronously starts a newly connected peer after it has
4512
// been added to the server's peer map. This method sets up a
4513
// peerTerminationWatcher for the given peer, and ensures that it executes even
4514
// if the peer failed to start. In the event of a successful connection, this
4515
// method reads the negotiated, local feature-bits and spawns the appropriate
4516
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4517
// be signaled of the new peer once the method returns.
4518
//
4519
// NOTE: This MUST be launched as a goroutine.
4520
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4521
        defer s.wg.Done()
3✔
4522

3✔
4523
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4524

3✔
4525
        // Avoid initializing peers while the server is exiting.
3✔
4526
        if s.Stopped() {
3✔
UNCOV
4527
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
UNCOV
4528
                        pubBytes)
×
4529
                return
×
4530
        }
×
4531

4532
        // Create a channel that will be used to signal a successful start of
4533
        // the link. This prevents the peer termination watcher from beginning
4534
        // its duty too early.
4535
        ready := make(chan struct{})
3✔
4536

3✔
4537
        // Before starting the peer, launch a goroutine to watch for the
3✔
4538
        // unexpected termination of this peer, which will ensure all resources
3✔
4539
        // are properly cleaned up, and re-establish persistent connections when
3✔
4540
        // necessary. The peer termination watcher will be short circuited if
3✔
4541
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4542
        // that the server has already handled the removal of this peer.
3✔
4543
        s.wg.Add(1)
3✔
4544
        go s.peerTerminationWatcher(p, ready)
3✔
4545

3✔
4546
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4547
        // will unblock the peerTerminationWatcher.
3✔
4548
        if err := p.Start(); err != nil {
6✔
4549
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4550

3✔
4551
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4552
                return
3✔
4553
        }
3✔
4554

4555
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4556
        // was successful, and to begin watching the peer's wait group.
4557
        close(ready)
3✔
4558

3✔
4559
        s.mu.Lock()
3✔
4560
        defer s.mu.Unlock()
3✔
4561

3✔
4562
        // Check if there are listeners waiting for this peer to come online.
3✔
4563
        srvrLog.Debugf("Notifying that peer %v is online", p)
3✔
4564

3✔
4565
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4566
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4567
        pubStr := string(pubBytes)
3✔
4568
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4569
                select {
3✔
4570
                case peerChan <- p:
3✔
UNCOV
4571
                case <-s.quit:
×
UNCOV
4572
                        return
×
4573
                }
4574
        }
4575
        delete(s.peerConnectedListeners, pubStr)
3✔
4576

3✔
4577
        // Since the peer has been fully initialized, now it's time to notify
3✔
4578
        // the RPC about the peer online event.
3✔
4579
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4580
}
4581

4582
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4583
// and then cleans up all resources allocated to the peer, notifies relevant
4584
// sub-systems of its demise, and finally handles re-connecting to the peer if
4585
// it's persistent. If the server intentionally disconnects a peer, it should
4586
// have a corresponding entry in the ignorePeerTermination map which will cause
4587
// the cleanup routine to exit early. The passed `ready` chan is used to
4588
// synchronize when WaitForDisconnect should begin watching on the peer's
4589
// waitgroup. The ready chan should only be signaled if the peer starts
4590
// successfully, otherwise the peer should be disconnected instead.
4591
//
4592
// NOTE: This MUST be launched as a goroutine.
4593
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4594
        defer s.wg.Done()
3✔
4595

3✔
4596
        ctx := btclog.WithCtx(
3✔
4597
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4598
        )
3✔
4599

3✔
4600
        p.WaitForDisconnect(ready)
3✔
4601

3✔
4602
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4603

3✔
4604
        // If the server is exiting then we can bail out early ourselves as all
3✔
4605
        // the other sub-systems will already be shutting down.
3✔
4606
        if s.Stopped() {
6✔
4607
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4608
                return
3✔
4609
        }
3✔
4610

4611
        // Next, we'll cancel all pending funding reservations with this node.
4612
        // If we tried to initiate any funding flows that haven't yet finished,
4613
        // then we need to unlock those committed outputs so they're still
4614
        // available for use.
4615
        s.fundingMgr.CancelPeerReservations(p.PubKey())
3✔
4616

3✔
4617
        pubKey := p.IdentityKey()
3✔
4618

3✔
4619
        // We'll also inform the gossiper that this peer is no longer active,
3✔
4620
        // so we don't need to maintain sync state for it any longer.
3✔
4621
        s.authGossiper.PruneSyncState(p.PubKey())
3✔
4622

3✔
4623
        // Tell the switch to remove all links associated with this peer.
3✔
4624
        // Passing nil as the target link indicates that all links associated
3✔
4625
        // with this interface should be closed.
3✔
4626
        //
3✔
4627
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4628
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4629
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
UNCOV
4630
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
UNCOV
4631
        }
×
4632

4633
        for _, link := range links {
6✔
4634
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4635
        }
3✔
4636

4637
        s.mu.Lock()
3✔
4638
        defer s.mu.Unlock()
3✔
4639

3✔
4640
        // If there were any notification requests for when this peer
3✔
4641
        // disconnected, we can trigger them now.
3✔
4642
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4643
        pubStr := string(pubKey.SerializeCompressed())
3✔
4644
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4645
                close(offlineChan)
3✔
4646
        }
3✔
4647
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4648

3✔
4649
        // If the server has already removed this peer, we can short circuit the
3✔
4650
        // peer termination watcher and skip cleanup.
3✔
4651
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4652
                delete(s.ignorePeerTermination, p)
3✔
4653

3✔
4654
                pubKey := p.PubKey()
3✔
4655
                pubStr := string(pubKey[:])
3✔
4656

3✔
4657
                // If a connection callback is present, we'll go ahead and
3✔
4658
                // execute it now that previous peer has fully disconnected. If
3✔
4659
                // the callback is not present, this likely implies the peer was
3✔
4660
                // purposefully disconnected via RPC, and that no reconnect
3✔
4661
                // should be attempted.
3✔
4662
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4663
                if ok {
6✔
4664
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4665
                        connCallback()
3✔
4666
                }
3✔
4667
                return
3✔
4668
        }
4669

4670
        // First, cleanup any remaining state the server has regarding the peer
4671
        // in question.
4672
        s.removePeerUnsafe(ctx, p)
3✔
4673

3✔
4674
        // Next, check to see if this is a persistent peer or not.
3✔
4675
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4676
                return
3✔
4677
        }
3✔
4678

4679
        // Get the last address that we used to connect to the peer.
4680
        addrs := []net.Addr{
3✔
4681
                p.NetAddress().Address,
3✔
4682
        }
3✔
4683

3✔
4684
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4685
        // reconnection purposes.
3✔
4686
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4687
        switch {
3✔
4688
        // We found advertised addresses, so use them.
4689
        case err == nil:
3✔
4690
                addrs = advertisedAddrs
3✔
4691

4692
        // The peer doesn't have an advertised address.
4693
        case err == errNoAdvertisedAddr:
3✔
4694
                // If it is an outbound peer then we fall back to the existing
3✔
4695
                // peer address.
3✔
4696
                if !p.Inbound() {
6✔
4697
                        break
3✔
4698
                }
4699

4700
                // Fall back to the existing peer address if
4701
                // we're not accepting connections over Tor.
4702
                if s.torController == nil {
6✔
4703
                        break
3✔
4704
                }
4705

4706
                // If we are, the peer's address won't be known
4707
                // to us (we'll see a private address, which is
4708
                // the address used by our onion service to dial
4709
                // to lnd), so we don't have enough information
4710
                // to attempt a reconnect.
UNCOV
4711
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
UNCOV
4712
                        "to inbound peer without advertised address")
×
4713
                return
×
4714

4715
        // We came across an error retrieving an advertised
4716
        // address, log it, and fall back to the existing peer
4717
        // address.
4718
        default:
3✔
4719
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4720
                        "address for peer", err)
3✔
4721
        }
4722

4723
        // Make an easy lookup map so that we can check if an address
4724
        // is already in the address list that we have stored for this peer.
4725
        existingAddrs := make(map[string]bool)
3✔
4726
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4727
                existingAddrs[addr.String()] = true
3✔
4728
        }
3✔
4729

4730
        // Add any missing addresses for this peer to persistentPeerAddr.
4731
        for _, addr := range addrs {
6✔
4732
                if existingAddrs[addr.String()] {
3✔
UNCOV
4733
                        continue
×
4734
                }
4735

4736
                s.persistentPeerAddrs[pubStr] = append(
3✔
4737
                        s.persistentPeerAddrs[pubStr],
3✔
4738
                        &lnwire.NetAddress{
3✔
4739
                                IdentityKey: p.IdentityKey(),
3✔
4740
                                Address:     addr,
3✔
4741
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4742
                        },
3✔
4743
                )
3✔
4744
        }
4745

4746
        // Record the computed backoff in the backoff map.
4747
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4748
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4749

3✔
4750
        // Initialize a retry canceller for this peer if one does not
3✔
4751
        // exist.
3✔
4752
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4753
        if !ok {
6✔
4754
                cancelChan = make(chan struct{})
3✔
4755
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4756
        }
3✔
4757

4758
        // We choose not to wait group this go routine since the Connect
4759
        // call can stall for arbitrarily long if we shutdown while an
4760
        // outbound connection attempt is being made.
4761
        go func() {
6✔
4762
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4763
                        "re-establishment to persistent peer",
3✔
4764
                        "reconnecting_in", backoff)
3✔
4765

3✔
4766
                select {
3✔
4767
                case <-time.After(backoff):
3✔
4768
                case <-cancelChan:
3✔
4769
                        return
3✔
4770
                case <-s.quit:
3✔
4771
                        return
3✔
4772
                }
4773

4774
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4775
                        "connection")
3✔
4776

3✔
4777
                s.connectToPersistentPeer(pubStr)
3✔
4778
        }()
4779
}
4780

4781
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4782
// to connect to the peer. It creates connection requests if there are
4783
// currently none for a given address and it removes old connection requests
4784
// if the associated address is no longer in the latest address list for the
4785
// peer.
4786
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4787
        s.mu.Lock()
3✔
4788
        defer s.mu.Unlock()
3✔
4789

3✔
4790
        // Create an easy lookup map of the addresses we have stored for the
3✔
4791
        // peer. We will remove entries from this map if we have existing
3✔
4792
        // connection requests for the associated address and then any leftover
3✔
4793
        // entries will indicate which addresses we should create new
3✔
4794
        // connection requests for.
3✔
4795
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4796
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4797
                addrMap[addr.String()] = addr
3✔
4798
        }
3✔
4799

4800
        // Go through each of the existing connection requests and
4801
        // check if they correspond to the latest set of addresses. If
4802
        // there is a connection requests that does not use one of the latest
4803
        // advertised addresses then remove that connection request.
4804
        var updatedConnReqs []*connmgr.ConnReq
3✔
4805
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4806
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4807

3✔
4808
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4809
                // If the existing connection request is using one of the
4810
                // latest advertised addresses for the peer then we add it to
4811
                // updatedConnReqs and remove the associated address from
4812
                // addrMap so that we don't recreate this connReq later on.
UNCOV
4813
                case true:
×
UNCOV
4814
                        updatedConnReqs = append(
×
4815
                                updatedConnReqs, connReq,
×
4816
                        )
×
4817
                        delete(addrMap, lnAddr)
×
4818

4819
                // If the existing connection request is using an address that
4820
                // is not one of the latest advertised addresses for the peer
4821
                // then we remove the connecting request from the connection
4822
                // manager.
4823
                case false:
3✔
4824
                        srvrLog.Info(
3✔
4825
                                "Removing conn req:", connReq.Addr.String(),
3✔
4826
                        )
3✔
4827
                        s.connMgr.Remove(connReq.ID())
3✔
4828
                }
4829
        }
4830

4831
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4832

3✔
4833
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4834
        if !ok {
6✔
4835
                cancelChan = make(chan struct{})
3✔
4836
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4837
        }
3✔
4838

4839
        // Any addresses left in addrMap are new ones that we have not made
4840
        // connection requests for. So create new connection requests for those.
4841
        // If there is more than one address in the address map, stagger the
4842
        // creation of the connection requests for those.
4843
        go func() {
6✔
4844
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4845
                defer ticker.Stop()
3✔
4846

3✔
4847
                for _, addr := range addrMap {
6✔
4848
                        // Send the persistent connection request to the
3✔
4849
                        // connection manager, saving the request itself so we
3✔
4850
                        // can cancel/restart the process as needed.
3✔
4851
                        connReq := &connmgr.ConnReq{
3✔
4852
                                Addr:      addr,
3✔
4853
                                Permanent: true,
3✔
4854
                        }
3✔
4855

3✔
4856
                        s.mu.Lock()
3✔
4857
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4858
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4859
                        )
3✔
4860
                        s.mu.Unlock()
3✔
4861

3✔
4862
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4863
                                "channel peer %v", addr)
3✔
4864

3✔
4865
                        go s.connMgr.Connect(connReq)
3✔
4866

3✔
4867
                        select {
3✔
4868
                        case <-s.quit:
3✔
4869
                                return
3✔
4870
                        case <-cancelChan:
3✔
4871
                                return
3✔
4872
                        case <-ticker.C:
3✔
4873
                        }
4874
                }
4875
        }()
4876
}
4877

4878
// removePeerUnsafe removes the passed peer from the server's state of all
4879
// active peers.
4880
//
4881
// NOTE: Server mutex must be held when calling this function.
4882
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4883
        if p == nil {
3✔
UNCOV
4884
                return
×
UNCOV
4885
        }
×
4886

4887
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4888

3✔
4889
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4890
        // will be disconnected in the server shutdown process.
3✔
4891
        if s.Stopped() {
3✔
UNCOV
4892
                return
×
UNCOV
4893
        }
×
4894

4895
        // Capture the peer's public key and string representation.
4896
        pKey := p.PubKey()
3✔
4897
        pubSer := pKey[:]
3✔
4898
        pubStr := string(pubSer)
3✔
4899

3✔
4900
        delete(s.peersByPub, pubStr)
3✔
4901

3✔
4902
        if p.Inbound() {
6✔
4903
                delete(s.inboundPeers, pubStr)
3✔
4904
        } else {
6✔
4905
                delete(s.outboundPeers, pubStr)
3✔
4906
        }
3✔
4907

4908
        // When removing the peer we make sure to disconnect it asynchronously
4909
        // to avoid blocking the main server goroutine because it is holding the
4910
        // server's mutex. Disconnecting the peer might block and wait until the
4911
        // peer has fully started up. This can happen if an inbound and outbound
4912
        // race condition occurs.
4913
        s.wg.Add(1)
3✔
4914
        go func() {
6✔
4915
                defer s.wg.Done()
3✔
4916

3✔
4917
                p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
3✔
4918

3✔
4919
                // If this peer had an active persistent connection request,
3✔
4920
                // remove it.
3✔
4921
                if p.ConnReq() != nil {
6✔
4922
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4923
                }
3✔
4924

4925
                // Remove the peer's access permission from the access manager.
4926
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4927
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4928

3✔
4929
                // Copy the peer's error buffer across to the server if it has
3✔
4930
                // any items in it so that we can restore peer errors across
3✔
4931
                // connections. We need to look up the error after the peer has
3✔
4932
                // been disconnected because we write the error in the
3✔
4933
                // `Disconnect` method.
3✔
4934
                s.mu.Lock()
3✔
4935
                if p.ErrorBuffer().Total() > 0 {
6✔
4936
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4937
                }
3✔
4938
                s.mu.Unlock()
3✔
4939

3✔
4940
                // Inform the peer notifier of a peer offline event so that it
3✔
4941
                // can be reported to clients listening for peer events.
3✔
4942
                var pubKey [33]byte
3✔
4943
                copy(pubKey[:], pubSer)
3✔
4944

3✔
4945
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4946
        }()
4947
}
4948

4949
// ConnectToPeer requests that the server connect to a Lightning Network peer
4950
// at the specified address. This function will *block* until either a
4951
// connection is established, or the initial handshake process fails.
4952
//
4953
// NOTE: This function is safe for concurrent access.
4954
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4955
        perm bool, timeout time.Duration) error {
3✔
4956

3✔
4957
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4958

3✔
4959
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4960
        // better granularity.  In certain conditions, this method requires
3✔
4961
        // making an outbound connection to a remote peer, which requires the
3✔
4962
        // lock to be released, and subsequently reacquired.
3✔
4963
        s.mu.Lock()
3✔
4964

3✔
4965
        // Ensure we're not already connected to this peer.
3✔
4966
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4967

3✔
4968
        // When there's no error it means we already have a connection with this
3✔
4969
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4970
        // set, we will ignore the existing connection and continue.
3✔
4971
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4972
                s.mu.Unlock()
3✔
4973
                return &errPeerAlreadyConnected{peer: peer}
3✔
4974
        }
3✔
4975

4976
        // Peer was not found, continue to pursue connection with peer.
4977

4978
        // If there's already a pending connection request for this pubkey,
4979
        // then we ignore this request to ensure we don't create a redundant
4980
        // connection.
4981
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4982
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4983
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4984
        }
3✔
4985

4986
        // If there's not already a pending or active connection to this node,
4987
        // then instruct the connection manager to attempt to establish a
4988
        // persistent connection to the peer.
4989
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4990
        if perm {
6✔
4991
                connReq := &connmgr.ConnReq{
3✔
4992
                        Addr:      addr,
3✔
4993
                        Permanent: true,
3✔
4994
                }
3✔
4995

3✔
4996
                // Since the user requested a permanent connection, we'll set
3✔
4997
                // the entry to true which will tell the server to continue
3✔
4998
                // reconnecting even if the number of channels with this peer is
3✔
4999
                // zero.
3✔
5000
                s.persistentPeers[targetPub] = true
3✔
5001
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5002
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5003
                }
3✔
5004
                s.persistentConnReqs[targetPub] = append(
3✔
5005
                        s.persistentConnReqs[targetPub], connReq,
3✔
5006
                )
3✔
5007
                s.mu.Unlock()
3✔
5008

3✔
5009
                go s.connMgr.Connect(connReq)
3✔
5010

3✔
5011
                return nil
3✔
5012
        }
5013
        s.mu.Unlock()
3✔
5014

3✔
5015
        // If we're not making a persistent connection, then we'll attempt to
3✔
5016
        // connect to the target peer. If the we can't make the connection, or
3✔
5017
        // the crypto negotiation breaks down, then return an error to the
3✔
5018
        // caller.
3✔
5019
        errChan := make(chan error, 1)
3✔
5020
        s.connectToPeer(addr, errChan, timeout)
3✔
5021

3✔
5022
        select {
3✔
5023
        case err := <-errChan:
3✔
5024
                return err
3✔
UNCOV
5025
        case <-s.quit:
×
UNCOV
5026
                return ErrServerShuttingDown
×
5027
        }
5028
}
5029

5030
// connectToPeer establishes a connection to a remote peer. errChan is used to
5031
// notify the caller if the connection attempt has failed. Otherwise, it will be
5032
// closed.
5033
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5034
        errChan chan<- error, timeout time.Duration) {
3✔
5035

3✔
5036
        conn, err := brontide.Dial(
3✔
5037
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5038
        )
3✔
5039
        if err != nil {
6✔
5040
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5041
                select {
3✔
5042
                case errChan <- err:
3✔
UNCOV
5043
                case <-s.quit:
×
5044
                }
5045
                return
3✔
5046
        }
5047

5048
        close(errChan)
3✔
5049

3✔
5050
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5051
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5052

3✔
5053
        s.OutboundPeerConnected(nil, conn)
3✔
5054
}
5055

5056
// DisconnectPeer sends the request to server to close the connection with peer
5057
// identified by public key.
5058
//
5059
// NOTE: This function is safe for concurrent access.
5060
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5061
        pubBytes := pubKey.SerializeCompressed()
3✔
5062
        pubStr := string(pubBytes)
3✔
5063

3✔
5064
        s.mu.Lock()
3✔
5065
        defer s.mu.Unlock()
3✔
5066

3✔
5067
        // Check that were actually connected to this peer. If not, then we'll
3✔
5068
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5069
        // currently connected to.
3✔
5070
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5071
        if err == ErrPeerNotConnected {
6✔
5072
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5073
        }
3✔
5074

5075
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5076

3✔
5077
        s.cancelConnReqs(pubStr, nil)
3✔
5078

3✔
5079
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5080
        // them from this map so we don't attempt to re-connect after we
3✔
5081
        // disconnect.
3✔
5082
        delete(s.persistentPeers, pubStr)
3✔
5083
        delete(s.persistentPeersBackoff, pubStr)
3✔
5084

3✔
5085
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5086
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5087
        //
3✔
5088
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5089
        // goroutine because we might hold the server's mutex.
3✔
5090
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5091

3✔
5092
        return nil
3✔
5093
}
5094

5095
// OpenChannel sends a request to the server to open a channel to the specified
5096
// peer identified by nodeKey with the passed channel funding parameters.
5097
//
5098
// NOTE: This function is safe for concurrent access.
5099
func (s *server) OpenChannel(
5100
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5101

3✔
5102
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5103
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5104
        // not blocked if the caller is not reading the updates.
3✔
5105
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5106
        req.Err = make(chan error, 1)
3✔
5107

3✔
5108
        // First attempt to locate the target peer to open a channel with, if
3✔
5109
        // we're unable to locate the peer then this request will fail.
3✔
5110
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5111
        s.mu.RLock()
3✔
5112
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5113
        if !ok {
3✔
UNCOV
5114
                s.mu.RUnlock()
×
UNCOV
5115

×
5116
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5117
                return req.Updates, req.Err
×
5118
        }
×
5119
        req.Peer = peer
3✔
5120
        s.mu.RUnlock()
3✔
5121

3✔
5122
        // We'll wait until the peer is active before beginning the channel
3✔
5123
        // opening process.
3✔
5124
        select {
3✔
5125
        case <-peer.ActiveSignal():
3✔
UNCOV
5126
        case <-peer.QuitSignal():
×
UNCOV
5127
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5128
                return req.Updates, req.Err
×
5129
        case <-s.quit:
×
5130
                req.Err <- ErrServerShuttingDown
×
5131
                return req.Updates, req.Err
×
5132
        }
5133

5134
        // If the fee rate wasn't specified at this point we fail the funding
5135
        // because of the missing fee rate information. The caller of the
5136
        // `OpenChannel` method needs to make sure that default values for the
5137
        // fee rate are set beforehand.
5138
        if req.FundingFeePerKw == 0 {
3✔
UNCOV
5139
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
UNCOV
5140
                        "the channel opening transaction")
×
5141

×
5142
                return req.Updates, req.Err
×
5143
        }
×
5144

5145
        // Spawn a goroutine to send the funding workflow request to the funding
5146
        // manager. This allows the server to continue handling queries instead
5147
        // of blocking on this request which is exported as a synchronous
5148
        // request to the outside world.
5149
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5150

3✔
5151
        return req.Updates, req.Err
3✔
5152
}
5153

5154
// Peers returns a slice of all active peers.
5155
//
5156
// NOTE: This function is safe for concurrent access.
5157
func (s *server) Peers() []*peer.Brontide {
3✔
5158
        s.mu.RLock()
3✔
5159
        defer s.mu.RUnlock()
3✔
5160

3✔
5161
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5162
        for _, peer := range s.peersByPub {
6✔
5163
                peers = append(peers, peer)
3✔
5164
        }
3✔
5165

5166
        return peers
3✔
5167
}
5168

5169
// computeNextBackoff uses a truncated exponential backoff to compute the next
5170
// backoff using the value of the exiting backoff. The returned duration is
5171
// randomized in either direction by 1/20 to prevent tight loops from
5172
// stabilizing.
5173
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5174
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5175
        nextBackoff := 2 * currBackoff
3✔
5176
        if nextBackoff > maxBackoff {
6✔
5177
                nextBackoff = maxBackoff
3✔
5178
        }
3✔
5179

5180
        // Using 1/10 of our duration as a margin, compute a random offset to
5181
        // avoid the nodes entering connection cycles.
5182
        margin := nextBackoff / 10
3✔
5183

3✔
5184
        var wiggle big.Int
3✔
5185
        wiggle.SetUint64(uint64(margin))
3✔
5186
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
UNCOV
5187
                // Randomizing is not mission critical, so we'll just return the
×
UNCOV
5188
                // current backoff.
×
5189
                return nextBackoff
×
5190
        }
×
5191

5192
        // Otherwise add in our wiggle, but subtract out half of the margin so
5193
        // that the backoff can tweaked by 1/20 in either direction.
5194
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5195
}
5196

5197
// errNoAdvertisedAddr is an error returned when we attempt to retrieve the
5198
// advertised address of a node, but they don't have one.
5199
var errNoAdvertisedAddr = errors.New("no advertised address found")
5200

5201
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5202
func (s *server) fetchNodeAdvertisedAddrs(ctx context.Context,
5203
        pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5204

3✔
5205
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5206
        if err != nil {
3✔
UNCOV
5207
                return nil, err
×
UNCOV
5208
        }
×
5209

5210
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5211
        if err != nil {
6✔
5212
                return nil, err
3✔
5213
        }
3✔
5214

5215
        if len(node.Addresses) == 0 {
6✔
5216
                return nil, errNoAdvertisedAddr
3✔
5217
        }
3✔
5218

5219
        return node.Addresses, nil
3✔
5220
}
5221

5222
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5223
// channel update for a target channel.
5224
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5225
        *lnwire.ChannelUpdate1, error) {
3✔
5226

3✔
5227
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5228
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5229
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5230
                if err != nil {
6✔
5231
                        return nil, err
3✔
5232
                }
3✔
5233

5234
                return netann.ExtractChannelUpdate(
3✔
5235
                        ourPubKey[:], info, edge1, edge2,
3✔
5236
                )
3✔
5237
        }
5238
}
5239

5240
// applyChannelUpdate applies the channel update to the different sub-systems of
5241
// the server. The useAlias boolean denotes whether or not to send an alias in
5242
// place of the real SCID.
5243
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5244
        op *wire.OutPoint, useAlias bool) error {
3✔
5245

3✔
5246
        var (
3✔
5247
                peerAlias    *lnwire.ShortChannelID
3✔
5248
                defaultAlias lnwire.ShortChannelID
3✔
5249
        )
3✔
5250

3✔
5251
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5252

3✔
5253
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5254
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5255
        if useAlias {
6✔
5256
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5257
                if foundAlias != defaultAlias {
6✔
5258
                        peerAlias = &foundAlias
3✔
5259
                }
3✔
5260
        }
5261

5262
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5263
                update, discovery.RemoteAlias(peerAlias),
3✔
5264
        )
3✔
5265
        select {
3✔
5266
        case err := <-errChan:
3✔
5267
                return err
3✔
UNCOV
5268
        case <-s.quit:
×
UNCOV
5269
                return ErrServerShuttingDown
×
5270
        }
5271
}
5272

5273
// SendCustomMessage sends a custom message to the peer with the specified
5274
// pubkey.
5275
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5276
        data []byte) error {
3✔
5277

3✔
5278
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5279
        if err != nil {
6✔
5280
                return err
3✔
5281
        }
3✔
5282

5283
        // We'll wait until the peer is active.
5284
        select {
3✔
5285
        case <-peer.ActiveSignal():
3✔
UNCOV
5286
        case <-peer.QuitSignal():
×
UNCOV
5287
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5288
        case <-s.quit:
×
5289
                return ErrServerShuttingDown
×
5290
        }
5291

5292
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5293
        if err != nil {
6✔
5294
                return err
3✔
5295
        }
3✔
5296

5297
        // Send the message as low-priority. For now we assume that all
5298
        // application-defined message are low priority.
5299
        return peer.SendMessageLazy(true, msg)
3✔
5300
}
5301

5302
// newSweepPkScriptGen creates closure that generates a new public key script
5303
// which should be used to sweep any funds into the on-chain wallet.
5304
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5305
// (p2wkh) output.
5306
func newSweepPkScriptGen(
5307
        wallet lnwallet.WalletController,
5308
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5309

3✔
5310
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5311
                sweepAddr, err := wallet.NewAddress(
3✔
5312
                        lnwallet.TaprootPubkey, false,
3✔
5313
                        lnwallet.DefaultAccountName,
3✔
5314
                )
3✔
5315
                if err != nil {
3✔
UNCOV
5316
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5317
                }
×
5318

5319
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5320
                if err != nil {
3✔
UNCOV
5321
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5322
                }
×
5323

5324
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5325
                        wallet, netParams, addr,
3✔
5326
                )
3✔
5327
                if err != nil {
3✔
UNCOV
5328
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5329
                }
×
5330

5331
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5332
                        DeliveryAddress: addr,
3✔
5333
                        InternalKey:     internalKeyDesc,
3✔
5334
                })
3✔
5335
        }
5336
}
5337

5338
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5339
// finished.
5340
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5341
        // Get a list of closed channels.
3✔
5342
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5343
        if err != nil {
3✔
UNCOV
5344
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
UNCOV
5345
                return nil
×
5346
        }
×
5347

5348
        // Save the SCIDs in a map.
5349
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5350
        for _, c := range channels {
6✔
5351
                // If the channel is not pending, its FC has been finalized.
3✔
5352
                if !c.IsPending {
6✔
5353
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5354
                }
3✔
5355
        }
5356

5357
        // Double check whether the reported closed channel has indeed finished
5358
        // closing.
5359
        //
5360
        // NOTE: There are misalignments regarding when a channel's FC is
5361
        // marked as finalized. We double check the pending channels to make
5362
        // sure the returned SCIDs are indeed terminated.
5363
        //
5364
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5365
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5366
        if err != nil {
3✔
UNCOV
5367
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
UNCOV
5368
                return nil
×
5369
        }
×
5370

5371
        for _, c := range pendings {
6✔
5372
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5373
                        continue
3✔
5374
                }
5375

5376
                // If the channel is still reported as pending, remove it from
5377
                // the map.
UNCOV
5378
                delete(closedSCIDs, c.ShortChannelID)
×
UNCOV
5379

×
5380
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5381
                        c.ShortChannelID)
×
5382
        }
5383

5384
        return closedSCIDs
3✔
5385
}
5386

5387
// getStartingBeat returns the current beat. This is used during the startup to
5388
// initialize blockbeat consumers.
5389
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5390
        // beat is the current blockbeat.
3✔
5391
        var beat *chainio.Beat
3✔
5392

3✔
5393
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5394
        // we will skip fetching the best block.
3✔
5395
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
UNCOV
5396
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
UNCOV
5397
                        "mode")
×
5398

×
5399
                return &chainio.Beat{}, nil
×
5400
        }
×
5401

5402
        // We should get a notification with the current best block immediately
5403
        // by passing a nil block.
5404
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5405
        if err != nil {
3✔
UNCOV
5406
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
UNCOV
5407
        }
×
5408
        defer blockEpochs.Cancel()
3✔
5409

3✔
5410
        // We registered for the block epochs with a nil request. The notifier
3✔
5411
        // should send us the current best block immediately. So we need to
3✔
5412
        // wait for it here because we need to know the current best height.
3✔
5413
        select {
3✔
5414
        case bestBlock := <-blockEpochs.Epochs:
3✔
5415
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5416
                        bestBlock.Hash, bestBlock.Height)
3✔
5417

3✔
5418
                // Update the current blockbeat.
3✔
5419
                beat = chainio.NewBeat(*bestBlock)
3✔
5420

UNCOV
5421
        case <-s.quit:
×
UNCOV
5422
                srvrLog.Debug("LND shutting down")
×
5423
        }
5424

5425
        return beat, nil
3✔
5426
}
5427

5428
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5429
// point has an active RBF chan closer.
5430
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5431
        chanPoint wire.OutPoint) bool {
3✔
5432

3✔
5433
        pubBytes := peerPub.SerializeCompressed()
3✔
5434

3✔
5435
        s.mu.RLock()
3✔
5436
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5437
        s.mu.RUnlock()
3✔
5438
        if !ok {
3✔
UNCOV
5439
                return false
×
UNCOV
5440
        }
×
5441

5442
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5443
}
5444

5445
// attemptCoopRbfFeeBump attempts to look up the active chan closer for a
5446
// channel given the outpoint. If found, we'll attempt to do a fee bump,
5447
// returning channels used for updates. If the channel isn't currently active
5448
// (p2p connection established), then his function will return an error.
5449
func (s *server) attemptCoopRbfFeeBump(ctx context.Context,
5450
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5451
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
3✔
5452

3✔
5453
        // First, we'll attempt to look up the channel based on it's
3✔
5454
        // ChannelPoint.
3✔
5455
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5456
        if err != nil {
3✔
UNCOV
5457
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
UNCOV
5458
        }
×
5459

5460
        // From the channel, we can now get the pubkey of the peer, then use
5461
        // that to eventually get the chan closer.
5462
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5463

3✔
5464
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5465
        s.mu.RLock()
3✔
5466
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5467
        s.mu.RUnlock()
3✔
5468
        if !ok {
3✔
UNCOV
5469
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
UNCOV
5470
                        "not online", chanPoint)
×
5471
        }
×
5472

5473
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5474
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5475
        )
3✔
5476
        if err != nil {
3✔
UNCOV
5477
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
UNCOV
5478
                        "%w", err)
×
5479
        }
×
5480

5481
        return closeUpdates, nil
3✔
5482
}
5483

5484
// AttemptRBFCloseUpdate attempts to trigger a new RBF iteration for a co-op
5485
// close update. This route it to be used only if the target channel in question
5486
// is no longer active in the link. This can happen when we restart while we
5487
// already have done a single RBF co-op close iteration.
5488
func (s *server) AttemptRBFCloseUpdate(ctx context.Context,
5489
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5490
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
3✔
5491

3✔
5492
        // If the channel is present in the switch, then the request should flow
3✔
5493
        // through the switch instead.
3✔
5494
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5495
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
UNCOV
5496
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
UNCOV
5497
                        "invalid request", chanPoint)
×
5498
        }
×
5499

5500
        // At this point, we know that the channel isn't present in the link, so
5501
        // we'll check to see if we have an entry in the active chan closer map.
5502
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5503
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5504
        )
3✔
5505
        if err != nil {
3✔
UNCOV
5506
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
UNCOV
5507
                        "ChannelPoint(%v)", chanPoint)
×
5508
        }
×
5509

5510
        return updates, nil
3✔
5511
}
5512

5513
// setSelfNode configures and sets the server's self node. It sets the node
5514
// announcement, signs it, and updates the source node in the graph. When
5515
// determining values such as color and alias, the method prioritizes values
5516
// set in the config, then values previously persisted on disk, and finally
5517
// falls back to the defaults.
5518
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5519
        listenAddrs []net.Addr) error {
3✔
5520

3✔
5521
        // If we were requested to automatically configure port forwarding,
3✔
5522
        // we'll use the ports that the server will be listening on.
3✔
5523
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
3✔
5524
        for _, ip := range s.cfg.ExternalIPs {
6✔
5525
                externalIPStrings = append(externalIPStrings, ip.String())
3✔
5526
        }
3✔
5527
        if s.natTraversal != nil {
3✔
UNCOV
5528
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
UNCOV
5529
                for _, listenAddr := range listenAddrs {
×
5530
                        // At this point, the listen addresses should have
×
5531
                        // already been normalized, so it's safe to ignore the
×
5532
                        // errors.
×
5533
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5534
                        port, _ := strconv.Atoi(portStr)
×
5535

×
5536
                        listenPorts = append(listenPorts, uint16(port))
×
5537
                }
×
5538

5539
                ips, err := s.configurePortForwarding(listenPorts...)
×
UNCOV
5540
                if err != nil {
×
5541
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5542
                                "forwarding using %s: %v",
×
5543
                                s.natTraversal.Name(), err)
×
5544
                } else {
×
5545
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5546
                                "using %s to advertise external IP",
×
5547
                                s.natTraversal.Name())
×
5548
                        externalIPStrings = append(externalIPStrings, ips...)
×
5549
                }
×
5550
        }
5551

5552
        // Normalize the external IP strings to net.Addr.
5553
        addrs, err := lncfg.NormalizeAddresses(
3✔
5554
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5555
                s.cfg.net.ResolveTCPAddr,
3✔
5556
        )
3✔
5557
        if err != nil {
3✔
UNCOV
5558
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
UNCOV
5559
        }
×
5560

5561
        // To avoid having duplicate addresses, we'll only add addresses from
5562
        // the source node that are not already in our address list yet. We
5563
        // create this map for quick lookup.
5564
        addressMap := make(map[string]struct{}, len(addrs))
3✔
5565
        // Populate the map with the existing addresses.
3✔
5566
        for _, existingAddr := range addrs {
6✔
5567
                addressMap[existingAddr.String()] = struct{}{}
3✔
5568
        }
3✔
5569

5570
        // Parse the color from config. We will update this later if the config
5571
        // color is not changed from default (#3399FF) and we have a value in
5572
        // the source node.
5573
        color, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5574
        if err != nil {
3✔
UNCOV
5575
                return fmt.Errorf("unable to parse color: %w", err)
×
UNCOV
5576
        }
×
5577

5578
        var (
3✔
5579
                alias          = s.cfg.Alias
3✔
5580
                nodeLastUpdate = time.Now()
3✔
5581
        )
3✔
5582

3✔
5583
        srcNode, err := s.graphDB.SourceNode(ctx)
3✔
5584
        switch {
3✔
5585
        case err == nil:
3✔
5586
                // If we have a source node persisted in the DB already, then we
3✔
5587
                // just need to make sure that the new LastUpdate time is at
3✔
5588
                // least one second after the last update time.
3✔
5589
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
5590
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
5591
                }
3✔
5592

5593
                // If the color is not changed from default, it means that we
5594
                // didn't specify a different color in the config. We'll use the
5595
                // source node's color.
5596
                if s.cfg.Color == defaultColor {
6✔
5597
                        color = srcNode.Color
3✔
5598
                }
3✔
5599

5600
                // If an alias is not specified in the config, we'll use the
5601
                // source node's alias.
5602
                if alias == "" {
6✔
5603
                        alias = srcNode.Alias
3✔
5604
                }
3✔
5605

5606
                // Append unique addresses from the source node to the address
5607
                // list.
5608
                for _, addr := range srcNode.Addresses {
6✔
5609
                        if _, found := addressMap[addr.String()]; !found {
6✔
5610
                                addrs = append(addrs, addr)
3✔
5611
                                addressMap[addr.String()] = struct{}{}
3✔
5612
                        }
3✔
5613
                }
5614

5615
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5616
                // If an alias is not specified in the config, we'll use the
3✔
5617
                // default, which is the first 10 bytes of the serialized
3✔
5618
                // pubkey.
3✔
5619
                if alias == "" {
6✔
5620
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5621
                }
3✔
5622

5623
        // If the above cases are not matched, then we have an unhandled non
5624
        // nil error.
UNCOV
5625
        default:
×
UNCOV
5626
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5627
        }
5628

5629
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5630
        if err != nil {
3✔
UNCOV
5631
                return err
×
UNCOV
5632
        }
×
5633

5634
        // TODO(abdulkbk): potentially find a way to use the source node's
5635
        // features in the self node.
5636
        selfNode := &models.LightningNode{
3✔
5637
                HaveNodeAnnouncement: true,
3✔
5638
                LastUpdate:           nodeLastUpdate,
3✔
5639
                Addresses:            addrs,
3✔
5640
                Alias:                nodeAlias.String(),
3✔
5641
                Color:                color,
3✔
5642
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
5643
        }
3✔
5644

3✔
5645
        copy(selfNode.PubKeyBytes[:], nodePub[:])
3✔
5646

3✔
5647
        // Based on the disk representation of the node announcement generated
3✔
5648
        // above, we'll generate a node announcement that can go out on the
3✔
5649
        // network so we can properly sign it.
3✔
5650
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5651
        if err != nil {
3✔
UNCOV
5652
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
UNCOV
5653
        }
×
5654

5655
        // With the announcement generated, we'll sign it to properly
5656
        // authenticate the message on the network.
5657
        authSig, err := netann.SignAnnouncement(
3✔
5658
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5659
        )
3✔
5660
        if err != nil {
3✔
UNCOV
5661
                return fmt.Errorf("unable to generate signature for self node "+
×
UNCOV
5662
                        "announcement: %v", err)
×
5663
        }
×
5664

5665
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5666
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5667
                selfNode.AuthSigBytes,
3✔
5668
        )
3✔
5669
        if err != nil {
3✔
UNCOV
5670
                return err
×
UNCOV
5671
        }
×
5672

5673
        // Finally, we'll update the representation on disk, and update our
5674
        // cached in-memory version as well.
5675
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
UNCOV
5676
                return fmt.Errorf("can't set self node: %w", err)
×
UNCOV
5677
        }
×
5678

5679
        s.currentNodeAnn = nodeAnn
3✔
5680

3✔
5681
        return nil
3✔
5682
}
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