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

lightningnetwork / lnd / 17132206455

21 Aug 2025 03:56PM UTC coverage: 54.685% (-2.6%) from 57.321%
17132206455

Pull #10167

github

web-flow
Merge 5dd2ed093 into 0c2f045f5
Pull Request #10167: multi: bump Go to 1.24.6

4 of 31 new or added lines in 10 files covered. (12.9%)

23854 existing lines in 284 files now uncovered.

108937 of 199210 relevant lines covered (54.68%)

22026.48 hits per line

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

0.0
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
208
        case peerStatusProtected:
×
UNCOV
209
                return "protected"
×
210

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

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

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

231
        start sync.Once
232
        stop  sync.Once
233

234
        cfg *Config
235

236
        implCfg *ImplementationCfg
237

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

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

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

249
        chanStatusMgr *netann.ChanStatusManager
250

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

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

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

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

271
        mu sync.RWMutex
272

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

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

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

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

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

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

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

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

323
        cc *chainreg.ChainControl
324

325
        fundingMgr *funding.Manager
326

327
        graphDB *graphdb.ChannelGraph
328

329
        chanStateDB *channeldb.ChannelStateDB
330

331
        addrSource channeldb.AddrSource
332

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

337
        invoicesDB invoices.InvoiceDB
338

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

343
        aliasMgr *aliasmgr.Manager
344

345
        htlcSwitch *htlcswitch.Switch
346

347
        interceptableSwitch *htlcswitch.InterceptableSwitch
348

349
        invoices *invoices.InvoiceRegistry
350

351
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
352

353
        channelNotifier *channelnotifier.ChannelNotifier
354

355
        peerNotifier *peernotifier.PeerNotifier
356

357
        htlcNotifier *htlcswitch.HtlcNotifier
358

359
        witnessBeacon contractcourt.WitnessBeacon
360

361
        breachArbitrator *contractcourt.BreachArbitrator
362

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

366
        graphBuilder *graph.Builder
367

368
        chanRouter *routing.ChannelRouter
369

370
        controlTower routing.ControlTower
371

372
        authGossiper *discovery.AuthenticatedGossiper
373

374
        localChanMgr *localchans.Manager
375

376
        utxoNursery *contractcourt.UtxoNursery
377

378
        sweeper *sweep.UtxoSweeper
379

380
        chainArb *contractcourt.ChainArbitrator
381

382
        sphinx *hop.OnionProcessor
383

384
        towerClientMgr *wtclient.Manager
385

386
        connMgr *connmgr.ConnManager
387

388
        sigPool *lnwallet.SigPool
389

390
        writePool *pool.Write
391

392
        readPool *pool.Read
393

394
        tlsManager *TLSManager
395

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

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

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

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

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

418
        hostAnn *netann.HostAnnouncer
419

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

423
        customMessageServer *subscribe.Server
424

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

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

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

435
        quit chan struct{}
436

437
        wg sync.WaitGroup
438
}
439

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
519
        return nil
×
520
}
521

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
702
                listenAddrs: listenAddrs,
×
UNCOV
703

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

×
UNCOV
708
                torController: torController,
×
UNCOV
709

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

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

×
UNCOV
726
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
727

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

×
UNCOV
730
                tlsManager: tlsManager,
×
UNCOV
731

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

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

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

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

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

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

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

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

×
UNCOV
773
                return nil
×
774
        }
775

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1126
        s.peerAccessMan = peerAccessMan
×
UNCOV
1127

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
1686
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1687

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

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

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

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

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

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

UNCOV
1726
                        return br, channel.ChanType, nil
×
1727
                }
1728

UNCOV
1729
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1730

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
1849
        return s, nil
×
1850
}
1851

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

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

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

UNCOV
1868
        case routing.BimodalConfig:
×
UNCOV
1869
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1870
                        routing.BimodalEstimatorName
×
UNCOV
1871

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

UNCOV
1878
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1879
}
1880

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

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

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

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

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

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

×
1932
                chainBackendAttempts = 0
×
1933
        }
×
1934

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
2135
        cleanup := cleaner{}
×
UNCOV
2136

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

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

UNCOV
2146
        return startErr
×
2147
}
2148

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

UNCOV
2161
        var startErr error
×
UNCOV
2162

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
2600
                ctx := context.Background()
×
UNCOV
2601

×
UNCOV
2602
                close(s.quit)
×
UNCOV
2603

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

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

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

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

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

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

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

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

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

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

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

UNCOV
2751
        return nil
×
2752
}
2753

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

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

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

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

2783
        return externalIPs, nil
×
2784
}
2785

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
2943
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
UNCOV
2944

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

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

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

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

UNCOV
2977
        return bootStrappers, nil
×
2978
}
2979

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

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

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

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

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

UNCOV
3010
        return ignore
×
3011
}
3012

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

×
UNCOV
3021
        defer s.wg.Done()
×
UNCOV
3022

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

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

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

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

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

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

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

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

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

×
3074
                                sampleTicker.Stop()
×
3075

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
3184
                if numActivePeers >= numTargetPeers {
×
UNCOV
3185
                        return
×
UNCOV
3186
                }
×
3187

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

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

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

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

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

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

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

UNCOV
3259
                wg.Wait()
×
3260
        }
3261
}
3262

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

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

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

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

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

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

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

3334
        return nil
×
3335
}
3336

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

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

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

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

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

×
UNCOV
3362
        return *s.currentNodeAnn
×
UNCOV
3363
}
×
3364

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

×
UNCOV
3371
        s.mu.Lock()
×
UNCOV
3372
        defer s.mu.Unlock()
×
UNCOV
3373

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

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

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

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

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

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

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

×
UNCOV
3418
        return *s.currentNodeAnn, nil
×
3419
}
3420

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

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

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

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

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

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

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

UNCOV
3465
        return nil
×
3466
}
3467

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

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

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

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

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

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

UNCOV
3517
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3518

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

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

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

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

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

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

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

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

×
3586
                        return err
×
3587
                }
×
3588
        }
3589

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

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

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

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

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

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

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

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

UNCOV
3645
                numOutboundConns++
×
3646
        }
3647

UNCOV
3648
        return nil
×
3649
}
3650

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

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

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

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

×
UNCOV
3681
                return
×
UNCOV
3682
        }
×
UNCOV
3683
        s.mu.Unlock()
×
3684
}
3685

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

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

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

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

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

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

×
UNCOV
3744
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3745
                }(sPeer)
×
3746
        }
3747

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

×
UNCOV
3752
        return nil
×
3753
}
3754

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

×
UNCOV
3762
        s.mu.Lock()
×
UNCOV
3763

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

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

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

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

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

UNCOV
3797
                return
×
3798
        }
3799

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

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

×
UNCOV
3815
        c := make(chan struct{})
×
UNCOV
3816

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

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

×
UNCOV
3833
        return c
×
3834
}
3835

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

×
UNCOV
3845
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3846

×
UNCOV
3847
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3848
}
×
3849

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

×
UNCOV
3859
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3860
}
×
3861

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

UNCOV
3870
        return peer, nil
×
3871
}
3872

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

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

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

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

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

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

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

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

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

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

×
UNCOV
3949
        var pubBytes [33]byte
×
UNCOV
3950
        copy(pubBytes[:], pubSer)
×
UNCOV
3951

×
UNCOV
3952
        s.mu.Lock()
×
UNCOV
3953
        defer s.mu.Unlock()
×
UNCOV
3954

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

×
UNCOV
3962
                conn.Close()
×
UNCOV
3963
                return
×
UNCOV
3964
        }
×
3965

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

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

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

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

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

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

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

×
UNCOV
4018
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4019

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

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

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

×
UNCOV
4045
        var pubBytes [33]byte
×
UNCOV
4046
        copy(pubBytes[:], pubSer)
×
UNCOV
4047

×
UNCOV
4048
        s.mu.Lock()
×
UNCOV
4049
        defer s.mu.Unlock()
×
UNCOV
4050

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
4198
                s.connMgr.Remove(connID)
×
4199
        }
4200

UNCOV
4201
        delete(s.persistentConnReqs, pubStr)
×
4202
}
4203

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4308
                conn.Close()
×
4309

×
4310
                return
×
4311
        }
×
4312

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

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

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

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

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

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

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

×
UNCOV
4397
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4398
                },
×
4399

4400
                PongBuf: s.pongBuf,
4401

4402
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4403

4404
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4405

4406
                FundingManager: s.fundingMgr,
4407

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

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

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

×
UNCOV
4448
        p := peer.NewBrontide(pCfg)
×
UNCOV
4449

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

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

×
UNCOV
4456
        s.addPeer(p)
×
UNCOV
4457

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

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

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

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

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

×
4485
                return
×
4486
        }
×
4487

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

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

×
UNCOV
4497
        s.peersByPub[pubStr] = p
×
UNCOV
4498

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

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

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

×
UNCOV
4523
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4524

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

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

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

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

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

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

×
UNCOV
4559
        s.mu.Lock()
×
UNCOV
4560
        defer s.mu.Unlock()
×
UNCOV
4561

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

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

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

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

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

×
UNCOV
4600
        p.WaitForDisconnect(ready)
×
UNCOV
4601

×
UNCOV
4602
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
UNCOV
4603

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

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

×
UNCOV
4617
        pubKey := p.IdentityKey()
×
UNCOV
4618

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

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

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

UNCOV
4637
        s.mu.Lock()
×
UNCOV
4638
        defer s.mu.Unlock()
×
UNCOV
4639

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

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

×
UNCOV
4654
                pubKey := p.PubKey()
×
UNCOV
4655
                pubStr := string(pubKey[:])
×
UNCOV
4656

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
4777
                s.connectToPersistentPeer(pubStr)
×
4778
        }()
4779
}
4780

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

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

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

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

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

UNCOV
4831
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4832

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

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

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

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

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

×
UNCOV
4865
                        go s.connMgr.Connect(connReq)
×
UNCOV
4866

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

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

UNCOV
4887
        srvrLog.DebugS(ctx, "Removing peer")
×
UNCOV
4888

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

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

×
UNCOV
4900
        delete(s.peersByPub, pubStr)
×
UNCOV
4901

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

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

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

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

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

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

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

×
UNCOV
4945
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
4946
        }()
4947
}
4948

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

×
UNCOV
4957
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4958

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

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

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

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

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

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

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

×
UNCOV
5009
                go s.connMgr.Connect(connReq)
×
UNCOV
5010

×
UNCOV
5011
                return nil
×
5012
        }
UNCOV
5013
        s.mu.Unlock()
×
UNCOV
5014

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

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

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

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

UNCOV
5048
        close(errChan)
×
UNCOV
5049

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

×
UNCOV
5053
        s.OutboundPeerConnected(nil, conn)
×
5054
}
5055

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

×
UNCOV
5064
        s.mu.Lock()
×
UNCOV
5065
        defer s.mu.Unlock()
×
UNCOV
5066

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

UNCOV
5075
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
5076

×
UNCOV
5077
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
5078

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

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

×
UNCOV
5092
        return nil
×
5093
}
5094

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

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

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

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

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

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

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

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

×
UNCOV
5151
        return req.Updates, req.Err
×
5152
}
5153

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

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

UNCOV
5166
        return peers
×
5167
}
5168

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

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

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

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

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

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

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

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

UNCOV
5215
        if len(node.Addresses) == 0 {
×
UNCOV
5216
                return nil, errNoAdvertisedAddr
×
UNCOV
5217
        }
×
5218

UNCOV
5219
        return node.Addresses, nil
×
5220
}
5221

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

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

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

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

×
UNCOV
5246
        var (
×
UNCOV
5247
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5248
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5249
        )
×
UNCOV
5250

×
UNCOV
5251
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5252

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
5384
        return closedSCIDs
×
5385
}
5386

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

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

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

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

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

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

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

UNCOV
5425
        return beat, nil
×
5426
}
5427

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

×
UNCOV
5433
        pubBytes := peerPub.SerializeCompressed()
×
UNCOV
5434

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

UNCOV
5442
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5443
}
5444

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

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

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

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

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

UNCOV
5481
        return closeUpdates, nil
×
5482
}
5483

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

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

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

UNCOV
5510
        return updates, nil
×
5511
}
5512

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
5645
        copy(selfNode.PubKeyBytes[:], nodePub[:])
×
UNCOV
5646

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

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

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

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

UNCOV
5679
        s.currentNodeAnn = nodeAnn
×
UNCOV
5680

×
UNCOV
5681
        return nil
×
5682
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc