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

lightningnetwork / lnd / 18852986778

27 Oct 2025 07:10PM UTC coverage: 54.859% (-11.8%) from 66.648%
18852986778

Pull #10265

github

web-flow
Merge 45787b3d5 into 9a7b526c0
Pull Request #10265: multi: update close logic to handle re-orgs of depth n-1, where n is num confs - add min conf floor

529 of 828 new or added lines in 17 files covered. (63.89%)

24026 existing lines in 286 files now uncovered.

110927 of 202205 relevant lines covered (54.86%)

21658.16 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.NodeAnnouncement1
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
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
737
        if err != nil {
×
UNCOV
738
                return nil, err
×
UNCOV
739
        }
×
740

UNCOV
741
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
UNCOV
742
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
UNCOV
743
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
744
        )
×
745
        s.invoices = invoices.NewRegistry(
×
UNCOV
746
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
UNCOV
747
        )
×
UNCOV
748

×
749
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
750

×
UNCOV
751
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
752
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
753

×
UNCOV
754
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
UNCOV
755
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
UNCOV
756
                if err != nil {
×
UNCOV
757
                        return err
×
UNCOV
758
                }
×
759

UNCOV
760
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
761

×
UNCOV
762
                return nil
×
763
        }
764

UNCOV
765
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
766
        if err != nil {
×
UNCOV
767
                return nil, err
×
768
        }
×
769

UNCOV
770
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
UNCOV
771
                DB:                   dbs.ChanStateDB,
×
UNCOV
772
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
×
UNCOV
773
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
UNCOV
774
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
UNCOV
775
                LocalChannelClose: func(pubKey []byte,
×
UNCOV
776
                        request *htlcswitch.ChanClose) {
×
UNCOV
777

×
778
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
779
                        if err != nil {
×
UNCOV
780
                                srvrLog.Errorf("unable to close channel, peer"+
×
UNCOV
781
                                        " with %v id can't be found: %v",
×
UNCOV
782
                                        pubKey, err,
×
UNCOV
783
                                )
×
UNCOV
784
                                return
×
UNCOV
785
                        }
×
786

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

UNCOV
822
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
823
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
824
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
825
        )
×
UNCOV
826

×
UNCOV
827
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
UNCOV
828
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
UNCOV
829
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
830
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
831
                OurPubKey:                nodeKeyDesc.PubKey,
×
UNCOV
832
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
UNCOV
833
                MessageSigner:            s.nodeSigner,
×
UNCOV
834
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
×
UNCOV
835
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
UNCOV
836
                DB:                       s.chanStateDB,
×
UNCOV
837
                Graph:                    dbs.GraphDB,
×
UNCOV
838
        }
×
UNCOV
839

×
UNCOV
840
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
841
        if err != nil {
×
UNCOV
842
                return nil, err
×
UNCOV
843
        }
×
UNCOV
844
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
845

×
UNCOV
846
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
UNCOV
847
        // port forwarding for users behind a NAT.
×
UNCOV
848
        if cfg.NAT {
×
UNCOV
849
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
UNCOV
850

×
UNCOV
851
                discoveryTimeout := time.Duration(10 * time.Second)
×
UNCOV
852

×
853
                ctx, cancel := context.WithTimeout(
×
854
                        context.Background(), discoveryTimeout,
×
UNCOV
855
                )
×
UNCOV
856
                defer cancel()
×
UNCOV
857
                upnp, err := nat.DiscoverUPnP(ctx)
×
UNCOV
858
                if err == nil {
×
UNCOV
859
                        s.natTraversal = upnp
×
860
                } else {
×
861
                        // If we were not able to discover a UPnP enabled device
×
862
                        // on the local network, we'll fall back to attempting
×
863
                        // to discover a NAT-PMP enabled device.
×
864
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
865
                                "device on the local network: %v", err)
×
866

×
867
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
868
                                "enabled device")
×
869

×
870
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
871
                        if err != nil {
×
872
                                err := fmt.Errorf("unable to discover a "+
×
873
                                        "NAT-PMP enabled device on the local "+
×
874
                                        "network: %v", err)
×
875
                                srvrLog.Error(err)
×
876
                                return nil, err
×
877
                        }
×
878

879
                        s.natTraversal = pmp
×
880
                }
881
        }
882

883
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
×
884
        // Set the self node which represents our node in the graph.
×
885
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
×
886
        if err != nil {
×
887
                return nil, err
×
888
        }
×
889

890
        // The router will get access to the payment ID sequencer, such that it
891
        // can generate unique payment IDs.
UNCOV
892
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
893
        if err != nil {
×
UNCOV
894
                return nil, err
×
UNCOV
895
        }
×
896

897
        // Instantiate mission control with config from the sub server.
898
        //
899
        // TODO(joostjager): When we are further in the process of moving to sub
900
        // servers, the mission control instance itself can be moved there too.
UNCOV
901
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
902

×
UNCOV
903
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
904
        var estimator routing.Estimator
×
905
        if cfg.Estimator != nil {
×
906
                estimator = cfg.Estimator
×
UNCOV
907
        } else {
×
UNCOV
908
                switch routingConfig.ProbabilityEstimatorType {
×
UNCOV
909
                case routing.AprioriEstimatorName:
×
UNCOV
910
                        aCfg := routingConfig.AprioriConfig
×
UNCOV
911
                        aprioriConfig := routing.AprioriConfig{
×
UNCOV
912
                                AprioriHopProbability: aCfg.HopProbability,
×
UNCOV
913
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
UNCOV
914
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
915
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
916
                        }
×
917

×
UNCOV
918
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
919
                                aprioriConfig,
×
UNCOV
920
                        )
×
UNCOV
921
                        if err != nil {
×
UNCOV
922
                                return nil, err
×
UNCOV
923
                        }
×
924

UNCOV
925
                case routing.BimodalEstimatorName:
×
UNCOV
926
                        bCfg := routingConfig.BimodalConfig
×
UNCOV
927
                        bimodalConfig := routing.BimodalConfig{
×
UNCOV
928
                                BimodalNodeWeight: bCfg.NodeWeight,
×
UNCOV
929
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
UNCOV
930
                                        bCfg.Scale,
×
UNCOV
931
                                ),
×
UNCOV
932
                                BimodalDecayTime: bCfg.DecayTime,
×
933
                        }
×
934

×
UNCOV
935
                        estimator, err = routing.NewBimodalEstimator(
×
936
                                bimodalConfig,
×
937
                        )
×
938
                        if err != nil {
×
939
                                return nil, err
×
940
                        }
×
941

942
                default:
×
943
                        return nil, fmt.Errorf("unknown estimator type %v",
×
944
                                routingConfig.ProbabilityEstimatorType)
×
945
                }
946
        }
947

948
        mcCfg := &routing.MissionControlConfig{
×
949
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
950
                Estimator:               estimator,
×
951
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
952
                McFlushInterval:         routingConfig.McFlushInterval,
×
953
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
954
        }
×
955

×
UNCOV
956
        s.missionController, err = routing.NewMissionController(
×
UNCOV
957
                dbs.ChanStateDB, nodePubKey, mcCfg,
×
UNCOV
958
        )
×
UNCOV
959
        if err != nil {
×
UNCOV
960
                return nil, fmt.Errorf("can't create mission control "+
×
UNCOV
961
                        "manager: %w", err)
×
UNCOV
962
        }
×
UNCOV
963
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
964
                routing.DefaultMissionControlNamespace,
×
UNCOV
965
        )
×
UNCOV
966
        if err != nil {
×
UNCOV
967
                return nil, fmt.Errorf("can't create mission control in the "+
×
UNCOV
968
                        "default namespace: %w", err)
×
UNCOV
969
        }
×
970

971
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
972
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
973
                int64(routingConfig.AttemptCost),
×
UNCOV
974
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
975
                routingConfig.MinRouteProbability)
×
UNCOV
976

×
UNCOV
977
        pathFindingConfig := routing.PathFindingConfig{
×
978
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
979
                        routingConfig.AttemptCost,
×
980
                ),
×
UNCOV
981
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
982
                MinProbability: routingConfig.MinRouteProbability,
×
UNCOV
983
        }
×
UNCOV
984

×
UNCOV
985
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
×
UNCOV
986
        if err != nil {
×
UNCOV
987
                return nil, fmt.Errorf("error getting source node: %w", err)
×
UNCOV
988
        }
×
UNCOV
989
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
990
                GraphSessionFactory: dbs.GraphDB,
×
UNCOV
991
                SourceNode:          sourceNode,
×
UNCOV
992
                MissionControl:      s.defaultMC,
×
UNCOV
993
                GetLink:             s.htlcSwitch.GetLinkByShortID,
×
UNCOV
994
                PathFindingConfig:   pathFindingConfig,
×
UNCOV
995
        }
×
UNCOV
996

×
UNCOV
997
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
×
998

×
999
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1000
                cfg.Routing.StrictZombiePruning
×
UNCOV
1001

×
UNCOV
1002
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1003
                SelfNode:            nodePubKey,
×
UNCOV
1004
                Graph:               dbs.GraphDB,
×
UNCOV
1005
                Chain:               cc.ChainIO,
×
UNCOV
1006
                ChainView:           cc.ChainView,
×
UNCOV
1007
                Notifier:            cc.ChainNotifier,
×
UNCOV
1008
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1009
                GraphPruneInterval:  time.Hour,
×
UNCOV
1010
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1011
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1012
                StrictZombiePruning: strictPruning,
×
UNCOV
1013
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1014
        })
×
UNCOV
1015
        if err != nil {
×
UNCOV
1016
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
UNCOV
1017
        }
×
1018

UNCOV
1019
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1020
                SelfNode:           nodePubKey,
×
UNCOV
1021
                RoutingGraph:       dbs.GraphDB,
×
UNCOV
1022
                Chain:              cc.ChainIO,
×
UNCOV
1023
                Payer:              s.htlcSwitch,
×
UNCOV
1024
                Control:            s.controlTower,
×
UNCOV
1025
                MissionControl:     s.defaultMC,
×
UNCOV
1026
                SessionSource:      paymentSessionSource,
×
1027
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
1028
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1029
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1030
                Clock:              clock.NewDefaultClock(),
×
UNCOV
1031
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
UNCOV
1032
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1033
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1034
        })
×
UNCOV
1035
        if err != nil {
×
UNCOV
1036
                return nil, fmt.Errorf("can't create router: %w", err)
×
UNCOV
1037
        }
×
1038

UNCOV
1039
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1040
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1041
        if err != nil {
×
UNCOV
1042
                return nil, err
×
UNCOV
1043
        }
×
UNCOV
1044
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1045
        if err != nil {
×
UNCOV
1046
                return nil, err
×
1047
        }
×
1048

UNCOV
1049
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1050

×
UNCOV
1051
        s.authGossiper = discovery.New(discovery.Config{
×
UNCOV
1052
                Graph:                 s.graphBuilder,
×
1053
                ChainIO:               s.cc.ChainIO,
×
1054
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1055
                ChainParams:           s.cfg.ActiveNetParams.Params,
×
UNCOV
1056
                Broadcast:             s.BroadcastMessage,
×
1057
                ChanSeries:            chanSeries,
×
1058
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1059
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1060
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
UNCOV
1061
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
×
UNCOV
1062
                        error) {
×
UNCOV
1063

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

UNCOV
1098
        accessCfg := &accessManConfig{
×
UNCOV
1099
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
UNCOV
1100
                        error) {
×
UNCOV
1101

×
UNCOV
1102
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
×
UNCOV
1103
                        return s.chanStateDB.FetchPermAndTempPeers(
×
UNCOV
1104
                                genesisHash[:],
×
UNCOV
1105
                        )
×
UNCOV
1106
                },
×
1107
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1108
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1109
        }
1110

UNCOV
1111
        peerAccessMan, err := newAccessMan(accessCfg)
×
UNCOV
1112
        if err != nil {
×
UNCOV
1113
                return nil, err
×
UNCOV
1114
        }
×
1115

UNCOV
1116
        s.peerAccessMan = peerAccessMan
×
UNCOV
1117

×
UNCOV
1118
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1119
        //nolint:ll
×
UNCOV
1120
        s.localChanMgr = &localchans.Manager{
×
UNCOV
1121
                SelfPub:              nodeKeyDesc.PubKey,
×
UNCOV
1122
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
UNCOV
1123
                ForAllOutgoingChannels: func(ctx context.Context,
×
1124
                        cb func(*models.ChannelEdgeInfo,
×
1125
                                *models.ChannelEdgePolicy) error,
×
UNCOV
1126
                        reset func()) error {
×
UNCOV
1127

×
UNCOV
1128
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
×
UNCOV
1129
                                func(c *models.ChannelEdgeInfo,
×
UNCOV
1130
                                        e *models.ChannelEdgePolicy,
×
UNCOV
1131
                                        _ *models.ChannelEdgePolicy) error {
×
UNCOV
1132

×
UNCOV
1133
                                        // NOTE: The invoked callback here may
×
UNCOV
1134
                                        // receive a nil channel policy.
×
UNCOV
1135
                                        return cb(c, e)
×
UNCOV
1136
                                }, reset,
×
1137
                        )
1138
                },
1139
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1140
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1141
                FetchChannel:              s.chanStateDB.FetchChannel,
1142
                AddEdge: func(ctx context.Context,
UNCOV
1143
                        edge *models.ChannelEdgeInfo) error {
×
UNCOV
1144

×
UNCOV
1145
                        return s.graphBuilder.AddEdge(ctx, edge)
×
UNCOV
1146
                },
×
1147
        }
1148

UNCOV
1149
        utxnStore, err := contractcourt.NewNurseryStore(
×
UNCOV
1150
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
UNCOV
1151
        )
×
UNCOV
1152
        if err != nil {
×
UNCOV
1153
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1154
                return nil, err
×
1155
        }
×
1156

1157
        sweeperStore, err := sweep.NewSweeperStore(
×
UNCOV
1158
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1159
        )
×
UNCOV
1160
        if err != nil {
×
UNCOV
1161
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
UNCOV
1162
                return nil, err
×
UNCOV
1163
        }
×
1164

1165
        aggregator := sweep.NewBudgetAggregator(
×
1166
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1167
                s.implCfg.AuxSweeper,
×
UNCOV
1168
        )
×
UNCOV
1169

×
UNCOV
1170
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
UNCOV
1171
                Signer:     cc.Wallet.Cfg.Signer,
×
1172
                Wallet:     cc.Wallet,
×
1173
                Estimator:  cc.FeeEstimator,
×
1174
                Notifier:   cc.ChainNotifier,
×
UNCOV
1175
                AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1176
        })
×
UNCOV
1177

×
UNCOV
1178
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
UNCOV
1179
                FeeEstimator: cc.FeeEstimator,
×
UNCOV
1180
                GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1181
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1182
                ),
×
UNCOV
1183
                Signer:               cc.Wallet.Cfg.Signer,
×
UNCOV
1184
                Wallet:               newSweeperWallet(cc.Wallet),
×
UNCOV
1185
                Mempool:              cc.MempoolNotifier,
×
UNCOV
1186
                Notifier:             cc.ChainNotifier,
×
UNCOV
1187
                Store:                sweeperStore,
×
UNCOV
1188
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
UNCOV
1189
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
UNCOV
1190
                Aggregator:           aggregator,
×
UNCOV
1191
                Publisher:            s.txPublisher,
×
UNCOV
1192
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
UNCOV
1193
        })
×
UNCOV
1194

×
UNCOV
1195
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
UNCOV
1196
                ChainIO:             cc.ChainIO,
×
UNCOV
1197
                ConfDepth:           1,
×
UNCOV
1198
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
UNCOV
1199
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
UNCOV
1200
                Notifier:            cc.ChainNotifier,
×
UNCOV
1201
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
UNCOV
1202
                Store:               utxnStore,
×
UNCOV
1203
                SweepInput:          s.sweeper.SweepInput,
×
UNCOV
1204
                Budget:              s.cfg.Sweeper.Budget,
×
UNCOV
1205
        })
×
UNCOV
1206

×
UNCOV
1207
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
UNCOV
1208
        closeLink := func(chanPoint *wire.OutPoint,
×
UNCOV
1209
                closureType contractcourt.ChannelCloseType) {
×
UNCOV
1210
                // TODO(conner): Properly respect the update and error channels
×
UNCOV
1211
                // returned by CloseLink.
×
UNCOV
1212

×
UNCOV
1213
                // Instruct the switch to close the channel.  Provide no close out
×
UNCOV
1214
                // delivery script or target fee per kw because user input is not
×
UNCOV
1215
                // available when the remote peer closes the channel.
×
UNCOV
1216
                s.htlcSwitch.CloseLink(
×
UNCOV
1217
                        context.Background(), chanPoint, closureType, 0, 0, nil,
×
UNCOV
1218
                )
×
UNCOV
1219
        }
×
1220

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

×
UNCOV
1225
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
UNCOV
1226
                &contractcourt.BreachConfig{
×
UNCOV
1227
                        CloseLink: closeLink,
×
UNCOV
1228
                        DB:        s.chanStateDB,
×
UNCOV
1229
                        Estimator: s.cc.FeeEstimator,
×
UNCOV
1230
                        GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1231
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1232
                        ),
×
UNCOV
1233
                        Notifier:           cc.ChainNotifier,
×
UNCOV
1234
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1235
                        ContractBreaches:   contractBreaches,
×
UNCOV
1236
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1237
                        Store: contractcourt.NewRetributionStore(
×
UNCOV
1238
                                dbs.ChanStateDB,
×
UNCOV
1239
                        ),
×
UNCOV
1240
                        AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1241
                },
×
UNCOV
1242
        )
×
UNCOV
1243

×
UNCOV
1244
        //nolint:ll
×
UNCOV
1245
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
UNCOV
1246
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1247
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
UNCOV
1248
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
UNCOV
1249
                NewSweepAddr: func() ([]byte, error) {
×
UNCOV
1250
                        addr, err := newSweepPkScriptGen(
×
UNCOV
1251
                                cc.Wallet, netParams,
×
UNCOV
1252
                        )().Unpack()
×
UNCOV
1253
                        if err != nil {
×
UNCOV
1254
                                return nil, err
×
UNCOV
1255
                        }
×
1256

UNCOV
1257
                        return addr.DeliveryAddress, nil
×
1258
                },
1259
                PublishTx: cc.Wallet.PublishTransaction,
UNCOV
1260
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
1261
                        for _, msg := range msgs {
×
1262
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
1263
                                if err != nil {
×
1264
                                        return err
×
1265
                                }
×
1266
                        }
UNCOV
1267
                        return nil
×
1268
                },
1269
                IncubateOutputs: func(chanPoint wire.OutPoint,
1270
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1271
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1272
                        broadcastHeight uint32,
UNCOV
1273
                        deadlineHeight fn.Option[int32]) error {
×
UNCOV
1274

×
1275
                        return s.utxoNursery.IncubateOutputs(
×
1276
                                chanPoint, outHtlcRes, inHtlcRes,
×
UNCOV
1277
                                broadcastHeight, deadlineHeight,
×
UNCOV
1278
                        )
×
UNCOV
1279
                },
×
1280
                PreimageDB:   s.witnessBeacon,
1281
                Notifier:     cc.ChainNotifier,
1282
                Mempool:      cc.MempoolNotifier,
1283
                Signer:       cc.Wallet.Cfg.Signer,
1284
                FeeEstimator: cc.FeeEstimator,
1285
                ChainIO:      cc.ChainIO,
UNCOV
1286
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
UNCOV
1287
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1288
                        s.htlcSwitch.RemoveLink(chanID)
×
UNCOV
1289
                        return nil
×
UNCOV
1290
                },
×
1291
                IsOurAddress: cc.Wallet.IsOurAddress,
1292
                ContractBreach: func(chanPoint wire.OutPoint,
UNCOV
1293
                        breachRet *lnwallet.BreachRetribution) error {
×
UNCOV
1294

×
UNCOV
1295
                        // processACK will handle the BreachArbitrator ACKing
×
UNCOV
1296
                        // the event.
×
UNCOV
1297
                        finalErr := make(chan error, 1)
×
UNCOV
1298
                        processACK := func(brarErr error) {
×
UNCOV
1299
                                if brarErr != nil {
×
UNCOV
1300
                                        finalErr <- brarErr
×
UNCOV
1301
                                        return
×
UNCOV
1302
                                }
×
1303

1304
                                // If the BreachArbitrator successfully handled
1305
                                // the event, we can signal that the handoff
1306
                                // was successful.
UNCOV
1307
                                finalErr <- nil
×
1308
                        }
1309

UNCOV
1310
                        event := &contractcourt.ContractBreachEvent{
×
1311
                                ChanPoint:         chanPoint,
×
1312
                                ProcessACK:        processACK,
×
1313
                                BreachRetribution: breachRet,
×
UNCOV
1314
                        }
×
UNCOV
1315

×
UNCOV
1316
                        // Send the contract breach event to the
×
UNCOV
1317
                        // BreachArbitrator.
×
UNCOV
1318
                        select {
×
UNCOV
1319
                        case contractBreaches <- event:
×
UNCOV
1320
                        case <-s.quit:
×
UNCOV
1321
                                return ErrServerShuttingDown
×
1322
                        }
1323

1324
                        // We'll wait for a final error to be available from
1325
                        // the BreachArbitrator.
UNCOV
1326
                        select {
×
UNCOV
1327
                        case err := <-finalErr:
×
UNCOV
1328
                                return err
×
UNCOV
1329
                        case <-s.quit:
×
UNCOV
1330
                                return ErrServerShuttingDown
×
1331
                        }
1332
                },
UNCOV
1333
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
UNCOV
1334
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
UNCOV
1335
                },
×
1336
                Sweeper:                       s.sweeper,
1337
                Registry:                      s.invoices,
1338
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1339
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1340
                OnionProcessor:                s.sphinx,
1341
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1342
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1343
                Clock:                         clock.NewDefaultClock(),
1344
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1345
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1346
                HtlcNotifier:                  s.htlcNotifier,
1347
                Budget:                        *s.cfg.Sweeper.Budget,
1348

1349
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1350
                QueryIncomingCircuit: func(
UNCOV
1351
                        circuit models.CircuitKey) *models.CircuitKey {
×
UNCOV
1352

×
UNCOV
1353
                        // Get the circuit map.
×
UNCOV
1354
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1355

×
UNCOV
1356
                        // Lookup the outgoing circuit.
×
UNCOV
1357
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1358
                        if pc == nil {
×
UNCOV
1359
                                return nil
×
UNCOV
1360
                        }
×
1361

UNCOV
1362
                        return &pc.Incoming
×
1363
                },
1364
                AuxLeafStore:   implCfg.AuxLeafStore,
1365
                AuxSigner:      implCfg.AuxSigner,
1366
                AuxResolver:    implCfg.AuxContractResolver,
1367
                ChannelCloseConfs: s.cfg.Dev.ChannelCloseConfs(),
1368
        }, dbs.ChanStateDB)
1369

1370
        // Select the configuration and funding parameters for Bitcoin.
UNCOV
1371
        chainCfg := cfg.Bitcoin
×
UNCOV
1372
        minRemoteDelay := funding.MinBtcRemoteDelay
×
UNCOV
1373
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
UNCOV
1374

×
NEW
1375
        var chanIDSeed [32]byte
×
NEW
1376
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
NEW
1377
                return nil, err
×
NEW
1378
        }
×
1379

1380
        // Wrap the DeleteChannelEdges method so that the funding manager can
1381
        // use it without depending on several layers of indirection.
UNCOV
1382
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
UNCOV
1383
                *models.ChannelEdgePolicy, error) {
×
UNCOV
1384

×
UNCOV
1385
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
UNCOV
1386
                        scid.ToUint64(),
×
UNCOV
1387
                )
×
1388
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1389
                        // This is unlikely but there is a slim chance of this
×
UNCOV
1390
                        // being hit if lnd was killed via SIGKILL and the
×
UNCOV
1391
                        // funding manager was stepping through the delete
×
UNCOV
1392
                        // alias edge logic.
×
UNCOV
1393
                        return nil, nil
×
UNCOV
1394
                } else if err != nil {
×
UNCOV
1395
                        return nil, err
×
UNCOV
1396
                }
×
1397

1398
                // Grab our key to find our policy.
UNCOV
1399
                var ourKey [33]byte
×
1400
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
1401

×
1402
                var ourPolicy *models.ChannelEdgePolicy
×
1403
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1404
                        ourPolicy = e1
×
UNCOV
1405
                } else {
×
1406
                        ourPolicy = e2
×
1407
                }
×
1408

UNCOV
1409
                if ourPolicy == nil {
×
UNCOV
1410
                        // Something is wrong, so return an error.
×
UNCOV
1411
                        return nil, fmt.Errorf("we don't have an edge")
×
UNCOV
1412
                }
×
1413

UNCOV
1414
                err = s.graphDB.DeleteChannelEdges(
×
UNCOV
1415
                        false, false, scid.ToUint64(),
×
UNCOV
1416
                )
×
UNCOV
1417
                return ourPolicy, err
×
1418
        }
1419

1420
        // For the reservationTimeout and the zombieSweeperInterval different
1421
        // values are set in case we are in a dev environment so enhance test
1422
        // capacilities.
1423
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1424
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1425

×
UNCOV
1426
        // Get the development config for funding manager. If we are not in
×
UNCOV
1427
        // development mode, this would be nil.
×
UNCOV
1428
        var devCfg *funding.DevConfig
×
UNCOV
1429
        if lncfg.IsDevBuild() {
×
UNCOV
1430
                devCfg = &funding.DevConfig{
×
UNCOV
1431
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1432
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
×
UNCOV
1433
                                GetMaxWaitNumBlocksFundingConf(),
×
UNCOV
1434
                }
×
UNCOV
1435

×
UNCOV
1436
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1437
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1438

×
UNCOV
1439
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1440
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1441
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1442
        }
×
1443

1444
        //nolint:ll
UNCOV
1445
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1446
                Dev:                devCfg,
×
UNCOV
1447
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1448
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1449
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1450
                Wallet:             cc.Wallet,
×
UNCOV
1451
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1452
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1453
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1454
                },
×
1455
                Notifier:     cc.ChainNotifier,
1456
                ChannelDB:    s.chanStateDB,
1457
                FeeEstimator: cc.FeeEstimator,
1458
                SignMessage:  cc.MsgSigner.SignMessage,
1459
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
UNCOV
1460
                        error) {
×
UNCOV
1461

×
UNCOV
1462
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1463
                },
×
1464
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1465
                NotifyWhenOnline:     s.NotifyWhenOnline,
1466
                TempChanIDSeed:       chanIDSeed,
1467
                FindChannel:          s.findChannel,
1468
                DefaultRoutingPolicy: cc.RoutingPolicy,
1469
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1470
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1471
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1472
                        // In case the user has explicitly specified
×
UNCOV
1473
                        // a default value for the number of
×
UNCOV
1474
                        // confirmations, we use it.
×
UNCOV
1475
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1476
                        if defaultConf != 0 {
×
UNCOV
1477
                                return defaultConf
×
UNCOV
1478
                        }
×
1479

1480
                        // Otherwise, scale the number of confirmations based on
1481
                        // the channel amount and push amount. For large
1482
                        // channels we increase the number of
1483
                        // confirmations we require for the channel to be
1484
                        // considered open. As it is always the
1485
                        // responder that gets to choose value, the
1486
                        // pushAmt is value being pushed to us. This
1487
                        // means we have more to lose in the case this
1488
                        // gets re-orged out, and we will require more
1489
                        // confirmations before we consider it open.
UNCOV
1490
                        return lnwallet.FundingConfsForAmounts(chanAmt, pushAmt)
×
1491
                },
NEW
1492
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
NEW
1493
                        // We scale the remote CSV delay (the time the
×
NEW
1494
                        // remote have to claim funds in case of a unilateral
×
NEW
1495
                        // close) linearly from minRemoteDelay blocks
×
NEW
1496
                        // for small channels, to maxRemoteDelay blocks
×
NEW
1497
                        // for channels of size MaxFundingAmount.
×
NEW
1498

×
NEW
1499
                        // In case the user has explicitly specified
×
NEW
1500
                        // a default value for the remote delay, we
×
NEW
1501
                        // use it.
×
UNCOV
1502
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1503
                        if defaultDelay > 0 {
×
UNCOV
1504
                                return defaultDelay
×
UNCOV
1505
                        }
×
1506

1507
                        // If this is a wumbo channel, then we'll require the
1508
                        // max value.
UNCOV
1509
                        if chanAmt > MaxFundingAmount {
×
UNCOV
1510
                                return maxRemoteDelay
×
UNCOV
1511
                        }
×
1512

1513
                        // If not we scale according to channel size.
UNCOV
1514
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
UNCOV
1515
                                chanAmt / MaxFundingAmount)
×
UNCOV
1516
                        if delay < minRemoteDelay {
×
UNCOV
1517
                                delay = minRemoteDelay
×
UNCOV
1518
                        }
×
UNCOV
1519
                        if delay > maxRemoteDelay {
×
1520
                                delay = maxRemoteDelay
×
1521
                        }
×
1522
                        return delay
×
1523
                },
1524
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1525
                        peerKey *btcec.PublicKey) error {
×
1526

×
1527
                        // First, we'll mark this new peer as a persistent peer
×
1528
                        // for re-connection purposes. If the peer is not yet
×
1529
                        // tracked or the user hasn't requested it to be perm,
×
1530
                        // we'll set false to prevent the server from continuing
×
1531
                        // to connect to this peer even if the number of
×
1532
                        // channels with this peer is zero.
×
1533
                        s.mu.Lock()
×
UNCOV
1534
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1535
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1536
                                s.persistentPeers[pubStr] = false
×
UNCOV
1537
                        }
×
UNCOV
1538
                        s.mu.Unlock()
×
UNCOV
1539

×
UNCOV
1540
                        // With that taken care of, we'll send this channel to
×
UNCOV
1541
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1542
                        return s.chainArb.WatchNewChannel(channel)
×
1543
                },
UNCOV
1544
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1545
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1546
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1547
                },
×
1548
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1549
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1550

×
UNCOV
1551
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1552
                        // at least 1% of the total channel capacity at all
×
UNCOV
1553
                        // times. If this value ends up dipping below the dust
×
UNCOV
1554
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1555
                        // reserve as required by BOLT #2.
×
UNCOV
1556
                        reserve := chanAmt / 100
×
UNCOV
1557
                        if reserve < dustLimit {
×
UNCOV
1558
                                reserve = dustLimit
×
UNCOV
1559
                        }
×
1560

UNCOV
1561
                        return reserve
×
1562
                },
UNCOV
1563
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1564
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1565
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1566
                        // required reserve.
×
UNCOV
1567
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1568
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1569
                },
×
UNCOV
1570
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1571
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1572
                                return cfg.DefaultRemoteMaxHtlcs
×
UNCOV
1573
                        }
×
1574

1575
                        // By default, we'll permit them to utilize the full
1576
                        // channel bandwidth.
UNCOV
1577
                        return uint16(input.MaxHTLCNumber / 2)
×
1578
                },
1579
                ZombieSweeperInterval:         zombieSweeperInterval,
1580
                ReservationTimeout:            reservationTimeout,
1581
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1582
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1583
                MaxPendingChannels:            cfg.MaxPendingChannels,
1584
                RejectPush:                    cfg.RejectPush,
1585
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1586
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1587
                OpenChannelPredicate:          chanPredicate,
1588
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1589
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1590
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1591
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1592
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1593
                DeleteAliasEdge:      deleteAliasEdge,
1594
                AliasManager:         s.aliasMgr,
1595
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1596
                AuxFundingController: implCfg.AuxFundingController,
1597
                AuxSigner:            implCfg.AuxSigner,
1598
                AuxResolver:          implCfg.AuxContractResolver,
1599
                AuxChannelNegotiator: implCfg.AuxChannelNegotiator,
1600
        })
UNCOV
1601
        if err != nil {
×
UNCOV
1602
                return nil, err
×
UNCOV
1603
        }
×
1604

1605
        // Next, we'll assemble the sub-system that will maintain an on-disk
1606
        // static backup of the latest channel state.
UNCOV
1607
        chanNotifier := &channelNotifier{
×
UNCOV
1608
                chanNotifier: s.channelNotifier,
×
UNCOV
1609
                addrs:        s.addrSource,
×
UNCOV
1610
        }
×
UNCOV
1611
        backupFile := chanbackup.NewMultiFile(
×
UNCOV
1612
                cfg.BackupFilePath, cfg.NoBackupArchive,
×
1613
        )
×
1614
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1615
                ctx, s.chanStateDB, s.addrSource,
×
UNCOV
1616
        )
×
UNCOV
1617
        if err != nil {
×
UNCOV
1618
                return nil, err
×
UNCOV
1619
        }
×
UNCOV
1620
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1621
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1622
        )
×
UNCOV
1623
        if err != nil {
×
UNCOV
1624
                return nil, err
×
UNCOV
1625
        }
×
1626

1627
        // Assemble a peer notifier which will provide clients with subscriptions
1628
        // to peer online and offline events.
1629
        s.peerNotifier = peernotifier.New()
×
1630

×
UNCOV
1631
        // Create a channel event store which monitors all open channels.
×
UNCOV
1632
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1633
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1634
                        return s.channelNotifier.SubscribeChannelEvents()
×
1635
                },
×
1636
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1637
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1638
                },
×
1639
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1640
                Clock:           clock.NewDefaultClock(),
1641
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1642
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1643
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1644
        })
1645

UNCOV
1646
        if cfg.WtClient.Active {
×
UNCOV
1647
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1648
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1649

×
UNCOV
1650
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1651
                // protocol operations on sat/kw.
×
UNCOV
1652
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1653
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1654
                )
×
UNCOV
1655

×
UNCOV
1656
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1657

×
UNCOV
1658
                if err := policy.Validate(); err != nil {
×
UNCOV
1659
                        return nil, err
×
UNCOV
1660
                }
×
1661

1662
                // authDial is the wrapper around the btrontide.Dial for the
1663
                // watchtower.
UNCOV
1664
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1665
                        netAddr *lnwire.NetAddress,
×
UNCOV
1666
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1667

×
UNCOV
1668
                        return brontide.Dial(
×
UNCOV
1669
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
1670
                        )
×
1671
                }
×
1672

1673
                // buildBreachRetribution is a call-back that can be used to
1674
                // query the BreachRetribution info and channel type given a
1675
                // channel ID and commitment height.
UNCOV
1676
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1677
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1678
                        channeldb.ChannelType, error) {
×
UNCOV
1679

×
UNCOV
1680
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1681
                                nil, chanID,
×
UNCOV
1682
                        )
×
UNCOV
1683
                        if err != nil {
×
UNCOV
1684
                                return nil, 0, err
×
UNCOV
1685
                        }
×
1686

UNCOV
1687
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1688
                                channel, commitHeight, 0, nil,
×
UNCOV
1689
                                implCfg.AuxLeafStore,
×
UNCOV
1690
                                implCfg.AuxContractResolver,
×
UNCOV
1691
                        )
×
UNCOV
1692
                        if err != nil {
×
UNCOV
1693
                                return nil, 0, err
×
UNCOV
1694
                        }
×
1695

1696
                        return br, channel.ChanType, nil
×
1697
                }
1698

UNCOV
1699
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1700

×
UNCOV
1701
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1702
                // signalling support for anchor channels.
×
UNCOV
1703
                anchorPolicy := policy
×
1704
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
1705

×
UNCOV
1706
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1707
                // signalling support for taproot channels.
×
UNCOV
1708
                taprootPolicy := policy
×
UNCOV
1709
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1710
                        blob.FlagTaprootChannel,
×
UNCOV
1711
                )
×
UNCOV
1712

×
UNCOV
1713
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1714
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1715
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1716
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1717
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1718
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1719
                                error) {
×
UNCOV
1720

×
UNCOV
1721
                                return s.channelNotifier.
×
UNCOV
1722
                                        SubscribeChannelEvents()
×
UNCOV
1723
                        },
×
1724
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1725
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1726
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1727
                                        cc.Wallet, netParams,
×
UNCOV
1728
                                )().Unpack()
×
UNCOV
1729
                                if err != nil {
×
UNCOV
1730
                                        return nil, err
×
UNCOV
1731
                                }
×
1732

UNCOV
1733
                                return addr.DeliveryAddress, nil
×
1734
                        },
1735
                        SecretKeyRing:      s.cc.KeyRing,
1736
                        Dial:               cfg.net.Dial,
1737
                        AuthDial:           authDial,
1738
                        DB:                 dbs.TowerClientDB,
1739
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1740
                        MinBackoff:         10 * time.Second,
1741
                        MaxBackoff:         5 * time.Minute,
1742
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1743
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1744
                if err != nil {
×
UNCOV
1745
                        return nil, err
×
UNCOV
1746
                }
×
1747
        }
1748

UNCOV
1749
        if len(cfg.ExternalHosts) != 0 {
×
UNCOV
1750
                advertisedIPs := make(map[string]struct{})
×
UNCOV
1751
                for _, addr := range s.currentNodeAnn.Addresses {
×
UNCOV
1752
                        advertisedIPs[addr.String()] = struct{}{}
×
UNCOV
1753
                }
×
1754

UNCOV
1755
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1756
                        Hosts:         cfg.ExternalHosts,
×
1757
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
UNCOV
1758
                        LookupHost: func(host string) (net.Addr, error) {
×
UNCOV
1759
                                return lncfg.ParseAddressString(
×
UNCOV
1760
                                        host, strconv.Itoa(defaultPeerPort),
×
1761
                                        cfg.net.ResolveTCPAddr,
×
1762
                                )
×
1763
                        },
×
1764
                        AdvertisedIPs: advertisedIPs,
1765
                        AnnounceNewIPs: netann.IPAnnouncer(
1766
                                func(modifier ...netann.NodeAnnModifier) (
1767
                                        lnwire.NodeAnnouncement1, error) {
×
1768

×
1769
                                        return s.genNodeAnnouncement(
×
1770
                                                nil, modifier...,
×
1771
                                        )
×
1772
                                }),
×
1773
                })
1774
        }
1775

1776
        // Create liveness monitor.
UNCOV
1777
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1778

×
1779
        listeners := make([]net.Listener, len(listenAddrs))
×
1780
        for i, listenAddr := range listenAddrs {
×
1781
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
1782
                // doesn't need to call the general lndResolveTCP function
×
1783
                // since we are resolving a local address.
×
UNCOV
1784

×
UNCOV
1785
                // RESOLVE: We are actually partially accepting inbound
×
UNCOV
1786
                // connection requests when we call NewListener.
×
UNCOV
1787
                listeners[i], err = brontide.NewListener(
×
UNCOV
1788
                        nodeKeyECDH, listenAddr.String(),
×
UNCOV
1789
                        // TODO(yy): remove this check and unify the inbound
×
UNCOV
1790
                        // connection check inside `InboundPeerConnected`.
×
UNCOV
1791
                        s.peerAccessMan.checkAcceptIncomingConn,
×
UNCOV
1792
                )
×
UNCOV
1793
                if err != nil {
×
UNCOV
1794
                        return nil, err
×
UNCOV
1795
                }
×
1796
        }
1797

1798
        // Create the connection manager which will be responsible for
1799
        // maintaining persistent outbound connections and also accepting new
1800
        // incoming connections
UNCOV
1801
        cmgr, err := connmgr.New(&connmgr.Config{
×
UNCOV
1802
                Listeners:      listeners,
×
UNCOV
1803
                OnAccept:       s.InboundPeerConnected,
×
UNCOV
1804
                RetryDuration:  time.Second * 5,
×
1805
                TargetOutbound: 100,
×
1806
                Dial: noiseDial(
×
UNCOV
1807
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
1808
                ),
×
UNCOV
1809
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
1810
        })
×
UNCOV
1811
        if err != nil {
×
UNCOV
1812
                return nil, err
×
UNCOV
1813
        }
×
UNCOV
1814
        s.connMgr = cmgr
×
UNCOV
1815

×
UNCOV
1816
        // Finally, register the subsystems in blockbeat.
×
UNCOV
1817
        s.registerBlockConsumers()
×
UNCOV
1818

×
UNCOV
1819
        return s, nil
×
1820
}
1821

1822
// UpdateRoutingConfig is a callback function to update the routing config
1823
// values in the main cfg.
1824
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
1825
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
1826

×
UNCOV
1827
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
1828
        case routing.AprioriConfig:
×
UNCOV
1829
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1830
                        routing.AprioriEstimatorName
×
UNCOV
1831

×
UNCOV
1832
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1833
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1834
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1835
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1836
                targetCfg.HopProbability = c.AprioriHopProbability
×
1837

UNCOV
1838
        case routing.BimodalConfig:
×
UNCOV
1839
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1840
                        routing.BimodalEstimatorName
×
UNCOV
1841

×
UNCOV
1842
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1843
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1844
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1845
                targetCfg.DecayTime = c.BimodalDecayTime
×
1846
        }
1847

UNCOV
1848
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1849
}
1850

1851
// registerBlockConsumers registers the subsystems that consume block events.
1852
// By calling `RegisterQueue`, a list of subsystems are registered in the
1853
// blockbeat for block notifications. When a new block arrives, the subsystems
1854
// in the same queue are notified sequentially, and different queues are
1855
// notified concurrently.
1856
//
1857
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1858
// a new `RegisterQueue` call.
UNCOV
1859
func (s *server) registerBlockConsumers() {
×
UNCOV
1860
        // In this queue, when a new block arrives, it will be received and
×
UNCOV
1861
        // processed in this order: chainArb -> sweeper -> txPublisher.
×
UNCOV
1862
        consumers := []chainio.Consumer{
×
UNCOV
1863
                s.chainArb,
×
UNCOV
1864
                s.sweeper,
×
UNCOV
1865
                s.txPublisher,
×
UNCOV
1866
        }
×
UNCOV
1867
        s.blockbeatDispatcher.RegisterQueue(consumers)
×
UNCOV
1868
}
×
1869

1870
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1871
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1872
// may differ from what is on disk.
1873
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
1874
        error) {
×
UNCOV
1875

×
UNCOV
1876
        data, err := u.DataToSign()
×
UNCOV
1877
        if err != nil {
×
UNCOV
1878
                return nil, err
×
UNCOV
1879
        }
×
1880

UNCOV
1881
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1882
}
1883

1884
// createLivenessMonitor creates a set of health checks using our configured
1885
// values and uses these checks to create a liveness monitor. Available
1886
// health checks,
1887
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1888
//   - diskCheck
1889
//   - tlsHealthCheck
1890
//   - torController, only created when tor is enabled.
1891
//
1892
// If a health check has been disabled by setting attempts to 0, our monitor
1893
// will not run it.
1894
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
UNCOV
1895
        leaderElector cluster.LeaderElector) {
×
UNCOV
1896

×
UNCOV
1897
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
1898
        if cfg.Bitcoin.Node == "nochainbackend" {
×
UNCOV
1899
                srvrLog.Info("Disabling chain backend checks for " +
×
UNCOV
1900
                        "nochainbackend mode")
×
UNCOV
1901

×
UNCOV
1902
                chainBackendAttempts = 0
×
UNCOV
1903
        }
×
1904

UNCOV
1905
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
1906
                "chain backend",
×
UNCOV
1907
                cc.HealthCheck,
×
UNCOV
1908
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
1909
                cfg.HealthChecks.ChainCheck.Timeout,
×
1910
                cfg.HealthChecks.ChainCheck.Backoff,
×
1911
                chainBackendAttempts,
×
1912
        )
×
1913

×
1914
        diskCheck := healthcheck.NewObservation(
×
UNCOV
1915
                "disk space",
×
UNCOV
1916
                func() error {
×
UNCOV
1917
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
UNCOV
1918
                                cfg.LndDir,
×
UNCOV
1919
                        )
×
UNCOV
1920
                        if err != nil {
×
UNCOV
1921
                                return err
×
UNCOV
1922
                        }
×
1923

1924
                        // If we have more free space than we require,
1925
                        // we return a nil error.
UNCOV
1926
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
UNCOV
1927
                                return nil
×
1928
                        }
×
1929

1930
                        return fmt.Errorf("require: %v free space, got: %v",
×
1931
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1932
                                free)
×
1933
                },
1934
                cfg.HealthChecks.DiskCheck.Interval,
1935
                cfg.HealthChecks.DiskCheck.Timeout,
1936
                cfg.HealthChecks.DiskCheck.Backoff,
1937
                cfg.HealthChecks.DiskCheck.Attempts,
1938
        )
1939

UNCOV
1940
        tlsHealthCheck := healthcheck.NewObservation(
×
1941
                "tls",
×
1942
                func() error {
×
1943
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
UNCOV
1944
                                s.cc.KeyRing,
×
UNCOV
1945
                        )
×
UNCOV
1946
                        if err != nil {
×
UNCOV
1947
                                return err
×
UNCOV
1948
                        }
×
UNCOV
1949
                        if expired {
×
UNCOV
1950
                                return fmt.Errorf("TLS certificate is "+
×
UNCOV
1951
                                        "expired as of %v", expTime)
×
UNCOV
1952
                        }
×
1953

1954
                        // If the certificate is not outdated, no error needs
1955
                        // to be returned
1956
                        return nil
×
1957
                },
1958
                cfg.HealthChecks.TLSCheck.Interval,
1959
                cfg.HealthChecks.TLSCheck.Timeout,
1960
                cfg.HealthChecks.TLSCheck.Backoff,
1961
                cfg.HealthChecks.TLSCheck.Attempts,
1962
        )
1963

UNCOV
1964
        checks := []*healthcheck.Observation{
×
UNCOV
1965
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
1966
        }
×
1967

×
UNCOV
1968
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
1969
        if s.torController != nil {
×
UNCOV
1970
                torConnectionCheck := healthcheck.NewObservation(
×
UNCOV
1971
                        "tor connection",
×
UNCOV
1972
                        func() error {
×
UNCOV
1973
                                return healthcheck.CheckTorServiceStatus(
×
UNCOV
1974
                                        s.torController,
×
UNCOV
1975
                                        func() error {
×
UNCOV
1976
                                                return s.createNewHiddenService(
×
UNCOV
1977
                                                        context.TODO(),
×
UNCOV
1978
                                                )
×
UNCOV
1979
                                        },
×
1980
                                )
1981
                        },
1982
                        cfg.HealthChecks.TorConnection.Interval,
1983
                        cfg.HealthChecks.TorConnection.Timeout,
1984
                        cfg.HealthChecks.TorConnection.Backoff,
1985
                        cfg.HealthChecks.TorConnection.Attempts,
1986
                )
1987
                checks = append(checks, torConnectionCheck)
×
1988
        }
1989

1990
        // If remote signing is enabled, add the healthcheck for the remote
1991
        // signing RPC interface.
UNCOV
1992
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
1993
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
1994
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
1995
                // returns exactly on time.
×
UNCOV
1996
                overhead := time.Millisecond * 10
×
UNCOV
1997

×
1998
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
1999
                        "remote signer connection",
×
UNCOV
2000
                        rpcwallet.HealthCheck(
×
UNCOV
2001
                                s.cfg.RemoteSigner,
×
UNCOV
2002

×
UNCOV
2003
                                // For the health check we might to be even
×
UNCOV
2004
                                // stricter than the initial/normal connect, so
×
UNCOV
2005
                                // we use the health check timeout here.
×
UNCOV
2006
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
2007
                        ),
×
UNCOV
2008
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
2009
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
2010
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
2011
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
2012
                )
×
UNCOV
2013
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
2014
        }
×
2015

2016
        // If we have a leader elector, we add a health check to ensure we are
2017
        // still the leader. During normal operation, we should always be the
2018
        // leader, but there are circumstances where this may change, such as
2019
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
2020
        if leaderElector != nil {
×
UNCOV
2021
                leaderCheck := healthcheck.NewObservation(
×
UNCOV
2022
                        "leader status",
×
UNCOV
2023
                        func() error {
×
UNCOV
2024
                                // Check if we are still the leader. Note that
×
UNCOV
2025
                                // we don't need to use a timeout context here
×
UNCOV
2026
                                // as the healthcheck observer will handle the
×
UNCOV
2027
                                // timeout case for us.
×
UNCOV
2028
                                timeoutCtx, cancel := context.WithTimeout(
×
UNCOV
2029
                                        context.Background(),
×
UNCOV
2030
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
UNCOV
2031
                                )
×
2032
                                defer cancel()
×
2033

×
2034
                                leader, err := leaderElector.IsLeader(
×
2035
                                        timeoutCtx,
×
2036
                                )
×
2037
                                if err != nil {
×
2038
                                        return fmt.Errorf("unable to check if "+
×
2039
                                                "still leader: %v", err)
×
2040
                                }
×
2041

2042
                                if !leader {
×
2043
                                        srvrLog.Debug("Not the current leader")
×
2044
                                        return fmt.Errorf("not the current " +
×
2045
                                                "leader")
×
2046
                                }
×
2047

2048
                                return nil
×
2049
                        },
2050
                        cfg.HealthChecks.LeaderCheck.Interval,
2051
                        cfg.HealthChecks.LeaderCheck.Timeout,
2052
                        cfg.HealthChecks.LeaderCheck.Backoff,
2053
                        cfg.HealthChecks.LeaderCheck.Attempts,
2054
                )
2055

2056
                checks = append(checks, leaderCheck)
×
2057
        }
2058

2059
        // If we have not disabled all of our health checks, we create a
2060
        // liveness monitor with our configured checks.
UNCOV
2061
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2062
                &healthcheck.Config{
×
UNCOV
2063
                        Checks:   checks,
×
UNCOV
2064
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2065
                },
×
UNCOV
2066
        )
×
2067
}
2068

2069
// Started returns true if the server has been started, and false otherwise.
2070
// NOTE: This function is safe for concurrent access.
UNCOV
2071
func (s *server) Started() bool {
×
UNCOV
2072
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2073
}
×
2074

2075
// cleaner is used to aggregate "cleanup" functions during an operation that
2076
// starts several subsystems. In case one of the subsystem fails to start
2077
// and a proper resource cleanup is required, the "run" method achieves this
2078
// by running all these added "cleanup" functions.
2079
type cleaner []func() error
2080

2081
// add is used to add a cleanup function to be called when
2082
// the run function is executed.
UNCOV
2083
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2084
        return append(c, cleanup)
×
UNCOV
2085
}
×
2086

2087
// run is used to run all the previousely added cleanup functions.
UNCOV
2088
func (c cleaner) run() {
×
UNCOV
2089
        for i := len(c) - 1; i >= 0; i-- {
×
UNCOV
2090
                if err := c[i](); err != nil {
×
UNCOV
2091
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
UNCOV
2092
                }
×
2093
        }
2094
}
2095

2096
// Start starts the main daemon server, all requested listeners, and any helper
2097
// goroutines.
2098
// NOTE: This function is safe for concurrent access.
2099
//
2100
//nolint:funlen
2101
func (s *server) Start(ctx context.Context) error {
×
2102
        var startErr error
×
2103

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

×
UNCOV
2109
        s.start.Do(func() {
×
UNCOV
2110
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
UNCOV
2111
                if err := s.customMessageServer.Start(); err != nil {
×
UNCOV
2112
                        startErr = err
×
UNCOV
2113
                        return
×
UNCOV
2114
                }
×
2115

UNCOV
2116
                if s.hostAnn != nil {
×
UNCOV
2117
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
UNCOV
2118
                        if err := s.hostAnn.Start(); err != nil {
×
UNCOV
2119
                                startErr = err
×
2120
                                return
×
2121
                        }
×
2122
                }
2123

2124
                if s.livenessMonitor != nil {
×
2125
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
UNCOV
2126
                        if err := s.livenessMonitor.Start(); err != nil {
×
UNCOV
2127
                                startErr = err
×
UNCOV
2128
                                return
×
UNCOV
2129
                        }
×
2130
                }
2131

2132
                // Start the notification server. This is used so channel
2133
                // management goroutines can be notified when a funding
2134
                // transaction reaches a sufficient number of confirmations, or
2135
                // when the input for the funding transaction is spent in an
2136
                // attempt at an uncooperative close by the counterparty.
UNCOV
2137
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2138
                if err := s.sigPool.Start(); err != nil {
×
2139
                        startErr = err
×
2140
                        return
×
UNCOV
2141
                }
×
2142

UNCOV
2143
                cleanup = cleanup.add(s.writePool.Stop)
×
UNCOV
2144
                if err := s.writePool.Start(); err != nil {
×
UNCOV
2145
                        startErr = err
×
UNCOV
2146
                        return
×
UNCOV
2147
                }
×
2148

UNCOV
2149
                cleanup = cleanup.add(s.readPool.Stop)
×
UNCOV
2150
                if err := s.readPool.Start(); err != nil {
×
UNCOV
2151
                        startErr = err
×
2152
                        return
×
2153
                }
×
2154

UNCOV
2155
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
UNCOV
2156
                if err := s.cc.ChainNotifier.Start(); err != nil {
×
2157
                        startErr = err
×
2158
                        return
×
2159
                }
×
2160

2161
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
UNCOV
2162
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
UNCOV
2163
                        startErr = err
×
UNCOV
2164
                        return
×
UNCOV
2165
                }
×
2166

2167
                cleanup = cleanup.add(s.channelNotifier.Stop)
×
2168
                if err := s.channelNotifier.Start(); err != nil {
×
2169
                        startErr = err
×
UNCOV
2170
                        return
×
UNCOV
2171
                }
×
2172

UNCOV
2173
                cleanup = cleanup.add(func() error {
×
UNCOV
2174
                        return s.peerNotifier.Stop()
×
UNCOV
2175
                })
×
UNCOV
2176
                if err := s.peerNotifier.Start(); err != nil {
×
UNCOV
2177
                        startErr = err
×
UNCOV
2178
                        return
×
2179
                }
×
2180

2181
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
UNCOV
2182
                if err := s.htlcNotifier.Start(); err != nil {
×
UNCOV
2183
                        startErr = err
×
UNCOV
2184
                        return
×
2185
                }
×
2186

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

UNCOV
2195
                beat, err := s.getStartingBeat()
×
UNCOV
2196
                if err != nil {
×
2197
                        startErr = err
×
2198
                        return
×
2199
                }
×
2200

UNCOV
2201
                cleanup = cleanup.add(s.txPublisher.Stop)
×
UNCOV
2202
                if err := s.txPublisher.Start(beat); err != nil {
×
2203
                        startErr = err
×
2204
                        return
×
2205
                }
×
2206

UNCOV
2207
                cleanup = cleanup.add(s.sweeper.Stop)
×
2208
                if err := s.sweeper.Start(beat); err != nil {
×
2209
                        startErr = err
×
UNCOV
2210
                        return
×
2211
                }
×
2212

2213
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
UNCOV
2214
                if err := s.utxoNursery.Start(); err != nil {
×
UNCOV
2215
                        startErr = err
×
UNCOV
2216
                        return
×
2217
                }
×
2218

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

2225
                cleanup = cleanup.add(s.fundingMgr.Stop)
×
2226
                if err := s.fundingMgr.Start(); err != nil {
×
UNCOV
2227
                        startErr = err
×
UNCOV
2228
                        return
×
UNCOV
2229
                }
×
2230

2231
                // htlcSwitch must be started before chainArb since the latter
2232
                // relies on htlcSwitch to deliver resolution message upon
2233
                // start.
UNCOV
2234
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2235
                if err := s.htlcSwitch.Start(); err != nil {
×
UNCOV
2236
                        startErr = err
×
2237
                        return
×
2238
                }
×
2239

UNCOV
2240
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
×
UNCOV
2241
                if err := s.interceptableSwitch.Start(); err != nil {
×
UNCOV
2242
                        startErr = err
×
2243
                        return
×
2244
                }
×
2245

UNCOV
2246
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
×
UNCOV
2247
                if err := s.invoiceHtlcModifier.Start(); err != nil {
×
UNCOV
2248
                        startErr = err
×
2249
                        return
×
2250
                }
×
2251

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

UNCOV
2258
                cleanup = cleanup.add(s.graphDB.Stop)
×
UNCOV
2259
                if err := s.graphDB.Start(); err != nil {
×
UNCOV
2260
                        startErr = err
×
UNCOV
2261
                        return
×
UNCOV
2262
                }
×
2263

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

2270
                cleanup = cleanup.add(s.chanRouter.Stop)
×
2271
                if err := s.chanRouter.Start(); err != nil {
×
2272
                        startErr = err
×
UNCOV
2273
                        return
×
UNCOV
2274
                }
×
2275
                // The authGossiper depends on the chanRouter and therefore
2276
                // should be started after it.
2277
                cleanup = cleanup.add(s.authGossiper.Stop)
×
2278
                if err := s.authGossiper.Start(); err != nil {
×
UNCOV
2279
                        startErr = err
×
UNCOV
2280
                        return
×
UNCOV
2281
                }
×
2282

2283
                cleanup = cleanup.add(s.invoices.Stop)
×
2284
                if err := s.invoices.Start(); err != nil {
×
UNCOV
2285
                        startErr = err
×
UNCOV
2286
                        return
×
UNCOV
2287
                }
×
2288

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

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

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

2307
                cleanup.add(func() error {
×
2308
                        s.missionController.StopStoreTickers()
×
2309
                        return nil
×
UNCOV
2310
                })
×
UNCOV
2311
                s.missionController.RunStoreTickers()
×
UNCOV
2312

×
2313
                // Before we start the connMgr, we'll check to see if we have
×
2314
                // any backups to recover. We do this now as we want to ensure
×
2315
                // that have all the information we need to handle channel
×
UNCOV
2316
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2317
                chanRestorer := &chanDBRestorer{
×
UNCOV
2318
                        db:         s.chanStateDB,
×
2319
                        secretKeys: s.cc.KeyRing,
×
2320
                        chainArb:   s.chainArb,
×
2321
                }
×
UNCOV
2322
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
UNCOV
2323
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
UNCOV
2324
                                s.chansToRestore.PackedSingleChanBackups,
×
2325
                                s.cc.KeyRing, chanRestorer, s,
×
2326
                        )
×
2327
                        if err != nil {
×
UNCOV
2328
                                startErr = fmt.Errorf("unable to unpack single "+
×
UNCOV
2329
                                        "backups: %v", err)
×
UNCOV
2330
                                return
×
2331
                        }
×
2332
                }
2333
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2334
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2335
                                s.chansToRestore.PackedMultiChanBackup,
×
2336
                                s.cc.KeyRing, chanRestorer, s,
×
2337
                        )
×
2338
                        if err != nil {
×
UNCOV
2339
                                startErr = fmt.Errorf("unable to unpack chan "+
×
UNCOV
2340
                                        "backup: %v", err)
×
UNCOV
2341
                                return
×
UNCOV
2342
                        }
×
2343
                }
2344

2345
                // chanSubSwapper must be started after the `channelNotifier`
2346
                // because it depends on channel events as a synchronization
2347
                // point.
UNCOV
2348
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2349
                if err := s.chanSubSwapper.Start(); err != nil {
×
UNCOV
2350
                        startErr = err
×
2351
                        return
×
2352
                }
×
2353

2354
                if s.torController != nil {
×
2355
                        cleanup = cleanup.add(s.torController.Stop)
×
2356
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2357
                                startErr = err
×
2358
                                return
×
2359
                        }
×
2360
                }
2361

UNCOV
2362
                if s.natTraversal != nil {
×
UNCOV
2363
                        s.wg.Add(1)
×
UNCOV
2364
                        go s.watchExternalIP()
×
UNCOV
2365
                }
×
2366

2367
                // Start connmgr last to prevent connections before init.
2368
                cleanup = cleanup.add(func() error {
×
2369
                        s.connMgr.Stop()
×
2370
                        return nil
×
UNCOV
2371
                })
×
2372

2373
                // RESOLVE: s.connMgr.Start() is called here, but
2374
                // brontide.NewListener() is called in newServer. This means
2375
                // that we are actually listening and partially accepting
2376
                // inbound connections even before the connMgr starts.
2377
                //
2378
                // TODO(yy): move the log into the connMgr's `Start` method.
2379
                srvrLog.Info("connMgr starting...")
×
2380
                s.connMgr.Start()
×
UNCOV
2381
                srvrLog.Debug("connMgr started")
×
UNCOV
2382

×
2383
                // If peers are specified as a config option, we'll add those
×
2384
                // peers first.
×
2385
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
2386
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
2387
                                peerAddrCfg,
×
UNCOV
2388
                        )
×
UNCOV
2389
                        if err != nil {
×
UNCOV
2390
                                startErr = fmt.Errorf("unable to parse peer "+
×
2391
                                        "pubkey from config: %v", err)
×
2392
                                return
×
2393
                        }
×
UNCOV
2394
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
UNCOV
2395
                        if err != nil {
×
UNCOV
2396
                                startErr = fmt.Errorf("unable to parse peer "+
×
2397
                                        "address provided as a config option: "+
×
2398
                                        "%v", err)
×
2399
                                return
×
UNCOV
2400
                        }
×
2401

UNCOV
2402
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2403
                                IdentityKey: parsedPubkey,
×
UNCOV
2404
                                Address:     addr,
×
UNCOV
2405
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2406
                        }
×
UNCOV
2407

×
UNCOV
2408
                        err = s.ConnectToPeer(
×
UNCOV
2409
                                peerAddr, true,
×
UNCOV
2410
                                s.cfg.ConnectionTimeout,
×
UNCOV
2411
                        )
×
UNCOV
2412
                        if err != nil {
×
UNCOV
2413
                                startErr = fmt.Errorf("unable to connect to "+
×
UNCOV
2414
                                        "peer address provided as a config "+
×
UNCOV
2415
                                        "option: %v", err)
×
UNCOV
2416
                                return
×
UNCOV
2417
                        }
×
2418
                }
2419

2420
                // Subscribe to NodeAnnouncements that advertise new addresses
2421
                // our persistent peers.
UNCOV
2422
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
UNCOV
2423
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2424
                                "addr: %v", err)
×
2425

×
2426
                        startErr = err
×
2427
                        return
×
2428
                }
×
2429

2430
                // With all the relevant sub-systems started, we'll now attempt
2431
                // to establish persistent connections to our direct channel
2432
                // collaborators within the network. Before doing so however,
2433
                // we'll prune our set of link nodes found within the database
2434
                // to ensure we don't reconnect to any nodes we no longer have
2435
                // open channels with.
UNCOV
2436
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
UNCOV
2437
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
UNCOV
2438

×
UNCOV
2439
                        startErr = err
×
UNCOV
2440
                        return
×
2441
                }
×
2442

2443
                if err := s.establishPersistentConnections(ctx); err != nil {
×
2444
                        srvrLog.Errorf("Failed to establish persistent "+
×
2445
                                "connections: %v", err)
×
UNCOV
2446
                }
×
2447

2448
                // setSeedList is a helper function that turns multiple DNS seed
2449
                // server tuples from the command line or config file into the
2450
                // data structure we need and does a basic formal sanity check
2451
                // in the process.
2452
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2453
                        if len(tuples) == 0 {
×
2454
                                return
×
2455
                        }
×
2456

UNCOV
2457
                        result := make([][2]string, len(tuples))
×
UNCOV
2458
                        for idx, tuple := range tuples {
×
UNCOV
2459
                                tuple = strings.TrimSpace(tuple)
×
UNCOV
2460
                                if len(tuple) == 0 {
×
UNCOV
2461
                                        return
×
UNCOV
2462
                                }
×
2463

UNCOV
2464
                                servers := strings.Split(tuple, ",")
×
2465
                                if len(servers) > 2 || len(servers) == 0 {
×
2466
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2467
                                                "seed tuple: %v", servers)
×
2468
                                        return
×
2469
                                }
×
2470

UNCOV
2471
                                copy(result[idx][:], servers)
×
2472
                        }
2473

2474
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2475
                }
2476

2477
                // Let users overwrite the DNS seed nodes. We only allow them
2478
                // for bitcoin mainnet/testnet/signet.
UNCOV
2479
                if s.cfg.Bitcoin.MainNet {
×
UNCOV
2480
                        setSeedList(
×
2481
                                s.cfg.Bitcoin.DNSSeeds,
×
2482
                                chainreg.BitcoinMainnetGenesis,
×
2483
                        )
×
UNCOV
2484
                }
×
2485
                if s.cfg.Bitcoin.TestNet3 {
×
2486
                        setSeedList(
×
2487
                                s.cfg.Bitcoin.DNSSeeds,
×
2488
                                chainreg.BitcoinTestnetGenesis,
×
2489
                        )
×
2490
                }
×
UNCOV
2491
                if s.cfg.Bitcoin.TestNet4 {
×
2492
                        setSeedList(
×
2493
                                s.cfg.Bitcoin.DNSSeeds,
×
2494
                                chainreg.BitcoinTestnet4Genesis,
×
2495
                        )
×
2496
                }
×
2497
                if s.cfg.Bitcoin.SigNet {
×
UNCOV
2498
                        setSeedList(
×
2499
                                s.cfg.Bitcoin.DNSSeeds,
×
UNCOV
2500
                                chainreg.BitcoinSignetGenesis,
×
UNCOV
2501
                        )
×
2502
                }
×
2503

2504
                // If network bootstrapping hasn't been disabled, then we'll
2505
                // configure the set of active bootstrappers, and launch a
2506
                // dedicated goroutine to maintain a set of persistent
2507
                // connections.
2508
                if !s.cfg.NoNetBootstrap {
×
2509
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2510
                        if err != nil {
×
2511
                                startErr = err
×
2512
                                return
×
UNCOV
2513
                        }
×
2514

2515
                        s.wg.Add(1)
×
2516
                        go s.peerBootstrapper(
×
2517
                                ctx, defaultMinPeers, bootstrappers,
×
2518
                        )
×
UNCOV
2519
                } else {
×
2520
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2521
                }
×
2522

2523
                // Start the blockbeat after all other subsystems have been
2524
                // started so they are ready to receive new blocks.
UNCOV
2525
                cleanup = cleanup.add(func() error {
×
2526
                        s.blockbeatDispatcher.Stop()
×
2527
                        return nil
×
2528
                })
×
2529
                if err := s.blockbeatDispatcher.Start(); err != nil {
×
2530
                        startErr = err
×
UNCOV
2531
                        return
×
UNCOV
2532
                }
×
2533

2534
                // Set the active flag now that we've completed the full
2535
                // startup.
UNCOV
2536
                atomic.StoreInt32(&s.active, 1)
×
2537
        })
2538

2539
        if startErr != nil {
×
2540
                cleanup.run()
×
2541
        }
×
UNCOV
2542
        return startErr
×
2543
}
2544

2545
// Stop gracefully shutsdown the main daemon server. This function will signal
2546
// any active goroutines, or helper objects to exit, then blocks until they've
2547
// all successfully exited. Additionally, any/all listeners are closed.
2548
// NOTE: This function is safe for concurrent access.
UNCOV
2549
func (s *server) Stop() error {
×
UNCOV
2550
        s.stop.Do(func() {
×
UNCOV
2551
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2552

×
UNCOV
2553
                ctx := context.Background()
×
2554

×
2555
                close(s.quit)
×
2556

×
UNCOV
2557
                // Shutdown connMgr first to prevent conns during shutdown.
×
2558
                s.connMgr.Stop()
×
2559

×
2560
                // Stop dispatching blocks to other systems immediately.
×
UNCOV
2561
                s.blockbeatDispatcher.Stop()
×
UNCOV
2562

×
UNCOV
2563
                // Shutdown the wallet, funding manager, and the rpc server.
×
UNCOV
2564
                if err := s.chanStatusMgr.Stop(); err != nil {
×
UNCOV
2565
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
UNCOV
2566
                }
×
UNCOV
2567
                if err := s.htlcSwitch.Stop(); err != nil {
×
2568
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2569
                }
×
UNCOV
2570
                if err := s.sphinx.Stop(); err != nil {
×
UNCOV
2571
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
UNCOV
2572
                }
×
UNCOV
2573
                if err := s.invoices.Stop(); err != nil {
×
UNCOV
2574
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
UNCOV
2575
                }
×
UNCOV
2576
                if err := s.interceptableSwitch.Stop(); err != nil {
×
UNCOV
2577
                        srvrLog.Warnf("failed to stop interceptable "+
×
UNCOV
2578
                                "switch: %v", err)
×
UNCOV
2579
                }
×
UNCOV
2580
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
UNCOV
2581
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
UNCOV
2582
                                "modifier: %v", err)
×
UNCOV
2583
                }
×
UNCOV
2584
                if err := s.chanRouter.Stop(); err != nil {
×
UNCOV
2585
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
UNCOV
2586
                }
×
UNCOV
2587
                if err := s.graphBuilder.Stop(); err != nil {
×
UNCOV
2588
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
UNCOV
2589
                }
×
UNCOV
2590
                if err := s.graphDB.Stop(); err != nil {
×
UNCOV
2591
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
UNCOV
2592
                }
×
2593
                if err := s.chainArb.Stop(); err != nil {
×
2594
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
UNCOV
2595
                }
×
2596
                if err := s.fundingMgr.Stop(); err != nil {
×
2597
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
UNCOV
2598
                }
×
2599
                if err := s.breachArbitrator.Stop(); err != nil {
×
2600
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
UNCOV
2601
                                err)
×
2602
                }
×
2603
                if err := s.utxoNursery.Stop(); err != nil {
×
UNCOV
2604
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2605
                }
×
2606
                if err := s.authGossiper.Stop(); err != nil {
×
2607
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
UNCOV
2608
                }
×
2609
                if err := s.sweeper.Stop(); err != nil {
×
2610
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2611
                }
×
UNCOV
2612
                if err := s.txPublisher.Stop(); err != nil {
×
2613
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2614
                }
×
UNCOV
2615
                if err := s.channelNotifier.Stop(); err != nil {
×
2616
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2617
                }
×
UNCOV
2618
                if err := s.peerNotifier.Stop(); err != nil {
×
2619
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2620
                }
×
UNCOV
2621
                if err := s.htlcNotifier.Stop(); err != nil {
×
2622
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2623
                }
×
2624

2625
                // Update channel.backup file. Make sure to do it before
2626
                // stopping chanSubSwapper.
UNCOV
2627
                singles, err := chanbackup.FetchStaticChanBackups(
×
2628
                        ctx, s.chanStateDB, s.addrSource,
×
2629
                )
×
2630
                if err != nil {
×
UNCOV
2631
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2632
                                err)
×
2633
                } else {
×
UNCOV
2634
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
2635
                        if err != nil {
×
2636
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2637
                                        "backup failed: %v", err)
×
2638
                        }
×
2639
                }
2640

2641
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2642
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
UNCOV
2643
                }
×
2644
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2645
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
UNCOV
2646
                }
×
2647
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2648
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
UNCOV
2649
                                err)
×
2650
                }
×
2651
                if err := s.chanEventStore.Stop(); err != nil {
×
UNCOV
2652
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
UNCOV
2653
                                err)
×
UNCOV
2654
                }
×
UNCOV
2655
                s.missionController.StopStoreTickers()
×
UNCOV
2656

×
UNCOV
2657
                // Disconnect from each active peers to ensure that
×
UNCOV
2658
                // peerTerminationWatchers signal completion to each peer.
×
2659
                for _, peer := range s.Peers() {
×
2660
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2661
                        if err != nil {
×
UNCOV
2662
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
UNCOV
2663
                                        "received error: %v", peer.IdentityKey(),
×
UNCOV
2664
                                        err,
×
UNCOV
2665
                                )
×
UNCOV
2666
                        }
×
2667
                }
2668

2669
                // Now that all connections have been torn down, stop the tower
2670
                // client which will reliably flush all queued states to the
2671
                // tower. If this is halted for any reason, the force quit timer
2672
                // will kick in and abort to allow this method to return.
2673
                if s.towerClientMgr != nil {
×
2674
                        if err := s.towerClientMgr.Stop(); err != nil {
×
UNCOV
2675
                                srvrLog.Warnf("Unable to shut down tower "+
×
2676
                                        "client manager: %v", err)
×
2677
                        }
×
2678
                }
2679

2680
                if s.hostAnn != nil {
×
2681
                        if err := s.hostAnn.Stop(); err != nil {
×
2682
                                srvrLog.Warnf("unable to shut down host "+
×
UNCOV
2683
                                        "annoucner: %v", err)
×
UNCOV
2684
                        }
×
2685
                }
2686

UNCOV
2687
                if s.livenessMonitor != nil {
×
UNCOV
2688
                        if err := s.livenessMonitor.Stop(); err != nil {
×
UNCOV
2689
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2690
                                        "monitor: %v", err)
×
2691
                        }
×
2692
                }
2693

2694
                // Wait for all lingering goroutines to quit.
UNCOV
2695
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2696
                s.wg.Wait()
×
UNCOV
2697

×
UNCOV
2698
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2699
                s.sigPool.Stop()
×
UNCOV
2700
                s.writePool.Stop()
×
UNCOV
2701
                s.readPool.Stop()
×
2702
        })
2703

2704
        return nil
×
2705
}
2706

2707
// Stopped returns true if the server has been instructed to shutdown.
2708
// NOTE: This function is safe for concurrent access.
2709
func (s *server) Stopped() bool {
×
2710
        return atomic.LoadInt32(&s.stopping) != 0
×
2711
}
×
2712

2713
// configurePortForwarding attempts to set up port forwarding for the different
2714
// ports that the server will be listening on.
2715
//
2716
// NOTE: This should only be used when using some kind of NAT traversal to
2717
// automatically set up forwarding rules.
2718
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2719
        ip, err := s.natTraversal.ExternalIP()
×
UNCOV
2720
        if err != nil {
×
UNCOV
2721
                return nil, err
×
UNCOV
2722
        }
×
UNCOV
2723
        s.lastDetectedIP = ip
×
UNCOV
2724

×
UNCOV
2725
        externalIPs := make([]string, 0, len(ports))
×
UNCOV
2726
        for _, port := range ports {
×
UNCOV
2727
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
UNCOV
2728
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
UNCOV
2729
                        continue
×
2730
                }
2731

UNCOV
2732
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
UNCOV
2733
                externalIPs = append(externalIPs, hostIP)
×
2734
        }
2735

UNCOV
2736
        return externalIPs, nil
×
2737
}
2738

2739
// removePortForwarding attempts to clear the forwarding rules for the different
2740
// ports the server is currently listening on.
2741
//
2742
// NOTE: This should only be used when using some kind of NAT traversal to
2743
// automatically set up forwarding rules.
UNCOV
2744
func (s *server) removePortForwarding() {
×
UNCOV
2745
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2746
        for _, port := range forwardedPorts {
×
2747
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2748
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2749
                                "port %d: %v", port, err)
×
2750
                }
×
2751
        }
2752
}
2753

2754
// watchExternalIP continuously checks for an updated external IP address every
2755
// 15 minutes. Once a new IP address has been detected, it will automatically
2756
// handle port forwarding rules and send updated node announcements to the
2757
// currently connected peers.
2758
//
2759
// NOTE: This MUST be run as a goroutine.
2760
func (s *server) watchExternalIP() {
×
2761
        defer s.wg.Done()
×
UNCOV
2762

×
UNCOV
2763
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2764
        // up by the server.
×
UNCOV
2765
        defer s.removePortForwarding()
×
UNCOV
2766

×
UNCOV
2767
        // Keep track of the external IPs set by the user to avoid replacing
×
UNCOV
2768
        // them when detecting a new IP.
×
UNCOV
2769
        ipsSetByUser := make(map[string]struct{})
×
UNCOV
2770
        for _, ip := range s.cfg.ExternalIPs {
×
UNCOV
2771
                ipsSetByUser[ip.String()] = struct{}{}
×
2772
        }
×
2773

2774
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2775

×
2776
        ticker := time.NewTicker(15 * time.Minute)
×
2777
        defer ticker.Stop()
×
2778
out:
×
UNCOV
2779
        for {
×
UNCOV
2780
                select {
×
UNCOV
2781
                case <-ticker.C:
×
UNCOV
2782
                        // We'll start off by making sure a new IP address has
×
UNCOV
2783
                        // been detected.
×
UNCOV
2784
                        ip, err := s.natTraversal.ExternalIP()
×
UNCOV
2785
                        if err != nil {
×
UNCOV
2786
                                srvrLog.Debugf("Unable to retrieve the "+
×
UNCOV
2787
                                        "external IP address: %v", err)
×
2788
                                continue
×
2789
                        }
2790

2791
                        // Periodically renew the NAT port forwarding.
2792
                        for _, port := range forwardedPorts {
×
2793
                                err := s.natTraversal.AddPortMapping(port)
×
2794
                                if err != nil {
×
2795
                                        srvrLog.Warnf("Unable to automatically "+
×
2796
                                                "re-create port forwarding using %s: %v",
×
2797
                                                s.natTraversal.Name(), err)
×
2798
                                } else {
×
2799
                                        srvrLog.Debugf("Automatically re-created "+
×
2800
                                                "forwarding for port %d using %s to "+
×
UNCOV
2801
                                                "advertise external IP",
×
2802
                                                port, s.natTraversal.Name())
×
2803
                                }
×
2804
                        }
2805

2806
                        if ip.Equal(s.lastDetectedIP) {
×
2807
                                continue
×
2808
                        }
2809

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

×
2812
                        // Next, we'll craft the new addresses that will be
×
2813
                        // included in the new node announcement and advertised
×
2814
                        // to the network. Each address will consist of the new
×
2815
                        // IP detected and one of the currently advertised
×
2816
                        // ports.
×
UNCOV
2817
                        var newAddrs []net.Addr
×
UNCOV
2818
                        for _, port := range forwardedPorts {
×
UNCOV
2819
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2820
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2821
                                if err != nil {
×
2822
                                        srvrLog.Debugf("Unable to resolve "+
×
2823
                                                "host %v: %v", addr, err)
×
2824
                                        continue
×
2825
                                }
2826

2827
                                newAddrs = append(newAddrs, addr)
×
2828
                        }
2829

2830
                        // Skip the update if we weren't able to resolve any of
2831
                        // the new addresses.
UNCOV
2832
                        if len(newAddrs) == 0 {
×
UNCOV
2833
                                srvrLog.Debug("Skipping node announcement " +
×
2834
                                        "update due to not being able to " +
×
2835
                                        "resolve any new addresses")
×
UNCOV
2836
                                continue
×
2837
                        }
2838

2839
                        // Now, we'll need to update the addresses in our node's
2840
                        // announcement in order to propagate the update
2841
                        // throughout the network. We'll only include addresses
2842
                        // that have a different IP from the previous one, as
2843
                        // the previous IP is no longer valid.
2844
                        currentNodeAnn := s.getNodeAnnouncement()
×
2845

×
2846
                        for _, addr := range currentNodeAnn.Addresses {
×
2847
                                host, _, err := net.SplitHostPort(addr.String())
×
2848
                                if err != nil {
×
2849
                                        srvrLog.Debugf("Unable to determine "+
×
2850
                                                "host from address %v: %v",
×
2851
                                                addr, err)
×
2852
                                        continue
×
2853
                                }
2854

2855
                                // We'll also make sure to include external IPs
2856
                                // set manually by the user.
UNCOV
2857
                                _, setByUser := ipsSetByUser[addr.String()]
×
UNCOV
2858
                                if setByUser || host != s.lastDetectedIP.String() {
×
UNCOV
2859
                                        newAddrs = append(newAddrs, addr)
×
2860
                                }
×
2861
                        }
2862

2863
                        // Then, we'll generate a new timestamped node
2864
                        // announcement with the updated addresses and broadcast
2865
                        // it to our peers.
UNCOV
2866
                        newNodeAnn, err := s.genNodeAnnouncement(
×
UNCOV
2867
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
UNCOV
2868
                        )
×
UNCOV
2869
                        if err != nil {
×
UNCOV
2870
                                srvrLog.Debugf("Unable to generate new node "+
×
UNCOV
2871
                                        "announcement: %v", err)
×
2872
                                continue
×
2873
                        }
2874

2875
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2876
                        if err != nil {
×
2877
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2878
                                        "announcement to peers: %v", err)
×
2879
                                continue
×
2880
                        }
2881

2882
                        // Finally, update the last IP seen to the current one.
UNCOV
2883
                        s.lastDetectedIP = ip
×
UNCOV
2884
                case <-s.quit:
×
2885
                        break out
×
2886
                }
2887
        }
2888
}
2889

2890
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2891
// based on the server, and currently active bootstrap mechanisms as defined
2892
// within the current configuration.
UNCOV
2893
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2894
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2895

×
2896
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2897

×
2898
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2899
        // this can be used by default if we've already partially seeded the
×
2900
        // network.
×
UNCOV
2901
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
UNCOV
2902
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
×
2903
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
×
2904
        )
×
2905
        if err != nil {
×
2906
                return nil, err
×
2907
        }
×
UNCOV
2908
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
UNCOV
2909

×
UNCOV
2910
        // If this isn't using simnet or regtest mode, then one of our
×
2911
        // additional bootstrapping sources will be the set of running DNS
×
2912
        // seeds.
×
2913
        if !s.cfg.Bitcoin.IsLocalNetwork() {
×
UNCOV
2914
                //nolint:ll
×
UNCOV
2915
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
UNCOV
2916

×
UNCOV
2917
                // If we have a set of DNS seeds for this chain, then we'll add
×
UNCOV
2918
                // it as an additional bootstrapping source.
×
UNCOV
2919
                if ok {
×
UNCOV
2920
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
UNCOV
2921
                                "seeds: %v", dnsSeeds)
×
UNCOV
2922

×
UNCOV
2923
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
UNCOV
2924
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
2925
                        )
×
UNCOV
2926
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
UNCOV
2927
                }
×
2928
        }
2929

UNCOV
2930
        return bootStrappers, nil
×
2931
}
2932

2933
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2934
// needs to ignore, which is made of three parts,
2935
//   - the node itself needs to be skipped as it doesn't make sense to connect
2936
//     to itself.
2937
//   - the peers that already have connections with, as in s.peersByPub.
2938
//   - the peers that we are attempting to connect, as in s.persistentPeers.
UNCOV
2939
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
UNCOV
2940
        s.mu.RLock()
×
UNCOV
2941
        defer s.mu.RUnlock()
×
2942

×
2943
        ignore := make(map[autopilot.NodeID]struct{})
×
2944

×
2945
        // We should ignore ourselves from bootstrapping.
×
2946
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2947
        ignore[selfKey] = struct{}{}
×
2948

×
2949
        // Ignore all connected peers.
×
2950
        for _, peer := range s.peersByPub {
×
2951
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2952
                ignore[nID] = struct{}{}
×
2953
        }
×
2954

2955
        // Ignore all persistent peers as they have a dedicated reconnecting
2956
        // process.
UNCOV
2957
        for pubKeyStr := range s.persistentPeers {
×
UNCOV
2958
                var nID autopilot.NodeID
×
UNCOV
2959
                copy(nID[:], []byte(pubKeyStr))
×
UNCOV
2960
                ignore[nID] = struct{}{}
×
UNCOV
2961
        }
×
2962

UNCOV
2963
        return ignore
×
2964
}
2965

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

×
UNCOV
2974
        defer s.wg.Done()
×
UNCOV
2975

×
UNCOV
2976
        // Before we continue, init the ignore peers map.
×
UNCOV
2977
        ignoreList := s.createBootstrapIgnorePeers()
×
UNCOV
2978

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

×
UNCOV
2983
        // Once done, we'll attempt to maintain our target minimum number of
×
UNCOV
2984
        // peers.
×
UNCOV
2985
        //
×
2986
        // We'll use a 15 second backoff, and double the time every time an
×
2987
        // epoch fails up to a ceiling.
×
2988
        backOff := time.Second * 15
×
2989

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

×
UNCOV
2995
        // We'll use the number of attempts and errors to determine if we need
×
UNCOV
2996
        // to increase the time between discovery epochs.
×
UNCOV
2997
        var epochErrors uint32 // To be used atomically.
×
UNCOV
2998
        var epochAttempts uint32
×
UNCOV
2999

×
UNCOV
3000
        for {
×
UNCOV
3001
                select {
×
3002
                // The ticker has just woken us up, so we'll need to check if
3003
                // we need to attempt to connect our to any more peers.
UNCOV
3004
                case <-sampleTicker.C:
×
UNCOV
3005
                        // Obtain the current number of peers, so we can gauge
×
UNCOV
3006
                        // if we need to sample more peers or not.
×
UNCOV
3007
                        s.mu.RLock()
×
UNCOV
3008
                        numActivePeers := uint32(len(s.peersByPub))
×
UNCOV
3009
                        s.mu.RUnlock()
×
UNCOV
3010

×
UNCOV
3011
                        // If we have enough peers, then we can loop back
×
UNCOV
3012
                        // around to the next round as we're done here.
×
UNCOV
3013
                        if numActivePeers >= numTargetPeers {
×
UNCOV
3014
                                continue
×
3015
                        }
3016

3017
                        // If all of our attempts failed during this last back
3018
                        // off period, then will increase our backoff to 5
3019
                        // minute ceiling to avoid an excessive number of
3020
                        // queries
3021
                        //
3022
                        // TODO(roasbeef): add reverse policy too?
3023

UNCOV
3024
                        if epochAttempts > 0 &&
×
UNCOV
3025
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
UNCOV
3026

×
UNCOV
3027
                                sampleTicker.Stop()
×
UNCOV
3028

×
UNCOV
3029
                                backOff *= 2
×
UNCOV
3030
                                if backOff > bootstrapBackOffCeiling {
×
UNCOV
3031
                                        backOff = bootstrapBackOffCeiling
×
3032
                                }
×
3033

3034
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3035
                                        "%v", backOff)
×
3036
                                sampleTicker = time.NewTicker(backOff)
×
3037
                                continue
×
3038
                        }
3039

3040
                        atomic.StoreUint32(&epochErrors, 0)
×
3041
                        epochAttempts = 0
×
3042

×
UNCOV
3043
                        // Since we know need more peers, we'll compute the
×
UNCOV
3044
                        // exact number we need to reach our threshold.
×
UNCOV
3045
                        numNeeded := numTargetPeers - numActivePeers
×
UNCOV
3046

×
UNCOV
3047
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
UNCOV
3048
                                "peers", numNeeded)
×
UNCOV
3049

×
UNCOV
3050
                        // With the number of peers we need calculated, we'll
×
UNCOV
3051
                        // query the network bootstrappers to sample a set of
×
3052
                        // random addrs for us.
×
3053
                        //
×
3054
                        // Before we continue, get a copy of the ignore peers
×
3055
                        // map.
×
3056
                        ignoreList = s.createBootstrapIgnorePeers()
×
3057

×
3058
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3059
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3060
                        )
×
UNCOV
3061
                        if err != nil {
×
3062
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3063
                                        "peers: %v", err)
×
3064
                                continue
×
3065
                        }
3066

3067
                        // Finally, we'll launch a new goroutine for each
3068
                        // prospective peer candidates.
3069
                        for _, addr := range peerAddrs {
×
3070
                                epochAttempts++
×
3071

×
3072
                                go func(a *lnwire.NetAddress) {
×
3073
                                        // TODO(roasbeef): can do AS, subnet,
×
3074
                                        // country diversity, etc
×
3075
                                        errChan := make(chan error, 1)
×
3076
                                        s.connectToPeer(
×
3077
                                                a, errChan,
×
3078
                                                s.cfg.ConnectionTimeout,
×
3079
                                        )
×
3080
                                        select {
×
3081
                                        case err := <-errChan:
×
3082
                                                if err == nil {
×
3083
                                                        return
×
3084
                                                }
×
3085

3086
                                                srvrLog.Errorf("Unable to "+
×
3087
                                                        "connect to %v: %v",
×
3088
                                                        a, err)
×
3089
                                                atomic.AddUint32(&epochErrors, 1)
×
3090
                                        case <-s.quit:
×
3091
                                        }
3092
                                }(addr)
3093
                        }
UNCOV
3094
                case <-s.quit:
×
UNCOV
3095
                        return
×
3096
                }
3097
        }
3098
}
3099

3100
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3101
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3102
// query back off each time we encounter a failure.
3103
const bootstrapBackOffCeiling = time.Minute * 5
3104

3105
// initialPeerBootstrap attempts to continuously connect to peers on startup
3106
// until the target number of peers has been reached. This ensures that nodes
3107
// receive an up to date network view as soon as possible.
3108
func (s *server) initialPeerBootstrap(ctx context.Context,
3109
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3110
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3111

×
3112
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
UNCOV
3113
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3114

×
3115
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3116
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3117
        var delaySignal <-chan time.Time
×
3118
        delayTime := time.Second * 2
×
UNCOV
3119

×
UNCOV
3120
        // As want to be more aggressive, we'll use a lower back off celling
×
UNCOV
3121
        // then the main peer bootstrap logic.
×
UNCOV
3122
        backOffCeiling := bootstrapBackOffCeiling / 5
×
UNCOV
3123

×
UNCOV
3124
        for attempts := 0; ; attempts++ {
×
UNCOV
3125
                // Check if the server has been requested to shut down in order
×
UNCOV
3126
                // to prevent blocking.
×
UNCOV
3127
                if s.Stopped() {
×
UNCOV
3128
                        return
×
UNCOV
3129
                }
×
3130

3131
                // We can exit our aggressive initial peer bootstrapping stage
3132
                // if we've reached out target number of peers.
UNCOV
3133
                s.mu.RLock()
×
UNCOV
3134
                numActivePeers := uint32(len(s.peersByPub))
×
UNCOV
3135
                s.mu.RUnlock()
×
UNCOV
3136

×
UNCOV
3137
                if numActivePeers >= numTargetPeers {
×
UNCOV
3138
                        return
×
UNCOV
3139
                }
×
3140

UNCOV
3141
                if attempts > 0 {
×
UNCOV
3142
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3143
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3144
                                attempts)
×
UNCOV
3145

×
UNCOV
3146
                        // We've completed at least one iterating and haven't
×
UNCOV
3147
                        // finished, so we'll start to insert a delay period
×
UNCOV
3148
                        // between each attempt.
×
UNCOV
3149
                        delaySignal = time.After(delayTime)
×
UNCOV
3150
                        select {
×
UNCOV
3151
                        case <-delaySignal:
×
UNCOV
3152
                        case <-s.quit:
×
UNCOV
3153
                                return
×
3154
                        }
3155

3156
                        // After our delay, we'll double the time we wait up to
3157
                        // the max back off period.
UNCOV
3158
                        delayTime *= 2
×
UNCOV
3159
                        if delayTime > backOffCeiling {
×
UNCOV
3160
                                delayTime = backOffCeiling
×
UNCOV
3161
                        }
×
3162
                }
3163

3164
                // Otherwise, we'll request for the remaining number of peers
3165
                // in order to reach our target.
UNCOV
3166
                peersNeeded := numTargetPeers - numActivePeers
×
UNCOV
3167
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
UNCOV
3168
                        ctx, ignore, peersNeeded, bootstrappers...,
×
UNCOV
3169
                )
×
3170
                if err != nil {
×
3171
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3172
                                "peers: %v", err)
×
3173
                        continue
×
3174
                }
3175

3176
                // Then, we'll attempt to establish a connection to the
3177
                // different peer addresses retrieved by our bootstrappers.
3178
                var wg sync.WaitGroup
×
3179
                for _, bootstrapAddr := range bootstrapAddrs {
×
3180
                        wg.Add(1)
×
3181
                        go func(addr *lnwire.NetAddress) {
×
UNCOV
3182
                                defer wg.Done()
×
UNCOV
3183

×
UNCOV
3184
                                errChan := make(chan error, 1)
×
UNCOV
3185
                                go s.connectToPeer(
×
3186
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3187
                                )
×
3188

×
3189
                                // We'll only allow this connection attempt to
×
UNCOV
3190
                                // take up to 3 seconds. This allows us to move
×
UNCOV
3191
                                // quickly by discarding peers that are slowing
×
UNCOV
3192
                                // us down.
×
UNCOV
3193
                                select {
×
UNCOV
3194
                                case err := <-errChan:
×
UNCOV
3195
                                        if err == nil {
×
UNCOV
3196
                                                return
×
UNCOV
3197
                                        }
×
UNCOV
3198
                                        srvrLog.Errorf("Unable to connect to "+
×
3199
                                                "%v: %v", addr, err)
×
3200
                                // TODO: tune timeout? 3 seconds might be *too*
3201
                                // aggressive but works well.
UNCOV
3202
                                case <-time.After(3 * time.Second):
×
UNCOV
3203
                                        srvrLog.Tracef("Skipping peer %v due "+
×
UNCOV
3204
                                                "to not establishing a "+
×
UNCOV
3205
                                                "connection within 3 seconds",
×
UNCOV
3206
                                                addr)
×
UNCOV
3207
                                case <-s.quit:
×
3208
                                }
3209
                        }(bootstrapAddr)
3210
                }
3211

UNCOV
3212
                wg.Wait()
×
3213
        }
3214
}
3215

3216
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3217
// order to listen for inbound connections over Tor.
UNCOV
3218
func (s *server) createNewHiddenService(ctx context.Context) error {
×
UNCOV
3219
        // Determine the different ports the server is listening on. The onion
×
UNCOV
3220
        // service's virtual port will map to these ports and one will be picked
×
UNCOV
3221
        // at random when the onion service is being accessed.
×
UNCOV
3222
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
UNCOV
3223
        for _, listenAddr := range s.listenAddrs {
×
UNCOV
3224
                port := listenAddr.(*net.TCPAddr).Port
×
UNCOV
3225
                listenPorts = append(listenPorts, port)
×
3226
        }
×
3227

UNCOV
3228
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
UNCOV
3229
        if err != nil {
×
3230
                return err
×
3231
        }
×
3232

3233
        // Once the port mapping has been set, we can go ahead and automatically
3234
        // create our onion service. The service's private key will be saved to
3235
        // disk in order to regain access to this service when restarting `lnd`.
UNCOV
3236
        onionCfg := tor.AddOnionConfig{
×
UNCOV
3237
                VirtualPort: defaultPeerPort,
×
UNCOV
3238
                TargetPorts: listenPorts,
×
UNCOV
3239
                Store: tor.NewOnionFile(
×
UNCOV
3240
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
UNCOV
3241
                        encrypter,
×
UNCOV
3242
                ),
×
UNCOV
3243
        }
×
UNCOV
3244

×
UNCOV
3245
        switch {
×
3246
        case s.cfg.Tor.V2:
×
3247
                onionCfg.Type = tor.V2
×
3248
        case s.cfg.Tor.V3:
×
3249
                onionCfg.Type = tor.V3
×
3250
        }
3251

3252
        addr, err := s.torController.AddOnion(onionCfg)
×
3253
        if err != nil {
×
3254
                return err
×
UNCOV
3255
        }
×
3256

3257
        // Now that the onion service has been created, we'll add the onion
3258
        // address it can be reached at to our list of advertised addresses.
3259
        newNodeAnn, err := s.genNodeAnnouncement(
×
UNCOV
3260
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
UNCOV
3261
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
UNCOV
3262
                },
×
3263
        )
3264
        if err != nil {
×
3265
                return fmt.Errorf("unable to generate new node "+
×
3266
                        "announcement: %v", err)
×
3267
        }
×
3268

3269
        // Finally, we'll update the on-disk version of our announcement so it
3270
        // will eventually propagate to nodes in the network.
3271
        selfNode := &models.Node{
×
3272
                HaveNodeAnnouncement: true,
×
3273
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3274
                Addresses:            newNodeAnn.Addresses,
×
3275
                Alias:                newNodeAnn.Alias.String(),
×
3276
                Features: lnwire.NewFeatureVector(
×
3277
                        newNodeAnn.Features, lnwire.Features,
×
UNCOV
3278
                ),
×
UNCOV
3279
                Color:        newNodeAnn.RGBColor,
×
3280
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3281
        }
×
3282
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3283
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
UNCOV
3284
                return fmt.Errorf("can't set self node: %w", err)
×
UNCOV
3285
        }
×
3286

3287
        return nil
×
3288
}
3289

3290
// findChannel finds a channel given a public key and ChannelID. It is an
3291
// optimization that is quicker than seeking for a channel given only the
3292
// ChannelID.
3293
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3294
        *channeldb.OpenChannel, error) {
×
3295

×
UNCOV
3296
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3297
        if err != nil {
×
UNCOV
3298
                return nil, err
×
3299
        }
×
3300

3301
        for _, channel := range nodeChans {
×
3302
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
3303
                        return channel, nil
×
3304
                }
×
3305
        }
3306

3307
        return nil, fmt.Errorf("unable to find channel")
×
3308
}
3309

3310
// getNodeAnnouncement fetches the current, fully signed node announcement.
3311
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
×
3312
        s.mu.Lock()
×
3313
        defer s.mu.Unlock()
×
UNCOV
3314

×
3315
        return *s.currentNodeAnn
×
UNCOV
3316
}
×
3317

3318
// genNodeAnnouncement generates and returns the current fully signed node
3319
// announcement. The time stamp of the announcement will be updated in order
3320
// to ensure it propagates through the network.
3321
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3322
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
×
UNCOV
3323

×
UNCOV
3324
        s.mu.Lock()
×
UNCOV
3325
        defer s.mu.Unlock()
×
3326

×
3327
        // Create a shallow copy of the current node announcement to work on.
×
UNCOV
3328
        // This ensures the original announcement remains unchanged
×
UNCOV
3329
        // until the new announcement is fully signed and valid.
×
UNCOV
3330
        newNodeAnn := *s.currentNodeAnn
×
UNCOV
3331

×
UNCOV
3332
        // First, try to update our feature manager with the updated set of
×
UNCOV
3333
        // features.
×
UNCOV
3334
        if features != nil {
×
UNCOV
3335
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3336
                        feature.SetNodeAnn: features,
×
UNCOV
3337
                }
×
UNCOV
3338
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3339
                if err != nil {
×
UNCOV
3340
                        return lnwire.NodeAnnouncement1{}, err
×
UNCOV
3341
                }
×
3342

3343
                // If we could successfully update our feature manager, add
3344
                // an update modifier to include these new features to our
3345
                // set.
UNCOV
3346
                modifiers = append(
×
UNCOV
3347
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3348
                )
×
3349
        }
3350

3351
        // Always update the timestamp when refreshing to ensure the update
3352
        // propagates.
UNCOV
3353
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3354

×
UNCOV
3355
        // Apply the requested changes to the node announcement.
×
UNCOV
3356
        for _, modifier := range modifiers {
×
UNCOV
3357
                modifier(&newNodeAnn)
×
UNCOV
3358
        }
×
3359

3360
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3361
        err := netann.SignNodeAnnouncement(
×
UNCOV
3362
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
UNCOV
3363
        )
×
UNCOV
3364
        if err != nil {
×
UNCOV
3365
                return lnwire.NodeAnnouncement1{}, err
×
UNCOV
3366
        }
×
3367

3368
        // If signing succeeds, update the current announcement.
UNCOV
3369
        *s.currentNodeAnn = newNodeAnn
×
UNCOV
3370

×
UNCOV
3371
        return *s.currentNodeAnn, nil
×
3372
}
3373

3374
// updateAndBroadcastSelfNode generates a new node announcement
3375
// applying the giving modifiers and updating the time stamp
3376
// to ensure it propagates through the network. Then it broadcasts
3377
// it to the network.
3378
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3379
        features *lnwire.RawFeatureVector,
UNCOV
3380
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3381

×
UNCOV
3382
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3383
        if err != nil {
×
UNCOV
3384
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3385
                        "announcement: %v", err)
×
UNCOV
3386
        }
×
3387

3388
        // Update the on-disk version of our announcement.
3389
        // Load and modify self node istead of creating anew instance so we
3390
        // don't risk overwriting any existing values.
UNCOV
3391
        selfNode, err := s.graphDB.SourceNode(ctx)
×
UNCOV
3392
        if err != nil {
×
3393
                return fmt.Errorf("unable to get current source node: %w", err)
×
3394
        }
×
3395

UNCOV
3396
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3397
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3398
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3399
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3400
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3401
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3402
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3403

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

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

3410
        // Finally, propagate it to the nodes in the network.
UNCOV
3411
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3412
        if err != nil {
×
UNCOV
3413
                rpcsLog.Debugf("Unable to broadcast new node "+
×
UNCOV
3414
                        "announcement to peers: %v", err)
×
UNCOV
3415
                return err
×
UNCOV
3416
        }
×
3417

UNCOV
3418
        return nil
×
3419
}
3420

3421
type nodeAddresses struct {
3422
        pubKey    *btcec.PublicKey
3423
        addresses []net.Addr
3424
}
3425

3426
// establishPersistentConnections attempts to establish persistent connections
3427
// to all our direct channel collaborators. In order to promote liveness of our
3428
// active channels, we instruct the connection manager to attempt to establish
3429
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3430
func (s *server) establishPersistentConnections(ctx context.Context) error {
×
UNCOV
3431
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3432
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3433
        // since other PubKey forms can't be compared.
×
UNCOV
3434
        nodeAddrsMap := make(map[string]*nodeAddresses)
×
3435

×
3436
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3437
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3438
        // the reconnection port to the default peer port.
×
UNCOV
3439
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3440
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
×
3441
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3442
        }
×
3443

3444
        for _, node := range linkNodes {
×
UNCOV
3445
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3446
                nodeAddrs := &nodeAddresses{
×
UNCOV
3447
                        pubKey:    node.IdentityPub,
×
UNCOV
3448
                        addresses: node.Addresses,
×
UNCOV
3449
                }
×
UNCOV
3450
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3451
        }
×
3452

3453
        // After checking our previous connections for addresses to connect to,
3454
        // iterate through the nodes in our channel graph to find addresses
3455
        // that have been added via NodeAnnouncement1 messages.
3456
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3457
        // each of the nodes.
UNCOV
3458
        graphAddrs := make(map[string]*nodeAddresses)
×
UNCOV
3459
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
×
UNCOV
3460
                havePolicy bool, channelPeer *models.Node) error {
×
UNCOV
3461

×
UNCOV
3462
                // If the remote party has announced the channel to us, but we
×
UNCOV
3463
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3464
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3465
                if !havePolicy {
×
UNCOV
3466
                        srvrLog.Warnf("No channel policy found for "+
×
UNCOV
3467
                                "ChannelPoint(%v): ", chanPoint)
×
UNCOV
3468
                }
×
3469

3470
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3471

×
UNCOV
3472
                // Add all unique addresses from channel
×
UNCOV
3473
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3474
                // connect to for this peer.
×
UNCOV
3475
                addrSet := make(map[string]net.Addr)
×
UNCOV
3476
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3477
                        switch addr.(type) {
×
UNCOV
3478
                        case *net.TCPAddr:
×
UNCOV
3479
                                addrSet[addr.String()] = addr
×
3480

3481
                        // We'll only attempt to connect to Tor addresses if Tor
3482
                        // outbound support is enabled.
UNCOV
3483
                        case *tor.OnionAddr:
×
UNCOV
3484
                                if s.cfg.Tor.Active {
×
UNCOV
3485
                                        addrSet[addr.String()] = addr
×
UNCOV
3486
                                }
×
3487
                        }
3488
                }
3489

3490
                // If this peer is also recorded as a link node, we'll add any
3491
                // additional addresses that have not already been selected.
UNCOV
3492
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3493
                if ok {
×
3494
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
3495
                                switch lnAddress.(type) {
×
3496
                                case *net.TCPAddr:
×
UNCOV
3497
                                        addrSet[lnAddress.String()] = lnAddress
×
3498

3499
                                // We'll only attempt to connect to Tor
3500
                                // addresses if Tor outbound support is enabled.
UNCOV
3501
                                case *tor.OnionAddr:
×
UNCOV
3502
                                        if s.cfg.Tor.Active {
×
UNCOV
3503
                                                //nolint:ll
×
UNCOV
3504
                                                addrSet[lnAddress.String()] = lnAddress
×
UNCOV
3505
                                        }
×
3506
                                }
3507
                        }
3508
                }
3509

3510
                // Construct a slice of the deduped addresses.
3511
                var addrs []net.Addr
×
3512
                for _, addr := range addrSet {
×
3513
                        addrs = append(addrs, addr)
×
3514
                }
×
3515

UNCOV
3516
                n := &nodeAddresses{
×
UNCOV
3517
                        addresses: addrs,
×
UNCOV
3518
                }
×
UNCOV
3519
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3520
                if err != nil {
×
UNCOV
3521
                        return err
×
UNCOV
3522
                }
×
3523

UNCOV
3524
                graphAddrs[pubStr] = n
×
UNCOV
3525
                return nil
×
3526
        }
UNCOV
3527
        err = s.graphDB.ForEachSourceNodeChannel(
×
UNCOV
3528
                ctx, forEachSrcNodeChan, func() {
×
3529
                        clear(graphAddrs)
×
3530
                },
×
3531
        )
3532
        if err != nil {
×
3533
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
UNCOV
3534
                        "%v", err)
×
UNCOV
3535

×
UNCOV
3536
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
UNCOV
3537
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
UNCOV
3538

×
UNCOV
3539
                        return err
×
UNCOV
3540
                }
×
3541
        }
3542

3543
        // Combine the addresses from the link nodes and the channel graph.
UNCOV
3544
        for pubStr, nodeAddr := range graphAddrs {
×
UNCOV
3545
                nodeAddrsMap[pubStr] = nodeAddr
×
UNCOV
3546
        }
×
3547

UNCOV
3548
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
3549
                len(nodeAddrsMap))
×
3550

×
UNCOV
3551
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3552
        // have been recorded and sent to the connection manager.
×
UNCOV
3553
        s.mu.Lock()
×
UNCOV
3554
        defer s.mu.Unlock()
×
UNCOV
3555

×
UNCOV
3556
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3557
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3558
        var numOutboundConns int
×
UNCOV
3559
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3560
                // Add this peer to the set of peers we should maintain a
×
3561
                // persistent connection with. We set the value to false to
×
3562
                // indicate that we should not continue to reconnect if the
×
3563
                // number of channels returns to zero, since this peer has not
×
3564
                // been requested as perm by the user.
×
3565
                s.persistentPeers[pubStr] = false
×
3566
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
3567
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
3568
                }
×
3569

UNCOV
3570
                for _, address := range nodeAddr.addresses {
×
UNCOV
3571
                        // Create a wrapper address which couples the IP and
×
UNCOV
3572
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3573
                        // can be established.
×
UNCOV
3574
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3575
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3576
                                Address:     address,
×
UNCOV
3577
                        }
×
UNCOV
3578

×
UNCOV
3579
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3580
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3581
                }
×
3582

3583
                // We'll connect to the first 10 peers immediately, then
3584
                // randomly stagger any remaining connections if the
3585
                // stagger initial reconnect flag is set. This ensures
3586
                // that mobile nodes or nodes with a small number of
3587
                // channels obtain connectivity quickly, but larger
3588
                // nodes are able to disperse the costs of connecting to
3589
                // all peers at once.
UNCOV
3590
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3591
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3592

×
UNCOV
3593
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3594
                } else {
×
UNCOV
3595
                        go s.delayInitialReconnect(pubStr)
×
UNCOV
3596
                }
×
3597

UNCOV
3598
                numOutboundConns++
×
3599
        }
3600

UNCOV
3601
        return nil
×
3602
}
3603

3604
// delayInitialReconnect will attempt a reconnection to the given peer after
3605
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3606
//
3607
// NOTE: This method MUST be run as a goroutine.
UNCOV
3608
func (s *server) delayInitialReconnect(pubStr string) {
×
UNCOV
3609
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
UNCOV
3610
        select {
×
UNCOV
3611
        case <-time.After(delay):
×
UNCOV
3612
                s.connectToPersistentPeer(pubStr)
×
UNCOV
3613
        case <-s.quit:
×
3614
        }
3615
}
3616

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

×
3623
        s.mu.Lock()
×
3624
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3625
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3626
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3627
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3628
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3629
                s.mu.Unlock()
×
UNCOV
3630

×
UNCOV
3631
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3632
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3633

×
UNCOV
3634
                return
×
UNCOV
3635
        }
×
3636
        s.mu.Unlock()
×
3637
}
3638

3639
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3640
// is instead used to remove persistent peer state for a peer that has been
3641
// disconnected for good cause by the server. Currently, a gossip ban from
3642
// sending garbage and the server running out of restricted-access
3643
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3644
// future, this function may expand when more ban criteria is added.
3645
//
3646
// NOTE: The server's write lock MUST be held when this is called.
UNCOV
3647
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
UNCOV
3648
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
UNCOV
3649
                delete(s.persistentPeers, remotePub)
×
UNCOV
3650
                delete(s.persistentPeersBackoff, remotePub)
×
UNCOV
3651
                delete(s.persistentPeerAddrs, remotePub)
×
UNCOV
3652
                s.cancelConnReqs(remotePub, nil)
×
UNCOV
3653
        }
×
3654
}
3655

3656
// BroadcastMessage sends a request to the server to broadcast a set of
3657
// messages to all peers other than the one specified by the `skips` parameter.
3658
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3659
// the target peers.
3660
//
3661
// NOTE: This function is safe for concurrent access.
3662
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3663
        msgs ...lnwire.Message) error {
×
UNCOV
3664

×
UNCOV
3665
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3666
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3667
        // exact set of peers present at the time of invocation.
×
UNCOV
3668
        s.mu.RLock()
×
UNCOV
3669
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3670
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3671
                if skips != nil {
×
UNCOV
3672
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3673
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3674
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
3675
                                continue
×
3676
                        }
3677
                }
3678

3679
                peers = append(peers, sPeer)
×
3680
        }
3681
        s.mu.RUnlock()
×
UNCOV
3682

×
UNCOV
3683
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3684
        // all messages to each of peers.
×
UNCOV
3685
        var wg sync.WaitGroup
×
UNCOV
3686
        for _, sPeer := range peers {
×
UNCOV
3687
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3688
                        sPeer.PubKey())
×
UNCOV
3689

×
UNCOV
3690
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3691
                wg.Add(1)
×
UNCOV
3692
                s.wg.Add(1)
×
UNCOV
3693
                go func(p lnpeer.Peer) {
×
UNCOV
3694
                        defer s.wg.Done()
×
UNCOV
3695
                        defer wg.Done()
×
UNCOV
3696

×
UNCOV
3697
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3698
                }(sPeer)
×
3699
        }
3700

3701
        // Wait for all messages to have been dispatched before returning to
3702
        // caller.
UNCOV
3703
        wg.Wait()
×
UNCOV
3704

×
UNCOV
3705
        return nil
×
3706
}
3707

3708
// NotifyWhenOnline can be called by other subsystems to get notified when a
3709
// particular peer comes online. The peer itself is sent across the peerChan.
3710
//
3711
// NOTE: This function is safe for concurrent access.
3712
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3713
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3714

×
UNCOV
3715
        s.mu.Lock()
×
UNCOV
3716

×
UNCOV
3717
        // Compute the target peer's identifier.
×
UNCOV
3718
        pubStr := string(peerKey[:])
×
UNCOV
3719

×
UNCOV
3720
        // Check if peer is connected.
×
UNCOV
3721
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3722
        if ok {
×
UNCOV
3723
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3724
                // waiting for the peer to become active.
×
UNCOV
3725
                s.mu.Unlock()
×
UNCOV
3726

×
UNCOV
3727
                // Wait until the peer signals that it is actually active
×
UNCOV
3728
                // rather than only in the server's maps.
×
UNCOV
3729
                select {
×
UNCOV
3730
                case <-peer.ActiveSignal():
×
UNCOV
3731
                case <-peer.QuitSignal():
×
UNCOV
3732
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3733
                        // and return.
×
UNCOV
3734
                        s.mu.Lock()
×
UNCOV
3735
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3736
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3737
                        )
×
UNCOV
3738
                        s.mu.Unlock()
×
UNCOV
3739
                        return
×
3740
                }
3741

3742
                // Connected, can return early.
UNCOV
3743
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3744

×
UNCOV
3745
                select {
×
UNCOV
3746
                case peerChan <- peer:
×
UNCOV
3747
                case <-s.quit:
×
3748
                }
3749

UNCOV
3750
                return
×
3751
        }
3752

3753
        // Not connected, store this listener such that it can be notified when
3754
        // the peer comes online.
UNCOV
3755
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3756
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3757
        )
×
UNCOV
3758
        s.mu.Unlock()
×
3759
}
3760

3761
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3762
// the given public key has been disconnected. The notification is signaled by
3763
// closing the channel returned.
UNCOV
3764
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3765
        s.mu.Lock()
×
UNCOV
3766
        defer s.mu.Unlock()
×
UNCOV
3767

×
UNCOV
3768
        c := make(chan struct{})
×
UNCOV
3769

×
UNCOV
3770
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3771
        // notification.
×
UNCOV
3772
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3773
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
UNCOV
3774
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
UNCOV
3775
                close(c)
×
UNCOV
3776
                return c
×
UNCOV
3777
        }
×
3778

3779
        // Otherwise, the peer is online, so we'll keep track of the channel to
3780
        // trigger the notification once the server detects the peer
3781
        // disconnects.
UNCOV
3782
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
3783
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
3784
        )
×
UNCOV
3785

×
UNCOV
3786
        return c
×
3787
}
3788

3789
// FindPeer will return the peer that corresponds to the passed in public key.
3790
// This function is used by the funding manager, allowing it to update the
3791
// daemon's local representation of the remote peer.
3792
//
3793
// NOTE: This function is safe for concurrent access.
UNCOV
3794
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
3795
        s.mu.RLock()
×
UNCOV
3796
        defer s.mu.RUnlock()
×
UNCOV
3797

×
UNCOV
3798
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3799

×
UNCOV
3800
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3801
}
×
3802

3803
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3804
// which should be a string representation of the peer's serialized, compressed
3805
// public key.
3806
//
3807
// NOTE: This function is safe for concurrent access.
UNCOV
3808
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3809
        s.mu.RLock()
×
UNCOV
3810
        defer s.mu.RUnlock()
×
UNCOV
3811

×
UNCOV
3812
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3813
}
×
3814

3815
// findPeerByPubStr is an internal method that retrieves the specified peer from
3816
// the server's internal state using.
UNCOV
3817
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3818
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3819
        if !ok {
×
UNCOV
3820
                return nil, ErrPeerNotConnected
×
UNCOV
3821
        }
×
3822

UNCOV
3823
        return peer, nil
×
3824
}
3825

3826
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3827
// exponential backoff. If no previous backoff was known, the default is
3828
// returned.
3829
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
3830
        startTime time.Time) time.Duration {
×
UNCOV
3831

×
UNCOV
3832
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
3833
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
3834
        if !ok {
×
UNCOV
3835
                // If an existing backoff was unknown, use the default.
×
UNCOV
3836
                return s.cfg.MinBackoff
×
UNCOV
3837
        }
×
3838

3839
        // If the peer failed to start properly, we'll just use the previous
3840
        // backoff to compute the subsequent randomized exponential backoff
3841
        // duration. This will roughly double on average.
UNCOV
3842
        if startTime.IsZero() {
×
UNCOV
3843
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3844
        }
×
3845

3846
        // The peer succeeded in starting. If the connection didn't last long
3847
        // enough to be considered stable, we'll continue to back off retries
3848
        // with this peer.
UNCOV
3849
        connDuration := time.Since(startTime)
×
UNCOV
3850
        if connDuration < defaultStableConnDuration {
×
UNCOV
3851
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3852
        }
×
3853

3854
        // The peer succeed in starting and this was stable peer, so we'll
3855
        // reduce the timeout duration by the length of the connection after
3856
        // applying randomized exponential backoff. We'll only apply this in the
3857
        // case that:
3858
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
UNCOV
3859
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
UNCOV
3860
        if relaxedBackoff > s.cfg.MinBackoff {
×
UNCOV
3861
                return relaxedBackoff
×
UNCOV
3862
        }
×
3863

3864
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3865
        // the stable connection lasted much longer than our previous backoff.
3866
        // To reward such good behavior, we'll reconnect after the default
3867
        // timeout.
UNCOV
3868
        return s.cfg.MinBackoff
×
3869
}
3870

3871
// shouldDropLocalConnection determines if our local connection to a remote peer
3872
// should be dropped in the case of concurrent connection establishment. In
3873
// order to deterministically decide which connection should be dropped, we'll
3874
// utilize the ordering of the local and remote public key. If we didn't use
3875
// such a tie breaker, then we risk _both_ connections erroneously being
3876
// dropped.
UNCOV
3877
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
UNCOV
3878
        localPubBytes := local.SerializeCompressed()
×
UNCOV
3879
        remotePubPbytes := remote.SerializeCompressed()
×
UNCOV
3880

×
UNCOV
3881
        // The connection that comes from the node with a "smaller" pubkey
×
UNCOV
3882
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
UNCOV
3883
        // should drop our established connection.
×
UNCOV
3884
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
UNCOV
3885
}
×
3886

3887
// InboundPeerConnected initializes a new peer in response to a new inbound
3888
// connection.
3889
//
3890
// NOTE: This function is safe for concurrent access.
UNCOV
3891
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
3892
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3893
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3894
        if s.Stopped() {
×
UNCOV
3895
                return
×
3896
        }
×
3897

UNCOV
3898
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3899
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3900
        pubStr := string(pubSer)
×
UNCOV
3901

×
UNCOV
3902
        var pubBytes [33]byte
×
UNCOV
3903
        copy(pubBytes[:], pubSer)
×
UNCOV
3904

×
3905
        s.mu.Lock()
×
3906
        defer s.mu.Unlock()
×
3907

×
3908
        // If we already have an outbound connection to this peer, then ignore
×
3909
        // this new connection.
×
3910
        if p, ok := s.outboundPeers[pubStr]; ok {
×
3911
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
3912
                        "ignoring inbound connection from local=%v, remote=%v",
×
3913
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3914

×
UNCOV
3915
                conn.Close()
×
UNCOV
3916
                return
×
UNCOV
3917
        }
×
3918

3919
        // If we already have a valid connection that is scheduled to take
3920
        // precedence once the prior peer has finished disconnecting, we'll
3921
        // ignore this connection.
UNCOV
3922
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3923
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3924
                        "scheduled", conn.RemoteAddr(), p)
×
UNCOV
3925
                conn.Close()
×
UNCOV
3926
                return
×
UNCOV
3927
        }
×
3928

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

×
UNCOV
3931
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
3932
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
3933
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
3934
        // default case as we expect these to be the only error values returned
×
UNCOV
3935
        // from findPeerByPubStr.
×
UNCOV
3936
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3937
        switch err {
×
UNCOV
3938
        case ErrPeerNotConnected:
×
UNCOV
3939
                // We were unable to locate an existing connection with the
×
UNCOV
3940
                // target peer, proceed to connect.
×
UNCOV
3941
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3942
                s.peerConnected(conn, nil, true)
×
3943

UNCOV
3944
        case nil:
×
UNCOV
3945
                ctx := btclog.WithCtx(
×
UNCOV
3946
                        context.TODO(),
×
UNCOV
3947
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
3948
                )
×
UNCOV
3949

×
UNCOV
3950
                // We already have a connection with the incoming peer. If the
×
3951
                // connection we've already established should be kept and is
×
3952
                // not of the same type of the new connection (inbound), then
×
3953
                // we'll close out the new connection s.t there's only a single
×
3954
                // connection between us.
×
3955
                localPub := s.identityECDH.PubKey()
×
UNCOV
3956
                if !connectedPeer.Inbound() &&
×
UNCOV
3957
                        !shouldDropLocalConnection(localPub, nodePub) {
×
UNCOV
3958

×
UNCOV
3959
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
UNCOV
3960
                                "peer, but already have outbound "+
×
UNCOV
3961
                                "connection, dropping conn",
×
UNCOV
3962
                                fmt.Errorf("already have outbound conn"))
×
UNCOV
3963
                        conn.Close()
×
UNCOV
3964
                        return
×
UNCOV
3965
                }
×
3966

3967
                // Otherwise, if we should drop the connection, then we'll
3968
                // disconnect our already connected peer.
UNCOV
3969
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
3970

×
UNCOV
3971
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3972

×
UNCOV
3973
                // Remove the current peer from the server's internal state and
×
UNCOV
3974
                // signal that the peer termination watcher does not need to
×
UNCOV
3975
                // execute for this peer.
×
UNCOV
3976
                s.removePeerUnsafe(ctx, connectedPeer)
×
UNCOV
3977
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
3978
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
3979
                        s.peerConnected(conn, nil, true)
×
UNCOV
3980
                }
×
3981
        }
3982
}
3983

3984
// OutboundPeerConnected initializes a new peer in response to a new outbound
3985
// connection.
3986
// NOTE: This function is safe for concurrent access.
3987
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
3988
        // Exit early if we have already been instructed to shutdown, this
×
3989
        // prevents any delayed callbacks from accidentally registering peers.
×
3990
        if s.Stopped() {
×
3991
                return
×
3992
        }
×
3993

UNCOV
3994
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3995
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3996
        pubStr := string(pubSer)
×
UNCOV
3997

×
UNCOV
3998
        var pubBytes [33]byte
×
UNCOV
3999
        copy(pubBytes[:], pubSer)
×
UNCOV
4000

×
UNCOV
4001
        s.mu.Lock()
×
UNCOV
4002
        defer s.mu.Unlock()
×
UNCOV
4003

×
UNCOV
4004
        // If we already have an inbound connection to this peer, then ignore
×
UNCOV
4005
        // this new connection.
×
UNCOV
4006
        if p, ok := s.inboundPeers[pubStr]; ok {
×
UNCOV
4007
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
UNCOV
4008
                        "ignoring outbound connection from local=%v, remote=%v",
×
UNCOV
4009
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4010

×
UNCOV
4011
                if connReq != nil {
×
UNCOV
4012
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4013
                }
×
UNCOV
4014
                conn.Close()
×
UNCOV
4015
                return
×
4016
        }
UNCOV
4017
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
UNCOV
4018
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4019
                s.connMgr.Remove(connReq.ID())
×
4020
                conn.Close()
×
UNCOV
4021
                return
×
UNCOV
4022
        }
×
4023

4024
        // If we already have a valid connection that is scheduled to take
4025
        // precedence once the prior peer has finished disconnecting, we'll
4026
        // ignore this connection.
UNCOV
4027
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
UNCOV
4028
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
UNCOV
4029

×
UNCOV
4030
                if connReq != nil {
×
UNCOV
4031
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4032
                }
×
4033

UNCOV
4034
                conn.Close()
×
UNCOV
4035
                return
×
4036
        }
4037

UNCOV
4038
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
UNCOV
4039
                conn.RemoteAddr())
×
UNCOV
4040

×
UNCOV
4041
        if connReq != nil {
×
UNCOV
4042
                // A successful connection was returned by the connmgr.
×
UNCOV
4043
                // Immediately cancel all pending requests, excluding the
×
UNCOV
4044
                // outbound connection we just established.
×
UNCOV
4045
                ignore := connReq.ID()
×
4046
                s.cancelConnReqs(pubStr, &ignore)
×
4047
        } else {
×
4048
                // This was a successful connection made by some other
×
4049
                // subsystem. Remove all requests being managed by the connmgr.
×
4050
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4051
        }
×
4052

4053
        // If we already have a connection with this peer, decide whether or not
4054
        // we need to drop the stale connection. We forgo adding a default case
4055
        // as we expect these to be the only error values returned from
4056
        // findPeerByPubStr.
4057
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
4058
        switch err {
×
4059
        case ErrPeerNotConnected:
×
4060
                // We were unable to locate an existing connection with the
×
UNCOV
4061
                // target peer, proceed to connect.
×
4062
                s.peerConnected(conn, connReq, false)
×
4063

UNCOV
4064
        case nil:
×
UNCOV
4065
                ctx := btclog.WithCtx(
×
UNCOV
4066
                        context.TODO(),
×
UNCOV
4067
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
4068
                )
×
UNCOV
4069

×
UNCOV
4070
                // We already have a connection with the incoming peer. If the
×
UNCOV
4071
                // connection we've already established should be kept and is
×
UNCOV
4072
                // not of the same type of the new connection (outbound), then
×
UNCOV
4073
                // we'll close out the new connection s.t there's only a single
×
UNCOV
4074
                // connection between us.
×
UNCOV
4075
                localPub := s.identityECDH.PubKey()
×
UNCOV
4076
                if connectedPeer.Inbound() &&
×
UNCOV
4077
                        shouldDropLocalConnection(localPub, nodePub) {
×
UNCOV
4078

×
UNCOV
4079
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
UNCOV
4080
                                "to peer, but already have inbound "+
×
UNCOV
4081
                                "connection, dropping conn",
×
UNCOV
4082
                                fmt.Errorf("already have inbound conn"))
×
UNCOV
4083
                        if connReq != nil {
×
UNCOV
4084
                                s.connMgr.Remove(connReq.ID())
×
UNCOV
4085
                        }
×
UNCOV
4086
                        conn.Close()
×
UNCOV
4087
                        return
×
4088
                }
4089

4090
                // Otherwise, _their_ connection should be dropped. So we'll
4091
                // disconnect the peer and send the now obsolete peer to the
4092
                // server for garbage collection.
UNCOV
4093
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
4094

×
UNCOV
4095
                // Remove the current peer from the server's internal state and
×
UNCOV
4096
                // signal that the peer termination watcher does not need to
×
UNCOV
4097
                // execute for this peer.
×
UNCOV
4098
                s.removePeerUnsafe(ctx, connectedPeer)
×
UNCOV
4099
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
4100
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
4101
                        s.peerConnected(conn, connReq, false)
×
UNCOV
4102
                }
×
4103
        }
4104
}
4105

4106
// UnassignedConnID is the default connection ID that a request can have before
4107
// it actually is submitted to the connmgr.
4108
// TODO(conner): move into connmgr package, or better, add connmgr method for
4109
// generating atomic IDs
4110
const UnassignedConnID uint64 = 0
4111

4112
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4113
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4114
// Afterwards, each connection request removed from the connmgr. The caller can
4115
// optionally specify a connection ID to ignore, which prevents us from
4116
// canceling a successful request. All persistent connreqs for the provided
4117
// pubkey are discarded after the operationjw.
UNCOV
4118
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
4119
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
4120
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
4121
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
4122
                close(cancelChan)
×
UNCOV
4123
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
4124
        }
×
4125

4126
        // Next, check to see if we have any outstanding persistent connection
4127
        // requests to this peer. If so, then we'll remove all of these
4128
        // connection requests, and also delete the entry from the map.
UNCOV
4129
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4130
        if !ok {
×
UNCOV
4131
                return
×
UNCOV
4132
        }
×
4133

UNCOV
4134
        for _, connReq := range connReqs {
×
UNCOV
4135
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4136

×
UNCOV
4137
                // Atomically capture the current request identifier.
×
UNCOV
4138
                connID := connReq.ID()
×
UNCOV
4139

×
UNCOV
4140
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4141
                // yet been schedule.
×
UNCOV
4142
                if connID == UnassignedConnID {
×
UNCOV
4143
                        continue
×
4144
                }
4145

4146
                // Skip a particular connection ID if instructed.
UNCOV
4147
                if skip != nil && connID == *skip {
×
UNCOV
4148
                        continue
×
4149
                }
4150

UNCOV
4151
                s.connMgr.Remove(connID)
×
4152
        }
4153

UNCOV
4154
        delete(s.persistentConnReqs, pubStr)
×
4155
}
4156

4157
// handleCustomMessage dispatches an incoming custom peers message to
4158
// subscribers.
UNCOV
4159
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4160
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4161
                peer, msg.Type)
×
UNCOV
4162

×
UNCOV
4163
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4164
                Peer: peer,
×
UNCOV
4165
                Msg:  msg,
×
UNCOV
4166
        })
×
UNCOV
4167
}
×
4168

4169
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4170
// messages.
4171
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4172
        return s.customMessageServer.Subscribe()
×
UNCOV
4173
}
×
4174

4175
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4176
// the channelNotifier's NotifyOpenChannelEvent.
4177
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
UNCOV
4178
        remotePub *btcec.PublicKey) {
×
UNCOV
4179

×
UNCOV
4180
        // Call newOpenChan to update the access manager's maps for this peer.
×
UNCOV
4181
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
×
UNCOV
4182
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4183
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
×
UNCOV
4184
        }
×
4185

4186
        // Notify subscribers about this open channel event.
UNCOV
4187
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4188
}
4189

4190
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4191
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4192
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
UNCOV
4193
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
×
UNCOV
4194

×
UNCOV
4195
        // Call newPendingOpenChan to update the access manager's maps for this
×
UNCOV
4196
        // peer.
×
UNCOV
4197
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
×
UNCOV
4198
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4199
                        "channel[%v] pending open",
×
UNCOV
4200
                        remotePub.SerializeCompressed(), op)
×
UNCOV
4201
        }
×
4202

4203
        // Notify subscribers about this event.
UNCOV
4204
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4205
}
4206

4207
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4208
// calls the channelNotifier's NotifyFundingTimeout.
4209
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
UNCOV
4210
        remotePub *btcec.PublicKey) {
×
UNCOV
4211

×
UNCOV
4212
        // Call newPendingCloseChan to potentially demote the peer.
×
UNCOV
4213
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
UNCOV
4214
        if err != nil {
×
UNCOV
4215
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4216
                        "channel[%v] pending close",
×
UNCOV
4217
                        remotePub.SerializeCompressed(), op)
×
UNCOV
4218
        }
×
4219

UNCOV
4220
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
×
UNCOV
4221
                // If we encounter an error while attempting to disconnect the
×
UNCOV
4222
                // peer, log the error.
×
UNCOV
4223
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
UNCOV
4224
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
UNCOV
4225
                }
×
4226
        }
4227

4228
        // Notify subscribers about this event.
4229
        s.channelNotifier.NotifyFundingTimeout(op)
×
4230
}
4231

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

×
UNCOV
4239
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4240
        addr := conn.RemoteAddr()
×
UNCOV
4241
        pubKey := brontideConn.RemotePub()
×
UNCOV
4242

×
4243
        // Only restrict access for inbound connections, which means if the
×
4244
        // remote node's public key is banned or the restricted slots are used
×
4245
        // up, we will drop the connection.
×
4246
        //
×
UNCOV
4247
        // TODO(yy): Consider perform this check in
×
UNCOV
4248
        // `peerAccessMan.addPeerAccess`.
×
4249
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
×
4250
        if inbound && err != nil {
×
4251
                pubSer := pubKey.SerializeCompressed()
×
4252

×
4253
                // Clean up the persistent peer maps if we're dropping this
×
UNCOV
4254
                // connection.
×
UNCOV
4255
                s.bannedPersistentPeerConnection(string(pubSer))
×
UNCOV
4256

×
UNCOV
4257
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
UNCOV
4258
                        "of restricted-access connection slots: %v.", pubSer,
×
UNCOV
4259
                        err)
×
UNCOV
4260

×
UNCOV
4261
                conn.Close()
×
UNCOV
4262

×
UNCOV
4263
                return
×
UNCOV
4264
        }
×
4265

UNCOV
4266
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4267
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4268

×
UNCOV
4269
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4270
                IdentityKey: pubKey,
×
UNCOV
4271
                Address:     addr,
×
UNCOV
4272
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4273
        }
×
UNCOV
4274

×
UNCOV
4275
        // With the brontide connection established, we'll now craft the feature
×
UNCOV
4276
        // vectors to advertise to the remote node.
×
UNCOV
4277
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
UNCOV
4278
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
4279

×
4280
        // Lookup past error caches for the peer in the server. If no buffer is
×
4281
        // found, create a fresh buffer.
×
4282
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
4283
        errBuffer, ok := s.peerErrors[pkStr]
×
4284
        if !ok {
×
4285
                var err error
×
4286
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
4287
                if err != nil {
×
4288
                        srvrLog.Errorf("unable to create peer %v", err)
×
4289
                        return
×
4290
                }
×
4291
        }
4292

4293
        // If we directly set the peer.Config TowerClient member to the
4294
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4295
        // the peer.Config's TowerClient member will not evaluate to nil even
4296
        // though the underlying value is nil. To avoid this gotcha which can
4297
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4298
        // TowerClient if needed.
UNCOV
4299
        var towerClient wtclient.ClientManager
×
UNCOV
4300
        if s.towerClientMgr != nil {
×
UNCOV
4301
                towerClient = s.towerClientMgr
×
UNCOV
4302
        }
×
4303

UNCOV
4304
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4305
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4306

×
UNCOV
4307
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4308
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4309
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4310
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4311
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4312
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4313
        pCfg := peer.Config{
×
UNCOV
4314
                Conn:                    brontideConn,
×
UNCOV
4315
                ConnReq:                 connReq,
×
4316
                Addr:                    peerAddr,
×
4317
                Inbound:                 inbound,
×
4318
                Features:                initFeatures,
×
UNCOV
4319
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4320
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4321
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4322
                ErrorBuffer:             errBuffer,
×
UNCOV
4323
                WritePool:               s.writePool,
×
UNCOV
4324
                ReadPool:                s.readPool,
×
UNCOV
4325
                Switch:                  s.htlcSwitch,
×
UNCOV
4326
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4327
                ChannelDB:               s.chanStateDB,
×
UNCOV
4328
                ChannelGraph:            s.graphDB,
×
UNCOV
4329
                ChainArb:                s.chainArb,
×
UNCOV
4330
                AuthGossiper:            s.authGossiper,
×
UNCOV
4331
                ChanStatusMgr:           s.chanStatusMgr,
×
UNCOV
4332
                ChainIO:                 s.cc.ChainIO,
×
UNCOV
4333
                FeeEstimator:            s.cc.FeeEstimator,
×
UNCOV
4334
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
UNCOV
4335
                SigPool:                 s.sigPool,
×
UNCOV
4336
                Wallet:                  s.cc.Wallet,
×
UNCOV
4337
                ChainNotifier:           s.cc.ChainNotifier,
×
UNCOV
4338
                BestBlockView:           s.cc.BestBlockTracker,
×
UNCOV
4339
                RoutingPolicy:           s.cc.RoutingPolicy,
×
UNCOV
4340
                Sphinx:                  s.sphinx,
×
UNCOV
4341
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4342
                Invoices:                s.invoices,
×
UNCOV
4343
                ChannelNotifier:         s.channelNotifier,
×
UNCOV
4344
                HtlcNotifier:            s.htlcNotifier,
×
UNCOV
4345
                TowerClient:             towerClient,
×
UNCOV
4346
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4347
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4348
                        lnwire.NodeAnnouncement1, error) {
×
UNCOV
4349

×
UNCOV
4350
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4351
                },
×
4352

4353
                PongBuf: s.pongBuf,
4354

4355
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4356

4357
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4358

4359
                FundingManager: s.fundingMgr,
4360

4361
                Hodl:                    s.cfg.Hodl,
4362
                UnsafeReplay:            s.cfg.UnsafeReplay,
4363
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4364
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4365
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4366
                ChannelCloseConfs:       s.cfg.Dev.ChannelCloseConfs(),
4367
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4368
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4369
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4370
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4371
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4372
                HandleCustomMessage:    s.handleCustomMessage,
4373
                GetAliases:             s.aliasMgr.GetAliases,
4374
                RequestAlias:           s.aliasMgr.RequestAlias,
4375
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4376
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4377
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4378
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4379
                MaxFeeExposure:         thresholdMSats,
4380
                Quit:                   s.quit,
4381
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4382
                AuxSigner:              s.implCfg.AuxSigner,
4383
                MsgRouter:              s.implCfg.MsgRouter,
4384
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4385
                AuxResolver:            s.implCfg.AuxContractResolver,
4386
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4387
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
UNCOV
4388
                ShouldFwdExpEndorsement: func() bool {
×
UNCOV
4389
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
UNCOV
4390
                                return false
×
UNCOV
4391
                        }
×
4392

UNCOV
4393
                        return clock.NewDefaultClock().Now().Before(
×
NEW
4394
                                EndorsementExperimentEnd,
×
UNCOV
4395
                        )
×
4396
                },
4397
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4398
        }
4399

UNCOV
4400
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4401
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4402

×
UNCOV
4403
        p := peer.NewBrontide(pCfg)
×
UNCOV
4404

×
UNCOV
4405
        // Update the access manager with the access permission for this peer.
×
UNCOV
4406
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
UNCOV
4407

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

×
UNCOV
4411
        s.addPeer(p)
×
UNCOV
4412

×
UNCOV
4413
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4414
        // delete the previous error buffer from the server's map of error
×
UNCOV
4415
        // buffers.
×
UNCOV
4416
        delete(s.peerErrors, pkStr)
×
UNCOV
4417

×
UNCOV
4418
        // Dispatch a goroutine to asynchronously start the peer. This process
×
UNCOV
4419
        // includes sending and receiving Init messages, which would be a DOS
×
UNCOV
4420
        // vector if we held the server's mutex throughout the procedure.
×
UNCOV
4421
        s.wg.Add(1)
×
UNCOV
4422
        go s.peerInitializer(p)
×
4423
}
4424

4425
// addPeer adds the passed peer to the server's global state of all active
4426
// peers.
UNCOV
4427
func (s *server) addPeer(p *peer.Brontide) {
×
UNCOV
4428
        if p == nil {
×
UNCOV
4429
                return
×
UNCOV
4430
        }
×
4431

UNCOV
4432
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4433

×
UNCOV
4434
        // Ignore new peers if we're shutting down.
×
UNCOV
4435
        if s.Stopped() {
×
UNCOV
4436
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
UNCOV
4437
                        pubBytes)
×
UNCOV
4438
                p.Disconnect(ErrServerShuttingDown)
×
UNCOV
4439

×
UNCOV
4440
                return
×
UNCOV
4441
        }
×
4442

4443
        // Track the new peer in our indexes so we can quickly look it up either
4444
        // according to its public key, or its peer ID.
4445
        // TODO(roasbeef): pipe all requests through to the
4446
        // queryHandler/peerManager
4447

4448
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4449
        // be human-readable.
UNCOV
4450
        pubStr := string(pubBytes)
×
UNCOV
4451

×
UNCOV
4452
        s.peersByPub[pubStr] = p
×
UNCOV
4453

×
UNCOV
4454
        if p.Inbound() {
×
UNCOV
4455
                s.inboundPeers[pubStr] = p
×
UNCOV
4456
        } else {
×
4457
                s.outboundPeers[pubStr] = p
×
4458
        }
×
4459

4460
        // Inform the peer notifier of a peer online event so that it can be reported
4461
        // to clients listening for peer events.
UNCOV
4462
        var pubKey [33]byte
×
UNCOV
4463
        copy(pubKey[:], pubBytes)
×
4464
}
4465

4466
// peerInitializer asynchronously starts a newly connected peer after it has
4467
// been added to the server's peer map. This method sets up a
4468
// peerTerminationWatcher for the given peer, and ensures that it executes even
4469
// if the peer failed to start. In the event of a successful connection, this
4470
// method reads the negotiated, local feature-bits and spawns the appropriate
4471
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4472
// be signaled of the new peer once the method returns.
4473
//
4474
// NOTE: This MUST be launched as a goroutine.
UNCOV
4475
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4476
        defer s.wg.Done()
×
UNCOV
4477

×
UNCOV
4478
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4479

×
UNCOV
4480
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4481
        if s.Stopped() {
×
UNCOV
4482
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
UNCOV
4483
                        pubBytes)
×
UNCOV
4484
                return
×
UNCOV
4485
        }
×
4486

4487
        // Create a channel that will be used to signal a successful start of
4488
        // the link. This prevents the peer termination watcher from beginning
4489
        // its duty too early.
UNCOV
4490
        ready := make(chan struct{})
×
UNCOV
4491

×
UNCOV
4492
        // Before starting the peer, launch a goroutine to watch for the
×
UNCOV
4493
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4494
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4495
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4496
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4497
        // that the server has already handled the removal of this peer.
×
UNCOV
4498
        s.wg.Add(1)
×
UNCOV
4499
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4500

×
UNCOV
4501
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4502
        // will unblock the peerTerminationWatcher.
×
UNCOV
4503
        if err := p.Start(); err != nil {
×
UNCOV
4504
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4505

×
UNCOV
4506
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4507
                return
×
UNCOV
4508
        }
×
4509

4510
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4511
        // was successful, and to begin watching the peer's wait group.
4512
        close(ready)
×
4513

×
UNCOV
4514
        s.mu.Lock()
×
UNCOV
4515
        defer s.mu.Unlock()
×
UNCOV
4516

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

×
UNCOV
4520
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4521
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4522
        pubStr := string(pubBytes)
×
UNCOV
4523
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4524
                select {
×
UNCOV
4525
                case peerChan <- p:
×
UNCOV
4526
                case <-s.quit:
×
UNCOV
4527
                        return
×
4528
                }
4529
        }
UNCOV
4530
        delete(s.peerConnectedListeners, pubStr)
×
UNCOV
4531

×
UNCOV
4532
        // Since the peer has been fully initialized, now it's time to notify
×
UNCOV
4533
        // the RPC about the peer online event.
×
UNCOV
4534
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
×
4535
}
4536

4537
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4538
// and then cleans up all resources allocated to the peer, notifies relevant
4539
// sub-systems of its demise, and finally handles re-connecting to the peer if
4540
// it's persistent. If the server intentionally disconnects a peer, it should
4541
// have a corresponding entry in the ignorePeerTermination map which will cause
4542
// the cleanup routine to exit early. The passed `ready` chan is used to
4543
// synchronize when WaitForDisconnect should begin watching on the peer's
4544
// waitgroup. The ready chan should only be signaled if the peer starts
4545
// successfully, otherwise the peer should be disconnected instead.
4546
//
4547
// NOTE: This MUST be launched as a goroutine.
UNCOV
4548
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4549
        defer s.wg.Done()
×
UNCOV
4550

×
UNCOV
4551
        ctx := btclog.WithCtx(
×
UNCOV
4552
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
UNCOV
4553
        )
×
4554

×
4555
        p.WaitForDisconnect(ready)
×
UNCOV
4556

×
UNCOV
4557
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
UNCOV
4558

×
UNCOV
4559
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4560
        // the other sub-systems will already be shutting down.
×
UNCOV
4561
        if s.Stopped() {
×
UNCOV
4562
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
×
UNCOV
4563
                return
×
UNCOV
4564
        }
×
4565

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

×
UNCOV
4572
        pubKey := p.IdentityKey()
×
UNCOV
4573

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

×
UNCOV
4578
        // Tell the switch to remove all links associated with this peer.
×
UNCOV
4579
        // Passing nil as the target link indicates that all links associated
×
UNCOV
4580
        // with this interface should be closed.
×
UNCOV
4581
        //
×
UNCOV
4582
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
UNCOV
4583
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
UNCOV
4584
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
UNCOV
4585
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
UNCOV
4586
        }
×
4587

UNCOV
4588
        for _, link := range links {
×
UNCOV
4589
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4590
        }
×
4591

UNCOV
4592
        s.mu.Lock()
×
UNCOV
4593
        defer s.mu.Unlock()
×
UNCOV
4594

×
UNCOV
4595
        // If there were any notification requests for when this peer
×
UNCOV
4596
        // disconnected, we can trigger them now.
×
UNCOV
4597
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
UNCOV
4598
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4599
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4600
                close(offlineChan)
×
UNCOV
4601
        }
×
UNCOV
4602
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4603

×
UNCOV
4604
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4605
        // peer termination watcher and skip cleanup.
×
UNCOV
4606
        if _, ok := s.ignorePeerTermination[p]; ok {
×
UNCOV
4607
                delete(s.ignorePeerTermination, p)
×
UNCOV
4608

×
UNCOV
4609
                pubKey := p.PubKey()
×
UNCOV
4610
                pubStr := string(pubKey[:])
×
UNCOV
4611

×
UNCOV
4612
                // If a connection callback is present, we'll go ahead and
×
4613
                // execute it now that previous peer has fully disconnected. If
×
4614
                // the callback is not present, this likely implies the peer was
×
UNCOV
4615
                // purposefully disconnected via RPC, and that no reconnect
×
UNCOV
4616
                // should be attempted.
×
UNCOV
4617
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
UNCOV
4618
                if ok {
×
UNCOV
4619
                        delete(s.scheduledPeerConnection, pubStr)
×
UNCOV
4620
                        connCallback()
×
UNCOV
4621
                }
×
UNCOV
4622
                return
×
4623
        }
4624

4625
        // First, cleanup any remaining state the server has regarding the peer
4626
        // in question.
UNCOV
4627
        s.removePeerUnsafe(ctx, p)
×
UNCOV
4628

×
UNCOV
4629
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4630
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4631
                return
×
UNCOV
4632
        }
×
4633

4634
        // Get the last address that we used to connect to the peer.
UNCOV
4635
        addrs := []net.Addr{
×
UNCOV
4636
                p.NetAddress().Address,
×
UNCOV
4637
        }
×
UNCOV
4638

×
UNCOV
4639
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4640
        // reconnection purposes.
×
UNCOV
4641
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
×
UNCOV
4642
        switch {
×
4643
        // We found advertised addresses, so use them.
UNCOV
4644
        case err == nil:
×
UNCOV
4645
                addrs = advertisedAddrs
×
4646

4647
        // The peer doesn't have an advertised address.
UNCOV
4648
        case err == errNoAdvertisedAddr:
×
UNCOV
4649
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4650
                // peer address.
×
UNCOV
4651
                if !p.Inbound() {
×
UNCOV
4652
                        break
×
4653
                }
4654

4655
                // Fall back to the existing peer address if
4656
                // we're not accepting connections over Tor.
UNCOV
4657
                if s.torController == nil {
×
UNCOV
4658
                        break
×
4659
                }
4660

4661
                // If we are, the peer's address won't be known
4662
                // to us (we'll see a private address, which is
4663
                // the address used by our onion service to dial
4664
                // to lnd), so we don't have enough information
4665
                // to attempt a reconnect.
UNCOV
4666
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
UNCOV
4667
                        "to inbound peer without advertised address")
×
UNCOV
4668
                return
×
4669

4670
        // We came across an error retrieving an advertised
4671
        // address, log it, and fall back to the existing peer
4672
        // address.
UNCOV
4673
        default:
×
UNCOV
4674
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
UNCOV
4675
                        "address for peer", err)
×
4676
        }
4677

4678
        // Make an easy lookup map so that we can check if an address
4679
        // is already in the address list that we have stored for this peer.
UNCOV
4680
        existingAddrs := make(map[string]bool)
×
UNCOV
4681
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4682
                existingAddrs[addr.String()] = true
×
UNCOV
4683
        }
×
4684

4685
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4686
        for _, addr := range addrs {
×
UNCOV
4687
                if existingAddrs[addr.String()] {
×
UNCOV
4688
                        continue
×
4689
                }
4690

UNCOV
4691
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4692
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4693
                        &lnwire.NetAddress{
×
4694
                                IdentityKey: p.IdentityKey(),
×
4695
                                Address:     addr,
×
4696
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4697
                        },
×
UNCOV
4698
                )
×
4699
        }
4700

4701
        // Record the computed backoff in the backoff map.
UNCOV
4702
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4703
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4704

×
UNCOV
4705
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4706
        // exist.
×
UNCOV
4707
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4708
        if !ok {
×
UNCOV
4709
                cancelChan = make(chan struct{})
×
UNCOV
4710
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4711
        }
×
4712

4713
        // We choose not to wait group this go routine since the Connect
4714
        // call can stall for arbitrarily long if we shutdown while an
4715
        // outbound connection attempt is being made.
4716
        go func() {
×
UNCOV
4717
                srvrLog.DebugS(ctx, "Scheduling connection "+
×
UNCOV
4718
                        "re-establishment to persistent peer",
×
UNCOV
4719
                        "reconnecting_in", backoff)
×
UNCOV
4720

×
UNCOV
4721
                select {
×
UNCOV
4722
                case <-time.After(backoff):
×
UNCOV
4723
                case <-cancelChan:
×
UNCOV
4724
                        return
×
UNCOV
4725
                case <-s.quit:
×
UNCOV
4726
                        return
×
4727
                }
4728

UNCOV
4729
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
UNCOV
4730
                        "connection")
×
UNCOV
4731

×
UNCOV
4732
                s.connectToPersistentPeer(pubStr)
×
4733
        }()
4734
}
4735

4736
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4737
// to connect to the peer. It creates connection requests if there are
4738
// currently none for a given address and it removes old connection requests
4739
// if the associated address is no longer in the latest address list for the
4740
// peer.
UNCOV
4741
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
UNCOV
4742
        s.mu.Lock()
×
UNCOV
4743
        defer s.mu.Unlock()
×
UNCOV
4744

×
UNCOV
4745
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4746
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4747
        // connection requests for the associated address and then any leftover
×
UNCOV
4748
        // entries will indicate which addresses we should create new
×
UNCOV
4749
        // connection requests for.
×
UNCOV
4750
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4751
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4752
                addrMap[addr.String()] = addr
×
UNCOV
4753
        }
×
4754

4755
        // Go through each of the existing connection requests and
4756
        // check if they correspond to the latest set of addresses. If
4757
        // there is a connection requests that does not use one of the latest
4758
        // advertised addresses then remove that connection request.
UNCOV
4759
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4760
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4761
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4762

×
UNCOV
4763
                switch _, ok := addrMap[lnAddr]; ok {
×
4764
                // If the existing connection request is using one of the
4765
                // latest advertised addresses for the peer then we add it to
4766
                // updatedConnReqs and remove the associated address from
4767
                // addrMap so that we don't recreate this connReq later on.
UNCOV
4768
                case true:
×
UNCOV
4769
                        updatedConnReqs = append(
×
UNCOV
4770
                                updatedConnReqs, connReq,
×
UNCOV
4771
                        )
×
UNCOV
4772
                        delete(addrMap, lnAddr)
×
4773

4774
                // If the existing connection request is using an address that
4775
                // is not one of the latest advertised addresses for the peer
4776
                // then we remove the connecting request from the connection
4777
                // manager.
UNCOV
4778
                case false:
×
UNCOV
4779
                        srvrLog.Info(
×
UNCOV
4780
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4781
                        )
×
UNCOV
4782
                        s.connMgr.Remove(connReq.ID())
×
4783
                }
4784
        }
4785

UNCOV
4786
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4787

×
UNCOV
4788
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4789
        if !ok {
×
UNCOV
4790
                cancelChan = make(chan struct{})
×
UNCOV
4791
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4792
        }
×
4793

4794
        // Any addresses left in addrMap are new ones that we have not made
4795
        // connection requests for. So create new connection requests for those.
4796
        // If there is more than one address in the address map, stagger the
4797
        // creation of the connection requests for those.
4798
        go func() {
×
4799
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
4800
                defer ticker.Stop()
×
UNCOV
4801

×
UNCOV
4802
                for _, addr := range addrMap {
×
UNCOV
4803
                        // Send the persistent connection request to the
×
UNCOV
4804
                        // connection manager, saving the request itself so we
×
UNCOV
4805
                        // can cancel/restart the process as needed.
×
UNCOV
4806
                        connReq := &connmgr.ConnReq{
×
UNCOV
4807
                                Addr:      addr,
×
UNCOV
4808
                                Permanent: true,
×
UNCOV
4809
                        }
×
UNCOV
4810

×
UNCOV
4811
                        s.mu.Lock()
×
UNCOV
4812
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4813
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4814
                        )
×
UNCOV
4815
                        s.mu.Unlock()
×
UNCOV
4816

×
UNCOV
4817
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4818
                                "channel peer %v", addr)
×
UNCOV
4819

×
UNCOV
4820
                        go s.connMgr.Connect(connReq)
×
UNCOV
4821

×
UNCOV
4822
                        select {
×
UNCOV
4823
                        case <-s.quit:
×
UNCOV
4824
                                return
×
UNCOV
4825
                        case <-cancelChan:
×
UNCOV
4826
                                return
×
UNCOV
4827
                        case <-ticker.C:
×
4828
                        }
4829
                }
4830
        }()
4831
}
4832

4833
// removePeerUnsafe removes the passed peer from the server's state of all
4834
// active peers.
4835
//
4836
// NOTE: Server mutex must be held when calling this function.
UNCOV
4837
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
×
UNCOV
4838
        if p == nil {
×
UNCOV
4839
                return
×
UNCOV
4840
        }
×
4841

UNCOV
4842
        srvrLog.DebugS(ctx, "Removing peer")
×
UNCOV
4843

×
UNCOV
4844
        // Exit early if we have already been instructed to shutdown, the peers
×
UNCOV
4845
        // will be disconnected in the server shutdown process.
×
UNCOV
4846
        if s.Stopped() {
×
UNCOV
4847
                return
×
UNCOV
4848
        }
×
4849

4850
        // Capture the peer's public key and string representation.
UNCOV
4851
        pKey := p.PubKey()
×
UNCOV
4852
        pubSer := pKey[:]
×
UNCOV
4853
        pubStr := string(pubSer)
×
UNCOV
4854

×
UNCOV
4855
        delete(s.peersByPub, pubStr)
×
UNCOV
4856

×
UNCOV
4857
        if p.Inbound() {
×
UNCOV
4858
                delete(s.inboundPeers, pubStr)
×
UNCOV
4859
        } else {
×
UNCOV
4860
                delete(s.outboundPeers, pubStr)
×
UNCOV
4861
        }
×
4862

4863
        // When removing the peer we make sure to disconnect it asynchronously
4864
        // to avoid blocking the main server goroutine because it is holding the
4865
        // server's mutex. Disconnecting the peer might block and wait until the
4866
        // peer has fully started up. This can happen if an inbound and outbound
4867
        // race condition occurs.
4868
        s.wg.Add(1)
×
UNCOV
4869
        go func() {
×
UNCOV
4870
                defer s.wg.Done()
×
UNCOV
4871

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

×
UNCOV
4874
                // If this peer had an active persistent connection request,
×
4875
                // remove it.
×
4876
                if p.ConnReq() != nil {
×
UNCOV
4877
                        s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4878
                }
×
4879

4880
                // Remove the peer's access permission from the access manager.
UNCOV
4881
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
UNCOV
4882
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
UNCOV
4883

×
UNCOV
4884
                // Copy the peer's error buffer across to the server if it has
×
UNCOV
4885
                // any items in it so that we can restore peer errors across
×
UNCOV
4886
                // connections. We need to look up the error after the peer has
×
UNCOV
4887
                // been disconnected because we write the error in the
×
UNCOV
4888
                // `Disconnect` method.
×
UNCOV
4889
                s.mu.Lock()
×
UNCOV
4890
                if p.ErrorBuffer().Total() > 0 {
×
UNCOV
4891
                        s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
4892
                }
×
UNCOV
4893
                s.mu.Unlock()
×
UNCOV
4894

×
UNCOV
4895
                // Inform the peer notifier of a peer offline event so that it
×
UNCOV
4896
                // can be reported to clients listening for peer events.
×
UNCOV
4897
                var pubKey [33]byte
×
UNCOV
4898
                copy(pubKey[:], pubSer)
×
UNCOV
4899

×
UNCOV
4900
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
4901
        }()
4902
}
4903

4904
// ConnectToPeer requests that the server connect to a Lightning Network peer
4905
// at the specified address. This function will *block* until either a
4906
// connection is established, or the initial handshake process fails.
4907
//
4908
// NOTE: This function is safe for concurrent access.
4909
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
4910
        perm bool, timeout time.Duration) error {
×
UNCOV
4911

×
UNCOV
4912
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4913

×
UNCOV
4914
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
4915
        // better granularity.  In certain conditions, this method requires
×
UNCOV
4916
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
4917
        // lock to be released, and subsequently reacquired.
×
UNCOV
4918
        s.mu.Lock()
×
UNCOV
4919

×
UNCOV
4920
        // Ensure we're not already connected to this peer.
×
UNCOV
4921
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
4922

×
UNCOV
4923
        // When there's no error it means we already have a connection with this
×
UNCOV
4924
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
UNCOV
4925
        // set, we will ignore the existing connection and continue.
×
UNCOV
4926
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
UNCOV
4927
                s.mu.Unlock()
×
UNCOV
4928
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
4929
        }
×
4930

4931
        // Peer was not found, continue to pursue connection with peer.
4932

4933
        // If there's already a pending connection request for this pubkey,
4934
        // then we ignore this request to ensure we don't create a redundant
4935
        // connection.
UNCOV
4936
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
4937
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
4938
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
4939
        }
×
4940

4941
        // If there's not already a pending or active connection to this node,
4942
        // then instruct the connection manager to attempt to establish a
4943
        // persistent connection to the peer.
UNCOV
4944
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
4945
        if perm {
×
UNCOV
4946
                connReq := &connmgr.ConnReq{
×
UNCOV
4947
                        Addr:      addr,
×
UNCOV
4948
                        Permanent: true,
×
UNCOV
4949
                }
×
UNCOV
4950

×
UNCOV
4951
                // Since the user requested a permanent connection, we'll set
×
UNCOV
4952
                // the entry to true which will tell the server to continue
×
UNCOV
4953
                // reconnecting even if the number of channels with this peer is
×
UNCOV
4954
                // zero.
×
UNCOV
4955
                s.persistentPeers[targetPub] = true
×
UNCOV
4956
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
4957
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
4958
                }
×
UNCOV
4959
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
4960
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
4961
                )
×
UNCOV
4962
                s.mu.Unlock()
×
UNCOV
4963

×
UNCOV
4964
                go s.connMgr.Connect(connReq)
×
UNCOV
4965

×
UNCOV
4966
                return nil
×
4967
        }
UNCOV
4968
        s.mu.Unlock()
×
UNCOV
4969

×
UNCOV
4970
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
4971
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
4972
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
4973
        // caller.
×
UNCOV
4974
        errChan := make(chan error, 1)
×
UNCOV
4975
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
4976

×
UNCOV
4977
        select {
×
UNCOV
4978
        case err := <-errChan:
×
UNCOV
4979
                return err
×
UNCOV
4980
        case <-s.quit:
×
UNCOV
4981
                return ErrServerShuttingDown
×
4982
        }
4983
}
4984

4985
// connectToPeer establishes a connection to a remote peer. errChan is used to
4986
// notify the caller if the connection attempt has failed. Otherwise, it will be
4987
// closed.
4988
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
4989
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
4990

×
UNCOV
4991
        conn, err := brontide.Dial(
×
UNCOV
4992
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
4993
        )
×
UNCOV
4994
        if err != nil {
×
UNCOV
4995
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
4996
                select {
×
UNCOV
4997
                case errChan <- err:
×
UNCOV
4998
                case <-s.quit:
×
4999
                }
UNCOV
5000
                return
×
5001
        }
5002

UNCOV
5003
        close(errChan)
×
UNCOV
5004

×
UNCOV
5005
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
5006
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
5007

×
5008
        s.OutboundPeerConnected(nil, conn)
×
5009
}
5010

5011
// DisconnectPeer sends the request to server to close the connection with peer
5012
// identified by public key.
5013
//
5014
// NOTE: This function is safe for concurrent access.
UNCOV
5015
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
5016
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
5017
        pubStr := string(pubBytes)
×
UNCOV
5018

×
UNCOV
5019
        s.mu.Lock()
×
UNCOV
5020
        defer s.mu.Unlock()
×
UNCOV
5021

×
UNCOV
5022
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
5023
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
5024
        // currently connected to.
×
UNCOV
5025
        peer, err := s.findPeerByPubStr(pubStr)
×
5026
        if err == ErrPeerNotConnected {
×
UNCOV
5027
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
5028
        }
×
5029

UNCOV
5030
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
5031

×
UNCOV
5032
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
5033

×
UNCOV
5034
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
5035
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
5036
        // disconnect.
×
UNCOV
5037
        delete(s.persistentPeers, pubStr)
×
UNCOV
5038
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
5039

×
UNCOV
5040
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
5041
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
×
UNCOV
5042
        //
×
UNCOV
5043
        // NOTE: We call it in a goroutine to avoid blocking the main server
×
UNCOV
5044
        // goroutine because we might hold the server's mutex.
×
UNCOV
5045
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
5046

×
UNCOV
5047
        return nil
×
5048
}
5049

5050
// OpenChannel sends a request to the server to open a channel to the specified
5051
// peer identified by nodeKey with the passed channel funding parameters.
5052
//
5053
// NOTE: This function is safe for concurrent access.
5054
func (s *server) OpenChannel(
UNCOV
5055
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
5056

×
UNCOV
5057
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
5058
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
5059
        // not blocked if the caller is not reading the updates.
×
UNCOV
5060
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
5061
        req.Err = make(chan error, 1)
×
UNCOV
5062

×
UNCOV
5063
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
5064
        // we're unable to locate the peer then this request will fail.
×
UNCOV
5065
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
5066
        s.mu.RLock()
×
UNCOV
5067
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
5068
        if !ok {
×
UNCOV
5069
                s.mu.RUnlock()
×
UNCOV
5070

×
UNCOV
5071
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
UNCOV
5072
                return req.Updates, req.Err
×
UNCOV
5073
        }
×
UNCOV
5074
        req.Peer = peer
×
UNCOV
5075
        s.mu.RUnlock()
×
UNCOV
5076

×
UNCOV
5077
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
5078
        // opening process.
×
UNCOV
5079
        select {
×
UNCOV
5080
        case <-peer.ActiveSignal():
×
UNCOV
5081
        case <-peer.QuitSignal():
×
UNCOV
5082
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
UNCOV
5083
                return req.Updates, req.Err
×
UNCOV
5084
        case <-s.quit:
×
UNCOV
5085
                req.Err <- ErrServerShuttingDown
×
UNCOV
5086
                return req.Updates, req.Err
×
5087
        }
5088

5089
        // If the fee rate wasn't specified at this point we fail the funding
5090
        // because of the missing fee rate information. The caller of the
5091
        // `OpenChannel` method needs to make sure that default values for the
5092
        // fee rate are set beforehand.
UNCOV
5093
        if req.FundingFeePerKw == 0 {
×
UNCOV
5094
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
UNCOV
5095
                        "the channel opening transaction")
×
UNCOV
5096

×
5097
                return req.Updates, req.Err
×
5098
        }
×
5099

5100
        // Spawn a goroutine to send the funding workflow request to the funding
5101
        // manager. This allows the server to continue handling queries instead
5102
        // of blocking on this request which is exported as a synchronous
5103
        // request to the outside world.
UNCOV
5104
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
5105

×
UNCOV
5106
        return req.Updates, req.Err
×
5107
}
5108

5109
// Peers returns a slice of all active peers.
5110
//
5111
// NOTE: This function is safe for concurrent access.
5112
func (s *server) Peers() []*peer.Brontide {
×
5113
        s.mu.RLock()
×
5114
        defer s.mu.RUnlock()
×
UNCOV
5115

×
UNCOV
5116
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
5117
        for _, peer := range s.peersByPub {
×
UNCOV
5118
                peers = append(peers, peer)
×
UNCOV
5119
        }
×
5120

UNCOV
5121
        return peers
×
5122
}
5123

5124
// computeNextBackoff uses a truncated exponential backoff to compute the next
5125
// backoff using the value of the exiting backoff. The returned duration is
5126
// randomized in either direction by 1/20 to prevent tight loops from
5127
// stabilizing.
UNCOV
5128
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
5129
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
5130
        nextBackoff := 2 * currBackoff
×
UNCOV
5131
        if nextBackoff > maxBackoff {
×
UNCOV
5132
                nextBackoff = maxBackoff
×
UNCOV
5133
        }
×
5134

5135
        // Using 1/10 of our duration as a margin, compute a random offset to
5136
        // avoid the nodes entering connection cycles.
UNCOV
5137
        margin := nextBackoff / 10
×
UNCOV
5138

×
UNCOV
5139
        var wiggle big.Int
×
UNCOV
5140
        wiggle.SetUint64(uint64(margin))
×
UNCOV
5141
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
UNCOV
5142
                // Randomizing is not mission critical, so we'll just return the
×
UNCOV
5143
                // current backoff.
×
UNCOV
5144
                return nextBackoff
×
UNCOV
5145
        }
×
5146

5147
        // Otherwise add in our wiggle, but subtract out half of the margin so
5148
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
5149
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5150
}
5151

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

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

×
UNCOV
5160
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
5161
        if err != nil {
×
UNCOV
5162
                return nil, err
×
UNCOV
5163
        }
×
5164

UNCOV
5165
        node, err := s.graphDB.FetchNode(ctx, vertex)
×
UNCOV
5166
        if err != nil {
×
UNCOV
5167
                return nil, err
×
UNCOV
5168
        }
×
5169

5170
        if len(node.Addresses) == 0 {
×
5171
                return nil, errNoAdvertisedAddr
×
5172
        }
×
5173

UNCOV
5174
        return node.Addresses, nil
×
5175
}
5176

5177
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5178
// channel update for a target channel.
5179
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
5180
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
5181

×
UNCOV
5182
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
5183
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
5184
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
5185
                if err != nil {
×
UNCOV
5186
                        return nil, err
×
UNCOV
5187
                }
×
5188

UNCOV
5189
                return netann.ExtractChannelUpdate(
×
5190
                        ourPubKey[:], info, edge1, edge2,
×
5191
                )
×
5192
        }
5193
}
5194

5195
// applyChannelUpdate applies the channel update to the different sub-systems of
5196
// the server. The useAlias boolean denotes whether or not to send an alias in
5197
// place of the real SCID.
5198
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
5199
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
5200

×
UNCOV
5201
        var (
×
UNCOV
5202
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5203
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5204
        )
×
UNCOV
5205

×
UNCOV
5206
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5207

×
UNCOV
5208
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
5209
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
5210
        if useAlias {
×
UNCOV
5211
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
5212
                if foundAlias != defaultAlias {
×
UNCOV
5213
                        peerAlias = &foundAlias
×
UNCOV
5214
                }
×
5215
        }
5216

UNCOV
5217
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
5218
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
5219
        )
×
UNCOV
5220
        select {
×
UNCOV
5221
        case err := <-errChan:
×
UNCOV
5222
                return err
×
UNCOV
5223
        case <-s.quit:
×
UNCOV
5224
                return ErrServerShuttingDown
×
5225
        }
5226
}
5227

5228
// SendCustomMessage sends a custom message to the peer with the specified
5229
// pubkey.
5230
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5231
        data []byte) error {
×
UNCOV
5232

×
UNCOV
5233
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5234
        if err != nil {
×
UNCOV
5235
                return err
×
UNCOV
5236
        }
×
5237

5238
        // We'll wait until the peer is active.
UNCOV
5239
        select {
×
UNCOV
5240
        case <-peer.ActiveSignal():
×
UNCOV
5241
        case <-peer.QuitSignal():
×
UNCOV
5242
                return fmt.Errorf("peer %x disconnected", peerPub)
×
UNCOV
5243
        case <-s.quit:
×
UNCOV
5244
                return ErrServerShuttingDown
×
5245
        }
5246

UNCOV
5247
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5248
        if err != nil {
×
UNCOV
5249
                return err
×
UNCOV
5250
        }
×
5251

5252
        // Send the message as low-priority. For now we assume that all
5253
        // application-defined message are low priority.
UNCOV
5254
        return peer.SendMessageLazy(true, msg)
×
5255
}
5256

5257
// newSweepPkScriptGen creates closure that generates a new public key script
5258
// which should be used to sweep any funds into the on-chain wallet.
5259
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5260
// (p2wkh) output.
5261
func newSweepPkScriptGen(
5262
        wallet lnwallet.WalletController,
UNCOV
5263
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5264

×
UNCOV
5265
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5266
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5267
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5268
                        lnwallet.DefaultAccountName,
×
5269
                )
×
5270
                if err != nil {
×
5271
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5272
                }
×
5273

UNCOV
5274
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5275
                if err != nil {
×
UNCOV
5276
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5277
                }
×
5278

UNCOV
5279
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5280
                        wallet, netParams, addr,
×
UNCOV
5281
                )
×
UNCOV
5282
                if err != nil {
×
UNCOV
5283
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5284
                }
×
5285

UNCOV
5286
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5287
                        DeliveryAddress: addr,
×
UNCOV
5288
                        InternalKey:     internalKeyDesc,
×
UNCOV
5289
                })
×
5290
        }
5291
}
5292

5293
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5294
// finished.
UNCOV
5295
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5296
        // Get a list of closed channels.
×
UNCOV
5297
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5298
        if err != nil {
×
5299
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5300
                return nil
×
UNCOV
5301
        }
×
5302

5303
        // Save the SCIDs in a map.
5304
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
5305
        for _, c := range channels {
×
UNCOV
5306
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5307
                if !c.IsPending {
×
UNCOV
5308
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5309
                }
×
5310
        }
5311

5312
        // Double check whether the reported closed channel has indeed finished
5313
        // closing.
5314
        //
5315
        // NOTE: There are misalignments regarding when a channel's FC is
5316
        // marked as finalized. We double check the pending channels to make
5317
        // sure the returned SCIDs are indeed terminated.
5318
        //
5319
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5320
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5321
        if err != nil {
×
UNCOV
5322
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
UNCOV
5323
                return nil
×
UNCOV
5324
        }
×
5325

UNCOV
5326
        for _, c := range pendings {
×
5327
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
5328
                        continue
×
5329
                }
5330

5331
                // If the channel is still reported as pending, remove it from
5332
                // the map.
UNCOV
5333
                delete(closedSCIDs, c.ShortChannelID)
×
UNCOV
5334

×
UNCOV
5335
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
UNCOV
5336
                        c.ShortChannelID)
×
5337
        }
5338

UNCOV
5339
        return closedSCIDs
×
5340
}
5341

5342
// getStartingBeat returns the current beat. This is used during the startup to
5343
// initialize blockbeat consumers.
UNCOV
5344
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
UNCOV
5345
        // beat is the current blockbeat.
×
UNCOV
5346
        var beat *chainio.Beat
×
UNCOV
5347

×
UNCOV
5348
        // If the node is configured with nochainbackend mode (remote signer),
×
UNCOV
5349
        // we will skip fetching the best block.
×
5350
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5351
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5352
                        "mode")
×
UNCOV
5353

×
UNCOV
5354
                return &chainio.Beat{}, nil
×
UNCOV
5355
        }
×
5356

5357
        // We should get a notification with the current best block immediately
5358
        // by passing a nil block.
UNCOV
5359
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
UNCOV
5360
        if err != nil {
×
5361
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5362
        }
×
5363
        defer blockEpochs.Cancel()
×
5364

×
UNCOV
5365
        // We registered for the block epochs with a nil request. The notifier
×
UNCOV
5366
        // should send us the current best block immediately. So we need to
×
UNCOV
5367
        // wait for it here because we need to know the current best height.
×
UNCOV
5368
        select {
×
UNCOV
5369
        case bestBlock := <-blockEpochs.Epochs:
×
UNCOV
5370
                srvrLog.Infof("Received initial block %v at height %d",
×
UNCOV
5371
                        bestBlock.Hash, bestBlock.Height)
×
UNCOV
5372

×
UNCOV
5373
                // Update the current blockbeat.
×
UNCOV
5374
                beat = chainio.NewBeat(*bestBlock)
×
5375

UNCOV
5376
        case <-s.quit:
×
UNCOV
5377
                srvrLog.Debug("LND shutting down")
×
5378
        }
5379

5380
        return beat, nil
×
5381
}
5382

5383
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5384
// point has an active RBF chan closer.
5385
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
UNCOV
5386
        chanPoint wire.OutPoint) bool {
×
UNCOV
5387

×
UNCOV
5388
        pubBytes := peerPub.SerializeCompressed()
×
5389

×
5390
        s.mu.RLock()
×
UNCOV
5391
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
UNCOV
5392
        s.mu.RUnlock()
×
UNCOV
5393
        if !ok {
×
UNCOV
5394
                return false
×
UNCOV
5395
        }
×
5396

UNCOV
5397
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5398
}
5399

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

×
UNCOV
5408
        // First, we'll attempt to look up the channel based on it's
×
UNCOV
5409
        // ChannelPoint.
×
UNCOV
5410
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
UNCOV
5411
        if err != nil {
×
UNCOV
5412
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
UNCOV
5413
        }
×
5414

5415
        // From the channel, we can now get the pubkey of the peer, then use
5416
        // that to eventually get the chan closer.
UNCOV
5417
        peerPub := channel.IdentityPub.SerializeCompressed()
×
UNCOV
5418

×
UNCOV
5419
        // Now that we have the peer pub, we can look up the peer itself.
×
UNCOV
5420
        s.mu.RLock()
×
UNCOV
5421
        targetPeer, ok := s.peersByPub[string(peerPub)]
×
5422
        s.mu.RUnlock()
×
5423
        if !ok {
×
UNCOV
5424
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
UNCOV
5425
                        "not online", chanPoint)
×
UNCOV
5426
        }
×
5427

UNCOV
5428
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
UNCOV
5429
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5430
        )
×
UNCOV
5431
        if err != nil {
×
UNCOV
5432
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
UNCOV
5433
                        "%w", err)
×
UNCOV
5434
        }
×
5435

UNCOV
5436
        return closeUpdates, nil
×
5437
}
5438

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

×
UNCOV
5447
        // If the channel is present in the switch, then the request should flow
×
UNCOV
5448
        // through the switch instead.
×
UNCOV
5449
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5450
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
×
UNCOV
5451
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5452
                        "invalid request", chanPoint)
×
5453
        }
×
5454

5455
        // At this point, we know that the channel isn't present in the link, so
5456
        // we'll check to see if we have an entry in the active chan closer map.
UNCOV
5457
        updates, err := s.attemptCoopRbfFeeBump(
×
UNCOV
5458
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5459
        )
×
5460
        if err != nil {
×
5461
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5462
                        "ChannelPoint(%v)", chanPoint)
×
UNCOV
5463
        }
×
5464

UNCOV
5465
        return updates, nil
×
5466
}
5467

5468
// setSelfNode configures and sets the server's self node. It sets the node
5469
// announcement, signs it, and updates the source node in the graph. When
5470
// determining values such as color and alias, the method prioritizes values
5471
// set in the config, then values previously persisted on disk, and finally
5472
// falls back to the defaults.
5473
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
UNCOV
5474
        listenAddrs []net.Addr) error {
×
UNCOV
5475

×
UNCOV
5476
        // If we were requested to automatically configure port forwarding,
×
UNCOV
5477
        // we'll use the ports that the server will be listening on.
×
UNCOV
5478
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
×
5479
        for _, ip := range s.cfg.ExternalIPs {
×
5480
                externalIPStrings = append(externalIPStrings, ip.String())
×
5481
        }
×
UNCOV
5482
        if s.natTraversal != nil {
×
UNCOV
5483
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
UNCOV
5484
                for _, listenAddr := range listenAddrs {
×
UNCOV
5485
                        // At this point, the listen addresses should have
×
UNCOV
5486
                        // already been normalized, so it's safe to ignore the
×
UNCOV
5487
                        // errors.
×
UNCOV
5488
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5489
                        port, _ := strconv.Atoi(portStr)
×
5490

×
5491
                        listenPorts = append(listenPorts, uint16(port))
×
UNCOV
5492
                }
×
5493

UNCOV
5494
                ips, err := s.configurePortForwarding(listenPorts...)
×
UNCOV
5495
                if err != nil {
×
UNCOV
5496
                        srvrLog.Errorf("Unable to automatically set up port "+
×
UNCOV
5497
                                "forwarding using %s: %v",
×
UNCOV
5498
                                s.natTraversal.Name(), err)
×
UNCOV
5499
                } else {
×
UNCOV
5500
                        srvrLog.Infof("Automatically set up port forwarding "+
×
UNCOV
5501
                                "using %s to advertise external IP",
×
UNCOV
5502
                                s.natTraversal.Name())
×
UNCOV
5503
                        externalIPStrings = append(externalIPStrings, ips...)
×
UNCOV
5504
                }
×
5505
        }
5506

5507
        // Normalize the external IP strings to net.Addr.
UNCOV
5508
        addrs, err := lncfg.NormalizeAddresses(
×
UNCOV
5509
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
5510
                s.cfg.net.ResolveTCPAddr,
×
5511
        )
×
5512
        if err != nil {
×
5513
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5514
        }
×
5515

5516
        // Parse the color from config. We will update this later if the config
5517
        // color is not changed from default (#3399FF) and we have a value in
5518
        // the source node.
5519
        color, err := lncfg.ParseHexColor(s.cfg.Color)
×
5520
        if err != nil {
×
UNCOV
5521
                return fmt.Errorf("unable to parse color: %w", err)
×
5522
        }
×
5523

5524
        var (
×
5525
                alias          = s.cfg.Alias
×
5526
                nodeLastUpdate = time.Now()
×
5527
        )
×
5528

×
5529
        srcNode, err := s.graphDB.SourceNode(ctx)
×
5530
        switch {
×
5531
        case err == nil:
×
5532
                // If we have a source node persisted in the DB already, then we
×
UNCOV
5533
                // just need to make sure that the new LastUpdate time is at
×
UNCOV
5534
                // least one second after the last update time.
×
UNCOV
5535
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
×
UNCOV
5536
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
×
UNCOV
5537
                }
×
5538

5539
                // If the color is not changed from default, it means that we
5540
                // didn't specify a different color in the config. We'll use the
5541
                // source node's color.
5542
                if s.cfg.Color == defaultColor {
×
UNCOV
5543
                        color = srcNode.Color
×
UNCOV
5544
                }
×
5545

5546
                // If an alias is not specified in the config, we'll use the
5547
                // source node's alias.
UNCOV
5548
                if alias == "" {
×
5549
                        alias = srcNode.Alias
×
5550
                }
×
5551

5552
                // If the `externalip` is not specified in the config, it means
5553
                // `addrs` will be empty, we'll use the source node's addresses.
UNCOV
5554
                if len(s.cfg.ExternalIPs) == 0 {
×
UNCOV
5555
                        addrs = srcNode.Addresses
×
UNCOV
5556
                }
×
5557

UNCOV
5558
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
×
UNCOV
5559
                // If an alias is not specified in the config, we'll use the
×
UNCOV
5560
                // default, which is the first 10 bytes of the serialized
×
UNCOV
5561
                // pubkey.
×
UNCOV
5562
                if alias == "" {
×
UNCOV
5563
                        alias = hex.EncodeToString(nodePub[:10])
×
UNCOV
5564
                }
×
5565

5566
        // If the above cases are not matched, then we have an unhandled non
5567
        // nil error.
UNCOV
5568
        default:
×
UNCOV
5569
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5570
        }
5571

UNCOV
5572
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
5573
        if err != nil {
×
UNCOV
5574
                return err
×
UNCOV
5575
        }
×
5576

5577
        // TODO(abdulkbk): potentially find a way to use the source node's
5578
        // features in the self node.
UNCOV
5579
        selfNode := &models.Node{
×
UNCOV
5580
                HaveNodeAnnouncement: true,
×
UNCOV
5581
                LastUpdate:           nodeLastUpdate,
×
UNCOV
5582
                Addresses:            addrs,
×
UNCOV
5583
                Alias:                nodeAlias.String(),
×
UNCOV
5584
                Color:                color,
×
UNCOV
5585
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
5586
        }
×
UNCOV
5587

×
UNCOV
5588
        copy(selfNode.PubKeyBytes[:], nodePub[:])
×
UNCOV
5589

×
UNCOV
5590
        // Based on the disk representation of the node announcement generated
×
UNCOV
5591
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
5592
        // network so we can properly sign it.
×
UNCOV
5593
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
5594
        if err != nil {
×
UNCOV
5595
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5596
        }
×
5597

5598
        // With the announcement generated, we'll sign it to properly
5599
        // authenticate the message on the network.
UNCOV
5600
        authSig, err := netann.SignAnnouncement(
×
UNCOV
5601
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
×
5602
        )
×
5603
        if err != nil {
×
UNCOV
5604
                return fmt.Errorf("unable to generate signature for self node "+
×
UNCOV
5605
                        "announcement: %v", err)
×
UNCOV
5606
        }
×
5607

UNCOV
5608
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
5609
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
5610
                selfNode.AuthSigBytes,
×
UNCOV
5611
        )
×
UNCOV
5612
        if err != nil {
×
UNCOV
5613
                return err
×
UNCOV
5614
        }
×
5615

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

UNCOV
5622
        s.currentNodeAnn = nodeAnn
×
5623

×
5624
        return nil
×
5625
}
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