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

lightningnetwork / lnd / 18016273007

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

Pull #10248

github

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

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

23906 existing lines in 281 files now uncovered.

109536 of 200421 relevant lines covered (54.65%)

21816.97 hits per line

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

0.0
/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.
UNCOV
175
func (e *errPeerAlreadyConnected) Error() string {
×
UNCOV
176
        return fmt.Sprintf("already connected to peer: %v", e.peer)
×
UNCOV
177
}
×
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.
UNCOV
200
func (p peerAccessStatus) String() string {
×
UNCOV
201
        switch p {
×
UNCOV
202
        case peerStatusRestricted:
×
UNCOV
203
                return "restricted"
×
204

UNCOV
205
        case peerStatusTemporary:
×
UNCOV
206
                return "temporary"
×
207

UNCOV
208
        case peerStatusProtected:
×
UNCOV
209
                return "protected"
×
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.
UNCOV
442
func (s *server) updatePersistentPeerAddrs() error {
×
UNCOV
443
        graphSub, err := s.graphDB.SubscribeTopology()
×
UNCOV
444
        if err != nil {
×
445
                return err
×
446
        }
×
447

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

UNCOV
455
                for {
×
UNCOV
456
                        select {
×
UNCOV
457
                        case <-s.quit:
×
UNCOV
458
                                return
×
459

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

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

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

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

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

UNCOV
495
                                        s.mu.Lock()
×
UNCOV
496

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

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

UNCOV
511
                                        s.mu.Unlock()
×
UNCOV
512

×
UNCOV
513
                                        s.connectToPersistentPeer(pubKeyStr)
×
514
                                }
515
                        }
516
                }
517
        }()
518

UNCOV
519
        return nil
×
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.
UNCOV
532
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
×
UNCOV
533
        var (
×
UNCOV
534
                host string
×
UNCOV
535
                port int
×
UNCOV
536
        )
×
UNCOV
537

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

UNCOV
555
        if tor.IsOnionHost(host) {
×
556
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
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.
UNCOV
563
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
×
UNCOV
564
        return netCfg.ResolveTCPAddr("tcp", hostPort)
×
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,
UNCOV
570
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
×
UNCOV
571

×
UNCOV
572
        return func(a net.Addr) (net.Conn, error) {
×
UNCOV
573
                lnAddr := a.(*lnwire.NetAddress)
×
UNCOV
574
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
UNCOV
575
        }
×
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,
UNCOV
589
        implCfg *ImplementationCfg) (*server, error) {
×
UNCOV
590

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

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

×
UNCOV
602
        netParams := cfg.ActiveNetParams.Params
×
UNCOV
603

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

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

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

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

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

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

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

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

×
UNCOV
674
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
UNCOV
675

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

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

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

×
UNCOV
702
                listenAddrs: listenAddrs,
×
UNCOV
703

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

×
UNCOV
708
                torController: torController,
×
UNCOV
709

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

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

×
UNCOV
726
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
727

×
UNCOV
728
                customMessageServer: subscribe.NewServer(),
×
UNCOV
729

×
UNCOV
730
                tlsManager: tlsManager,
×
UNCOV
731

×
UNCOV
732
                featureMgr: featureMgr,
×
UNCOV
733
                quit:       make(chan struct{}),
×
UNCOV
734
        }
×
UNCOV
735

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

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

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

×
UNCOV
760
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
761

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

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

UNCOV
771
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
772

×
UNCOV
773
                return nil
×
774
        }
775

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

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

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

UNCOV
798
                        peer.HandleLocalCloseChanReqs(request)
×
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))
UNCOV
817
        if err != nil {
×
818
                return nil, err
×
819
        }
×
UNCOV
820
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
×
UNCOV
821
                &htlcswitch.InterceptableSwitchConfig{
×
UNCOV
822
                        Switch:             s.htlcSwitch,
×
UNCOV
823
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
824
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
×
UNCOV
825
                        RequireInterceptor: s.cfg.RequireInterceptor,
×
UNCOV
826
                        Notifier:           s.cc.ChainNotifier,
×
UNCOV
827
                },
×
UNCOV
828
        )
×
UNCOV
829
        if err != nil {
×
830
                return nil, err
×
831
        }
×
832

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

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

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

×
UNCOV
857
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
UNCOV
858
        // port forwarding for users behind a NAT.
×
UNCOV
859
        if cfg.NAT {
×
860
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
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

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

901
        // The router will get access to the payment ID sequencer, such that it
902
        // can generate unique payment IDs.
UNCOV
903
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
904
        if err != nil {
×
905
                return nil, err
×
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.
UNCOV
912
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
913

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

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

936
                case routing.BimodalEstimatorName:
×
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:
×
954
                        return nil, fmt.Errorf("unknown estimator type %v",
×
955
                                routingConfig.ProbabilityEstimatorType)
×
956
                }
957
        }
958

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

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

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

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

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

×
UNCOV
1008
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
×
UNCOV
1009

×
UNCOV
1010
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1011
                cfg.Routing.StrictZombiePruning
×
UNCOV
1012

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

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

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

UNCOV
1060
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1061

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

×
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
                PeerMsgRateBytes:        cfg.Gossip.PeerMsgRateBytes,
1107
        }, nodeKeyDesc)
1108

UNCOV
1109
        accessCfg := &accessManConfig{
×
UNCOV
1110
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
UNCOV
1111
                        error) {
×
UNCOV
1112

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

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

UNCOV
1127
        s.peerAccessMan = peerAccessMan
×
UNCOV
1128

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

×
UNCOV
1139
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
×
UNCOV
1140
                                func(c *models.ChannelEdgeInfo,
×
UNCOV
1141
                                        e *models.ChannelEdgePolicy,
×
UNCOV
1142
                                        _ *models.ChannelEdgePolicy) error {
×
UNCOV
1143

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

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

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

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

UNCOV
1176
        aggregator := sweep.NewBudgetAggregator(
×
UNCOV
1177
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1178
                s.implCfg.AuxSweeper,
×
UNCOV
1179
        )
×
UNCOV
1180

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1321
                        event := &contractcourt.ContractBreachEvent{
×
UNCOV
1322
                                ChanPoint:         chanPoint,
×
UNCOV
1323
                                ProcessACK:        processACK,
×
UNCOV
1324
                                BreachRetribution: breachRet,
×
UNCOV
1325
                        }
×
UNCOV
1326

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

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

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

×
UNCOV
1364
                        // Get the circuit map.
×
UNCOV
1365
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1366

×
UNCOV
1367
                        // Lookup the outgoing circuit.
×
UNCOV
1368
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1369
                        if pc == nil {
×
UNCOV
1370
                                return nil
×
UNCOV
1371
                        }
×
1372

UNCOV
1373
                        return &pc.Incoming
×
1374
                },
1375
                AuxLeafStore: implCfg.AuxLeafStore,
1376
                AuxSigner:    implCfg.AuxSigner,
1377
                AuxResolver:  implCfg.AuxContractResolver,
1378
        }, dbs.ChanStateDB)
1379

1380
        // Select the configuration and funding parameters for Bitcoin.
UNCOV
1381
        chainCfg := cfg.Bitcoin
×
UNCOV
1382
        minRemoteDelay := funding.MinBtcRemoteDelay
×
UNCOV
1383
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
UNCOV
1384

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

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

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

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

×
UNCOV
1412
                var ourPolicy *models.ChannelEdgePolicy
×
UNCOV
1413
                if info != nil && info.NodeKey1Bytes == ourKey {
×
UNCOV
1414
                        ourPolicy = e1
×
UNCOV
1415
                } else {
×
UNCOV
1416
                        ourPolicy = e2
×
UNCOV
1417
                }
×
1418

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

UNCOV
1424
                err = s.graphDB.DeleteChannelEdges(
×
UNCOV
1425
                        false, false, scid.ToUint64(),
×
UNCOV
1426
                )
×
UNCOV
1427
                return ourPolicy, err
×
1428
        }
1429

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

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

×
UNCOV
1446
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1447
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1448

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1659
        // Assemble a peer notifier which will provide clients with subscriptions
1660
        // to peer online and offline events.
UNCOV
1661
        s.peerNotifier = peernotifier.New()
×
UNCOV
1662

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

UNCOV
1678
        if cfg.WtClient.Active {
×
UNCOV
1679
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1680
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1681

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

×
UNCOV
1688
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1689

×
UNCOV
1690
                if err := policy.Validate(); err != nil {
×
1691
                        return nil, err
×
1692
                }
×
1693

1694
                // authDial is the wrapper around the btrontide.Dial for the
1695
                // watchtower.
UNCOV
1696
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1697
                        netAddr *lnwire.NetAddress,
×
UNCOV
1698
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1699

×
UNCOV
1700
                        return brontide.Dial(
×
UNCOV
1701
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1702
                        )
×
UNCOV
1703
                }
×
1704

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

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

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

UNCOV
1728
                        return br, channel.ChanType, nil
×
1729
                }
1730

UNCOV
1731
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1732

×
UNCOV
1733
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1734
                // signalling support for anchor channels.
×
UNCOV
1735
                anchorPolicy := policy
×
UNCOV
1736
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1737

×
UNCOV
1738
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1739
                // signalling support for taproot channels.
×
UNCOV
1740
                taprootPolicy := policy
×
UNCOV
1741
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1742
                        blob.FlagTaprootChannel,
×
UNCOV
1743
                )
×
UNCOV
1744

×
UNCOV
1745
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1746
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1747
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1748
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1749
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1750
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1751
                                error) {
×
UNCOV
1752

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

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

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

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

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

1808
        // Create liveness monitor.
UNCOV
1809
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1810

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

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

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

×
UNCOV
1848
        // Finally, register the subsystems in blockbeat.
×
UNCOV
1849
        s.registerBlockConsumers()
×
UNCOV
1850

×
UNCOV
1851
        return s, nil
×
1852
}
1853

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

×
UNCOV
1859
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
1860
        case routing.AprioriConfig:
×
UNCOV
1861
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1862
                        routing.AprioriEstimatorName
×
UNCOV
1863

×
UNCOV
1864
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1865
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1866
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1867
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1868
                targetCfg.HopProbability = c.AprioriHopProbability
×
1869

UNCOV
1870
        case routing.BimodalConfig:
×
UNCOV
1871
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1872
                        routing.BimodalEstimatorName
×
UNCOV
1873

×
UNCOV
1874
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1875
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1876
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1877
                targetCfg.DecayTime = c.BimodalDecayTime
×
1878
        }
1879

UNCOV
1880
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1881
}
1882

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

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

×
UNCOV
1908
        data, err := u.DataToSign()
×
UNCOV
1909
        if err != nil {
×
1910
                return nil, err
×
1911
        }
×
1912

UNCOV
1913
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1914
}
1915

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

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

×
1934
                chainBackendAttempts = 0
×
1935
        }
×
1936

UNCOV
1937
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
1938
                "chain backend",
×
UNCOV
1939
                cc.HealthCheck,
×
UNCOV
1940
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
1941
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
1942
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
1943
                chainBackendAttempts,
×
UNCOV
1944
        )
×
UNCOV
1945

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

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

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

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

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

UNCOV
1996
        checks := []*healthcheck.Observation{
×
UNCOV
1997
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
1998
        }
×
UNCOV
1999

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

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

×
UNCOV
2030
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
2031
                        "remote signer connection",
×
UNCOV
2032
                        rpcwallet.HealthCheck(
×
UNCOV
2033
                                s.cfg.RemoteSigner,
×
UNCOV
2034

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

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

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

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

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

2088
                checks = append(checks, leaderCheck)
×
2089
        }
2090

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

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

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

2113
// add is used to add a cleanup function to be called when
2114
// the run function is executed.
UNCOV
2115
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2116
        return append(c, cleanup)
×
UNCOV
2117
}
×
2118

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

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

×
UNCOV
2137
        cleanup := cleaner{}
×
UNCOV
2138

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

UNCOV
2144
        if startErr != nil {
×
2145
                cleanup.run()
×
2146
        }
×
2147

UNCOV
2148
        return startErr
×
2149
}
2150

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

UNCOV
2163
        var startErr error
×
UNCOV
2164

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
2356
                cleanup.add(func() error {
×
2357
                        s.missionController.StopStoreTickers()
×
2358
                        return nil
×
2359
                })
×
UNCOV
2360
                s.missionController.RunStoreTickers()
×
UNCOV
2361

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

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

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

UNCOV
2411
                if s.natTraversal != nil {
×
2412
                        s.wg.Add(1)
×
2413
                        go s.watchExternalIP()
×
2414
                }
×
2415

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

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

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

UNCOV
2451
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2452
                                IdentityKey: parsedPubkey,
×
UNCOV
2453
                                Address:     addr,
×
UNCOV
2454
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2455
                        }
×
UNCOV
2456

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

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

×
2475
                        startErr = err
×
2476
                        return
×
2477
                }
×
2478

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

×
2488
                        startErr = err
×
2489
                        return
×
2490
                }
×
2491

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

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

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

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

2520
                                copy(result[idx][:], servers)
×
2521
                        }
2522

2523
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2524
                }
2525

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

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

UNCOV
2564
                        s.wg.Add(1)
×
UNCOV
2565
                        go s.peerBootstrapper(
×
UNCOV
2566
                                ctx, defaultMinPeers, bootstrappers,
×
UNCOV
2567
                        )
×
UNCOV
2568
                } else {
×
UNCOV
2569
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2570
                }
×
2571

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

2583
                // Set the active flag now that we've completed the full
2584
                // startup.
UNCOV
2585
                atomic.StoreInt32(&s.active, 1)
×
2586
        })
2587

UNCOV
2588
        if startErr != nil {
×
2589
                cleanup.run()
×
2590
        }
×
UNCOV
2591
        return startErr
×
2592
}
2593

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

×
UNCOV
2602
                ctx := context.Background()
×
UNCOV
2603

×
UNCOV
2604
                close(s.quit)
×
UNCOV
2605

×
UNCOV
2606
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2607
                s.connMgr.Stop()
×
UNCOV
2608

×
UNCOV
2609
                // Stop dispatching blocks to other systems immediately.
×
UNCOV
2610
                s.blockbeatDispatcher.Stop()
×
UNCOV
2611

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

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

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

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

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

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

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

2743
                // Wait for all lingering goroutines to quit.
UNCOV
2744
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2745
                s.wg.Wait()
×
UNCOV
2746

×
UNCOV
2747
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2748
                s.sigPool.Stop()
×
UNCOV
2749
                s.writePool.Stop()
×
UNCOV
2750
                s.readPool.Stop()
×
2751
        })
2752

UNCOV
2753
        return nil
×
2754
}
2755

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

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

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

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

2785
        return externalIPs, nil
×
2786
}
2787

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

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

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

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

2823
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2824

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

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

2855
                        if ip.Equal(s.lastDetectedIP) {
×
2856
                                continue
×
2857
                        }
2858

2859
                        srvrLog.Infof("Detected new external IP address %s", ip)
×
2860

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

2876
                                newAddrs = append(newAddrs, addr)
×
2877
                        }
2878

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

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

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

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

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

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

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

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

×
UNCOV
2945
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
UNCOV
2946

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

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

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

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

UNCOV
2979
        return bootStrappers, nil
×
2980
}
2981

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

×
UNCOV
2992
        ignore := make(map[autopilot.NodeID]struct{})
×
UNCOV
2993

×
UNCOV
2994
        // We should ignore ourselves from bootstrapping.
×
UNCOV
2995
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
UNCOV
2996
        ignore[selfKey] = struct{}{}
×
UNCOV
2997

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

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

UNCOV
3012
        return ignore
×
3013
}
3014

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

×
UNCOV
3023
        defer s.wg.Done()
×
UNCOV
3024

×
UNCOV
3025
        // Before we continue, init the ignore peers map.
×
UNCOV
3026
        ignoreList := s.createBootstrapIgnorePeers()
×
UNCOV
3027

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

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

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

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

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

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

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

3073
                        if epochAttempts > 0 &&
×
3074
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3075

×
3076
                                sampleTicker.Stop()
×
3077

×
3078
                                backOff *= 2
×
3079
                                if backOff > bootstrapBackOffCeiling {
×
3080
                                        backOff = bootstrapBackOffCeiling
×
3081
                                }
×
3082

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

3089
                        atomic.StoreUint32(&epochErrors, 0)
×
3090
                        epochAttempts = 0
×
3091

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

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

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

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

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

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

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

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

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

×
UNCOV
3161
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
UNCOV
3162
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
UNCOV
3163

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

×
UNCOV
3169
        // As want to be more aggressive, we'll use a lower back off celling
×
UNCOV
3170
        // then the main peer bootstrap logic.
×
UNCOV
3171
        backOffCeiling := bootstrapBackOffCeiling / 5
×
UNCOV
3172

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

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

×
UNCOV
3186
                if numActivePeers >= numTargetPeers {
×
UNCOV
3187
                        return
×
UNCOV
3188
                }
×
3189

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

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

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

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

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

×
UNCOV
3233
                                errChan := make(chan error, 1)
×
UNCOV
3234
                                go s.connectToPeer(
×
UNCOV
3235
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
UNCOV
3236
                                )
×
UNCOV
3237

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

UNCOV
3261
                wg.Wait()
×
3262
        }
3263
}
3264

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

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

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

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

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

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

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

3336
        return nil
×
3337
}
3338

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

×
UNCOV
3345
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3346
        if err != nil {
×
3347
                return nil, err
×
3348
        }
×
3349

UNCOV
3350
        for _, channel := range nodeChans {
×
UNCOV
3351
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3352
                        return channel, nil
×
UNCOV
3353
                }
×
3354
        }
3355

UNCOV
3356
        return nil, fmt.Errorf("unable to find channel")
×
3357
}
3358

3359
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3360
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3361
        s.mu.Lock()
×
UNCOV
3362
        defer s.mu.Unlock()
×
UNCOV
3363

×
UNCOV
3364
        return *s.currentNodeAnn
×
UNCOV
3365
}
×
3366

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

×
UNCOV
3373
        s.mu.Lock()
×
UNCOV
3374
        defer s.mu.Unlock()
×
UNCOV
3375

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

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

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

3400
        // Always update the timestamp when refreshing to ensure the update
3401
        // propagates.
UNCOV
3402
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3403

×
UNCOV
3404
        // Apply the requested changes to the node announcement.
×
UNCOV
3405
        for _, modifier := range modifiers {
×
UNCOV
3406
                modifier(&newNodeAnn)
×
UNCOV
3407
        }
×
3408

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

3417
        // If signing succeeds, update the current announcement.
UNCOV
3418
        *s.currentNodeAnn = newNodeAnn
×
UNCOV
3419

×
UNCOV
3420
        return *s.currentNodeAnn, nil
×
3421
}
3422

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

×
UNCOV
3431
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3432
        if err != nil {
×
UNCOV
3433
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3434
                        "announcement: %v", err)
×
UNCOV
3435
        }
×
3436

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

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

×
UNCOV
3453
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
3454

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

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

UNCOV
3467
        return nil
×
3468
}
3469

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

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

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

UNCOV
3493
        for _, node := range linkNodes {
×
UNCOV
3494
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3495
                nodeAddrs := &nodeAddresses{
×
UNCOV
3496
                        pubKey:    node.IdentityPub,
×
UNCOV
3497
                        addresses: node.Addresses,
×
UNCOV
3498
                }
×
UNCOV
3499
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3500
        }
×
3501

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

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

UNCOV
3519
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3520

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

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

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

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

3559
                // Construct a slice of the deduped addresses.
UNCOV
3560
                var addrs []net.Addr
×
UNCOV
3561
                for _, addr := range addrSet {
×
UNCOV
3562
                        addrs = append(addrs, addr)
×
UNCOV
3563
                }
×
3564

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

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

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

×
3588
                        return err
×
3589
                }
×
3590
        }
3591

3592
        // Combine the addresses from the link nodes and the channel graph.
UNCOV
3593
        for pubStr, nodeAddr := range graphAddrs {
×
UNCOV
3594
                nodeAddrsMap[pubStr] = nodeAddr
×
UNCOV
3595
        }
×
3596

UNCOV
3597
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3598
                len(nodeAddrsMap))
×
UNCOV
3599

×
UNCOV
3600
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3601
        // have been recorded and sent to the connection manager.
×
UNCOV
3602
        s.mu.Lock()
×
UNCOV
3603
        defer s.mu.Unlock()
×
UNCOV
3604

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

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

×
UNCOV
3628
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3629
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3630
                }
×
3631

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

×
UNCOV
3642
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3643
                } else {
×
3644
                        go s.delayInitialReconnect(pubStr)
×
3645
                }
×
3646

UNCOV
3647
                numOutboundConns++
×
3648
        }
3649

UNCOV
3650
        return nil
×
3651
}
3652

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

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

×
UNCOV
3672
        s.mu.Lock()
×
UNCOV
3673
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3674
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3675
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3676
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3677
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3678
                s.mu.Unlock()
×
UNCOV
3679

×
UNCOV
3680
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3681
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3682

×
UNCOV
3683
                return
×
UNCOV
3684
        }
×
UNCOV
3685
        s.mu.Unlock()
×
3686
}
3687

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

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

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

UNCOV
3728
                peers = append(peers, sPeer)
×
3729
        }
UNCOV
3730
        s.mu.RUnlock()
×
UNCOV
3731

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

×
UNCOV
3739
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3740
                wg.Add(1)
×
UNCOV
3741
                s.wg.Add(1)
×
UNCOV
3742
                go func(p lnpeer.Peer) {
×
UNCOV
3743
                        defer s.wg.Done()
×
UNCOV
3744
                        defer wg.Done()
×
UNCOV
3745

×
UNCOV
3746
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3747
                }(sPeer)
×
3748
        }
3749

3750
        // Wait for all messages to have been dispatched before returning to
3751
        // caller.
UNCOV
3752
        wg.Wait()
×
UNCOV
3753

×
UNCOV
3754
        return nil
×
3755
}
3756

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

×
UNCOV
3764
        s.mu.Lock()
×
UNCOV
3765

×
UNCOV
3766
        // Compute the target peer's identifier.
×
UNCOV
3767
        pubStr := string(peerKey[:])
×
UNCOV
3768

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

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

3791
                // Connected, can return early.
UNCOV
3792
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3793

×
UNCOV
3794
                select {
×
UNCOV
3795
                case peerChan <- peer:
×
3796
                case <-s.quit:
×
3797
                }
3798

UNCOV
3799
                return
×
3800
        }
3801

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

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

×
UNCOV
3817
        c := make(chan struct{})
×
UNCOV
3818

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

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

×
UNCOV
3835
        return c
×
3836
}
3837

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

×
UNCOV
3847
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3848

×
UNCOV
3849
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3850
}
×
3851

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

×
UNCOV
3861
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3862
}
×
3863

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

UNCOV
3872
        return peer, nil
×
3873
}
3874

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

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

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

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

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

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

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

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

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

UNCOV
3947
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3948
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3949
        pubStr := string(pubSer)
×
UNCOV
3950

×
UNCOV
3951
        var pubBytes [33]byte
×
UNCOV
3952
        copy(pubBytes[:], pubSer)
×
UNCOV
3953

×
UNCOV
3954
        s.mu.Lock()
×
UNCOV
3955
        defer s.mu.Unlock()
×
UNCOV
3956

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

×
UNCOV
3964
                conn.Close()
×
UNCOV
3965
                return
×
UNCOV
3966
        }
×
3967

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

UNCOV
3978
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
×
UNCOV
3979

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

UNCOV
3993
        case nil:
×
UNCOV
3994
                ctx := btclog.WithCtx(
×
UNCOV
3995
                        context.TODO(),
×
UNCOV
3996
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
3997
                )
×
UNCOV
3998

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

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

4016
                // Otherwise, if we should drop the connection, then we'll
4017
                // disconnect our already connected peer.
UNCOV
4018
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
4019

×
UNCOV
4020
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4021

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

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

UNCOV
4043
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4044
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4045
        pubStr := string(pubSer)
×
UNCOV
4046

×
UNCOV
4047
        var pubBytes [33]byte
×
UNCOV
4048
        copy(pubBytes[:], pubSer)
×
UNCOV
4049

×
UNCOV
4050
        s.mu.Lock()
×
UNCOV
4051
        defer s.mu.Unlock()
×
UNCOV
4052

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

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

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

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

4083
                conn.Close()
×
4084
                return
×
4085
        }
4086

UNCOV
4087
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
UNCOV
4088
                conn.RemoteAddr())
×
UNCOV
4089

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

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

UNCOV
4113
        case nil:
×
UNCOV
4114
                ctx := btclog.WithCtx(
×
UNCOV
4115
                        context.TODO(),
×
UNCOV
4116
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
4117
                )
×
UNCOV
4118

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

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

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

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

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

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

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

UNCOV
4183
        for _, connReq := range connReqs {
×
UNCOV
4184
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4185

×
UNCOV
4186
                // Atomically capture the current request identifier.
×
UNCOV
4187
                connID := connReq.ID()
×
UNCOV
4188

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

4195
                // Skip a particular connection ID if instructed.
UNCOV
4196
                if skip != nil && connID == *skip {
×
UNCOV
4197
                        continue
×
4198
                }
4199

UNCOV
4200
                s.connMgr.Remove(connID)
×
4201
        }
4202

UNCOV
4203
        delete(s.persistentConnReqs, pubStr)
×
4204
}
4205

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

×
UNCOV
4212
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4213
                Peer: peer,
×
UNCOV
4214
                Msg:  msg,
×
UNCOV
4215
        })
×
UNCOV
4216
}
×
4217

4218
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4219
// messages.
UNCOV
4220
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4221
        return s.customMessageServer.Subscribe()
×
UNCOV
4222
}
×
4223

4224
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4225
// the channelNotifier's NotifyOpenChannelEvent.
4226
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
UNCOV
4227
        remotePub *btcec.PublicKey) {
×
UNCOV
4228

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

4235
        // Notify subscribers about this open channel event.
UNCOV
4236
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4237
}
4238

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

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

4252
        // Notify subscribers about this event.
UNCOV
4253
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4254
}
4255

4256
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4257
// calls the channelNotifier's NotifyFundingTimeout.
4258
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
UNCOV
4259
        remotePub *btcec.PublicKey) {
×
UNCOV
4260

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

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

4277
        // Notify subscribers about this event.
UNCOV
4278
        s.channelNotifier.NotifyFundingTimeout(op)
×
4279
}
4280

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

×
UNCOV
4288
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4289
        addr := conn.RemoteAddr()
×
UNCOV
4290
        pubKey := brontideConn.RemotePub()
×
UNCOV
4291

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

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

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

×
4310
                conn.Close()
×
4311

×
4312
                return
×
4313
        }
×
4314

UNCOV
4315
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4316
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4317

×
UNCOV
4318
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4319
                IdentityKey: pubKey,
×
UNCOV
4320
                Address:     addr,
×
UNCOV
4321
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4322
        }
×
UNCOV
4323

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

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

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

UNCOV
4353
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4354
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4355

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

×
UNCOV
4399
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4400
                },
×
4401

4402
                PongBuf: s.pongBuf,
4403

4404
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4405

4406
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4407

4408
                FundingManager: s.fundingMgr,
4409

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

UNCOV
4441
                        return clock.NewDefaultClock().Now().Before(
×
UNCOV
4442
                                EndorsementExperimentEnd,
×
UNCOV
4443
                        )
×
4444
                },
4445
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4446
        }
4447

UNCOV
4448
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4449
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4450

×
UNCOV
4451
        p := peer.NewBrontide(pCfg)
×
UNCOV
4452

×
UNCOV
4453
        // Update the access manager with the access permission for this peer.
×
UNCOV
4454
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
UNCOV
4455

×
UNCOV
4456
        // TODO(roasbeef): update IP address for link-node
×
UNCOV
4457
        //  * also mark last-seen, do it one single transaction?
×
UNCOV
4458

×
UNCOV
4459
        s.addPeer(p)
×
UNCOV
4460

×
UNCOV
4461
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4462
        // delete the previous error buffer from the server's map of error
×
UNCOV
4463
        // buffers.
×
UNCOV
4464
        delete(s.peerErrors, pkStr)
×
UNCOV
4465

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

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

UNCOV
4480
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4481

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

×
4488
                return
×
4489
        }
×
4490

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

4496
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4497
        // be human-readable.
UNCOV
4498
        pubStr := string(pubBytes)
×
UNCOV
4499

×
UNCOV
4500
        s.peersByPub[pubStr] = p
×
UNCOV
4501

×
UNCOV
4502
        if p.Inbound() {
×
UNCOV
4503
                s.inboundPeers[pubStr] = p
×
UNCOV
4504
        } else {
×
UNCOV
4505
                s.outboundPeers[pubStr] = p
×
UNCOV
4506
        }
×
4507

4508
        // Inform the peer notifier of a peer online event so that it can be reported
4509
        // to clients listening for peer events.
UNCOV
4510
        var pubKey [33]byte
×
UNCOV
4511
        copy(pubKey[:], pubBytes)
×
4512
}
4513

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

×
UNCOV
4526
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4527

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

4535
        // Create a channel that will be used to signal a successful start of
4536
        // the link. This prevents the peer termination watcher from beginning
4537
        // its duty too early.
UNCOV
4538
        ready := make(chan struct{})
×
UNCOV
4539

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

×
UNCOV
4549
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4550
        // will unblock the peerTerminationWatcher.
×
UNCOV
4551
        if err := p.Start(); err != nil {
×
UNCOV
4552
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4553

×
UNCOV
4554
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4555
                return
×
UNCOV
4556
        }
×
4557

4558
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4559
        // was successful, and to begin watching the peer's wait group.
UNCOV
4560
        close(ready)
×
UNCOV
4561

×
UNCOV
4562
        s.mu.Lock()
×
UNCOV
4563
        defer s.mu.Unlock()
×
UNCOV
4564

×
UNCOV
4565
        // Check if there are listeners waiting for this peer to come online.
×
UNCOV
4566
        srvrLog.Debugf("Notifying that peer %v is online", p)
×
UNCOV
4567

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

×
UNCOV
4580
        // Since the peer has been fully initialized, now it's time to notify
×
UNCOV
4581
        // the RPC about the peer online event.
×
UNCOV
4582
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
×
4583
}
4584

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

×
UNCOV
4599
        ctx := btclog.WithCtx(
×
UNCOV
4600
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
UNCOV
4601
        )
×
UNCOV
4602

×
UNCOV
4603
        p.WaitForDisconnect(ready)
×
UNCOV
4604

×
UNCOV
4605
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
UNCOV
4606

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

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

×
UNCOV
4620
        pubKey := p.IdentityKey()
×
UNCOV
4621

×
UNCOV
4622
        // We'll also inform the gossiper that this peer is no longer active,
×
UNCOV
4623
        // so we don't need to maintain sync state for it any longer.
×
UNCOV
4624
        s.authGossiper.PruneSyncState(p.PubKey())
×
UNCOV
4625

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

UNCOV
4636
        for _, link := range links {
×
UNCOV
4637
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4638
        }
×
4639

UNCOV
4640
        s.mu.Lock()
×
UNCOV
4641
        defer s.mu.Unlock()
×
UNCOV
4642

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

×
UNCOV
4652
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4653
        // peer termination watcher and skip cleanup.
×
UNCOV
4654
        if _, ok := s.ignorePeerTermination[p]; ok {
×
UNCOV
4655
                delete(s.ignorePeerTermination, p)
×
UNCOV
4656

×
UNCOV
4657
                pubKey := p.PubKey()
×
UNCOV
4658
                pubStr := string(pubKey[:])
×
UNCOV
4659

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

4673
        // First, cleanup any remaining state the server has regarding the peer
4674
        // in question.
UNCOV
4675
        s.removePeerUnsafe(ctx, p)
×
UNCOV
4676

×
UNCOV
4677
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4678
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4679
                return
×
UNCOV
4680
        }
×
4681

4682
        // Get the last address that we used to connect to the peer.
UNCOV
4683
        addrs := []net.Addr{
×
UNCOV
4684
                p.NetAddress().Address,
×
UNCOV
4685
        }
×
UNCOV
4686

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

4695
        // The peer doesn't have an advertised address.
UNCOV
4696
        case err == errNoAdvertisedAddr:
×
UNCOV
4697
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4698
                // peer address.
×
UNCOV
4699
                if !p.Inbound() {
×
UNCOV
4700
                        break
×
4701
                }
4702

4703
                // Fall back to the existing peer address if
4704
                // we're not accepting connections over Tor.
UNCOV
4705
                if s.torController == nil {
×
UNCOV
4706
                        break
×
4707
                }
4708

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

4718
        // We came across an error retrieving an advertised
4719
        // address, log it, and fall back to the existing peer
4720
        // address.
UNCOV
4721
        default:
×
UNCOV
4722
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
UNCOV
4723
                        "address for peer", err)
×
4724
        }
4725

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

4733
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4734
        for _, addr := range addrs {
×
UNCOV
4735
                if existingAddrs[addr.String()] {
×
4736
                        continue
×
4737
                }
4738

UNCOV
4739
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4740
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4741
                        &lnwire.NetAddress{
×
UNCOV
4742
                                IdentityKey: p.IdentityKey(),
×
UNCOV
4743
                                Address:     addr,
×
UNCOV
4744
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4745
                        },
×
UNCOV
4746
                )
×
4747
        }
4748

4749
        // Record the computed backoff in the backoff map.
UNCOV
4750
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4751
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4752

×
UNCOV
4753
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4754
        // exist.
×
UNCOV
4755
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4756
        if !ok {
×
UNCOV
4757
                cancelChan = make(chan struct{})
×
UNCOV
4758
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4759
        }
×
4760

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

×
UNCOV
4769
                select {
×
UNCOV
4770
                case <-time.After(backoff):
×
UNCOV
4771
                case <-cancelChan:
×
UNCOV
4772
                        return
×
UNCOV
4773
                case <-s.quit:
×
UNCOV
4774
                        return
×
4775
                }
4776

UNCOV
4777
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
UNCOV
4778
                        "connection")
×
UNCOV
4779

×
UNCOV
4780
                s.connectToPersistentPeer(pubStr)
×
4781
        }()
4782
}
4783

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

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

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

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

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

UNCOV
4834
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4835

×
UNCOV
4836
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4837
        if !ok {
×
UNCOV
4838
                cancelChan = make(chan struct{})
×
UNCOV
4839
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4840
        }
×
4841

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

×
UNCOV
4850
                for _, addr := range addrMap {
×
UNCOV
4851
                        // Send the persistent connection request to the
×
UNCOV
4852
                        // connection manager, saving the request itself so we
×
UNCOV
4853
                        // can cancel/restart the process as needed.
×
UNCOV
4854
                        connReq := &connmgr.ConnReq{
×
UNCOV
4855
                                Addr:      addr,
×
UNCOV
4856
                                Permanent: true,
×
UNCOV
4857
                        }
×
UNCOV
4858

×
UNCOV
4859
                        s.mu.Lock()
×
UNCOV
4860
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4861
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4862
                        )
×
UNCOV
4863
                        s.mu.Unlock()
×
UNCOV
4864

×
UNCOV
4865
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4866
                                "channel peer %v", addr)
×
UNCOV
4867

×
UNCOV
4868
                        go s.connMgr.Connect(connReq)
×
UNCOV
4869

×
UNCOV
4870
                        select {
×
UNCOV
4871
                        case <-s.quit:
×
UNCOV
4872
                                return
×
UNCOV
4873
                        case <-cancelChan:
×
UNCOV
4874
                                return
×
UNCOV
4875
                        case <-ticker.C:
×
4876
                        }
4877
                }
4878
        }()
4879
}
4880

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

UNCOV
4890
        srvrLog.DebugS(ctx, "Removing peer")
×
UNCOV
4891

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

4898
        // Capture the peer's public key and string representation.
UNCOV
4899
        pKey := p.PubKey()
×
UNCOV
4900
        pubSer := pKey[:]
×
UNCOV
4901
        pubStr := string(pubSer)
×
UNCOV
4902

×
UNCOV
4903
        delete(s.peersByPub, pubStr)
×
UNCOV
4904

×
UNCOV
4905
        if p.Inbound() {
×
UNCOV
4906
                delete(s.inboundPeers, pubStr)
×
UNCOV
4907
        } else {
×
UNCOV
4908
                delete(s.outboundPeers, pubStr)
×
UNCOV
4909
        }
×
4910

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

×
UNCOV
4920
                p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
×
UNCOV
4921

×
UNCOV
4922
                // If this peer had an active persistent connection request,
×
UNCOV
4923
                // remove it.
×
UNCOV
4924
                if p.ConnReq() != nil {
×
UNCOV
4925
                        s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4926
                }
×
4927

4928
                // Remove the peer's access permission from the access manager.
UNCOV
4929
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
UNCOV
4930
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
UNCOV
4931

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

×
UNCOV
4943
                // Inform the peer notifier of a peer offline event so that it
×
UNCOV
4944
                // can be reported to clients listening for peer events.
×
UNCOV
4945
                var pubKey [33]byte
×
UNCOV
4946
                copy(pubKey[:], pubSer)
×
UNCOV
4947

×
UNCOV
4948
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
4949
        }()
4950
}
4951

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

×
UNCOV
4960
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4961

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

×
UNCOV
4968
        // Ensure we're not already connected to this peer.
×
UNCOV
4969
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
4970

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

4979
        // Peer was not found, continue to pursue connection with peer.
4980

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

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

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

×
UNCOV
5012
                go s.connMgr.Connect(connReq)
×
UNCOV
5013

×
UNCOV
5014
                return nil
×
5015
        }
UNCOV
5016
        s.mu.Unlock()
×
UNCOV
5017

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

×
UNCOV
5025
        select {
×
UNCOV
5026
        case err := <-errChan:
×
UNCOV
5027
                return err
×
5028
        case <-s.quit:
×
5029
                return ErrServerShuttingDown
×
5030
        }
5031
}
5032

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

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

UNCOV
5051
        close(errChan)
×
UNCOV
5052

×
UNCOV
5053
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
5054
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
5055

×
UNCOV
5056
        s.OutboundPeerConnected(nil, conn)
×
5057
}
5058

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

×
UNCOV
5067
        s.mu.Lock()
×
UNCOV
5068
        defer s.mu.Unlock()
×
UNCOV
5069

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

UNCOV
5078
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
5079

×
UNCOV
5080
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
5081

×
UNCOV
5082
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
5083
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
5084
        // disconnect.
×
UNCOV
5085
        delete(s.persistentPeers, pubStr)
×
UNCOV
5086
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
5087

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

×
UNCOV
5095
        return nil
×
5096
}
5097

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

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

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

×
5119
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5120
                return req.Updates, req.Err
×
5121
        }
×
UNCOV
5122
        req.Peer = peer
×
UNCOV
5123
        s.mu.RUnlock()
×
UNCOV
5124

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

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

×
5145
                return req.Updates, req.Err
×
5146
        }
×
5147

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

×
UNCOV
5154
        return req.Updates, req.Err
×
5155
}
5156

5157
// Peers returns a slice of all active peers.
5158
//
5159
// NOTE: This function is safe for concurrent access.
UNCOV
5160
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
5161
        s.mu.RLock()
×
UNCOV
5162
        defer s.mu.RUnlock()
×
UNCOV
5163

×
UNCOV
5164
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
5165
        for _, peer := range s.peersByPub {
×
UNCOV
5166
                peers = append(peers, peer)
×
UNCOV
5167
        }
×
5168

UNCOV
5169
        return peers
×
5170
}
5171

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

5183
        // Using 1/10 of our duration as a margin, compute a random offset to
5184
        // avoid the nodes entering connection cycles.
UNCOV
5185
        margin := nextBackoff / 10
×
UNCOV
5186

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

5195
        // Otherwise add in our wiggle, but subtract out half of the margin so
5196
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
5197
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5198
}
5199

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

5204
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5205
func (s *server) fetchNodeAdvertisedAddrs(ctx context.Context,
UNCOV
5206
        pub *btcec.PublicKey) ([]net.Addr, error) {
×
UNCOV
5207

×
UNCOV
5208
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
5209
        if err != nil {
×
5210
                return nil, err
×
5211
        }
×
5212

UNCOV
5213
        node, err := s.graphDB.FetchNode(ctx, vertex)
×
UNCOV
5214
        if err != nil {
×
UNCOV
5215
                return nil, err
×
UNCOV
5216
        }
×
5217

UNCOV
5218
        if len(node.Addresses) == 0 {
×
UNCOV
5219
                return nil, errNoAdvertisedAddr
×
UNCOV
5220
        }
×
5221

UNCOV
5222
        return node.Addresses, nil
×
5223
}
5224

5225
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5226
// channel update for a target channel.
5227
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
5228
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
5229

×
UNCOV
5230
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
5231
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
5232
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
5233
                if err != nil {
×
UNCOV
5234
                        return nil, err
×
UNCOV
5235
                }
×
5236

UNCOV
5237
                return netann.ExtractChannelUpdate(
×
UNCOV
5238
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
5239
                )
×
5240
        }
5241
}
5242

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

×
UNCOV
5249
        var (
×
UNCOV
5250
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5251
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5252
        )
×
UNCOV
5253

×
UNCOV
5254
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5255

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

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

5276
// SendCustomMessage sends a custom message to the peer with the specified
5277
// pubkey.
5278
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5279
        data []byte) error {
×
UNCOV
5280

×
UNCOV
5281
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5282
        if err != nil {
×
UNCOV
5283
                return err
×
UNCOV
5284
        }
×
5285

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

UNCOV
5295
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5296
        if err != nil {
×
UNCOV
5297
                return err
×
UNCOV
5298
        }
×
5299

5300
        // Send the message as low-priority. For now we assume that all
5301
        // application-defined message are low priority.
UNCOV
5302
        return peer.SendMessageLazy(true, msg)
×
5303
}
5304

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

×
UNCOV
5313
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5314
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5315
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5316
                        lnwallet.DefaultAccountName,
×
UNCOV
5317
                )
×
UNCOV
5318
                if err != nil {
×
5319
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5320
                }
×
5321

UNCOV
5322
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5323
                if err != nil {
×
5324
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5325
                }
×
5326

UNCOV
5327
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5328
                        wallet, netParams, addr,
×
UNCOV
5329
                )
×
UNCOV
5330
                if err != nil {
×
5331
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5332
                }
×
5333

UNCOV
5334
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5335
                        DeliveryAddress: addr,
×
UNCOV
5336
                        InternalKey:     internalKeyDesc,
×
UNCOV
5337
                })
×
5338
        }
5339
}
5340

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

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

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

UNCOV
5374
        for _, c := range pendings {
×
UNCOV
5375
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5376
                        continue
×
5377
                }
5378

5379
                // If the channel is still reported as pending, remove it from
5380
                // the map.
5381
                delete(closedSCIDs, c.ShortChannelID)
×
5382

×
5383
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5384
                        c.ShortChannelID)
×
5385
        }
5386

UNCOV
5387
        return closedSCIDs
×
5388
}
5389

5390
// getStartingBeat returns the current beat. This is used during the startup to
5391
// initialize blockbeat consumers.
UNCOV
5392
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
UNCOV
5393
        // beat is the current blockbeat.
×
UNCOV
5394
        var beat *chainio.Beat
×
UNCOV
5395

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

×
5402
                return &chainio.Beat{}, nil
×
5403
        }
×
5404

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

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

×
UNCOV
5421
                // Update the current blockbeat.
×
UNCOV
5422
                beat = chainio.NewBeat(*bestBlock)
×
5423

5424
        case <-s.quit:
×
5425
                srvrLog.Debug("LND shutting down")
×
5426
        }
5427

UNCOV
5428
        return beat, nil
×
5429
}
5430

5431
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5432
// point has an active RBF chan closer.
5433
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
UNCOV
5434
        chanPoint wire.OutPoint) bool {
×
UNCOV
5435

×
UNCOV
5436
        pubBytes := peerPub.SerializeCompressed()
×
UNCOV
5437

×
UNCOV
5438
        s.mu.RLock()
×
UNCOV
5439
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
UNCOV
5440
        s.mu.RUnlock()
×
UNCOV
5441
        if !ok {
×
5442
                return false
×
5443
        }
×
5444

UNCOV
5445
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5446
}
5447

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

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

5463
        // From the channel, we can now get the pubkey of the peer, then use
5464
        // that to eventually get the chan closer.
UNCOV
5465
        peerPub := channel.IdentityPub.SerializeCompressed()
×
UNCOV
5466

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

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

UNCOV
5484
        return closeUpdates, nil
×
5485
}
5486

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

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

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

UNCOV
5513
        return updates, nil
×
5514
}
5515

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

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

×
5539
                        listenPorts = append(listenPorts, uint16(port))
×
5540
                }
×
5541

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

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

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

UNCOV
5572
        var (
×
UNCOV
5573
                alias          = s.cfg.Alias
×
UNCOV
5574
                nodeLastUpdate = time.Now()
×
UNCOV
5575
        )
×
UNCOV
5576

×
UNCOV
5577
        srcNode, err := s.graphDB.SourceNode(ctx)
×
UNCOV
5578
        switch {
×
UNCOV
5579
        case err == nil:
×
UNCOV
5580
                // If we have a source node persisted in the DB already, then we
×
UNCOV
5581
                // just need to make sure that the new LastUpdate time is at
×
UNCOV
5582
                // least one second after the last update time.
×
UNCOV
5583
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
×
UNCOV
5584
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
×
UNCOV
5585
                }
×
5586

5587
                // If the color is not changed from default, it means that we
5588
                // didn't specify a different color in the config. We'll use the
5589
                // source node's color.
UNCOV
5590
                if s.cfg.Color == defaultColor {
×
UNCOV
5591
                        color = srcNode.Color
×
UNCOV
5592
                }
×
5593

5594
                // If an alias is not specified in the config, we'll use the
5595
                // source node's alias.
UNCOV
5596
                if alias == "" {
×
UNCOV
5597
                        alias = srcNode.Alias
×
UNCOV
5598
                }
×
5599

5600
                // If the `externalip` is not specified in the config, it means
5601
                // `addrs` will be empty, we'll use the source node's addresses.
UNCOV
5602
                if len(s.cfg.ExternalIPs) == 0 {
×
UNCOV
5603
                        addrs = srcNode.Addresses
×
UNCOV
5604
                }
×
5605

UNCOV
5606
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
×
UNCOV
5607
                // If an alias is not specified in the config, we'll use the
×
UNCOV
5608
                // default, which is the first 10 bytes of the serialized
×
UNCOV
5609
                // pubkey.
×
UNCOV
5610
                if alias == "" {
×
UNCOV
5611
                        alias = hex.EncodeToString(nodePub[:10])
×
UNCOV
5612
                }
×
5613

5614
        // If the above cases are not matched, then we have an unhandled non
5615
        // nil error.
5616
        default:
×
5617
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5618
        }
5619

UNCOV
5620
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
5621
        if err != nil {
×
5622
                return err
×
5623
        }
×
5624

5625
        // TODO(abdulkbk): potentially find a way to use the source node's
5626
        // features in the self node.
UNCOV
5627
        selfNode := &models.Node{
×
UNCOV
5628
                HaveNodeAnnouncement: true,
×
UNCOV
5629
                LastUpdate:           nodeLastUpdate,
×
UNCOV
5630
                Addresses:            addrs,
×
UNCOV
5631
                Alias:                nodeAlias.String(),
×
UNCOV
5632
                Color:                color,
×
UNCOV
5633
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
5634
        }
×
UNCOV
5635

×
UNCOV
5636
        copy(selfNode.PubKeyBytes[:], nodePub[:])
×
UNCOV
5637

×
UNCOV
5638
        // Based on the disk representation of the node announcement generated
×
UNCOV
5639
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
5640
        // network so we can properly sign it.
×
UNCOV
5641
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
5642
        if err != nil {
×
5643
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5644
        }
×
5645

5646
        // With the announcement generated, we'll sign it to properly
5647
        // authenticate the message on the network.
UNCOV
5648
        authSig, err := netann.SignAnnouncement(
×
UNCOV
5649
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
×
UNCOV
5650
        )
×
UNCOV
5651
        if err != nil {
×
5652
                return fmt.Errorf("unable to generate signature for self node "+
×
5653
                        "announcement: %v", err)
×
5654
        }
×
5655

UNCOV
5656
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
5657
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
5658
                selfNode.AuthSigBytes,
×
UNCOV
5659
        )
×
UNCOV
5660
        if err != nil {
×
5661
                return err
×
5662
        }
×
5663

5664
        // Finally, we'll update the representation on disk, and update our
5665
        // cached in-memory version as well.
UNCOV
5666
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
5667
                return fmt.Errorf("can't set self node: %w", err)
×
5668
        }
×
5669

UNCOV
5670
        s.currentNodeAnn = nodeAnn
×
UNCOV
5671

×
UNCOV
5672
        return nil
×
5673
}
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