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

lightningnetwork / lnd / 19338576814

13 Nov 2025 04:31PM UTC coverage: 65.209% (-0.01%) from 65.219%
19338576814

Pull #10367

github

web-flow
Merge ade491779 into f6005ed35
Pull Request #10367: multi: rename experimental endorsement signal to accountable

65 of 85 new or added lines in 11 files covered. (76.47%)

1775 existing lines in 24 files now uncovered.

137557 of 210947 relevant lines covered (65.21%)

20763.21 hits per line

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

69.25
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

152
        // ErrNoPeerScore is returned when we expect to find a score in
153
        // peerScores, but one does not exist.
154
        ErrNoPeerScore = errors.New("peer score not found")
155

156
        // ErrNoPendingPeerInfo is returned when we couldn't find any pending
157
        // peer info.
158
        ErrNoPendingPeerInfo = errors.New("no pending peer info")
159
)
160

161
// errPeerAlreadyConnected is an error returned by the server when we're
162
// commanded to connect to a peer, but they're already connected.
163
type errPeerAlreadyConnected struct {
164
        peer *peer.Brontide
165
}
166

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

3✔
174
// peerAccessStatus denotes the p2p access status of a given peer. This will be
175
// used to assign peer ban scores that determine an action the server will
176
// take.
177
type peerAccessStatus int
178

179
const (
180
        // peerStatusRestricted indicates that the peer only has access to the
181
        // limited number of "free" reserved slots.
182
        peerStatusRestricted peerAccessStatus = iota
183

184
        // peerStatusTemporary indicates that the peer only has temporary p2p
185
        // access to the server.
186
        peerStatusTemporary
187

188
        // peerStatusProtected indicates that the peer has been granted
189
        // permanent p2p access to the server. The peer can still have its
190
        // access revoked.
191
        peerStatusProtected
192
)
193

194
// String returns a human-readable representation of the status code.
195
func (p peerAccessStatus) String() string {
196
        switch p {
3✔
197
        case peerStatusRestricted:
3✔
198
                return "restricted"
3✔
199

3✔
200
        case peerStatusTemporary:
201
                return "temporary"
3✔
202

3✔
203
        case peerStatusProtected:
204
                return "protected"
3✔
205

3✔
206
        default:
207
                return "unknown"
×
UNCOV
208
        }
×
209
}
210

211
// peerSlotStatus determines whether a peer gets access to one of our free
212
// slots or gets to bypass this safety mechanism.
213
type peerSlotStatus struct {
214
        // state determines which privileges the peer has with our server.
215
        state peerAccessStatus
216
}
217

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

226
        start sync.Once
227
        stop  sync.Once
228

229
        cfg *Config
230

231
        implCfg *ImplementationCfg
232

233
        // identityECDH is an ECDH capable wrapper for the private key used
234
        // to authenticate any incoming connections.
235
        identityECDH keychain.SingleKeyECDH
236

237
        // identityKeyLoc is the key locator for the above wrapped identity key.
238
        identityKeyLoc keychain.KeyLocator
239

240
        // nodeSigner is an implementation of the MessageSigner implementation
241
        // that's backed by the identity private key of the running lnd node.
242
        nodeSigner *netann.NodeSigner
243

244
        chanStatusMgr *netann.ChanStatusManager
245

246
        // listenAddrs is the list of addresses the server is currently
247
        // listening on.
248
        listenAddrs []net.Addr
249

250
        // torController is a client that will communicate with a locally
251
        // running Tor server. This client will handle initiating and
252
        // authenticating the connection to the Tor server, automatically
253
        // creating and setting up onion services, etc.
254
        torController *tor.Controller
255

256
        // natTraversal is the specific NAT traversal technique used to
257
        // automatically set up port forwarding rules in order to advertise to
258
        // the network that the node is accepting inbound connections.
259
        natTraversal nat.Traversal
260

261
        // lastDetectedIP is the last IP detected by the NAT traversal technique
262
        // above. This IP will be watched periodically in a goroutine in order
263
        // to handle dynamic IP changes.
264
        lastDetectedIP net.IP
265

266
        mu sync.RWMutex
267

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

277
        inboundPeers  map[string]*peer.Brontide
278
        outboundPeers map[string]*peer.Brontide
279

280
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
281
        peerDisconnectedListeners map[string][]chan<- struct{}
282

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

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

299
        // ignorePeerTermination tracks peers for which the server has initiated
300
        // a disconnect. Adding a peer to this map causes the peer termination
301
        // watcher to short circuit in the event that peers are purposefully
302
        // disconnected.
303
        ignorePeerTermination map[*peer.Brontide]struct{}
304

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

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

318
        cc *chainreg.ChainControl
319

320
        fundingMgr *funding.Manager
321

322
        graphDB *graphdb.ChannelGraph
323

324
        chanStateDB *channeldb.ChannelStateDB
325

326
        addrSource channeldb.AddrSource
327

328
        // miscDB is the DB that contains all "other" databases within the main
329
        // channel DB that haven't been separated out yet.
330
        miscDB *channeldb.DB
331

332
        invoicesDB invoices.InvoiceDB
333

334
        // paymentsDB is the DB that contains all functions for managing
335
        // payments.
336
        paymentsDB paymentsdb.DB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

358
        missionController *routing.MissionController
359
        defaultMC         *routing.MissionControl
360

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

391
        // featureMgr dispatches feature vectors for various contexts within the
392
        // daemon.
393
        featureMgr *feature.Manager
394

395
        // currentNodeAnn is the node announcement that has been broadcast to
396
        // the network upon startup, if the attributes of the node (us) has
397
        // changed since last start.
398
        currentNodeAnn *lnwire.NodeAnnouncement1
399

400
        // chansToRestore is the set of channels that upon starting, the server
401
        // should attempt to restore/recover.
402
        chansToRestore walletunlocker.ChannelsToRecover
403

404
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
405
        // backups are consistent at all times. It interacts with the
406
        // channelNotifier to be notified of newly opened and closed channels.
407
        chanSubSwapper *chanbackup.SubSwapper
408

409
        // chanEventStore tracks the behaviour of channels and their remote peers to
410
        // provide insights into their health and performance.
411
        chanEventStore *chanfitness.ChannelEventStore
412

413
        hostAnn *netann.HostAnnouncer
414

415
        // livenessMonitor monitors that lnd has access to critical resources.
416
        livenessMonitor *healthcheck.Monitor
417

418
        customMessageServer *subscribe.Server
419

420
        onionMessageServer *subscribe.Server
421

422
        // txPublisher is a publisher with fee-bumping capability.
423
        txPublisher *sweep.TxPublisher
424

425
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
426
        // of new blocks.
427
        blockbeatDispatcher *chainio.BlockbeatDispatcher
428

429
        // peerAccessMan implements peer access controls.
430
        peerAccessMan *accessMan
431

432
        quit chan struct{}
433

434
        wg sync.WaitGroup
435
}
436

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

×
445
        s.wg.Add(1)
446
        go func() {
3✔
447
                defer func() {
6✔
448
                        graphSub.Cancel()
6✔
449
                        s.wg.Done()
3✔
450
                }()
3✔
451

3✔
452
                for {
453
                        select {
6✔
454
                        case <-s.quit:
3✔
455
                                return
3✔
456

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

×
464
                                for _, update := range topChange.NodeUpdates {
465
                                        pubKeyStr := string(
6✔
466
                                                update.IdentityKey.
3✔
467
                                                        SerializeCompressed(),
3✔
468
                                        )
3✔
469

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

479
                                        addrs := make([]*lnwire.NetAddress, 0,
480
                                                len(update.Addresses))
3✔
481

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

3✔
492
                                        s.mu.Lock()
493

3✔
494
                                        // Update the stored addresses for this
3✔
495
                                        // to peer to reflect the new set.
3✔
496
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
497

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

508
                                        s.mu.Unlock()
509

3✔
510
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
511
                                }
3✔
512
                        }
513
                }
514
        }()
515

516
        return nil
517
}
3✔
518

519
// CustomMessage is a custom message that is received from a peer.
520
type CustomMessage struct {
521
        // Peer is the peer pubkey
522
        Peer [33]byte
523

524
        // Msg is the custom wire message.
525
        Msg *lnwire.Custom
526
}
527

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

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

552
        if tor.IsOnionHost(host) {
553
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
3✔
554
        }
×
UNCOV
555

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

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

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

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

3✔
588
        var (
3✔
589
                err         error
3✔
590
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
591

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

3✔
599
        netParams := cfg.ActiveNetParams.Params
3✔
600

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

3✔
607
        writeBufferPool := pool.NewWriteBuffer(
3✔
608
                pool.DefaultWriteBufferGCInterval,
3✔
609
                pool.DefaultWriteBufferExpiryInterval,
3✔
610
        )
3✔
611

3✔
612
        writePool := pool.NewWrite(
3✔
613
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
614
        )
3✔
615

3✔
616
        readBufferPool := pool.NewReadBuffer(
3✔
617
                pool.DefaultReadBufferGCInterval,
3✔
618
                pool.DefaultReadBufferExpiryInterval,
3✔
619
        )
3✔
620

3✔
621
        readPool := pool.NewRead(
3✔
622
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
623
        )
3✔
624

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

3✔
630
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
631
                        "overlay channels are not supported " +
×
632
                        "in a standalone lnd build")
×
633
        }
×
UNCOV
634

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

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

3✔
671
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
672

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

3✔
688
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
689
                        cc.ChainNotifier,
3✔
690
                ),
3✔
691
                channelNotifier: channelnotifier.New(
3✔
692
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
693
                ),
3✔
694

3✔
695
                identityECDH:   nodeKeyECDH,
3✔
696
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
697
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
698

3✔
699
                listenAddrs: listenAddrs,
3✔
700

3✔
701
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
702
                // schedule
3✔
703
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
704

3✔
705
                torController: torController,
3✔
706

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

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

3✔
723
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
724

3✔
725
                customMessageServer: subscribe.NewServer(),
3✔
726

3✔
727
                onionMessageServer: subscribe.NewServer(),
3✔
728

3✔
729
                tlsManager: tlsManager,
3✔
730

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

3✔
735
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
736
        if err != nil {
3✔
737
                return nil, err
3✔
738
        }
×
UNCOV
739

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

3✔
748
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
749

3✔
750
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
751
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
752

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

×
759
                s.htlcSwitch.UpdateLinkAliases(link)
760

3✔
761
                return nil
3✔
762
        }
3✔
763

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

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

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

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

×
821
        s.witnessBeacon = newPreimageBeacon(
822
                dbs.ChanStateDB.NewWitnessCache(),
3✔
823
                s.interceptableSwitch.ForwardPacket,
3✔
824
        )
3✔
825

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

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

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

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

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

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

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

×
878
                        s.natTraversal = pmp
UNCOV
879
                }
×
880
        }
881

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
996
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
997

3✔
998
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
999
                cfg.Routing.StrictZombiePruning
3✔
1000

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

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

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

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

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

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

1097
        accessCfg := &accessManConfig{
1098
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1099
                        error) {
3✔
1100

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

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

×
1115
        s.peerAccessMan = peerAccessMan
1116

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

6✔
1127
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1128
                                func(c *models.ChannelEdgeInfo,
3✔
1129
                                        e *models.ChannelEdgePolicy,
3✔
1130
                                        _ *models.ChannelEdgePolicy) error {
3✔
1131

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1309
                        event := &contractcourt.ContractBreachEvent{
1310
                                ChanPoint:         chanPoint,
3✔
1311
                                ProcessACK:        processACK,
3✔
1312
                                BreachRetribution: breachRet,
3✔
1313
                        }
3✔
1314

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

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

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

3✔
1352
                        // Get the circuit map.
3✔
1353
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1354

3✔
1355
                        // Lookup the outgoing circuit.
3✔
1356
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1357
                        if pc == nil {
3✔
1358
                                return nil
5✔
1359
                        }
2✔
1360

2✔
1361
                        return &pc.Incoming
1362
                },
3✔
1363
                AuxLeafStore: implCfg.AuxLeafStore,
1364
                AuxSigner:    implCfg.AuxSigner,
1365
                AuxResolver:  implCfg.AuxContractResolver,
1366
        }, dbs.ChanStateDB)
1367

1368
        // Select the configuration and funding parameters for Bitcoin.
1369
        chainCfg := cfg.Bitcoin
1370
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1371
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1372

3✔
1373
        var chanIDSeed [32]byte
3✔
1374
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1375
                return nil, err
3✔
1376
        }
×
UNCOV
1377

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

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

×
1396
                // Grab our key to find our policy.
1397
                var ourKey [33]byte
1398
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1399

3✔
1400
                var ourPolicy *models.ChannelEdgePolicy
3✔
1401
                if info != nil && info.NodeKey1Bytes == ourKey {
3✔
1402
                        ourPolicy = e1
6✔
1403
                } else {
3✔
1404
                        ourPolicy = e2
6✔
1405
                }
3✔
1406

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

×
1412
                err = s.graphDB.DeleteChannelEdges(
1413
                        false, false, scid.ToUint64(),
3✔
1414
                )
3✔
1415
                return ourPolicy, err
3✔
1416
        }
3✔
1417

1418
        // For the reservationTimeout and the zombieSweeperInterval different
1419
        // values are set in case we are in a dev environment so enhance test
1420
        // capacilities.
1421
        reservationTimeout := chanfunding.DefaultReservationTimeout
1422
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1423

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

3✔
1434
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1435
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1436

3✔
1437
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1438
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1439
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1440
        }
3✔
1441

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

3✔
1460
                        return s.genNodeAnnouncement(nil)
6✔
1461
                },
3✔
1462
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
3✔
1463
                NotifyWhenOnline:     s.NotifyWhenOnline,
1464
                TempChanIDSeed:       chanIDSeed,
1465
                FindChannel:          s.findChannel,
1466
                DefaultRoutingPolicy: cc.RoutingPolicy,
1467
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1468
                NumRequiredConfs: func(chanAmt btcutil.Amount,
3✔
1469
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1470
                        // For large channels we increase the number
3✔
1471
                        // of confirmations we require for the
3✔
1472
                        // channel to be considered open. As it is
1473
                        // always the responder that gets to choose
1474
                        // value, the pushAmt is value being pushed
1475
                        // to us. This means we have more to lose
1476
                        // in the case this gets re-orged out, and
1477
                        // we will require more confirmations before
1478
                        // we consider it open.
1479

3✔
1480
                        // In case the user has explicitly specified
3✔
1481
                        // a default value for the number of
3✔
1482
                        // confirmations, we use it.
3✔
1483
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1484
                        if defaultConf != 0 {
3✔
1485
                                return defaultConf
3✔
1486
                        }
3✔
1487

3✔
1488
                        minConf := uint64(3)
3✔
1489
                        maxConf := uint64(6)
3✔
1490

3✔
1491
                        // If this is a wumbo channel, then we'll require the
3✔
1492
                        // max amount of confirmations.
3✔
1493
                        if chanAmt > MaxFundingAmount {
3✔
1494
                                return uint16(maxConf)
6✔
1495
                        }
3✔
1496

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

×
UNCOV
1519
                        // In case the user has explicitly specified
×
UNCOV
1520
                        // a default value for the remote delay, we
×
1521
                        // use it.
1522
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1523
                        if defaultDelay > 0 {
3✔
1524
                                return defaultDelay
3✔
1525
                        }
3✔
1526

3✔
1527
                        // If this is a wumbo channel, then we'll require the
3✔
1528
                        // max value.
3✔
1529
                        if chanAmt > MaxFundingAmount {
3✔
1530
                                return maxRemoteDelay
3✔
1531
                        }
3✔
1532

3✔
1533
                        // If not we scale according to channel size.
6✔
1534
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
3✔
1535
                                chanAmt / MaxFundingAmount)
3✔
1536
                        if delay < minRemoteDelay {
1537
                                delay = minRemoteDelay
1538
                        }
1539
                        if delay > maxRemoteDelay {
×
1540
                                delay = maxRemoteDelay
×
1541
                        }
×
1542
                        return delay
1543
                },
UNCOV
1544
                WatchNewChannel: func(channel *channeldb.OpenChannel,
×
UNCOV
1545
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1546

×
UNCOV
1547
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1548
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1549
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1550
                        // we'll set false to prevent the server from continuing
×
UNCOV
1551
                        // to connect to this peer even if the number of
×
UNCOV
1552
                        // channels with this peer is zero.
×
1553
                        s.mu.Lock()
1554
                        pubStr := string(peerKey.SerializeCompressed())
1555
                        if _, ok := s.persistentPeers[pubStr]; !ok {
3✔
1556
                                s.persistentPeers[pubStr] = false
3✔
1557
                        }
3✔
1558
                        s.mu.Unlock()
3✔
1559

3✔
1560
                        // With that taken care of, we'll send this channel to
3✔
1561
                        // the chain arb so it can react to on-chain events.
3✔
1562
                        return s.chainArb.WatchNewChannel(channel)
3✔
1563
                },
3✔
1564
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1565
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
1566
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1567
                },
3✔
1568
                RequiredRemoteChanReserve: func(chanAmt,
3✔
1569
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1570

3✔
1571
                        // By default, we'll require the remote peer to maintain
3✔
1572
                        // at least 1% of the total channel capacity at all
3✔
1573
                        // times. If this value ends up dipping below the dust
1574
                        // limit, then we'll use the dust limit itself as the
3✔
1575
                        // reserve as required by BOLT #2.
3✔
1576
                        reserve := chanAmt / 100
3✔
1577
                        if reserve < dustLimit {
3✔
1578
                                reserve = dustLimit
1579
                        }
3✔
1580

3✔
1581
                        return reserve
3✔
1582
                },
3✔
1583
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1584
                        // By default, we'll allow the remote peer to fully
3✔
1585
                        // utilize the full bandwidth of the channel, minus our
3✔
1586
                        // required reserve.
3✔
1587
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
6✔
1588
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1589
                },
3✔
1590
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
1591
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
3✔
1592
                                return cfg.DefaultRemoteMaxHtlcs
1593
                        }
3✔
1594

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

1625
        // Next, we'll assemble the sub-system that will maintain an on-disk
1626
        // static backup of the latest channel state.
1627
        chanNotifier := &channelNotifier{
1628
                chanNotifier: s.channelNotifier,
1629
                addrs:        s.addrSource,
1630
        }
1631
        backupFile := chanbackup.NewMultiFile(
1632
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
UNCOV
1633
        )
×
UNCOV
1634
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
1635
                ctx, s.chanStateDB, s.addrSource,
1636
        )
1637
        if err != nil {
1638
                return nil, err
3✔
1639
        }
3✔
1640
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1641
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1642
        )
3✔
1643
        if err != nil {
3✔
1644
                return nil, err
3✔
1645
        }
3✔
1646

3✔
1647
        // Assemble a peer notifier which will provide clients with subscriptions
3✔
1648
        // to peer online and offline events.
3✔
UNCOV
1649
        s.peerNotifier = peernotifier.New()
×
UNCOV
1650

×
1651
        // Create a channel event store which monitors all open channels.
3✔
1652
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1653
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
3✔
1654
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
UNCOV
1655
                },
×
UNCOV
1656
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
1657
                        return s.peerNotifier.SubscribePeerEvents()
1658
                },
1659
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1660
                Clock:           clock.NewDefaultClock(),
3✔
1661
                ReadFlapCount:   s.miscDB.ReadFlapCount,
3✔
1662
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
3✔
1663
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
3✔
1664
        })
6✔
1665

3✔
1666
        if cfg.WtClient.Active {
3✔
1667
                policy := wtpolicy.DefaultPolicy()
3✔
1668
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1669

3✔
1670
                // We expose the sweep fee rate in sat/vbyte, but the tower
1671
                // protocol operations on sat/kw.
1672
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
1673
                        1000 * cfg.WtClient.SweepFeeRate,
1674
                )
1675

1676
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
1677

6✔
1678
                if err := policy.Validate(); err != nil {
3✔
1679
                        return nil, err
3✔
1680
                }
3✔
1681

3✔
1682
                // authDial is the wrapper around the btrontide.Dial for the
3✔
1683
                // watchtower.
3✔
1684
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1685
                        netAddr *lnwire.NetAddress,
3✔
1686
                        dialer tor.DialFunc) (wtserver.Peer, error) {
3✔
1687

3✔
1688
                        return brontide.Dial(
3✔
1689
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
UNCOV
1690
                        )
×
UNCOV
1691
                }
×
1692

1693
                // buildBreachRetribution is a call-back that can be used to
1694
                // query the BreachRetribution info and channel type given a
1695
                // channel ID and commitment height.
3✔
1696
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1697
                        commitHeight uint64) (*lnwallet.BreachRetribution,
6✔
1698
                        channeldb.ChannelType, error) {
3✔
1699

3✔
1700
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1701
                                nil, chanID,
3✔
1702
                        )
3✔
1703
                        if err != nil {
1704
                                return nil, 0, err
1705
                        }
1706

1707
                        br, err := lnwallet.NewBreachRetribution(
3✔
1708
                                channel, commitHeight, 0, nil,
3✔
1709
                                implCfg.AuxLeafStore,
6✔
1710
                                implCfg.AuxContractResolver,
3✔
1711
                        )
3✔
1712
                        if err != nil {
3✔
1713
                                return nil, 0, err
3✔
1714
                        }
3✔
UNCOV
1715

×
UNCOV
1716
                        return br, channel.ChanType, nil
×
1717
                }
1718

3✔
1719
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1720

3✔
1721
                // Copy the policy for legacy channels and set the blob flag
3✔
1722
                // signalling support for anchor channels.
3✔
1723
                anchorPolicy := policy
3✔
UNCOV
1724
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1725

×
1726
                // Copy the policy for legacy channels and set the blob flag
1727
                // signalling support for taproot channels.
3✔
1728
                taprootPolicy := policy
1729
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
1730
                        blob.FlagTaprootChannel,
3✔
1731
                )
3✔
1732

3✔
1733
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1734
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1735
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1736
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1737
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1738
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1739
                                error) {
3✔
1740

3✔
1741
                                return s.channelNotifier.
3✔
1742
                                        SubscribeChannelEvents()
3✔
1743
                        },
3✔
1744
                        Signer: cc.Wallet.Cfg.Signer,
3✔
1745
                        NewAddress: func() ([]byte, error) {
3✔
1746
                                addr, err := newSweepPkScriptGen(
3✔
1747
                                        cc.Wallet, netParams,
3✔
1748
                                )().Unpack()
3✔
1749
                                if err != nil {
3✔
1750
                                        return nil, err
6✔
1751
                                }
3✔
1752

3✔
1753
                                return addr.DeliveryAddress, nil
3✔
1754
                        },
3✔
1755
                        SecretKeyRing:      s.cc.KeyRing,
1756
                        Dial:               cfg.net.Dial,
3✔
1757
                        AuthDial:           authDial,
3✔
1758
                        DB:                 dbs.TowerClientDB,
3✔
1759
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
3✔
1760
                        MinBackoff:         10 * time.Second,
3✔
UNCOV
1761
                        MaxBackoff:         5 * time.Minute,
×
UNCOV
1762
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
×
1763
                }, policy, anchorPolicy, taprootPolicy)
1764
                if err != nil {
3✔
1765
                        return nil, err
1766
                }
1767
        }
1768

1769
        if len(cfg.ExternalHosts) != 0 {
1770
                advertisedIPs := make(map[string]struct{})
1771
                for _, addr := range s.currentNodeAnn.Addresses {
1772
                        advertisedIPs[addr.String()] = struct{}{}
1773
                }
1774

1775
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
3✔
1776
                        Hosts:         cfg.ExternalHosts,
×
1777
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1778
                        LookupHost: func(host string) (net.Addr, error) {
1779
                                return lncfg.ParseAddressString(
1780
                                        host, strconv.Itoa(defaultPeerPort),
3✔
1781
                                        cfg.net.ResolveTCPAddr,
×
1782
                                )
×
1783
                        },
×
UNCOV
1784
                        AdvertisedIPs: advertisedIPs,
×
1785
                        AnnounceNewIPs: netann.IPAnnouncer(
UNCOV
1786
                                func(modifier ...netann.NodeAnnModifier) (
×
1787
                                        lnwire.NodeAnnouncement1, error) {
×
1788

×
1789
                                        return s.genNodeAnnouncement(
×
1790
                                                nil, modifier...,
×
1791
                                        )
×
1792
                                }),
×
UNCOV
1793
                })
×
UNCOV
1794
        }
×
1795

1796
        // Create liveness monitor.
1797
        s.createLivenessMonitor(cfg, cc, leaderElector)
UNCOV
1798

×
UNCOV
1799
        listeners := make([]net.Listener, len(listenAddrs))
×
UNCOV
1800
        for i, listenAddr := range listenAddrs {
×
UNCOV
1801
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
UNCOV
1802
                // doesn't need to call the general lndResolveTCP function
×
UNCOV
1803
                // since we are resolving a local address.
×
1804

1805
                // RESOLVE: We are actually partially accepting inbound
1806
                // connection requests when we call NewListener.
1807
                listeners[i], err = brontide.NewListener(
1808
                        nodeKeyECDH, listenAddr.String(),
3✔
1809
                        // TODO(yy): remove this check and unify the inbound
3✔
1810
                        // connection check inside `InboundPeerConnected`.
3✔
1811
                        s.peerAccessMan.checkAcceptIncomingConn,
6✔
1812
                )
3✔
1813
                if err != nil {
3✔
1814
                        return nil, err
3✔
1815
                }
3✔
1816
        }
3✔
1817

3✔
1818
        // Create the connection manager which will be responsible for
3✔
1819
        // maintaining persistent outbound connections and also accepting new
3✔
1820
        // incoming connections
3✔
1821
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1822
                Listeners:      listeners,
3✔
1823
                OnAccept:       s.InboundPeerConnected,
3✔
1824
                RetryDuration:  time.Second * 5,
3✔
UNCOV
1825
                TargetOutbound: 100,
×
UNCOV
1826
                Dial: noiseDial(
×
1827
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
1828
                ),
1829
                OnConnection: s.OutboundPeerConnected,
1830
        })
1831
        if err != nil {
1832
                return nil, err
3✔
1833
        }
3✔
1834
        s.connMgr = cmgr
3✔
1835

3✔
1836
        // Finally, register the subsystems in blockbeat.
3✔
1837
        s.registerBlockConsumers()
3✔
1838

3✔
1839
        return s, nil
3✔
1840
}
3✔
1841

3✔
1842
// UpdateRoutingConfig is a callback function to update the routing config
3✔
UNCOV
1843
// values in the main cfg.
×
UNCOV
1844
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
1845
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1846

3✔
1847
        switch c := cfg.Estimator.Config().(type) {
3✔
1848
        case routing.AprioriConfig:
3✔
1849
                routerCfg.ProbabilityEstimatorType =
3✔
1850
                        routing.AprioriEstimatorName
3✔
1851

1852
                targetCfg := routerCfg.AprioriConfig
1853
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
1854
                targetCfg.Weight = c.AprioriWeight
1855
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1856
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1857

3✔
1858
        case routing.BimodalConfig:
3✔
1859
                routerCfg.ProbabilityEstimatorType =
3✔
1860
                        routing.BimodalEstimatorName
3✔
1861

3✔
1862
                targetCfg := routerCfg.BimodalConfig
3✔
1863
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1864
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1865
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1866
        }
3✔
1867

3✔
1868
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
1869
}
3✔
1870

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

1890
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
3✔
1891
// used for option_scid_alias channels where the ChannelUpdate to be sent back
3✔
1892
// may differ from what is on disk.
3✔
1893
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
3✔
1894
        error) {
3✔
1895

3✔
1896
        data, err := u.DataToSign()
3✔
1897
        if err != nil {
3✔
1898
                return nil, err
3✔
1899
        }
3✔
1900

1901
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
1902
}
1903

1904
// createLivenessMonitor creates a set of health checks using our configured
1905
// values and uses these checks to create a liveness monitor. Available
3✔
1906
// health checks,
3✔
1907
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
3✔
1908
//   - diskCheck
3✔
UNCOV
1909
//   - tlsHealthCheck
×
UNCOV
1910
//   - torController, only created when tor is enabled.
×
1911
//
1912
// If a health check has been disabled by setting attempts to 0, our monitor
3✔
1913
// will not run it.
1914
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1915
        leaderElector cluster.LeaderElector) {
1916

1917
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
1918
        if cfg.Bitcoin.Node == "nochainbackend" {
1919
                srvrLog.Info("Disabling chain backend checks for " +
1920
                        "nochainbackend mode")
1921

1922
                chainBackendAttempts = 0
1923
        }
1924

1925
        chainHealthCheck := healthcheck.NewObservation(
1926
                "chain backend",
3✔
1927
                cc.HealthCheck,
3✔
1928
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1929
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
UNCOV
1930
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
1931
                chainBackendAttempts,
×
UNCOV
1932
        )
×
UNCOV
1933

×
UNCOV
1934
        diskCheck := healthcheck.NewObservation(
×
1935
                "disk space",
1936
                func() error {
3✔
1937
                        free, err := healthcheck.AvailableDiskSpaceRatio(
3✔
1938
                                cfg.LndDir,
3✔
1939
                        )
3✔
1940
                        if err != nil {
3✔
1941
                                return err
3✔
1942
                        }
3✔
1943

3✔
1944
                        // If we have more free space than we require,
3✔
1945
                        // we return a nil error.
3✔
1946
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
3✔
1947
                                return nil
3✔
1948
                        }
×
UNCOV
1949

×
1950
                        return fmt.Errorf("require: %v free space, got: %v",
×
1951
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1952
                                free)
×
UNCOV
1953
                },
×
1954
                cfg.HealthChecks.DiskCheck.Interval,
1955
                cfg.HealthChecks.DiskCheck.Timeout,
1956
                cfg.HealthChecks.DiskCheck.Backoff,
UNCOV
1957
                cfg.HealthChecks.DiskCheck.Attempts,
×
UNCOV
1958
        )
×
UNCOV
1959

×
1960
        tlsHealthCheck := healthcheck.NewObservation(
UNCOV
1961
                "tls",
×
UNCOV
1962
                func() error {
×
1963
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1964
                                s.cc.KeyRing,
1965
                        )
1966
                        if err != nil {
1967
                                return err
1968
                        }
1969
                        if expired {
1970
                                return fmt.Errorf("TLS certificate is "+
1971
                                        "expired as of %v", expTime)
3✔
1972
                        }
3✔
1973

3✔
UNCOV
1974
                        // If the certificate is not outdated, no error needs
×
UNCOV
1975
                        // to be returned
×
1976
                        return nil
×
UNCOV
1977
                },
×
UNCOV
1978
                cfg.HealthChecks.TLSCheck.Interval,
×
UNCOV
1979
                cfg.HealthChecks.TLSCheck.Timeout,
×
UNCOV
1980
                cfg.HealthChecks.TLSCheck.Backoff,
×
UNCOV
1981
                cfg.HealthChecks.TLSCheck.Attempts,
×
UNCOV
1982
        )
×
UNCOV
1983

×
1984
        checks := []*healthcheck.Observation{
1985
                chainHealthCheck, diskCheck, tlsHealthCheck,
1986
        }
UNCOV
1987

×
1988
        // If Tor is enabled, add the healthcheck for tor connection.
1989
        if s.torController != nil {
1990
                torConnectionCheck := healthcheck.NewObservation(
1991
                        "tor connection",
1992
                        func() error {
1993
                                return healthcheck.CheckTorServiceStatus(
1994
                                        s.torController,
1995
                                        func() error {
3✔
1996
                                                return s.createNewHiddenService(
3✔
1997
                                                        context.TODO(),
3✔
1998
                                                )
3✔
1999
                                        },
3✔
2000
                                )
3✔
UNCOV
2001
                        },
×
UNCOV
2002
                        cfg.HealthChecks.TorConnection.Interval,
×
UNCOV
2003
                        cfg.HealthChecks.TorConnection.Timeout,
×
UNCOV
2004
                        cfg.HealthChecks.TorConnection.Backoff,
×
UNCOV
2005
                        cfg.HealthChecks.TorConnection.Attempts,
×
UNCOV
2006
                )
×
2007
                checks = append(checks, torConnectionCheck)
×
UNCOV
2008
        }
×
UNCOV
2009

×
UNCOV
2010
        // If remote signing is enabled, add the healthcheck for the remote
×
2011
        // signing RPC interface.
2012
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
2013
                // Because we have two cascading timeouts here, we need to add
2014
                // some slack to the "outer" one of them in case the "inner"
2015
                // returns exactly on time.
2016
                overhead := time.Millisecond * 10
2017

UNCOV
2018
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
2019
                        "remote signer connection",
2020
                        rpcwallet.HealthCheck(
2021
                                s.cfg.RemoteSigner,
2022

2023
                                // For the health check we might to be even
6✔
2024
                                // stricter than the initial/normal connect, so
3✔
2025
                                // we use the health check timeout here.
3✔
2026
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2027
                        ),
3✔
2028
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2029
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2030
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2031
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2032
                )
3✔
2033
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2034
        }
3✔
2035

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

×
2054
                                leader, err := leaderElector.IsLeader(
×
2055
                                        timeoutCtx,
×
2056
                                )
×
2057
                                if err != nil {
×
2058
                                        return fmt.Errorf("unable to check if "+
×
2059
                                                "still leader: %v", err)
×
2060
                                }
×
UNCOV
2061

×
2062
                                if !leader {
×
2063
                                        srvrLog.Debug("Not the current leader")
×
2064
                                        return fmt.Errorf("not the current " +
×
2065
                                                "leader")
×
2066
                                }
×
UNCOV
2067

×
2068
                                return nil
×
UNCOV
2069
                        },
×
UNCOV
2070
                        cfg.HealthChecks.LeaderCheck.Interval,
×
UNCOV
2071
                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2072
                        cfg.HealthChecks.LeaderCheck.Backoff,
UNCOV
2073
                        cfg.HealthChecks.LeaderCheck.Attempts,
×
UNCOV
2074
                )
×
UNCOV
2075

×
2076
                checks = append(checks, leaderCheck)
×
UNCOV
2077
        }
×
2078

UNCOV
2079
        // If we have not disabled all of our health checks, we create a
×
2080
        // liveness monitor with our configured checks.
2081
        s.livenessMonitor = healthcheck.NewMonitor(
2082
                &healthcheck.Config{
2083
                        Checks:   checks,
2084
                        Shutdown: srvrLog.Criticalf,
2085
                },
2086
        )
UNCOV
2087
}
×
2088

2089
// Started returns true if the server has been started, and false otherwise.
2090
// NOTE: This function is safe for concurrent access.
2091
func (s *server) Started() bool {
2092
        return atomic.LoadInt32(&s.active) != 0
3✔
2093
}
3✔
2094

3✔
2095
// cleaner is used to aggregate "cleanup" functions during an operation that
3✔
2096
// starts several subsystems. In case one of the subsystem fails to start
3✔
2097
// and a proper resource cleanup is required, the "run" method achieves this
3✔
2098
// by running all these added "cleanup" functions.
2099
type cleaner []func() error
2100

2101
// add is used to add a cleanup function to be called when
2102
// the run function is executed.
3✔
2103
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2104
        return append(c, cleanup)
3✔
2105
}
2106

2107
// run is used to run all the previousely added cleanup functions.
2108
func (c cleaner) run() {
2109
        for i := len(c) - 1; i >= 0; i-- {
2110
                if err := c[i](); err != nil {
2111
                        srvrLog.Errorf("Cleanup failed: %v", err)
2112
                }
2113
        }
2114
}
3✔
2115

3✔
2116
// Start starts the main daemon server, all requested listeners, and any helper
3✔
2117
// goroutines.
2118
// NOTE: This function is safe for concurrent access.
UNCOV
2119
//
×
UNCOV
2120
//nolint:funlen
×
UNCOV
2121
func (s *server) Start(ctx context.Context) error {
×
UNCOV
2122
        var startErr error
×
UNCOV
2123

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

2129
        s.start.Do(func() {
2130
                cleanup = cleanup.add(s.customMessageServer.Stop)
2131
                if err := s.customMessageServer.Start(); err != nil {
2132
                        startErr = err
3✔
2133
                        return
3✔
2134
                }
3✔
2135

3✔
2136
                cleanup = cleanup.add(s.onionMessageServer.Stop)
3✔
2137
                if err := s.onionMessageServer.Start(); err != nil {
3✔
2138
                        startErr = err
3✔
2139
                        return
3✔
2140
                }
6✔
2141

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

×
UNCOV
2150
                if s.livenessMonitor != nil {
×
UNCOV
2151
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
2152
                        if err := s.livenessMonitor.Start(); err != nil {
2153
                                startErr = err
3✔
2154
                                return
×
2155
                        }
×
UNCOV
2156
                }
×
UNCOV
2157

×
UNCOV
2158
                // Start the notification server. This is used so channel
×
2159
                // management goroutines can be notified when a funding
2160
                // transaction reaches a sufficient number of confirmations, or
2161
                // when the input for the funding transaction is spent in an
6✔
2162
                // attempt at an uncooperative close by the counterparty.
3✔
2163
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
UNCOV
2164
                if err := s.sigPool.Start(); err != nil {
×
2165
                        startErr = err
×
2166
                        return
×
2167
                }
2168

2169
                cleanup = cleanup.add(s.writePool.Stop)
2170
                if err := s.writePool.Start(); err != nil {
2171
                        startErr = err
2172
                        return
2173
                }
2174

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

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

3✔
2187
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
UNCOV
2188
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2189
                        startErr = err
×
2190
                        return
×
2191
                }
2192

3✔
2193
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
UNCOV
2194
                if err := s.channelNotifier.Start(); err != nil {
×
2195
                        startErr = err
×
2196
                        return
×
2197
                }
2198

3✔
2199
                cleanup = cleanup.add(func() error {
3✔
2200
                        return s.peerNotifier.Stop()
×
2201
                })
×
UNCOV
2202
                if err := s.peerNotifier.Start(); err != nil {
×
2203
                        startErr = err
2204
                        return
3✔
2205
                }
3✔
UNCOV
2206

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

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

×
UNCOV
2221
                beat, err := s.getStartingBeat()
×
UNCOV
2222
                if err != nil {
×
2223
                        startErr = err
2224
                        return
6✔
2225
                }
3✔
2226

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

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

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

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

3✔
2251
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
UNCOV
2252
                if err := s.fundingMgr.Start(); err != nil {
×
2253
                        startErr = err
×
2254
                        return
×
2255
                }
2256

3✔
2257
                // htlcSwitch must be started before chainArb since the latter
3✔
UNCOV
2258
                // relies on htlcSwitch to deliver resolution message upon
×
UNCOV
2259
                // start.
×
UNCOV
2260
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
2261
                if err := s.htlcSwitch.Start(); err != nil {
2262
                        startErr = err
3✔
2263
                        return
3✔
2264
                }
×
UNCOV
2265

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

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

3✔
2278
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
UNCOV
2279
                if err := s.chainArb.Start(beat); err != nil {
×
2280
                        startErr = err
×
2281
                        return
×
2282
                }
2283

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

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

3✔
2296
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
UNCOV
2297
                if err := s.chanRouter.Start(); err != nil {
×
2298
                        startErr = err
×
2299
                        return
×
2300
                }
2301
                // The authGossiper depends on the chanRouter and therefore
3✔
2302
                // should be started after it.
3✔
UNCOV
2303
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2304
                if err := s.authGossiper.Start(); err != nil {
×
2305
                        startErr = err
×
2306
                        return
2307
                }
3✔
2308

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

3✔
2315
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
UNCOV
2316
                if err := s.sphinx.Start(); err != nil {
×
2317
                        startErr = err
×
2318
                        return
×
2319
                }
2320

3✔
2321
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
UNCOV
2322
                if err := s.chanStatusMgr.Start(); err != nil {
×
2323
                        startErr = err
×
2324
                        return
×
2325
                }
2326

3✔
2327
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
UNCOV
2328
                if err := s.chanEventStore.Start(); err != nil {
×
2329
                        startErr = err
×
2330
                        return
×
2331
                }
2332

3✔
2333
                cleanup.add(func() error {
3✔
2334
                        s.missionController.StopStoreTickers()
×
2335
                        return nil
×
2336
                })
×
2337
                s.missionController.RunStoreTickers()
2338

3✔
2339
                // Before we start the connMgr, we'll check to see if we have
3✔
UNCOV
2340
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2341
                // that have all the information we need to handle channel
×
UNCOV
2342
                // recovery _before_ we even accept connections from any peers.
×
2343
                chanRestorer := &chanDBRestorer{
2344
                        db:         s.chanStateDB,
3✔
UNCOV
2345
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2346
                        chainArb:   s.chainArb,
×
UNCOV
2347
                }
×
2348
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2349
                        _, err := chanbackup.UnpackAndRecoverSingles(
3✔
2350
                                s.chansToRestore.PackedSingleChanBackups,
3✔
2351
                                s.cc.KeyRing, chanRestorer, s,
3✔
2352
                        )
3✔
2353
                        if err != nil {
3✔
2354
                                startErr = fmt.Errorf("unable to unpack single "+
3✔
2355
                                        "backups: %v", err)
3✔
2356
                                return
3✔
2357
                        }
3✔
2358
                }
3✔
2359
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
3✔
UNCOV
2360
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2361
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2362
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2363
                        )
×
UNCOV
2364
                        if err != nil {
×
2365
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2366
                                        "backup: %v", err)
×
2367
                                return
×
2368
                        }
×
2369
                }
2370

6✔
2371
                // chanSubSwapper must be started after the `channelNotifier`
3✔
2372
                // because it depends on channel events as a synchronization
3✔
2373
                // point.
3✔
2374
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2375
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2376
                        startErr = err
×
2377
                        return
×
2378
                }
×
UNCOV
2379

×
2380
                if s.torController != nil {
2381
                        cleanup = cleanup.add(s.torController.Stop)
2382
                        if err := s.createNewHiddenService(ctx); err != nil {
2383
                                startErr = err
2384
                                return
2385
                        }
3✔
2386
                }
3✔
UNCOV
2387

×
UNCOV
2388
                if s.natTraversal != nil {
×
2389
                        s.wg.Add(1)
×
2390
                        go s.watchExternalIP()
2391
                }
3✔
UNCOV
2392

×
UNCOV
2393
                // Start connmgr last to prevent connections before init.
×
UNCOV
2394
                cleanup = cleanup.add(func() error {
×
2395
                        s.connMgr.Stop()
×
2396
                        return nil
×
2397
                })
2398

2399
                // RESOLVE: s.connMgr.Start() is called here, but
3✔
UNCOV
2400
                // brontide.NewListener() is called in newServer. This means
×
UNCOV
2401
                // that we are actually listening and partially accepting
×
UNCOV
2402
                // inbound connections even before the connMgr starts.
×
2403
                //
2404
                // TODO(yy): move the log into the connMgr's `Start` method.
2405
                srvrLog.Info("connMgr starting...")
3✔
UNCOV
2406
                s.connMgr.Start()
×
UNCOV
2407
                srvrLog.Debug("connMgr started")
×
UNCOV
2408

×
2409
                // If peers are specified as a config option, we'll add those
2410
                // peers first.
2411
                for _, peerAddrCfg := range s.cfg.AddPeers {
2412
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
2413
                                peerAddrCfg,
2414
                        )
2415
                        if err != nil {
2416
                                startErr = fmt.Errorf("unable to parse peer "+
3✔
2417
                                        "pubkey from config: %v", err)
3✔
2418
                                return
3✔
2419
                        }
3✔
2420
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2421
                        if err != nil {
3✔
2422
                                startErr = fmt.Errorf("unable to parse peer "+
6✔
2423
                                        "address provided as a config option: "+
3✔
2424
                                        "%v", err)
3✔
2425
                                return
3✔
2426
                        }
3✔
UNCOV
2427

×
UNCOV
2428
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2429
                                IdentityKey: parsedPubkey,
×
UNCOV
2430
                                Address:     addr,
×
2431
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2432
                        }
3✔
UNCOV
2433

×
UNCOV
2434
                        err = s.ConnectToPeer(
×
UNCOV
2435
                                peerAddr, true,
×
UNCOV
2436
                                s.cfg.ConnectionTimeout,
×
UNCOV
2437
                        )
×
2438
                        if err != nil {
2439
                                startErr = fmt.Errorf("unable to connect to "+
3✔
2440
                                        "peer address provided as a config "+
3✔
2441
                                        "option: %v", err)
3✔
2442
                                return
3✔
2443
                        }
3✔
2444
                }
3✔
2445

3✔
2446
                // Subscribe to NodeAnnouncements that advertise new addresses
3✔
2447
                // our persistent peers.
3✔
2448
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2449
                        srvrLog.Errorf("Failed to update persistent peer "+
3✔
2450
                                "addr: %v", err)
×
2451

×
2452
                        startErr = err
×
2453
                        return
×
2454
                }
×
2455

2456
                // With all the relevant sub-systems started, we'll now attempt
2457
                // to establish persistent connections to our direct channel
2458
                // collaborators within the network. Before doing so however,
2459
                // we'll prune our set of link nodes found within the database
3✔
UNCOV
2460
                // to ensure we don't reconnect to any nodes we no longer have
×
UNCOV
2461
                // open channels with.
×
UNCOV
2462
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2463
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2464

×
2465
                        startErr = err
×
2466
                        return
2467
                }
2468

2469
                if err := s.establishPersistentConnections(ctx); err != nil {
2470
                        srvrLog.Errorf("Failed to establish persistent "+
2471
                                "connections: %v", err)
2472
                }
2473

3✔
UNCOV
2474
                // setSeedList is a helper function that turns multiple DNS seed
×
UNCOV
2475
                // server tuples from the command line or config file into the
×
UNCOV
2476
                // data structure we need and does a basic formal sanity check
×
UNCOV
2477
                // in the process.
×
UNCOV
2478
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2479
                        if len(tuples) == 0 {
2480
                                return
3✔
2481
                        }
×
UNCOV
2482

×
2483
                        result := make([][2]string, len(tuples))
×
2484
                        for idx, tuple := range tuples {
2485
                                tuple = strings.TrimSpace(tuple)
2486
                                if len(tuple) == 0 {
2487
                                        return
2488
                                }
2489

3✔
2490
                                servers := strings.Split(tuple, ",")
×
2491
                                if len(servers) > 2 || len(servers) == 0 {
×
2492
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2493
                                                "seed tuple: %v", servers)
2494
                                        return
×
2495
                                }
×
UNCOV
2496

×
2497
                                copy(result[idx][:], servers)
×
UNCOV
2498
                        }
×
UNCOV
2499

×
2500
                        chainreg.ChainDNSSeeds[genesisHash] = result
UNCOV
2501
                }
×
UNCOV
2502

×
UNCOV
2503
                // Let users overwrite the DNS seed nodes. We only allow them
×
UNCOV
2504
                // for bitcoin mainnet/testnet/signet.
×
UNCOV
2505
                if s.cfg.Bitcoin.MainNet {
×
2506
                        setSeedList(
×
2507
                                s.cfg.Bitcoin.DNSSeeds,
2508
                                chainreg.BitcoinMainnetGenesis,
×
2509
                        )
2510
                }
UNCOV
2511
                if s.cfg.Bitcoin.TestNet3 {
×
2512
                        setSeedList(
2513
                                s.cfg.Bitcoin.DNSSeeds,
2514
                                chainreg.BitcoinTestnetGenesis,
2515
                        )
2516
                }
3✔
UNCOV
2517
                if s.cfg.Bitcoin.TestNet4 {
×
2518
                        setSeedList(
×
2519
                                s.cfg.Bitcoin.DNSSeeds,
×
2520
                                chainreg.BitcoinTestnet4Genesis,
×
2521
                        )
×
2522
                }
3✔
UNCOV
2523
                if s.cfg.Bitcoin.SigNet {
×
2524
                        setSeedList(
×
2525
                                s.cfg.Bitcoin.DNSSeeds,
×
2526
                                chainreg.BitcoinSignetGenesis,
×
2527
                        )
×
2528
                }
3✔
UNCOV
2529

×
UNCOV
2530
                // If network bootstrapping hasn't been disabled, then we'll
×
UNCOV
2531
                // configure the set of active bootstrappers, and launch a
×
UNCOV
2532
                // dedicated goroutine to maintain a set of persistent
×
UNCOV
2533
                // connections.
×
2534
                if !s.cfg.NoNetBootstrap {
3✔
UNCOV
2535
                        bootstrappers, err := initNetworkBootstrappers(s)
×
UNCOV
2536
                        if err != nil {
×
2537
                                startErr = err
×
2538
                                return
×
2539
                        }
×
2540

2541
                        s.wg.Add(1)
2542
                        go s.peerBootstrapper(
2543
                                ctx, defaultMinPeers, bootstrappers,
2544
                        )
2545
                } else {
6✔
2546
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2547
                }
3✔
UNCOV
2548

×
UNCOV
2549
                // Start the blockbeat after all other subsystems have been
×
UNCOV
2550
                // started so they are ready to receive new blocks.
×
2551
                cleanup = cleanup.add(func() error {
2552
                        s.blockbeatDispatcher.Stop()
3✔
2553
                        return nil
3✔
2554
                })
3✔
2555
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2556
                        startErr = err
3✔
2557
                        return
3✔
2558
                }
3✔
2559

2560
                // Set the active flag now that we've completed the full
2561
                // startup.
2562
                atomic.StoreInt32(&s.active, 1)
3✔
UNCOV
2563
        })
×
UNCOV
2564

×
UNCOV
2565
        if startErr != nil {
×
2566
                cleanup.run()
3✔
2567
        }
×
UNCOV
2568
        return startErr
×
UNCOV
2569
}
×
2570

2571
// Stop gracefully shutsdown the main daemon server. This function will signal
2572
// any active goroutines, or helper objects to exit, then blocks until they've
2573
// all successfully exited. Additionally, any/all listeners are closed.
3✔
2574
// NOTE: This function is safe for concurrent access.
2575
func (s *server) Stop() error {
2576
        s.stop.Do(func() {
3✔
UNCOV
2577
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2578

×
2579
                ctx := context.Background()
3✔
2580

2581
                close(s.quit)
2582

2583
                // Shutdown connMgr first to prevent conns during shutdown.
2584
                s.connMgr.Stop()
2585

2586
                // Stop dispatching blocks to other systems immediately.
3✔
2587
                s.blockbeatDispatcher.Stop()
6✔
2588

3✔
2589
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2590
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2591
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
3✔
2592
                }
3✔
2593
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2594
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
3✔
2595
                }
3✔
2596
                if err := s.sphinx.Stop(); err != nil {
3✔
2597
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
3✔
2598
                }
3✔
2599
                if err := s.invoices.Stop(); err != nil {
3✔
2600
                        srvrLog.Warnf("failed to stop invoices: %v", err)
3✔
2601
                }
3✔
UNCOV
2602
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2603
                        srvrLog.Warnf("failed to stop interceptable "+
×
2604
                                "switch: %v", err)
3✔
2605
                }
×
UNCOV
2606
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2607
                        srvrLog.Warnf("failed to stop htlc invoices "+
3✔
2608
                                "modifier: %v", err)
×
2609
                }
×
2610
                if err := s.chanRouter.Stop(); err != nil {
3✔
2611
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2612
                }
×
2613
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2614
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2615
                }
×
UNCOV
2616
                if err := s.graphDB.Stop(); err != nil {
×
2617
                        srvrLog.Warnf("failed to stop graphDB %v", err)
3✔
2618
                }
×
UNCOV
2619
                if err := s.chainArb.Stop(); err != nil {
×
2620
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2621
                }
3✔
UNCOV
2622
                if err := s.fundingMgr.Stop(); err != nil {
×
2623
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2624
                }
3✔
UNCOV
2625
                if err := s.breachArbitrator.Stop(); err != nil {
×
2626
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2627
                                err)
3✔
2628
                }
×
UNCOV
2629
                if err := s.utxoNursery.Stop(); err != nil {
×
2630
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
3✔
2631
                }
×
UNCOV
2632
                if err := s.authGossiper.Stop(); err != nil {
×
2633
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
3✔
2634
                }
×
UNCOV
2635
                if err := s.sweeper.Stop(); err != nil {
×
2636
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
3✔
2637
                }
×
UNCOV
2638
                if err := s.txPublisher.Stop(); err != nil {
×
2639
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2640
                }
3✔
UNCOV
2641
                if err := s.channelNotifier.Stop(); err != nil {
×
2642
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2643
                }
3✔
UNCOV
2644
                if err := s.peerNotifier.Stop(); err != nil {
×
2645
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2646
                }
3✔
UNCOV
2647
                if err := s.htlcNotifier.Stop(); err != nil {
×
2648
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2649
                }
3✔
UNCOV
2650

×
UNCOV
2651
                // Update channel.backup file. Make sure to do it before
×
2652
                // stopping chanSubSwapper.
3✔
UNCOV
2653
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2654
                        ctx, s.chanStateDB, s.addrSource,
×
2655
                )
3✔
UNCOV
2656
                if err != nil {
×
2657
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2658
                                err)
3✔
UNCOV
2659
                } else {
×
UNCOV
2660
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
2661
                        if err != nil {
2662
                                srvrLog.Warnf("Manual update of channel "+
2663
                                        "backup failed: %v", err)
2664
                        }
3✔
2665
                }
3✔
2666

3✔
2667
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2668
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2669
                }
×
2670
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2671
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
3✔
2672
                }
6✔
2673
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2674
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
3✔
2675
                                err)
3✔
2676
                }
2677
                if err := s.chanEventStore.Stop(); err != nil {
2678
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
3✔
2679
                                err)
×
2680
                }
×
2681
                s.missionController.StopStoreTickers()
3✔
UNCOV
2682

×
UNCOV
2683
                // Disconnect from each active peers to ensure that
×
2684
                // peerTerminationWatchers signal completion to each peer.
3✔
UNCOV
2685
                for _, peer := range s.Peers() {
×
UNCOV
2686
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2687
                        if err != nil {
×
2688
                                srvrLog.Warnf("could not disconnect peer: %v"+
3✔
2689
                                        "received error: %v", peer.IdentityKey(),
×
2690
                                        err,
×
2691
                                )
×
2692
                        }
3✔
2693
                }
3✔
2694

3✔
2695
                // Now that all connections have been torn down, stop the tower
3✔
2696
                // client which will reliably flush all queued states to the
6✔
2697
                // tower. If this is halted for any reason, the force quit timer
3✔
2698
                // will kick in and abort to allow this method to return.
3✔
UNCOV
2699
                if s.towerClientMgr != nil {
×
UNCOV
2700
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2701
                                srvrLog.Warnf("Unable to shut down tower "+
×
2702
                                        "client manager: %v", err)
×
2703
                        }
×
2704
                }
2705

2706
                if s.hostAnn != nil {
2707
                        if err := s.hostAnn.Stop(); err != nil {
2708
                                srvrLog.Warnf("unable to shut down host "+
2709
                                        "annoucner: %v", err)
2710
                        }
6✔
2711
                }
3✔
UNCOV
2712

×
UNCOV
2713
                if s.livenessMonitor != nil {
×
UNCOV
2714
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2715
                                srvrLog.Warnf("unable to shutdown liveness "+
2716
                                        "monitor: %v", err)
2717
                        }
3✔
UNCOV
2718
                }
×
UNCOV
2719

×
UNCOV
2720
                // Wait for all lingering goroutines to quit.
×
UNCOV
2721
                srvrLog.Debug("Waiting for server to shutdown...")
×
2722
                s.wg.Wait()
2723

2724
                srvrLog.Debug("Stopping buffer pools...")
6✔
2725
                s.sigPool.Stop()
3✔
UNCOV
2726
                s.writePool.Stop()
×
UNCOV
2727
                s.readPool.Stop()
×
UNCOV
2728
        })
×
2729

2730
        return nil
2731
}
2732

3✔
2733
// Stopped returns true if the server has been instructed to shutdown.
3✔
2734
// NOTE: This function is safe for concurrent access.
3✔
2735
func (s *server) Stopped() bool {
3✔
2736
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2737
}
3✔
2738

3✔
2739
// configurePortForwarding attempts to set up port forwarding for the different
2740
// ports that the server will be listening on.
2741
//
3✔
2742
// NOTE: This should only be used when using some kind of NAT traversal to
2743
// automatically set up forwarding rules.
2744
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
2745
        ip, err := s.natTraversal.ExternalIP()
2746
        if err != nil {
3✔
2747
                return nil, err
3✔
2748
        }
3✔
2749
        s.lastDetectedIP = ip
2750

2751
        externalIPs := make([]string, 0, len(ports))
2752
        for _, port := range ports {
2753
                if err := s.natTraversal.AddPortMapping(port); err != nil {
2754
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
2755
                        continue
×
UNCOV
2756
                }
×
UNCOV
2757

×
2758
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2759
                externalIPs = append(externalIPs, hostIP)
×
UNCOV
2760
        }
×
UNCOV
2761

×
2762
        return externalIPs, nil
×
UNCOV
2763
}
×
UNCOV
2764

×
UNCOV
2765
// removePortForwarding attempts to clear the forwarding rules for the different
×
UNCOV
2766
// ports the server is currently listening on.
×
2767
//
2768
// NOTE: This should only be used when using some kind of NAT traversal to
UNCOV
2769
// automatically set up forwarding rules.
×
2770
func (s *server) removePortForwarding() {
×
2771
        forwardedPorts := s.natTraversal.ForwardedPorts()
2772
        for _, port := range forwardedPorts {
2773
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2774
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
2775
                                "port %d: %v", port, err)
2776
                }
2777
        }
2778
}
2779

2780
// watchExternalIP continuously checks for an updated external IP address every
UNCOV
2781
// 15 minutes. Once a new IP address has been detected, it will automatically
×
UNCOV
2782
// handle port forwarding rules and send updated node announcements to the
×
UNCOV
2783
// currently connected peers.
×
UNCOV
2784
//
×
UNCOV
2785
// NOTE: This MUST be run as a goroutine.
×
2786
func (s *server) watchExternalIP() {
×
2787
        defer s.wg.Done()
×
2788

2789
        // Before exiting, we'll make sure to remove the forwarding rules set
2790
        // up by the server.
2791
        defer s.removePortForwarding()
2792

2793
        // Keep track of the external IPs set by the user to avoid replacing
2794
        // them when detecting a new IP.
2795
        ipsSetByUser := make(map[string]struct{})
2796
        for _, ip := range s.cfg.ExternalIPs {
2797
                ipsSetByUser[ip.String()] = struct{}{}
×
2798
        }
×
UNCOV
2799

×
2800
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2801

×
2802
        ticker := time.NewTicker(15 * time.Minute)
×
2803
        defer ticker.Stop()
×
2804
out:
×
2805
        for {
×
2806
                select {
×
2807
                case <-ticker.C:
×
2808
                        // We'll start off by making sure a new IP address has
×
2809
                        // been detected.
×
2810
                        ip, err := s.natTraversal.ExternalIP()
2811
                        if err != nil {
×
2812
                                srvrLog.Debugf("Unable to retrieve the "+
×
2813
                                        "external IP address: %v", err)
×
2814
                                continue
×
UNCOV
2815
                        }
×
UNCOV
2816

×
UNCOV
2817
                        // Periodically renew the NAT port forwarding.
×
2818
                        for _, port := range forwardedPorts {
×
2819
                                err := s.natTraversal.AddPortMapping(port)
×
2820
                                if err != nil {
×
2821
                                        srvrLog.Warnf("Unable to automatically "+
×
2822
                                                "re-create port forwarding using %s: %v",
×
2823
                                                s.natTraversal.Name(), err)
×
2824
                                } else {
×
2825
                                        srvrLog.Debugf("Automatically re-created "+
×
2826
                                                "forwarding for port %d using %s to "+
2827
                                                "advertise external IP",
2828
                                                port, s.natTraversal.Name())
2829
                                }
×
UNCOV
2830
                        }
×
UNCOV
2831

×
2832
                        if ip.Equal(s.lastDetectedIP) {
×
2833
                                continue
×
UNCOV
2834
                        }
×
UNCOV
2835

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

×
2838
                        // Next, we'll craft the new addresses that will be
×
2839
                        // included in the new node announcement and advertised
×
2840
                        // to the network. Each address will consist of the new
×
2841
                        // IP detected and one of the currently advertised
2842
                        // ports.
2843
                        var newAddrs []net.Addr
×
2844
                        for _, port := range forwardedPorts {
×
2845
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
2846
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
2847
                                if err != nil {
×
2848
                                        srvrLog.Debugf("Unable to resolve "+
×
2849
                                                "host %v: %v", addr, err)
×
2850
                                        continue
×
UNCOV
2851
                                }
×
UNCOV
2852

×
2853
                                newAddrs = append(newAddrs, addr)
×
UNCOV
2854
                        }
×
UNCOV
2855

×
UNCOV
2856
                        // Skip the update if we weren't able to resolve any of
×
UNCOV
2857
                        // the new addresses.
×
2858
                        if len(newAddrs) == 0 {
×
2859
                                srvrLog.Debug("Skipping node announcement " +
×
2860
                                        "update due to not being able to " +
×
2861
                                        "resolve any new addresses")
×
2862
                                continue
2863
                        }
UNCOV
2864

×
2865
                        // Now, we'll need to update the addresses in our node's
2866
                        // announcement in order to propagate the update
2867
                        // throughout the network. We'll only include addresses
2868
                        // that have a different IP from the previous one, as
UNCOV
2869
                        // the previous IP is no longer valid.
×
2870
                        currentNodeAnn := s.getNodeAnnouncement()
×
2871

×
2872
                        for _, addr := range currentNodeAnn.Addresses {
×
2873
                                host, _, err := net.SplitHostPort(addr.String())
×
2874
                                if err != nil {
2875
                                        srvrLog.Debugf("Unable to determine "+
2876
                                                "host from address %v: %v",
2877
                                                addr, err)
2878
                                        continue
2879
                                }
2880

UNCOV
2881
                                // We'll also make sure to include external IPs
×
UNCOV
2882
                                // set manually by the user.
×
2883
                                _, setByUser := ipsSetByUser[addr.String()]
×
2884
                                if setByUser || host != s.lastDetectedIP.String() {
×
2885
                                        newAddrs = append(newAddrs, addr)
×
2886
                                }
×
UNCOV
2887
                        }
×
UNCOV
2888

×
UNCOV
2889
                        // Then, we'll generate a new timestamped node
×
2890
                        // announcement with the updated addresses and broadcast
2891
                        // it to our peers.
2892
                        newNodeAnn, err := s.genNodeAnnouncement(
2893
                                nil, netann.NodeAnnSetAddrs(newAddrs),
2894
                        )
×
2895
                        if err != nil {
×
2896
                                srvrLog.Debugf("Unable to generate new node "+
×
2897
                                        "announcement: %v", err)
×
2898
                                continue
2899
                        }
2900

2901
                        err = s.BroadcastMessage(nil, &newNodeAnn)
2902
                        if err != nil {
2903
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2904
                                        "announcement to peers: %v", err)
×
2905
                                continue
×
UNCOV
2906
                        }
×
UNCOV
2907

×
UNCOV
2908
                        // Finally, update the last IP seen to the current one.
×
2909
                        s.lastDetectedIP = ip
×
2910
                case <-s.quit:
2911
                        break out
UNCOV
2912
                }
×
UNCOV
2913
        }
×
UNCOV
2914
}
×
UNCOV
2915

×
UNCOV
2916
// initNetworkBootstrappers initializes a set of network peer bootstrappers
×
2917
// based on the server, and currently active bootstrap mechanisms as defined
2918
// within the current configuration.
2919
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
UNCOV
2920
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
UNCOV
2921

×
UNCOV
2922
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2923

2924
        // First, we'll create an instance of the ChannelGraphBootstrapper as
2925
        // this can be used by default if we've already partially seeded the
2926
        // network.
2927
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
2928
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
2929
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
2930
        )
3✔
2931
        if err != nil {
3✔
2932
                return nil, err
3✔
2933
        }
3✔
2934
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2935

3✔
2936
        // If this isn't using simnet or regtest mode, then one of our
3✔
2937
        // additional bootstrapping sources will be the set of running DNS
3✔
2938
        // seeds.
3✔
2939
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2940
                //nolint:ll
3✔
2941
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
3✔
2942

3✔
2943
                // If we have a set of DNS seeds for this chain, then we'll add
×
2944
                // it as an additional bootstrapping source.
×
2945
                if ok {
3✔
2946
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
3✔
2947
                                "seeds: %v", dnsSeeds)
3✔
2948

3✔
2949
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
3✔
2950
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
2951
                        )
×
2952
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2953
                }
×
UNCOV
2954
        }
×
UNCOV
2955

×
UNCOV
2956
        return bootStrappers, nil
×
UNCOV
2957
}
×
UNCOV
2958

×
UNCOV
2959
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
×
UNCOV
2960
// needs to ignore, which is made of three parts,
×
UNCOV
2961
//   - the node itself needs to be skipped as it doesn't make sense to connect
×
UNCOV
2962
//     to itself.
×
UNCOV
2963
//   - the peers that already have connections with, as in s.peersByPub.
×
UNCOV
2964
//   - the peers that we are attempting to connect, as in s.persistentPeers.
×
2965
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
2966
        s.mu.RLock()
2967
        defer s.mu.RUnlock()
3✔
2968

2969
        ignore := make(map[autopilot.NodeID]struct{})
2970

2971
        // We should ignore ourselves from bootstrapping.
2972
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
2973
        ignore[selfKey] = struct{}{}
2974

2975
        // Ignore all connected peers.
2976
        for _, peer := range s.peersByPub {
3✔
2977
                nID := autopilot.NewNodeID(peer.IdentityKey())
3✔
2978
                ignore[nID] = struct{}{}
3✔
2979
        }
3✔
2980

3✔
2981
        // Ignore all persistent peers as they have a dedicated reconnecting
3✔
2982
        // process.
3✔
2983
        for pubKeyStr := range s.persistentPeers {
3✔
2984
                var nID autopilot.NodeID
3✔
2985
                copy(nID[:], []byte(pubKeyStr))
3✔
2986
                ignore[nID] = struct{}{}
3✔
2987
        }
3✔
UNCOV
2988

×
UNCOV
2989
        return ignore
×
UNCOV
2990
}
×
2991

2992
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2993
// and maintain a target minimum number of outbound connections. With this
2994
// invariant, we ensure that our node is connected to a diverse set of peers
3✔
UNCOV
2995
// and that nodes newly joining the network receive an up to date network view
×
UNCOV
2996
// as soon as possible.
×
UNCOV
2997
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
×
UNCOV
2998
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2999

3000
        defer s.wg.Done()
3✔
3001

3002
        // Before we continue, init the ignore peers map.
3003
        ignoreList := s.createBootstrapIgnorePeers()
3004

3005
        // We'll start off by aggressively attempting connections to peers in
3006
        // order to be a part of the network as soon as possible.
3007
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
3008

3009
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3010
        // peers.
3✔
3011
        //
3✔
3012
        // We'll use a 15 second backoff, and double the time every time an
3✔
3013
        // epoch fails up to a ceiling.
3✔
3014
        backOff := time.Second * 15
3✔
3015

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

3✔
3021
        // We'll use the number of attempts and errors to determine if we need
3✔
3022
        // to increase the time between discovery epochs.
3✔
3023
        var epochErrors uint32 // To be used atomically.
3✔
3024
        var epochAttempts uint32
3✔
3025

3✔
3026
        for {
3✔
3027
                select {
3✔
3028
                // The ticker has just woken us up, so we'll need to check if
3✔
3029
                // we need to attempt to connect our to any more peers.
3✔
3030
                case <-sampleTicker.C:
3✔
3031
                        // Obtain the current number of peers, so we can gauge
3✔
3032
                        // if we need to sample more peers or not.
3✔
3033
                        s.mu.RLock()
3✔
3034
                        numActivePeers := uint32(len(s.peersByPub))
3✔
3035
                        s.mu.RUnlock()
3✔
3036

3✔
3037
                        // If we have enough peers, then we can loop back
6✔
3038
                        // around to the next round as we're done here.
3✔
3039
                        if numActivePeers >= numTargetPeers {
3040
                                continue
UNCOV
3041
                        }
×
UNCOV
3042

×
UNCOV
3043
                        // If all of our attempts failed during this last back
×
UNCOV
3044
                        // off period, then will increase our backoff to 5
×
UNCOV
3045
                        // minute ceiling to avoid an excessive number of
×
UNCOV
3046
                        // queries
×
UNCOV
3047
                        //
×
UNCOV
3048
                        // TODO(roasbeef): add reverse policy too?
×
UNCOV
3049

×
3050
                        if epochAttempts > 0 &&
×
3051
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3052

3053
                                sampleTicker.Stop()
3054

3055
                                backOff *= 2
3056
                                if backOff > bootstrapBackOffCeiling {
3057
                                        backOff = bootstrapBackOffCeiling
3058
                                }
3059

3060
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
3061
                                        "%v", backOff)
×
3062
                                sampleTicker = time.NewTicker(backOff)
×
3063
                                continue
×
UNCOV
3064
                        }
×
UNCOV
3065

×
3066
                        atomic.StoreUint32(&epochErrors, 0)
×
3067
                        epochAttempts = 0
×
3068

×
3069
                        // Since we know need more peers, we'll compute the
×
3070
                        // exact number we need to reach our threshold.
3071
                        numNeeded := numTargetPeers - numActivePeers
×
3072

×
3073
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3074
                                "peers", numNeeded)
×
3075

3076
                        // With the number of peers we need calculated, we'll
3077
                        // query the network bootstrappers to sample a set of
×
3078
                        // random addrs for us.
×
3079
                        //
×
3080
                        // Before we continue, get a copy of the ignore peers
×
3081
                        // map.
×
3082
                        ignoreList = s.createBootstrapIgnorePeers()
×
3083

×
3084
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3085
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3086
                        )
×
3087
                        if err != nil {
×
3088
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3089
                                        "peers: %v", err)
×
3090
                                continue
×
UNCOV
3091
                        }
×
UNCOV
3092

×
UNCOV
3093
                        // Finally, we'll launch a new goroutine for each
×
UNCOV
3094
                        // prospective peer candidates.
×
3095
                        for _, addr := range peerAddrs {
×
3096
                                epochAttempts++
×
3097

×
3098
                                go func(a *lnwire.NetAddress) {
×
3099
                                        // TODO(roasbeef): can do AS, subnet,
×
3100
                                        // country diversity, etc
×
3101
                                        errChan := make(chan error, 1)
×
3102
                                        s.connectToPeer(
3103
                                                a, errChan,
3104
                                                s.cfg.ConnectionTimeout,
3105
                                        )
3106
                                        select {
×
3107
                                        case err := <-errChan:
×
3108
                                                if err == nil {
×
3109
                                                        return
×
3110
                                                }
×
UNCOV
3111

×
3112
                                                srvrLog.Errorf("Unable to "+
×
3113
                                                        "connect to %v: %v",
×
3114
                                                        a, err)
×
3115
                                                atomic.AddUint32(&epochErrors, 1)
×
3116
                                        case <-s.quit:
×
UNCOV
3117
                                        }
×
UNCOV
3118
                                }(addr)
×
UNCOV
3119
                        }
×
UNCOV
3120
                case <-s.quit:
×
UNCOV
3121
                        return
×
3122
                }
UNCOV
3123
        }
×
UNCOV
3124
}
×
UNCOV
3125

×
UNCOV
3126
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
×
UNCOV
3127
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
×
3128
// query back off each time we encounter a failure.
3129
const bootstrapBackOffCeiling = time.Minute * 5
3130

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

3138
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3139
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3140

3141
        // We'll start off by waiting 2 seconds between failed attempts, then
3142
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3143
        var delaySignal <-chan time.Time
3144
        delayTime := time.Second * 2
3145

3146
        // As want to be more aggressive, we'll use a lower back off celling
3147
        // then the main peer bootstrap logic.
3✔
3148
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3149

3✔
3150
        for attempts := 0; ; attempts++ {
3✔
3151
                // Check if the server has been requested to shut down in order
3✔
3152
                // to prevent blocking.
3✔
3153
                if s.Stopped() {
3✔
3154
                        return
3✔
3155
                }
3✔
3156

3✔
3157
                // We can exit our aggressive initial peer bootstrapping stage
3✔
3158
                // if we've reached out target number of peers.
3✔
3159
                s.mu.RLock()
3✔
3160
                numActivePeers := uint32(len(s.peersByPub))
3✔
3161
                s.mu.RUnlock()
6✔
3162

3✔
3163
                if numActivePeers >= numTargetPeers {
3✔
3164
                        return
3✔
UNCOV
3165
                }
×
UNCOV
3166

×
3167
                if attempts > 0 {
3168
                        srvrLog.Debugf("Waiting %v before trying to locate "+
3169
                                "bootstrap peers (attempt #%v)", delayTime,
3170
                                attempts)
3✔
3171

3✔
3172
                        // We've completed at least one iterating and haven't
3✔
3173
                        // finished, so we'll start to insert a delay period
3✔
3174
                        // between each attempt.
6✔
3175
                        delaySignal = time.After(delayTime)
3✔
3176
                        select {
3✔
3177
                        case <-delaySignal:
3178
                        case <-s.quit:
3✔
3179
                                return
×
UNCOV
3180
                        }
×
UNCOV
3181

×
UNCOV
3182
                        // After our delay, we'll double the time we wait up to
×
UNCOV
3183
                        // the max back off period.
×
3184
                        delayTime *= 2
×
3185
                        if delayTime > backOffCeiling {
×
3186
                                delayTime = backOffCeiling
×
3187
                        }
×
UNCOV
3188
                }
×
UNCOV
3189

×
UNCOV
3190
                // Otherwise, we'll request for the remaining number of peers
×
3191
                // in order to reach our target.
3192
                peersNeeded := numTargetPeers - numActivePeers
3193
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3194
                        ctx, ignore, peersNeeded, bootstrappers...,
UNCOV
3195
                )
×
UNCOV
3196
                if err != nil {
×
3197
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3198
                                "peers: %v", err)
×
3199
                        continue
3200
                }
3201

3202
                // Then, we'll attempt to establish a connection to the
3203
                // different peer addresses retrieved by our bootstrappers.
3✔
3204
                var wg sync.WaitGroup
3✔
3205
                for _, bootstrapAddr := range bootstrapAddrs {
3✔
3206
                        wg.Add(1)
3✔
3207
                        go func(addr *lnwire.NetAddress) {
3✔
UNCOV
3208
                                defer wg.Done()
×
UNCOV
3209

×
UNCOV
3210
                                errChan := make(chan error, 1)
×
3211
                                go s.connectToPeer(
3212
                                        addr, errChan, s.cfg.ConnectionTimeout,
3213
                                )
3214

3215
                                // We'll only allow this connection attempt to
3✔
3216
                                // take up to 3 seconds. This allows us to move
6✔
3217
                                // quickly by discarding peers that are slowing
3✔
3218
                                // us down.
6✔
3219
                                select {
3✔
3220
                                case err := <-errChan:
3✔
3221
                                        if err == nil {
3✔
3222
                                                return
3✔
3223
                                        }
3✔
3224
                                        srvrLog.Errorf("Unable to connect to "+
3✔
3225
                                                "%v: %v", addr, err)
3✔
3226
                                // TODO: tune timeout? 3 seconds might be *too*
3✔
3227
                                // aggressive but works well.
3✔
3228
                                case <-time.After(3 * time.Second):
3✔
3229
                                        srvrLog.Tracef("Skipping peer %v due "+
3✔
3230
                                                "to not establishing a "+
3✔
3231
                                                "connection within 3 seconds",
3✔
3232
                                                addr)
6✔
3233
                                case <-s.quit:
3✔
3234
                                }
3✔
UNCOV
3235
                        }(bootstrapAddr)
×
UNCOV
3236
                }
×
3237

3238
                wg.Wait()
UNCOV
3239
        }
×
UNCOV
3240
}
×
UNCOV
3241

×
UNCOV
3242
// createNewHiddenService automatically sets up a v2 or v3 onion service in
×
UNCOV
3243
// order to listen for inbound connections over Tor.
×
3244
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3245
        // Determine the different ports the server is listening on. The onion
3246
        // service's virtual port will map to these ports and one will be picked
3247
        // at random when the onion service is being accessed.
3248
        listenPorts := make([]int, 0, len(s.listenAddrs))
3249
        for _, listenAddr := range s.listenAddrs {
3✔
3250
                port := listenAddr.(*net.TCPAddr).Port
3251
                listenPorts = append(listenPorts, port)
3252
        }
3253

3254
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
3255
        if err != nil {
×
3256
                return err
×
3257
        }
×
UNCOV
3258

×
UNCOV
3259
        // Once the port mapping has been set, we can go ahead and automatically
×
UNCOV
3260
        // create our onion service. The service's private key will be saved to
×
UNCOV
3261
        // disk in order to regain access to this service when restarting `lnd`.
×
3262
        onionCfg := tor.AddOnionConfig{
×
3263
                VirtualPort: defaultPeerPort,
×
3264
                TargetPorts: listenPorts,
3265
                Store: tor.NewOnionFile(
×
3266
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3267
                        encrypter,
×
3268
                ),
×
3269
        }
3270

3271
        switch {
3272
        case s.cfg.Tor.V2:
3273
                onionCfg.Type = tor.V2
×
3274
        case s.cfg.Tor.V3:
×
3275
                onionCfg.Type = tor.V3
×
UNCOV
3276
        }
×
UNCOV
3277

×
3278
        addr, err := s.torController.AddOnion(onionCfg)
×
3279
        if err != nil {
×
3280
                return err
×
3281
        }
×
UNCOV
3282

×
UNCOV
3283
        // Now that the onion service has been created, we'll add the onion
×
UNCOV
3284
        // address it can be reached at to our list of advertised addresses.
×
3285
        newNodeAnn, err := s.genNodeAnnouncement(
×
3286
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3287
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
3288
                },
UNCOV
3289
        )
×
3290
        if err != nil {
×
3291
                return fmt.Errorf("unable to generate new node "+
×
3292
                        "announcement: %v", err)
×
3293
        }
3294

3295
        // Finally, we'll update the on-disk version of our announcement so it
UNCOV
3296
        // will eventually propagate to nodes in the network.
×
3297
        selfNode := models.NewV1Node(
×
3298
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
3299
                        Addresses:    newNodeAnn.Addresses,
×
3300
                        Features:     newNodeAnn.Features,
3301
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3302
                        Color:        newNodeAnn.RGBColor,
×
3303
                        Alias:        newNodeAnn.Alias.String(),
×
3304
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3305
                },
3306
        )
3307

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

×
3312
        return nil
×
UNCOV
3313
}
×
UNCOV
3314

×
UNCOV
3315
// findChannel finds a channel given a public key and ChannelID. It is an
×
UNCOV
3316
// optimization that is quicker than seeking for a channel given only the
×
UNCOV
3317
// ChannelID.
×
UNCOV
3318
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
×
UNCOV
3319
        *channeldb.OpenChannel, error) {
×
UNCOV
3320

×
UNCOV
3321
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3322
        if err != nil {
3323
                return nil, err
×
3324
        }
3325

3326
        for _, channel := range nodeChans {
3327
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
3328
                        return channel, nil
3329
                }
3330
        }
3✔
3331

3✔
3332
        return nil, fmt.Errorf("unable to find channel")
3✔
3333
}
3✔
UNCOV
3334

×
UNCOV
3335
// getNodeAnnouncement fetches the current, fully signed node announcement.
×
3336
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
3337
        s.mu.Lock()
6✔
3338
        defer s.mu.Unlock()
6✔
3339

3✔
3340
        return *s.currentNodeAnn
3✔
3341
}
3342

3343
// genNodeAnnouncement generates and returns the current fully signed node
3✔
3344
// announcement. The time stamp of the announcement will be updated in order
3345
// to ensure it propagates through the network.
3346
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3347
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
3✔
3348

3✔
3349
        s.mu.Lock()
3✔
3350
        defer s.mu.Unlock()
3✔
3351

3✔
3352
        // Create a shallow copy of the current node announcement to work on.
3✔
3353
        // This ensures the original announcement remains unchanged
3354
        // until the new announcement is fully signed and valid.
3355
        newNodeAnn := *s.currentNodeAnn
3356

3357
        // First, try to update our feature manager with the updated set of
3358
        // features.
3✔
3359
        if features != nil {
3✔
3360
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3361
                        feature.SetNodeAnn: features,
3✔
3362
                }
3✔
3363
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3364
                if err != nil {
3✔
3365
                        return lnwire.NodeAnnouncement1{}, err
3✔
3366
                }
3✔
3367

3✔
3368
                // If we could successfully update our feature manager, add
3✔
3369
                // an update modifier to include these new features to our
3✔
3370
                // set.
6✔
3371
                modifiers = append(
3✔
3372
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3373
                )
3✔
3374
        }
3✔
3375

6✔
3376
        // Always update the timestamp when refreshing to ensure the update
3✔
3377
        // propagates.
3✔
3378
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3379

3380
        // Apply the requested changes to the node announcement.
3381
        for _, modifier := range modifiers {
3382
                modifier(&newNodeAnn)
3✔
3383
        }
3✔
3384

3✔
3385
        // Sign a new update after applying all of the passed modifiers.
3386
        err := netann.SignNodeAnnouncement(
3387
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3388
        )
3389
        if err != nil {
3✔
3390
                return lnwire.NodeAnnouncement1{}, err
3✔
3391
        }
3✔
3392

6✔
3393
        // If signing succeeds, update the current announcement.
3✔
3394
        *s.currentNodeAnn = newNodeAnn
3✔
3395

3396
        return *s.currentNodeAnn, nil
3397
}
3✔
3398

3✔
3399
// updateAndBroadcastSelfNode generates a new node announcement
3✔
3400
// applying the giving modifiers and updating the time stamp
3✔
UNCOV
3401
// to ensure it propagates through the network. Then it broadcasts
×
UNCOV
3402
// it to the network.
×
3403
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3404
        features *lnwire.RawFeatureVector,
3405
        modifiers ...netann.NodeAnnModifier) error {
3✔
3406

3✔
3407
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3408
        if err != nil {
3409
                return fmt.Errorf("unable to generate new node "+
3410
                        "announcement: %v", err)
3411
        }
3412

3413
        // Update the on-disk version of our announcement.
3414
        // Load and modify self node istead of creating anew instance so we
3415
        // don't risk overwriting any existing values.
3416
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3417
        if err != nil {
3✔
3418
                return fmt.Errorf("unable to get current source node: %w", err)
3✔
3419
        }
6✔
3420

3✔
3421
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3422
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3423
        selfNode.Alias = fn.Some(newNodeAnn.Alias.String())
3424
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3425
        selfNode.Color = fn.Some(newNodeAnn.RGBColor)
3426
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3427

3✔
3428
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
UNCOV
3429

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

3✔
3434
        // Finally, propagate it to the nodes in the network.
3✔
3435
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3436
        if err != nil {
3✔
3437
                rpcsLog.Debugf("Unable to broadcast new node "+
3✔
3438
                        "announcement to peers: %v", err)
3✔
3439
                return err
3✔
3440
        }
3✔
3441

3✔
UNCOV
3442
        return nil
×
UNCOV
3443
}
×
3444

3445
type nodeAddresses struct {
3446
        pubKey    *btcec.PublicKey
3✔
3447
        addresses []net.Addr
3✔
UNCOV
3448
}
×
UNCOV
3449

×
UNCOV
3450
// establishPersistentConnections attempts to establish persistent connections
×
UNCOV
3451
// to all our direct channel collaborators. In order to promote liveness of our
×
3452
// active channels, we instruct the connection manager to attempt to establish
3453
// and maintain persistent connections to all our direct channel counterparties.
3✔
3454
func (s *server) establishPersistentConnections(ctx context.Context) error {
3455
        // nodeAddrsMap stores the combination of node public keys and addresses
3456
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3457
        // since other PubKey forms can't be compared.
3458
        nodeAddrsMap := make(map[string]*nodeAddresses)
3459

3460
        // Iterate through the list of LinkNodes to find addresses we should
3461
        // attempt to connect to based on our set of previous connections. Set
3462
        // the reconnection port to the default peer port.
3463
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3464
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3465
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
3✔
3466
        }
3✔
3467

3✔
3468
        for _, node := range linkNodes {
3✔
3469
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3470
                nodeAddrs := &nodeAddresses{
3✔
3471
                        pubKey:    node.IdentityPub,
3✔
3472
                        addresses: node.Addresses,
3✔
3473
                }
3✔
3474
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3475
        }
3✔
UNCOV
3476

×
UNCOV
3477
        // After checking our previous connections for addresses to connect to,
×
3478
        // iterate through the nodes in our channel graph to find addresses
3479
        // that have been added via NodeAnnouncement1 messages.
6✔
3480
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3✔
3481
        // each of the nodes.
3✔
3482
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3483
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3484
                havePolicy bool, channelPeer *models.Node) error {
3✔
3485

3✔
3486
                // If the remote party has announced the channel to us, but we
3✔
3487
                // haven't yet, then we won't have a policy. However, we don't
3488
                // need this to connect to the peer, so we'll log it and move on.
3489
                if !havePolicy {
3490
                        srvrLog.Warnf("No channel policy found for "+
3491
                                "ChannelPoint(%v): ", chanPoint)
3492
                }
3493

3✔
3494
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3495

6✔
3496
                // Add all unique addresses from channel
3✔
3497
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3498
                // connect to for this peer.
3✔
3499
                addrSet := make(map[string]net.Addr)
3✔
3500
                for _, addr := range channelPeer.Addresses {
3✔
UNCOV
3501
                        switch addr.(type) {
×
UNCOV
3502
                        case *net.TCPAddr:
×
UNCOV
3503
                                addrSet[addr.String()] = addr
×
3504

3505
                        // We'll only attempt to connect to Tor addresses if Tor
3✔
3506
                        // outbound support is enabled.
3✔
3507
                        case *tor.OnionAddr:
3✔
3508
                                if s.cfg.Tor.Active {
3✔
3509
                                        addrSet[addr.String()] = addr
3✔
3510
                                }
3✔
3511
                        }
6✔
3512
                }
3✔
3513

3✔
3514
                // If this peer is also recorded as a link node, we'll add any
3✔
3515
                // additional addresses that have not already been selected.
3516
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3517
                if ok {
UNCOV
3518
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3519
                                switch lnAddress.(type) {
×
UNCOV
3520
                                case *net.TCPAddr:
×
UNCOV
3521
                                        addrSet[lnAddress.String()] = lnAddress
×
3522

3523
                                // We'll only attempt to connect to Tor
3524
                                // addresses if Tor outbound support is enabled.
3525
                                case *tor.OnionAddr:
3526
                                        if s.cfg.Tor.Active {
3527
                                                //nolint:ll
3✔
3528
                                                addrSet[lnAddress.String()] = lnAddress
6✔
3529
                                        }
6✔
3530
                                }
3✔
3531
                        }
3✔
3532
                }
3✔
3533

3534
                // Construct a slice of the deduped addresses.
3535
                var addrs []net.Addr
UNCOV
3536
                for _, addr := range addrSet {
×
UNCOV
3537
                        addrs = append(addrs, addr)
×
UNCOV
3538
                }
×
UNCOV
3539

×
UNCOV
3540
                n := &nodeAddresses{
×
3541
                        addresses: addrs,
3542
                }
3543
                n.pubKey, err = channelPeer.PubKey()
3544
                if err != nil {
3545
                        return err
3546
                }
3✔
3547

6✔
3548
                graphAddrs[pubStr] = n
3✔
3549
                return nil
3✔
3550
        }
3551
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3552
                ctx, forEachSrcNodeChan, func() {
3✔
3553
                        clear(graphAddrs)
3✔
3554
                },
3✔
3555
        )
3✔
UNCOV
3556
        if err != nil {
×
3557
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3558
                        "%v", err)
3559

3✔
3560
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
3✔
3561
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
3562

3✔
3563
                        return err
6✔
3564
                }
3✔
3565
        }
3✔
3566

3567
        // Combine the addresses from the link nodes and the channel graph.
3✔
UNCOV
3568
        for pubStr, nodeAddr := range graphAddrs {
×
UNCOV
3569
                nodeAddrsMap[pubStr] = nodeAddr
×
UNCOV
3570
        }
×
UNCOV
3571

×
UNCOV
3572
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3573
                len(nodeAddrsMap))
×
UNCOV
3574

×
UNCOV
3575
        // Acquire and hold server lock until all persistent connection requests
×
3576
        // have been recorded and sent to the connection manager.
3577
        s.mu.Lock()
3578
        defer s.mu.Unlock()
3579

6✔
3580
        // Iterate through the combined list of addresses from prior links and
3✔
3581
        // node announcements and attempt to reconnect to each node.
3✔
3582
        var numOutboundConns int
3583
        for pubStr, nodeAddr := range nodeAddrsMap {
3✔
3584
                // Add this peer to the set of peers we should maintain a
3✔
3585
                // persistent connection with. We set the value to false to
3✔
3586
                // indicate that we should not continue to reconnect if the
3✔
3587
                // number of channels returns to zero, since this peer has not
3✔
3588
                // been requested as perm by the user.
3✔
3589
                s.persistentPeers[pubStr] = false
3✔
3590
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
3✔
3591
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3592
                }
3✔
3593

3✔
3594
                for _, address := range nodeAddr.addresses {
6✔
3595
                        // Create a wrapper address which couples the IP and
3✔
3596
                        // the pubkey so the brontide authenticated connection
3✔
3597
                        // can be established.
3✔
3598
                        lnAddr := &lnwire.NetAddress{
3✔
3599
                                IdentityKey: nodeAddr.pubKey,
3✔
3600
                                Address:     address,
3✔
3601
                        }
6✔
3602

3✔
3603
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3604
                                s.persistentPeerAddrs[pubStr], lnAddr)
3605
                }
6✔
3606

3✔
3607
                // We'll connect to the first 10 peers immediately, then
3✔
3608
                // randomly stagger any remaining connections if the
3✔
3609
                // stagger initial reconnect flag is set. This ensures
3✔
3610
                // that mobile nodes or nodes with a small number of
3✔
3611
                // channels obtain connectivity quickly, but larger
3✔
3612
                // nodes are able to disperse the costs of connecting to
3✔
3613
                // all peers at once.
3✔
3614
                if numOutboundConns < numInstantInitReconnect ||
3✔
3615
                        !s.cfg.StaggerInitialReconnect {
3✔
3616

3✔
3617
                        go s.connectToPersistentPeer(pubStr)
3618
                } else {
3619
                        go s.delayInitialReconnect(pubStr)
3620
                }
3621

3622
                numOutboundConns++
3623
        }
3624

3625
        return nil
3✔
3626
}
6✔
3627

3✔
3628
// delayInitialReconnect will attempt a reconnection to the given peer after
3✔
3629
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3✔
UNCOV
3630
//
×
UNCOV
3631
// NOTE: This method MUST be run as a goroutine.
×
3632
func (s *server) delayInitialReconnect(pubStr string) {
3633
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
3✔
3634
        select {
3635
        case <-time.After(delay):
3636
                s.connectToPersistentPeer(pubStr)
3✔
3637
        case <-s.quit:
3638
        }
3639
}
3640

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

×
UNCOV
3647
        s.mu.Lock()
×
UNCOV
3648
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3649
                delete(s.persistentPeers, pubKeyStr)
3650
                delete(s.persistentPeersBackoff, pubKeyStr)
3651
                delete(s.persistentPeerAddrs, pubKeyStr)
3652
                s.cancelConnReqs(pubKeyStr, nil)
3653
                s.mu.Unlock()
3654

3655
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3656
                        "peer has no open channels", compressedPubKey)
3✔
3657

3✔
3658
                return
3✔
3659
        }
6✔
3660
        s.mu.Unlock()
3✔
3661
}
3✔
3662

3✔
3663
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3✔
3664
// is instead used to remove persistent peer state for a peer that has been
3✔
3665
// disconnected for good cause by the server. Currently, a gossip ban from
3✔
3666
// sending garbage and the server running out of restricted-access
3✔
3667
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3✔
3668
// future, this function may expand when more ban criteria is added.
3✔
3669
//
3✔
3670
// NOTE: The server's write lock MUST be held when this is called.
3✔
3671
func (s *server) bannedPersistentPeerConnection(remotePub string) {
3✔
3672
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
3673
                delete(s.persistentPeers, remotePub)
3674
                delete(s.persistentPeersBackoff, remotePub)
3675
                delete(s.persistentPeerAddrs, remotePub)
3676
                s.cancelConnReqs(remotePub, nil)
3677
        }
3678
}
3679

3680
// BroadcastMessage sends a request to the server to broadcast a set of
3681
// messages to all peers other than the one specified by the `skips` parameter.
UNCOV
3682
// All messages sent via BroadcastMessage will be queued for lazy delivery to
×
UNCOV
3683
// the target peers.
×
UNCOV
3684
//
×
UNCOV
3685
// NOTE: This function is safe for concurrent access.
×
UNCOV
3686
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
×
UNCOV
3687
        msgs ...lnwire.Message) error {
×
UNCOV
3688

×
3689
        // Filter out peers found in the skips map. We synchronize access to
3690
        // peersByPub throughout this process to ensure we deliver messages to
3691
        // exact set of peers present at the time of invocation.
3692
        s.mu.RLock()
3693
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3694
        for pubStr, sPeer := range s.peersByPub {
3695
                if skips != nil {
3696
                        if _, ok := skips[sPeer.PubKey()]; ok {
3697
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3698
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3699
                                continue
3✔
3700
                        }
3✔
3701
                }
3✔
3702

3✔
3703
                peers = append(peers, sPeer)
3✔
3704
        }
3✔
3705
        s.mu.RUnlock()
6✔
3706

6✔
3707
        // Iterate over all known peers, dispatching a go routine to enqueue
6✔
3708
        // all messages to each of peers.
3✔
3709
        var wg sync.WaitGroup
3✔
3710
        for _, sPeer := range peers {
3✔
3711
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3712
                        sPeer.PubKey())
3713

3714
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3715
                wg.Add(1)
3716
                s.wg.Add(1)
3✔
3717
                go func(p lnpeer.Peer) {
3✔
3718
                        defer s.wg.Done()
3✔
3719
                        defer wg.Done()
3✔
3720

3✔
3721
                        p.SendMessageLazy(false, msgs...)
6✔
3722
                }(sPeer)
3✔
3723
        }
3✔
3724

3✔
3725
        // Wait for all messages to have been dispatched before returning to
3✔
3726
        // caller.
3✔
3727
        wg.Wait()
3✔
3728

6✔
3729
        return nil
3✔
3730
}
3✔
3731

3✔
3732
// NotifyWhenOnline can be called by other subsystems to get notified when a
3✔
3733
// particular peer comes online. The peer itself is sent across the peerChan.
3✔
3734
//
3735
// NOTE: This function is safe for concurrent access.
3736
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3737
        peerChan chan<- lnpeer.Peer) {
3738

3✔
3739
        s.mu.Lock()
3✔
3740

3✔
3741
        // Compute the target peer's identifier.
3742
        pubStr := string(peerKey[:])
3743

3744
        // Check if peer is connected.
3745
        peer, ok := s.peersByPub[pubStr]
3746
        if ok {
3747
                // Unlock here so that the mutex isn't held while we are
3748
                // waiting for the peer to become active.
3✔
3749
                s.mu.Unlock()
3✔
3750

3✔
3751
                // Wait until the peer signals that it is actually active
3✔
3752
                // rather than only in the server's maps.
3✔
3753
                select {
3✔
3754
                case <-peer.ActiveSignal():
3✔
3755
                case <-peer.QuitSignal():
3✔
3756
                        // The peer quit, so we'll add the channel to the slice
3✔
3757
                        // and return.
6✔
3758
                        s.mu.Lock()
3✔
3759
                        s.peerConnectedListeners[pubStr] = append(
3✔
3760
                                s.peerConnectedListeners[pubStr], peerChan,
3✔
3761
                        )
3✔
3762
                        s.mu.Unlock()
3✔
3763
                        return
3✔
3764
                }
3✔
3765

3✔
UNCOV
3766
                // Connected, can return early.
×
UNCOV
3767
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3768

×
UNCOV
3769
                select {
×
UNCOV
3770
                case peerChan <- peer:
×
3771
                case <-s.quit:
×
UNCOV
3772
                }
×
UNCOV
3773

×
UNCOV
3774
                return
×
3775
        }
3776

3777
        // Not connected, store this listener such that it can be notified when
3778
        // the peer comes online.
3✔
3779
        s.peerConnectedListeners[pubStr] = append(
3✔
3780
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3781
        )
3✔
UNCOV
3782
        s.mu.Unlock()
×
3783
}
3784

3785
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3✔
3786
// the given public key has been disconnected. The notification is signaled by
3787
// closing the channel returned.
3788
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3789
        s.mu.Lock()
3790
        defer s.mu.Unlock()
3✔
3791

3✔
3792
        c := make(chan struct{})
3✔
3793

3✔
3794
        // If the peer is already offline, we can immediately trigger the
3795
        // notification.
3796
        peerPubKeyStr := string(peerPubKey[:])
3797
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3798
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
3799
                close(c)
3✔
3800
                return c
3✔
3801
        }
3✔
3802

3✔
3803
        // Otherwise, the peer is online, so we'll keep track of the channel to
3✔
3804
        // trigger the notification once the server detects the peer
3✔
3805
        // disconnects.
3✔
3806
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3807
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3808
        )
3✔
UNCOV
3809

×
UNCOV
3810
        return c
×
UNCOV
3811
}
×
UNCOV
3812

×
3813
// FindPeer will return the peer that corresponds to the passed in public key.
3814
// This function is used by the funding manager, allowing it to update the
3815
// daemon's local representation of the remote peer.
3816
//
3817
// NOTE: This function is safe for concurrent access.
3✔
3818
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3819
        s.mu.RLock()
3✔
3820
        defer s.mu.RUnlock()
3✔
3821

3✔
3822
        pubStr := string(peerKey.SerializeCompressed())
3823

3824
        return s.findPeerByPubStr(pubStr)
3825
}
3826

3827
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3828
// which should be a string representation of the peer's serialized, compressed
3829
// public key.
3✔
3830
//
3✔
3831
// NOTE: This function is safe for concurrent access.
3✔
3832
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3833
        s.mu.RLock()
3✔
3834
        defer s.mu.RUnlock()
3✔
3835

3✔
3836
        return s.findPeerByPubStr(pubStr)
3✔
3837
}
3838

3839
// findPeerByPubStr is an internal method that retrieves the specified peer from
3840
// the server's internal state using.
3841
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3842
        peer, ok := s.peersByPub[pubStr]
3843
        if !ok {
3✔
3844
                return nil, ErrPeerNotConnected
3✔
3845
        }
3✔
3846

3✔
3847
        return peer, nil
3✔
3848
}
3✔
3849

3850
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3851
// exponential backoff. If no previous backoff was known, the default is
3852
// returned.
3✔
3853
func (s *server) nextPeerBackoff(pubStr string,
3✔
3854
        startTime time.Time) time.Duration {
6✔
3855

3✔
3856
        // Now, determine the appropriate backoff to use for the retry.
3✔
3857
        backoff, ok := s.persistentPeersBackoff[pubStr]
3858
        if !ok {
3✔
3859
                // If an existing backoff was unknown, use the default.
3860
                return s.cfg.MinBackoff
3861
        }
3862

3863
        // If the peer failed to start properly, we'll just use the previous
3864
        // backoff to compute the subsequent randomized exponential backoff
3865
        // duration. This will roughly double on average.
3✔
3866
        if startTime.IsZero() {
3✔
3867
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3868
        }
3✔
3869

6✔
3870
        // The peer succeeded in starting. If the connection didn't last long
3✔
3871
        // enough to be considered stable, we'll continue to back off retries
3✔
3872
        // with this peer.
3✔
3873
        connDuration := time.Since(startTime)
3874
        if connDuration < defaultStableConnDuration {
3875
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3876
        }
3877

3✔
UNCOV
3878
        // The peer succeed in starting and this was stable peer, so we'll
×
UNCOV
3879
        // reduce the timeout duration by the length of the connection after
×
3880
        // applying randomized exponential backoff. We'll only apply this in the
3881
        // case that:
3882
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3883
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
3884
        if relaxedBackoff > s.cfg.MinBackoff {
3✔
3885
                return relaxedBackoff
6✔
3886
        }
3✔
3887

3✔
3888
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3889
        // the stable connection lasted much longer than our previous backoff.
3890
        // To reward such good behavior, we'll reconnect after the default
3891
        // timeout.
3892
        return s.cfg.MinBackoff
3893
}
UNCOV
3894

×
UNCOV
3895
// shouldDropLocalConnection determines if our local connection to a remote peer
×
UNCOV
3896
// should be dropped in the case of concurrent connection establishment. In
×
UNCOV
3897
// order to deterministically decide which connection should be dropped, we'll
×
3898
// utilize the ordering of the local and remote public key. If we didn't use
3899
// such a tie breaker, then we risk _both_ connections erroneously being
3900
// dropped.
3901
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
3902
        localPubBytes := local.SerializeCompressed()
3903
        remotePubPbytes := remote.SerializeCompressed()
×
3904

3905
        // The connection that comes from the node with a "smaller" pubkey
3906
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
3907
        // should drop our established connection.
3908
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
3909
}
3910

3911
// InboundPeerConnected initializes a new peer in response to a new inbound
UNCOV
3912
// connection.
×
UNCOV
3913
//
×
UNCOV
3914
// NOTE: This function is safe for concurrent access.
×
UNCOV
3915
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
3916
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3917
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3918
        if s.Stopped() {
×
3919
                return
×
3920
        }
×
3921

3922
        nodePub := conn.(*brontide.Conn).RemotePub()
3923
        pubSer := nodePub.SerializeCompressed()
3924
        pubStr := string(pubSer)
3925

3926
        var pubBytes [33]byte
3✔
3927
        copy(pubBytes[:], pubSer)
3✔
3928

3✔
3929
        s.mu.Lock()
3✔
UNCOV
3930
        defer s.mu.Unlock()
×
UNCOV
3931

×
3932
        // If we already have an outbound connection to this peer, then ignore
3933
        // this new connection.
3✔
3934
        if p, ok := s.outboundPeers[pubStr]; ok {
3✔
3935
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3936
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3937
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3938

3✔
3939
                conn.Close()
3✔
3940
                return
3✔
3941
        }
3✔
3942

3✔
3943
        // If we already have a valid connection that is scheduled to take
3✔
3944
        // precedence once the prior peer has finished disconnecting, we'll
3✔
3945
        // ignore this connection.
6✔
3946
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3947
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
3✔
3948
                        "scheduled", conn.RemoteAddr(), p)
3✔
3949
                conn.Close()
3✔
3950
                return
3✔
3951
        }
3✔
3952

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

3955
        // Check to see if we already have a connection with this peer. If so,
3956
        // we may need to drop our existing connection. This prevents us from
3957
        // having duplicate connections to the same peer. We forgo adding a
3✔
UNCOV
3958
        // default case as we expect these to be the only error values returned
×
UNCOV
3959
        // from findPeerByPubStr.
×
UNCOV
3960
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3961
        switch err {
×
UNCOV
3962
        case ErrPeerNotConnected:
×
3963
                // We were unable to locate an existing connection with the
3964
                // target peer, proceed to connect.
3✔
3965
                s.cancelConnReqs(pubStr, nil)
3✔
3966
                s.peerConnected(conn, nil, true)
3✔
3967

3✔
3968
        case nil:
3✔
3969
                ctx := btclog.WithCtx(
3✔
3970
                        context.TODO(),
3✔
3971
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
3972
                )
3✔
3973

3✔
3974
                // We already have a connection with the incoming peer. If the
3✔
3975
                // connection we've already established should be kept and is
3✔
3976
                // not of the same type of the new connection (inbound), then
3✔
3977
                // we'll close out the new connection s.t there's only a single
3✔
3978
                // connection between us.
3979
                localPub := s.identityECDH.PubKey()
3✔
3980
                if !connectedPeer.Inbound() &&
3✔
3981
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
3982

3✔
3983
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
3✔
3984
                                "peer, but already have outbound "+
3✔
3985
                                "connection, dropping conn",
3✔
3986
                                fmt.Errorf("already have outbound conn"))
3✔
3987
                        conn.Close()
3✔
3988
                        return
3✔
3989
                }
3✔
3990

3✔
3991
                // Otherwise, if we should drop the connection, then we'll
3✔
3992
                // disconnect our already connected peer.
3✔
UNCOV
3993
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
3994

×
UNCOV
3995
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3996

×
UNCOV
3997
                // Remove the current peer from the server's internal state and
×
UNCOV
3998
                // signal that the peer termination watcher does not need to
×
UNCOV
3999
                // execute for this peer.
×
UNCOV
4000
                s.removePeerUnsafe(ctx, connectedPeer)
×
4001
                s.ignorePeerTermination[connectedPeer] = struct{}{}
4002
                s.scheduledPeerConnection[pubStr] = func() {
4003
                        s.peerConnected(conn, nil, true)
4004
                }
3✔
4005
        }
3✔
4006
}
3✔
4007

3✔
4008
// OutboundPeerConnected initializes a new peer in response to a new outbound
3✔
4009
// connection.
3✔
4010
// NOTE: This function is safe for concurrent access.
3✔
4011
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4012
        // Exit early if we have already been instructed to shutdown, this
3✔
4013
        // prevents any delayed callbacks from accidentally registering peers.
6✔
4014
        if s.Stopped() {
3✔
4015
                return
3✔
4016
        }
4017

4018
        nodePub := conn.(*brontide.Conn).RemotePub()
4019
        pubSer := nodePub.SerializeCompressed()
4020
        pubStr := string(pubSer)
4021

4022
        var pubBytes [33]byte
3✔
4023
        copy(pubBytes[:], pubSer)
3✔
4024

3✔
4025
        s.mu.Lock()
3✔
UNCOV
4026
        defer s.mu.Unlock()
×
UNCOV
4027

×
4028
        // If we already have an inbound connection to this peer, then ignore
4029
        // this new connection.
3✔
4030
        if p, ok := s.inboundPeers[pubStr]; ok {
3✔
4031
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4032
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4033
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4034

3✔
4035
                if connReq != nil {
3✔
4036
                        s.connMgr.Remove(connReq.ID())
3✔
4037
                }
3✔
4038
                conn.Close()
3✔
4039
                return
3✔
4040
        }
3✔
4041
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
6✔
4042
                srvrLog.Debugf("Ignoring canceled outbound connection")
3✔
4043
                s.connMgr.Remove(connReq.ID())
3✔
4044
                conn.Close()
3✔
4045
                return
3✔
4046
        }
6✔
4047

3✔
4048
        // If we already have a valid connection that is scheduled to take
3✔
4049
        // precedence once the prior peer has finished disconnecting, we'll
3✔
4050
        // ignore this connection.
3✔
4051
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
4052
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
3✔
4053

×
4054
                if connReq != nil {
×
4055
                        s.connMgr.Remove(connReq.ID())
×
4056
                }
×
UNCOV
4057

×
4058
                conn.Close()
4059
                return
4060
        }
4061

4062
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
UNCOV
4063
                conn.RemoteAddr())
×
UNCOV
4064

×
UNCOV
4065
        if connReq != nil {
×
UNCOV
4066
                // A successful connection was returned by the connmgr.
×
UNCOV
4067
                // Immediately cancel all pending requests, excluding the
×
4068
                // outbound connection we just established.
UNCOV
4069
                ignore := connReq.ID()
×
UNCOV
4070
                s.cancelConnReqs(pubStr, &ignore)
×
4071
        } else {
4072
                // This was a successful connection made by some other
4073
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4074
                s.cancelConnReqs(pubStr, nil)
3✔
4075
        }
3✔
4076

6✔
4077
        // If we already have a connection with this peer, decide whether or not
3✔
4078
        // we need to drop the stale connection. We forgo adding a default case
3✔
4079
        // as we expect these to be the only error values returned from
3✔
4080
        // findPeerByPubStr.
3✔
4081
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4082
        switch err {
6✔
4083
        case ErrPeerNotConnected:
3✔
4084
                // We were unable to locate an existing connection with the
3✔
4085
                // target peer, proceed to connect.
3✔
4086
                s.peerConnected(conn, connReq, false)
3✔
4087

4088
        case nil:
4089
                ctx := btclog.WithCtx(
4090
                        context.TODO(),
4091
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
4092
                )
3✔
4093

3✔
4094
                // We already have a connection with the incoming peer. If the
3✔
4095
                // connection we've already established should be kept and is
3✔
4096
                // not of the same type of the new connection (outbound), then
3✔
4097
                // we'll close out the new connection s.t there's only a single
3✔
4098
                // connection between us.
4099
                localPub := s.identityECDH.PubKey()
3✔
4100
                if connectedPeer.Inbound() &&
3✔
4101
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4102

3✔
4103
                        srvrLog.WarnS(ctx, "Established outbound connection "+
3✔
4104
                                "to peer, but already have inbound "+
3✔
4105
                                "connection, dropping conn",
3✔
4106
                                fmt.Errorf("already have inbound conn"))
3✔
4107
                        if connReq != nil {
3✔
4108
                                s.connMgr.Remove(connReq.ID())
3✔
4109
                        }
3✔
4110
                        conn.Close()
3✔
4111
                        return
3✔
4112
                }
3✔
UNCOV
4113

×
UNCOV
4114
                // Otherwise, _their_ connection should be dropped. So we'll
×
UNCOV
4115
                // disconnect the peer and send the now obsolete peer to the
×
UNCOV
4116
                // server for garbage collection.
×
UNCOV
4117
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
4118

×
UNCOV
4119
                // Remove the current peer from the server's internal state and
×
UNCOV
4120
                // signal that the peer termination watcher does not need to
×
UNCOV
4121
                // execute for this peer.
×
UNCOV
4122
                s.removePeerUnsafe(ctx, connectedPeer)
×
4123
                s.ignorePeerTermination[connectedPeer] = struct{}{}
4124
                s.scheduledPeerConnection[pubStr] = func() {
4125
                        s.peerConnected(conn, connReq, false)
4126
                }
4127
        }
4128
}
3✔
4129

3✔
4130
// UnassignedConnID is the default connection ID that a request can have before
3✔
4131
// it actually is submitted to the connmgr.
3✔
4132
// TODO(conner): move into connmgr package, or better, add connmgr method for
3✔
4133
// generating atomic IDs
3✔
4134
const UnassignedConnID uint64 = 0
3✔
4135

6✔
4136
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3✔
4137
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3✔
4138
// Afterwards, each connection request removed from the connmgr. The caller can
4139
// optionally specify a connection ID to ignore, which prevents us from
4140
// canceling a successful request. All persistent connreqs for the provided
4141
// pubkey are discarded after the operationjw.
4142
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
4143
        // First, cancel any lingering persistent retry attempts, which will
4144
        // prevent retries for any with backoffs that are still maturing.
4145
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
4146
                close(cancelChan)
4147
                delete(s.persistentRetryCancels, pubStr)
4148
        }
4149

4150
        // Next, check to see if we have any outstanding persistent connection
4151
        // requests to this peer. If so, then we'll remove all of these
4152
        // connection requests, and also delete the entry from the map.
4153
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4154
        if !ok {
3✔
4155
                return
3✔
4156
        }
6✔
4157

3✔
4158
        for _, connReq := range connReqs {
3✔
4159
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4160

4161
                // Atomically capture the current request identifier.
4162
                connID := connReq.ID()
4163

4164
                // Skip any zero IDs, this indicates the request has not
3✔
4165
                // yet been schedule.
6✔
4166
                if connID == UnassignedConnID {
3✔
4167
                        continue
3✔
4168
                }
4169

6✔
4170
                // Skip a particular connection ID if instructed.
3✔
4171
                if skip != nil && connID == *skip {
3✔
4172
                        continue
3✔
4173
                }
3✔
4174

3✔
4175
                s.connMgr.Remove(connID)
3✔
4176
        }
3✔
4177

5✔
4178
        delete(s.persistentConnReqs, pubStr)
2✔
4179
}
4180

4181
// handleCustomMessage dispatches an incoming custom peers message to
4182
// subscribers.
6✔
4183
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4184
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
4185
                peer, msg.Type)
4186

3✔
4187
        return s.customMessageServer.SendUpdate(&CustomMessage{
4188
                Peer: peer,
4189
                Msg:  msg,
3✔
4190
        })
4191
}
4192

4193
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4194
// messages.
3✔
4195
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4196
        return s.customMessageServer.Subscribe()
3✔
4197
}
3✔
4198

3✔
4199
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
3✔
4200
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4201
        return s.onionMessageServer.Subscribe()
3✔
4202
}
3✔
4203

4204
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4205
// the channelNotifier's NotifyOpenChannelEvent.
4206
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
3✔
4207
        remotePub *btcec.PublicKey) {
3✔
4208

3✔
4209
        // Call newOpenChan to update the access manager's maps for this peer.
4210
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
4211
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
3✔
4212
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
3✔
4213
        }
3✔
4214

4215
        // Notify subscribers about this open channel event.
4216
        s.channelNotifier.NotifyOpenChannelEvent(op)
4217
}
4218

3✔
4219
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
3✔
4220
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
3✔
4221
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
6✔
4222
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4223

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

4232
        // Notify subscribers about this event.
4233
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4234
}
3✔
4235

3✔
4236
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
3✔
4237
// calls the channelNotifier's NotifyFundingTimeout.
3✔
UNCOV
4238
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
×
UNCOV
4239
        remotePub *btcec.PublicKey) {
×
UNCOV
4240

×
UNCOV
4241
        // Call newPendingCloseChan to potentially demote the peer.
×
4242
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
4243
        if err != nil {
4244
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
3✔
4245
                        "channel[%v] pending close",
4246
                        remotePub.SerializeCompressed(), op)
4247
        }
4248

4249
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
4250
                // If we encounter an error while attempting to disconnect the
3✔
4251
                // peer, log the error.
3✔
4252
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
3✔
4253
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
3✔
4254
                }
3✔
UNCOV
4255
        }
×
UNCOV
4256

×
UNCOV
4257
        // Notify subscribers about this event.
×
UNCOV
4258
        s.channelNotifier.NotifyFundingTimeout(op)
×
4259
}
4260

3✔
UNCOV
4261
// peerConnected is a function that handles initialization a newly connected
×
UNCOV
4262
// peer by adding it to the server's global list of all active peers, and
×
UNCOV
4263
// starting all the goroutines the peer needs to function properly. The inbound
×
UNCOV
4264
// boolean should be true if the peer initiated the connection to us.
×
UNCOV
4265
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
×
4266
        inbound bool) {
4267

4268
        brontideConn := conn.(*brontide.Conn)
4269
        addr := conn.RemoteAddr()
3✔
4270
        pubKey := brontideConn.RemotePub()
4271

4272
        // Only restrict access for inbound connections, which means if the
4273
        // remote node's public key is banned or the restricted slots are used
4274
        // up, we will drop the connection.
4275
        //
4276
        // TODO(yy): Consider perform this check in
4277
        // `peerAccessMan.addPeerAccess`.
3✔
4278
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4279
        if inbound && err != nil {
3✔
4280
                pubSer := pubKey.SerializeCompressed()
3✔
4281

3✔
4282
                // Clean up the persistent peer maps if we're dropping this
3✔
4283
                // connection.
3✔
4284
                s.bannedPersistentPeerConnection(string(pubSer))
3✔
4285

3✔
4286
                srvrLog.Debugf("Dropping connection for %x since we are out "+
3✔
4287
                        "of restricted-access connection slots: %v.", pubSer,
3✔
4288
                        err)
3✔
4289

3✔
4290
                conn.Close()
3✔
4291

×
4292
                return
×
4293
        }
×
UNCOV
4294

×
UNCOV
4295
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4296
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4297

×
UNCOV
4298
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4299
                IdentityKey: pubKey,
×
UNCOV
4300
                Address:     addr,
×
UNCOV
4301
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4302
        }
×
UNCOV
4303

×
UNCOV
4304
        // With the brontide connection established, we'll now craft the feature
×
4305
        // vectors to advertise to the remote node.
4306
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4307
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4308

3✔
4309
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4310
        // found, create a fresh buffer.
3✔
4311
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4312
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4313
        if !ok {
3✔
4314
                var err error
3✔
4315
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4316
                if err != nil {
3✔
4317
                        srvrLog.Errorf("unable to create peer %v", err)
3✔
4318
                        return
3✔
4319
                }
3✔
4320
        }
3✔
4321

3✔
4322
        // If we directly set the peer.Config TowerClient member to the
3✔
4323
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
3✔
4324
        // the peer.Config's TowerClient member will not evaluate to nil even
6✔
4325
        // though the underlying value is nil. To avoid this gotcha which can
3✔
4326
        // cause a panic, we need to explicitly pass nil to the peer.Config's
3✔
4327
        // TowerClient if needed.
3✔
UNCOV
4328
        var towerClient wtclient.ClientManager
×
UNCOV
4329
        if s.towerClientMgr != nil {
×
UNCOV
4330
                towerClient = s.towerClientMgr
×
4331
        }
4332

4333
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4334
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4335

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

3✔
4380
                        return s.genNodeAnnouncement(nil)
3✔
4381
                },
3✔
4382

3✔
4383
                PongBuf: s.pongBuf,
3✔
4384

3✔
4385
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
3✔
4386

3✔
4387
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
3✔
4388

3✔
4389
                FundingManager: s.fundingMgr,
6✔
4390

3✔
4391
                Hodl:                    s.cfg.Hodl,
3✔
4392
                UnsafeReplay:            s.cfg.UnsafeReplay,
3✔
4393
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4394
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4395
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4396
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4397
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4398
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4399
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4400
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4401
                HandleCustomMessage:    s.handleCustomMessage,
4402
                GetAliases:             s.aliasMgr.GetAliases,
4403
                RequestAlias:           s.aliasMgr.RequestAlias,
4404
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4405
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4406
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4407
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4408
                MaxFeeExposure:         thresholdMSats,
4409
                Quit:                   s.quit,
4410
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4411
                AuxSigner:              s.implCfg.AuxSigner,
4412
                MsgRouter:              s.implCfg.MsgRouter,
4413
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4414
                AuxResolver:            s.implCfg.AuxContractResolver,
4415
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4416
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4417
                ShouldFwdExpAccountability: func() bool {
4418
                        return !s.cfg.ProtocolOptions.NoExperimentalAccountability()
4419
                },
4420
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4421
        }
4422

4423
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4424
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4425

4426
        p := peer.NewBrontide(pCfg)
4427

4428
        // Update the access manager with the access permission for this peer.
3✔
4429
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4430

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

4434
        s.addPeer(p)
3✔
4435

3✔
4436
        // Once we have successfully added the peer to the server, we can
3✔
4437
        // delete the previous error buffer from the server's map of error
3✔
4438
        // buffers.
3✔
4439
        delete(s.peerErrors, pkStr)
3✔
4440

3✔
4441
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4442
        // includes sending and receiving Init messages, which would be a DOS
3✔
4443
        // vector if we held the server's mutex throughout the procedure.
3✔
4444
        s.wg.Add(1)
3✔
4445
        go s.peerInitializer(p)
3✔
4446
}
3✔
4447

3✔
4448
// addPeer adds the passed peer to the server's global state of all active
3✔
4449
// peers.
3✔
4450
func (s *server) addPeer(p *peer.Brontide) {
3✔
4451
        if p == nil {
3✔
4452
                return
3✔
4453
        }
3✔
4454

3✔
4455
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4456

3✔
4457
        // Ignore new peers if we're shutting down.
4458
        if s.Stopped() {
4459
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
4460
                        pubBytes)
4461
                p.Disconnect(ErrServerShuttingDown)
3✔
4462

3✔
4463
                return
×
4464
        }
×
4465

4466
        // Track the new peer in our indexes so we can quickly look it up either
3✔
4467
        // according to its public key, or its peer ID.
3✔
4468
        // TODO(roasbeef): pipe all requests through to the
3✔
4469
        // queryHandler/peerManager
3✔
UNCOV
4470

×
UNCOV
4471
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
×
UNCOV
4472
        // be human-readable.
×
UNCOV
4473
        pubStr := string(pubBytes)
×
UNCOV
4474

×
UNCOV
4475
        s.peersByPub[pubStr] = p
×
4476

4477
        if p.Inbound() {
4478
                s.inboundPeers[pubStr] = p
4479
        } else {
4480
                s.outboundPeers[pubStr] = p
4481
        }
4482

4483
        // Inform the peer notifier of a peer online event so that it can be reported
4484
        // to clients listening for peer events.
3✔
4485
        var pubKey [33]byte
3✔
4486
        copy(pubKey[:], pubBytes)
3✔
4487
}
3✔
4488

6✔
4489
// peerInitializer asynchronously starts a newly connected peer after it has
3✔
4490
// been added to the server's peer map. This method sets up a
6✔
4491
// peerTerminationWatcher for the given peer, and ensures that it executes even
3✔
4492
// if the peer failed to start. In the event of a successful connection, this
3✔
4493
// method reads the negotiated, local feature-bits and spawns the appropriate
4494
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4495
// be signaled of the new peer once the method returns.
4496
//
3✔
4497
// NOTE: This MUST be launched as a goroutine.
3✔
4498
func (s *server) peerInitializer(p *peer.Brontide) {
4499
        defer s.wg.Done()
4500

4501
        pubBytes := p.IdentityKey().SerializeCompressed()
4502

4503
        // Avoid initializing peers while the server is exiting.
4504
        if s.Stopped() {
4505
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
4506
                        pubBytes)
4507
                return
4508
        }
4509

3✔
4510
        // Create a channel that will be used to signal a successful start of
3✔
4511
        // the link. This prevents the peer termination watcher from beginning
3✔
4512
        // its duty too early.
3✔
4513
        ready := make(chan struct{})
3✔
4514

3✔
4515
        // Before starting the peer, launch a goroutine to watch for the
3✔
UNCOV
4516
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4517
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4518
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4519
        // the peer is ever added to the ignorePeerTermination map, indicating
×
4520
        // that the server has already handled the removal of this peer.
4521
        s.wg.Add(1)
4522
        go s.peerTerminationWatcher(p, ready)
4523

4524
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4525
        // will unblock the peerTerminationWatcher.
3✔
4526
        if err := p.Start(); err != nil {
3✔
4527
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4528

3✔
4529
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4530
                return
3✔
4531
        }
3✔
4532

3✔
4533
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
3✔
4534
        // was successful, and to begin watching the peer's wait group.
3✔
4535
        close(ready)
3✔
4536

3✔
4537
        s.mu.Lock()
6✔
4538
        defer s.mu.Unlock()
3✔
4539

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

3✔
4543
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
4544
        // route.Vertex as the key type of peerConnectedListeners.
4545
        pubStr := string(pubBytes)
4546
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
3✔
4547
                select {
3✔
4548
                case peerChan <- p:
3✔
4549
                case <-s.quit:
3✔
4550
                        return
3✔
4551
                }
3✔
4552
        }
3✔
4553
        delete(s.peerConnectedListeners, pubStr)
3✔
4554

3✔
4555
        // Since the peer has been fully initialized, now it's time to notify
3✔
4556
        // the RPC about the peer online event.
3✔
4557
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
6✔
4558
}
3✔
4559

3✔
UNCOV
4560
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
×
UNCOV
4561
// and then cleans up all resources allocated to the peer, notifies relevant
×
4562
// sub-systems of its demise, and finally handles re-connecting to the peer if
4563
// it's persistent. If the server intentionally disconnects a peer, it should
4564
// have a corresponding entry in the ignorePeerTermination map which will cause
3✔
4565
// the cleanup routine to exit early. The passed `ready` chan is used to
3✔
4566
// synchronize when WaitForDisconnect should begin watching on the peer's
3✔
4567
// waitgroup. The ready chan should only be signaled if the peer starts
3✔
4568
// successfully, otherwise the peer should be disconnected instead.
3✔
4569
//
4570
// NOTE: This MUST be launched as a goroutine.
4571
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
4572
        defer s.wg.Done()
4573

4574
        ctx := btclog.WithCtx(
4575
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
4576
        )
4577

4578
        p.WaitForDisconnect(ready)
4579

4580
        srvrLog.DebugS(ctx, "Peer has been disconnected")
4581

4582
        // If the server is exiting then we can bail out early ourselves as all
3✔
4583
        // the other sub-systems will already be shutting down.
3✔
4584
        if s.Stopped() {
3✔
4585
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4586
                return
3✔
4587
        }
3✔
4588

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

3✔
4595
        pubKey := p.IdentityKey()
6✔
4596

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

4601
        // Tell the switch to remove all links associated with this peer.
4602
        // Passing nil as the target link indicates that all links associated
4603
        // with this interface should be closed.
4604
        //
3✔
4605
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4606
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4607
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4608
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
3✔
4609
        }
3✔
4610

3✔
4611
        for _, link := range links {
3✔
4612
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4613
        }
3✔
4614

3✔
4615
        s.mu.Lock()
3✔
4616
        defer s.mu.Unlock()
3✔
4617

3✔
4618
        // If there were any notification requests for when this peer
3✔
UNCOV
4619
        // disconnected, we can trigger them now.
×
UNCOV
4620
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
4621
        pubStr := string(pubKey.SerializeCompressed())
4622
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4623
                close(offlineChan)
3✔
4624
        }
3✔
4625
        delete(s.peerDisconnectedListeners, pubStr)
4626

3✔
4627
        // If the server has already removed this peer, we can short circuit the
3✔
4628
        // peer termination watcher and skip cleanup.
3✔
4629
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4630
                delete(s.ignorePeerTermination, p)
3✔
4631

3✔
4632
                pubKey := p.PubKey()
3✔
4633
                pubStr := string(pubKey[:])
6✔
4634

3✔
4635
                // If a connection callback is present, we'll go ahead and
3✔
4636
                // execute it now that previous peer has fully disconnected. If
3✔
4637
                // the callback is not present, this likely implies the peer was
3✔
4638
                // purposefully disconnected via RPC, and that no reconnect
3✔
4639
                // should be attempted.
3✔
4640
                connCallback, ok := s.scheduledPeerConnection[pubStr]
6✔
4641
                if ok {
3✔
4642
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4643
                        connCallback()
3✔
4644
                }
3✔
4645
                return
3✔
4646
        }
3✔
4647

3✔
4648
        // First, cleanup any remaining state the server has regarding the peer
3✔
4649
        // in question.
3✔
4650
        s.removePeerUnsafe(ctx, p)
3✔
4651

3✔
4652
        // Next, check to see if this is a persistent peer or not.
6✔
4653
        if _, ok := s.persistentPeers[pubStr]; !ok {
3✔
4654
                return
3✔
4655
        }
3✔
4656

3✔
4657
        // Get the last address that we used to connect to the peer.
4658
        addrs := []net.Addr{
4659
                p.NetAddress().Address,
4660
        }
4661

3✔
4662
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4663
        // reconnection purposes.
3✔
4664
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
6✔
4665
        switch {
3✔
4666
        // We found advertised addresses, so use them.
3✔
4667
        case err == nil:
4668
                addrs = advertisedAddrs
4669

3✔
4670
        // The peer doesn't have an advertised address.
3✔
4671
        case err == errNoAdvertisedAddr:
3✔
4672
                // If it is an outbound peer then we fall back to the existing
3✔
4673
                // peer address.
3✔
4674
                if !p.Inbound() {
3✔
4675
                        break
3✔
4676
                }
3✔
4677

4678
                // Fall back to the existing peer address if
3✔
4679
                // we're not accepting connections over Tor.
3✔
4680
                if s.torController == nil {
4681
                        break
4682
                }
3✔
4683

3✔
4684
                // If we are, the peer's address won't be known
3✔
4685
                // to us (we'll see a private address, which is
6✔
4686
                // the address used by our onion service to dial
3✔
4687
                // to lnd), so we don't have enough information
4688
                // to attempt a reconnect.
4689
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
4690
                        "to inbound peer without advertised address")
4691
                return
6✔
4692

3✔
4693
        // We came across an error retrieving an advertised
4694
        // address, log it, and fall back to the existing peer
4695
        // address.
4696
        default:
4697
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
4698
                        "address for peer", err)
4699
        }
UNCOV
4700

×
UNCOV
4701
        // Make an easy lookup map so that we can check if an address
×
UNCOV
4702
        // is already in the address list that we have stored for this peer.
×
4703
        existingAddrs := make(map[string]bool)
4704
        for _, addr := range s.persistentPeerAddrs[pubStr] {
4705
                existingAddrs[addr.String()] = true
4706
        }
4707

3✔
4708
        // Add any missing addresses for this peer to persistentPeerAddr.
3✔
4709
        for _, addr := range addrs {
3✔
4710
                if existingAddrs[addr.String()] {
4711
                        continue
4712
                }
4713

4714
                s.persistentPeerAddrs[pubStr] = append(
3✔
4715
                        s.persistentPeerAddrs[pubStr],
6✔
4716
                        &lnwire.NetAddress{
3✔
4717
                                IdentityKey: p.IdentityKey(),
3✔
4718
                                Address:     addr,
4719
                                ChainNet:    p.NetAddress().ChainNet,
4720
                        },
6✔
4721
                )
3✔
UNCOV
4722
        }
×
4723

4724
        // Record the computed backoff in the backoff map.
4725
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4726
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4727

3✔
4728
        // Initialize a retry canceller for this peer if one does not
3✔
4729
        // exist.
3✔
4730
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4731
        if !ok {
3✔
4732
                cancelChan = make(chan struct{})
3✔
4733
                s.persistentRetryCancels[pubStr] = cancelChan
4734
        }
4735

4736
        // We choose not to wait group this go routine since the Connect
3✔
4737
        // call can stall for arbitrarily long if we shutdown while an
3✔
4738
        // outbound connection attempt is being made.
3✔
4739
        go func() {
3✔
4740
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4741
                        "re-establishment to persistent peer",
3✔
4742
                        "reconnecting_in", backoff)
6✔
4743

3✔
4744
                select {
3✔
4745
                case <-time.After(backoff):
3✔
4746
                case <-cancelChan:
4747
                        return
4748
                case <-s.quit:
4749
                        return
4750
                }
6✔
4751

3✔
4752
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4753
                        "connection")
3✔
4754

3✔
4755
                s.connectToPersistentPeer(pubStr)
3✔
4756
        }()
3✔
4757
}
3✔
4758

3✔
4759
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
3✔
4760
// to connect to the peer. It creates connection requests if there are
3✔
4761
// currently none for a given address and it removes old connection requests
4762
// if the associated address is no longer in the latest address list for the
4763
// peer.
3✔
4764
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4765
        s.mu.Lock()
3✔
4766
        defer s.mu.Unlock()
3✔
4767

4768
        // Create an easy lookup map of the addresses we have stored for the
4769
        // peer. We will remove entries from this map if we have existing
4770
        // connection requests for the associated address and then any leftover
4771
        // entries will indicate which addresses we should create new
4772
        // connection requests for.
4773
        addrMap := make(map[string]*lnwire.NetAddress)
4774
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
4775
                addrMap[addr.String()] = addr
3✔
4776
        }
3✔
4777

3✔
4778
        // Go through each of the existing connection requests and
3✔
4779
        // check if they correspond to the latest set of addresses. If
3✔
4780
        // there is a connection requests that does not use one of the latest
3✔
4781
        // advertised addresses then remove that connection request.
3✔
4782
        var updatedConnReqs []*connmgr.ConnReq
3✔
4783
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
3✔
4784
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4785

6✔
4786
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4787
                // If the existing connection request is using one of the
3✔
4788
                // latest advertised addresses for the peer then we add it to
4789
                // updatedConnReqs and remove the associated address from
4790
                // addrMap so that we don't recreate this connReq later on.
4791
                case true:
4792
                        updatedConnReqs = append(
4793
                                updatedConnReqs, connReq,
3✔
4794
                        )
6✔
4795
                        delete(addrMap, lnAddr)
3✔
4796

3✔
4797
                // If the existing connection request is using an address that
3✔
4798
                // is not one of the latest advertised addresses for the peer
4799
                // then we remove the connecting request from the connection
4800
                // manager.
4801
                case false:
UNCOV
4802
                        srvrLog.Info(
×
UNCOV
4803
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4804
                        )
×
UNCOV
4805
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4806
                }
×
4807
        }
4808

4809
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4810

4811
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
4812
        if !ok {
3✔
4813
                cancelChan = make(chan struct{})
3✔
4814
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4815
        }
3✔
4816

3✔
4817
        // Any addresses left in addrMap are new ones that we have not made
4818
        // connection requests for. So create new connection requests for those.
4819
        // If there is more than one address in the address map, stagger the
4820
        // creation of the connection requests for those.
3✔
4821
        go func() {
3✔
4822
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4823
                defer ticker.Stop()
6✔
4824

3✔
4825
                for _, addr := range addrMap {
3✔
4826
                        // Send the persistent connection request to the
3✔
4827
                        // connection manager, saving the request itself so we
4828
                        // can cancel/restart the process as needed.
4829
                        connReq := &connmgr.ConnReq{
4830
                                Addr:      addr,
4831
                                Permanent: true,
4832
                        }
6✔
4833

3✔
4834
                        s.mu.Lock()
3✔
4835
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4836
                                s.persistentConnReqs[pubKeyStr], connReq,
6✔
4837
                        )
3✔
4838
                        s.mu.Unlock()
3✔
4839

3✔
4840
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4841
                                "channel peer %v", addr)
3✔
4842

3✔
4843
                        go s.connMgr.Connect(connReq)
3✔
4844

3✔
4845
                        select {
3✔
4846
                        case <-s.quit:
3✔
4847
                                return
3✔
4848
                        case <-cancelChan:
3✔
4849
                                return
3✔
4850
                        case <-ticker.C:
3✔
4851
                        }
3✔
4852
                }
3✔
4853
        }()
3✔
4854
}
3✔
4855

3✔
4856
// removePeerUnsafe removes the passed peer from the server's state of all
3✔
4857
// active peers.
3✔
4858
//
3✔
4859
// NOTE: Server mutex must be held when calling this function.
3✔
4860
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4861
        if p == nil {
3✔
4862
                return
4863
        }
4864

4865
        srvrLog.DebugS(ctx, "Removing peer")
4866

4867
        // Exit early if we have already been instructed to shutdown, the peers
4868
        // will be disconnected in the server shutdown process.
4869
        if s.Stopped() {
4870
                return
4871
        }
3✔
4872

3✔
UNCOV
4873
        // Capture the peer's public key and string representation.
×
UNCOV
4874
        pKey := p.PubKey()
×
4875
        pubSer := pKey[:]
4876
        pubStr := string(pubSer)
3✔
4877

3✔
4878
        delete(s.peersByPub, pubStr)
3✔
4879

3✔
4880
        if p.Inbound() {
3✔
UNCOV
4881
                delete(s.inboundPeers, pubStr)
×
UNCOV
4882
        } else {
×
4883
                delete(s.outboundPeers, pubStr)
4884
        }
4885

3✔
4886
        // When removing the peer we make sure to disconnect it asynchronously
3✔
4887
        // to avoid blocking the main server goroutine because it is holding the
3✔
4888
        // server's mutex. Disconnecting the peer might block and wait until the
3✔
4889
        // peer has fully started up. This can happen if an inbound and outbound
3✔
4890
        // race condition occurs.
3✔
4891
        s.wg.Add(1)
6✔
4892
        go func() {
3✔
4893
                defer s.wg.Done()
6✔
4894

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

4897
                // If this peer had an active persistent connection request,
4898
                // remove it.
4899
                if p.ConnReq() != nil {
4900
                        s.connMgr.Remove(p.ConnReq().ID())
4901
                }
4902

3✔
4903
                // Remove the peer's access permission from the access manager.
6✔
4904
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4905
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4906

3✔
4907
                // Copy the peer's error buffer across to the server if it has
3✔
4908
                // any items in it so that we can restore peer errors across
3✔
4909
                // connections. We need to look up the error after the peer has
3✔
4910
                // been disconnected because we write the error in the
6✔
4911
                // `Disconnect` method.
3✔
4912
                s.mu.Lock()
3✔
4913
                if p.ErrorBuffer().Total() > 0 {
4914
                        s.peerErrors[pubStr] = p.ErrorBuffer()
4915
                }
3✔
4916
                s.mu.Unlock()
3✔
4917

3✔
4918
                // Inform the peer notifier of a peer offline event so that it
3✔
4919
                // can be reported to clients listening for peer events.
3✔
4920
                var pubKey [33]byte
3✔
4921
                copy(pubKey[:], pubSer)
3✔
4922

3✔
4923
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4924
        }()
6✔
4925
}
3✔
4926

3✔
4927
// ConnectToPeer requests that the server connect to a Lightning Network peer
3✔
4928
// at the specified address. This function will *block* until either a
3✔
4929
// connection is established, or the initial handshake process fails.
3✔
4930
//
3✔
4931
// NOTE: This function is safe for concurrent access.
3✔
4932
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
3✔
4933
        perm bool, timeout time.Duration) error {
3✔
4934

3✔
4935
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4936

4937
        // Acquire mutex, but use explicit unlocking instead of defer for
4938
        // better granularity.  In certain conditions, this method requires
4939
        // making an outbound connection to a remote peer, which requires the
4940
        // lock to be released, and subsequently reacquired.
4941
        s.mu.Lock()
4942

4943
        // Ensure we're not already connected to this peer.
4944
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4945

3✔
4946
        // When there's no error it means we already have a connection with this
3✔
4947
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4948
        // set, we will ignore the existing connection and continue.
3✔
4949
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
3✔
4950
                s.mu.Unlock()
3✔
4951
                return &errPeerAlreadyConnected{peer: peer}
3✔
4952
        }
3✔
4953

3✔
4954
        // Peer was not found, continue to pursue connection with peer.
3✔
4955

3✔
4956
        // If there's already a pending connection request for this pubkey,
3✔
4957
        // then we ignore this request to ensure we don't create a redundant
3✔
4958
        // connection.
3✔
4959
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
3✔
4960
                srvrLog.Warnf("Already have %d persistent connection "+
6✔
4961
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4962
        }
3✔
4963

3✔
4964
        // If there's not already a pending or active connection to this node,
4965
        // then instruct the connection manager to attempt to establish a
4966
        // persistent connection to the peer.
4967
        srvrLog.Debugf("Connecting to %v", addr)
4968
        if perm {
4969
                connReq := &connmgr.ConnReq{
4970
                        Addr:      addr,
6✔
4971
                        Permanent: true,
3✔
4972
                }
3✔
4973

3✔
4974
                // Since the user requested a permanent connection, we'll set
4975
                // the entry to true which will tell the server to continue
4976
                // reconnecting even if the number of channels with this peer is
4977
                // zero.
4978
                s.persistentPeers[targetPub] = true
3✔
4979
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4980
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4981
                }
3✔
4982
                s.persistentConnReqs[targetPub] = append(
3✔
4983
                        s.persistentConnReqs[targetPub], connReq,
3✔
4984
                )
3✔
4985
                s.mu.Unlock()
3✔
4986

3✔
4987
                go s.connMgr.Connect(connReq)
3✔
4988

3✔
4989
                return nil
3✔
4990
        }
6✔
4991
        s.mu.Unlock()
3✔
4992

3✔
4993
        // If we're not making a persistent connection, then we'll attempt to
3✔
4994
        // connect to the target peer. If the we can't make the connection, or
3✔
4995
        // the crypto negotiation breaks down, then return an error to the
3✔
4996
        // caller.
3✔
4997
        errChan := make(chan error, 1)
3✔
4998
        s.connectToPeer(addr, errChan, timeout)
3✔
4999

3✔
5000
        select {
3✔
5001
        case err := <-errChan:
5002
                return err
3✔
5003
        case <-s.quit:
3✔
5004
                return ErrServerShuttingDown
3✔
5005
        }
3✔
5006
}
3✔
5007

3✔
5008
// connectToPeer establishes a connection to a remote peer. errChan is used to
3✔
5009
// notify the caller if the connection attempt has failed. Otherwise, it will be
3✔
5010
// closed.
3✔
5011
func (s *server) connectToPeer(addr *lnwire.NetAddress,
3✔
5012
        errChan chan<- error, timeout time.Duration) {
3✔
5013

3✔
UNCOV
5014
        conn, err := brontide.Dial(
×
UNCOV
5015
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
5016
        )
5017
        if err != nil {
5018
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
5019
                select {
5020
                case errChan <- err:
5021
                case <-s.quit:
5022
                }
5023
                return
3✔
5024
        }
3✔
5025

3✔
5026
        close(errChan)
3✔
5027

3✔
5028
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
6✔
5029
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5030

3✔
5031
        s.OutboundPeerConnected(nil, conn)
3✔
UNCOV
5032
}
×
5033

5034
// DisconnectPeer sends the request to server to close the connection with peer
3✔
5035
// identified by public key.
5036
//
5037
// NOTE: This function is safe for concurrent access.
3✔
5038
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5039
        pubBytes := pubKey.SerializeCompressed()
3✔
5040
        pubStr := string(pubBytes)
3✔
5041

3✔
5042
        s.mu.Lock()
3✔
5043
        defer s.mu.Unlock()
5044

5045
        // Check that were actually connected to this peer. If not, then we'll
5046
        // exit in an error as we can't disconnect from a peer that we're not
5047
        // currently connected to.
5048
        peer, err := s.findPeerByPubStr(pubStr)
5049
        if err == ErrPeerNotConnected {
3✔
5050
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5051
        }
3✔
5052

3✔
5053
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5054

3✔
5055
        s.cancelConnReqs(pubStr, nil)
3✔
5056

3✔
5057
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5058
        // them from this map so we don't attempt to re-connect after we
3✔
5059
        // disconnect.
3✔
5060
        delete(s.persistentPeers, pubStr)
6✔
5061
        delete(s.persistentPeersBackoff, pubStr)
3✔
5062

3✔
5063
        // Remove the peer by calling Disconnect. Previously this was done with
5064
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5065
        //
3✔
5066
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5067
        // goroutine because we might hold the server's mutex.
3✔
5068
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5069

3✔
5070
        return nil
3✔
5071
}
3✔
5072

3✔
5073
// OpenChannel sends a request to the server to open a channel to the specified
3✔
5074
// peer identified by nodeKey with the passed channel funding parameters.
3✔
5075
//
3✔
5076
// NOTE: This function is safe for concurrent access.
3✔
5077
func (s *server) OpenChannel(
3✔
5078
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5079

3✔
5080
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5081
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5082
        // not blocked if the caller is not reading the updates.
5083
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
5084
        req.Err = make(chan error, 1)
5085

5086
        // First attempt to locate the target peer to open a channel with, if
5087
        // we're unable to locate the peer then this request will fail.
5088
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
5089
        s.mu.RLock()
3✔
5090
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5091
        if !ok {
3✔
5092
                s.mu.RUnlock()
3✔
5093

3✔
5094
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
3✔
5095
                return req.Updates, req.Err
3✔
5096
        }
3✔
5097
        req.Peer = peer
3✔
5098
        s.mu.RUnlock()
3✔
5099

3✔
5100
        // We'll wait until the peer is active before beginning the channel
3✔
5101
        // opening process.
3✔
5102
        select {
3✔
UNCOV
5103
        case <-peer.ActiveSignal():
×
5104
        case <-peer.QuitSignal():
×
5105
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5106
                return req.Updates, req.Err
×
5107
        case <-s.quit:
×
5108
                req.Err <- ErrServerShuttingDown
3✔
5109
                return req.Updates, req.Err
3✔
5110
        }
3✔
5111

3✔
5112
        // If the fee rate wasn't specified at this point we fail the funding
3✔
5113
        // because of the missing fee rate information. The caller of the
3✔
5114
        // `OpenChannel` method needs to make sure that default values for the
3✔
UNCOV
5115
        // fee rate are set beforehand.
×
UNCOV
5116
        if req.FundingFeePerKw == 0 {
×
5117
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5118
                        "the channel opening transaction")
×
5119

×
5120
                return req.Updates, req.Err
×
5121
        }
5122

5123
        // Spawn a goroutine to send the funding workflow request to the funding
5124
        // manager. This allows the server to continue handling queries instead
5125
        // of blocking on this request which is exported as a synchronous
5126
        // request to the outside world.
5127
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
UNCOV
5128

×
UNCOV
5129
        return req.Updates, req.Err
×
UNCOV
5130
}
×
UNCOV
5131

×
UNCOV
5132
// Peers returns a slice of all active peers.
×
5133
//
5134
// NOTE: This function is safe for concurrent access.
5135
func (s *server) Peers() []*peer.Brontide {
5136
        s.mu.RLock()
5137
        defer s.mu.RUnlock()
5138

3✔
5139
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5140
        for _, peer := range s.peersByPub {
3✔
5141
                peers = append(peers, peer)
5142
        }
5143

5144
        return peers
5145
}
5146

3✔
5147
// computeNextBackoff uses a truncated exponential backoff to compute the next
3✔
5148
// backoff using the value of the exiting backoff. The returned duration is
3✔
5149
// randomized in either direction by 1/20 to prevent tight loops from
3✔
5150
// stabilizing.
3✔
5151
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
6✔
5152
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5153
        nextBackoff := 2 * currBackoff
3✔
5154
        if nextBackoff > maxBackoff {
5155
                nextBackoff = maxBackoff
3✔
5156
        }
5157

5158
        // Using 1/10 of our duration as a margin, compute a random offset to
5159
        // avoid the nodes entering connection cycles.
5160
        margin := nextBackoff / 10
5161

5162
        var wiggle big.Int
3✔
5163
        wiggle.SetUint64(uint64(margin))
3✔
5164
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5165
                // Randomizing is not mission critical, so we'll just return the
6✔
5166
                // current backoff.
3✔
5167
                return nextBackoff
3✔
5168
        }
5169

5170
        // Otherwise add in our wiggle, but subtract out half of the margin so
5171
        // that the backoff can tweaked by 1/20 in either direction.
3✔
5172
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5173
}
3✔
5174

3✔
5175
// errNoAdvertisedAddr is an error returned when we attempt to retrieve the
3✔
UNCOV
5176
// advertised address of a node, but they don't have one.
×
UNCOV
5177
var errNoAdvertisedAddr = errors.New("no advertised address found")
×
UNCOV
5178

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

5183
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5184
        if err != nil {
5185
                return nil, err
5186
        }
5187

5188
        node, err := s.graphDB.FetchNode(ctx, vertex)
5189
        if err != nil {
5190
                return nil, err
5191
        }
5192

3✔
5193
        if len(node.Addresses) == 0 {
3✔
5194
                return nil, errNoAdvertisedAddr
3✔
5195
        }
3✔
UNCOV
5196

×
UNCOV
5197
        return node.Addresses, nil
×
5198
}
5199

3✔
5200
// fetchLastChanUpdate returns a function which is able to retrieve our latest
6✔
5201
// channel update for a target channel.
3✔
5202
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
3✔
5203
        *lnwire.ChannelUpdate1, error) {
5204

6✔
5205
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5206
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
3✔
5207
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
5208
                if err != nil {
3✔
5209
                        return nil, err
5210
                }
5211

5212
                return netann.ExtractChannelUpdate(
5213
                        ourPubKey[:], info, edge1, edge2,
5214
                )
3✔
5215
        }
3✔
5216
}
3✔
5217

6✔
5218
// applyChannelUpdate applies the channel update to the different sub-systems of
3✔
5219
// the server. The useAlias boolean denotes whether or not to send an alias in
6✔
5220
// place of the real SCID.
3✔
5221
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
3✔
5222
        op *wire.OutPoint, useAlias bool) error {
5223

3✔
5224
        var (
3✔
5225
                peerAlias    *lnwire.ShortChannelID
3✔
5226
                defaultAlias lnwire.ShortChannelID
5227
        )
5228

5229
        chanID := lnwire.NewChanIDFromOutPoint(*op)
5230

5231
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
5232
        // in the ChannelUpdate if it hasn't been announced yet.
5233
        if useAlias {
3✔
5234
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5235
                if foundAlias != defaultAlias {
3✔
5236
                        peerAlias = &foundAlias
3✔
5237
                }
3✔
5238
        }
3✔
5239

3✔
5240
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5241
                update, discovery.RemoteAlias(peerAlias),
3✔
5242
        )
3✔
5243
        select {
3✔
5244
        case err := <-errChan:
6✔
5245
                return err
3✔
5246
        case <-s.quit:
6✔
5247
                return ErrServerShuttingDown
3✔
5248
        }
3✔
5249
}
5250

5251
// SendCustomMessage sends a custom message to the peer with the specified
3✔
5252
// pubkey.
3✔
5253
func (s *server) SendCustomMessage(ctx context.Context, peerPub [33]byte,
3✔
5254
        msgType lnwire.MessageType, data []byte) error {
3✔
5255

3✔
5256
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
UNCOV
5257
        if err != nil {
×
UNCOV
5258
                return err
×
5259
        }
5260

5261
        // We'll wait until the peer is active, but also listen for
5262
        // cancellation.
5263
        select {
5264
        case <-peer.ActiveSignal():
5265
        case <-peer.QuitSignal():
3✔
5266
                return fmt.Errorf("peer %x disconnected", peerPub)
3✔
5267
        case <-s.quit:
3✔
5268
                return ErrServerShuttingDown
6✔
5269
        case <-ctx.Done():
3✔
5270
                return ctx.Err()
3✔
5271
        }
5272

5273
        msg, err := lnwire.NewCustom(msgType, data)
5274
        if err != nil {
3✔
5275
                return err
3✔
UNCOV
5276
        }
×
UNCOV
5277

×
UNCOV
5278
        // Send the message as low-priority. For now we assume that all
×
UNCOV
5279
        // application-defined message are low priority.
×
UNCOV
5280
        return peer.SendMessageLazy(true, msg)
×
UNCOV
5281
}
×
5282

5283
// SendOnionMessage sends a custom message to the peer with the specified
5284
// pubkey.
3✔
5285
// TODO(gijs): change this message to include path finding.
6✔
5286
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
3✔
5287
        pathKey *btcec.PublicKey, onion []byte) error {
3✔
5288

5289
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
5290
        if err != nil {
5291
                return err
3✔
5292
        }
5293

5294
        // We'll wait until the peer is active, but also listen for
5295
        // cancellation.
5296
        select {
5297
        case <-peer.ActiveSignal():
5298
        case <-peer.QuitSignal():
3✔
5299
                return fmt.Errorf("peer %x disconnected", peerPub)
3✔
5300
        case <-s.quit:
3✔
5301
                return ErrServerShuttingDown
3✔
5302
        case <-ctx.Done():
×
5303
                return ctx.Err()
×
5304
        }
5305

5306
        msg := lnwire.NewOnionMessage(pathKey, onion)
5307

3✔
5308
        // Send the message as low-priority. For now we assume that all
3✔
UNCOV
5309
        // application-defined message are low priority.
×
UNCOV
5310
        return peer.SendMessageLazy(true, msg)
×
UNCOV
5311
}
×
UNCOV
5312

×
UNCOV
5313
// newSweepPkScriptGen creates closure that generates a new public key script
×
UNCOV
5314
// which should be used to sweep any funds into the on-chain wallet.
×
5315
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5316
// (p2wkh) output.
5317
func newSweepPkScriptGen(
3✔
5318
        wallet lnwallet.WalletController,
3✔
5319
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5320

3✔
5321
        return func() fn.Result[lnwallet.AddrWithKey] {
3✔
5322
                sweepAddr, err := wallet.NewAddress(
5323
                        lnwallet.TaprootPubkey, false,
5324
                        lnwallet.DefaultAccountName,
5325
                )
5326
                if err != nil {
5327
                        return fn.Err[lnwallet.AddrWithKey](err)
5328
                }
5329

5330
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5331
                if err != nil {
3✔
5332
                        return fn.Err[lnwallet.AddrWithKey](err)
6✔
5333
                }
3✔
5334

3✔
5335
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5336
                        wallet, netParams, addr,
3✔
5337
                )
3✔
UNCOV
5338
                if err != nil {
×
5339
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5340
                }
5341

3✔
5342
                return fn.Ok(lnwallet.AddrWithKey{
3✔
UNCOV
5343
                        DeliveryAddress: addr,
×
UNCOV
5344
                        InternalKey:     internalKeyDesc,
×
5345
                })
5346
        }
3✔
5347
}
3✔
5348

3✔
5349
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
3✔
UNCOV
5350
// finished.
×
UNCOV
5351
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
5352
        // Get a list of closed channels.
5353
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5354
        if err != nil {
3✔
5355
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
3✔
5356
                return nil
3✔
5357
        }
5358

5359
        // Save the SCIDs in a map.
5360
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
5361
        for _, c := range channels {
5362
                // If the channel is not pending, its FC has been finalized.
3✔
5363
                if !c.IsPending {
3✔
5364
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5365
                }
3✔
UNCOV
5366
        }
×
UNCOV
5367

×
UNCOV
5368
        // Double check whether the reported closed channel has indeed finished
×
5369
        // closing.
5370
        //
5371
        // NOTE: There are misalignments regarding when a channel's FC is
3✔
5372
        // marked as finalized. We double check the pending channels to make
6✔
5373
        // sure the returned SCIDs are indeed terminated.
3✔
5374
        //
6✔
5375
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
3✔
5376
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5377
        if err != nil {
5378
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
5379
                return nil
5380
        }
5381

5382
        for _, c := range pendings {
5383
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
5384
                        continue
5385
                }
5386

5387
                // If the channel is still reported as pending, remove it from
3✔
5388
                // the map.
3✔
5389
                delete(closedSCIDs, c.ShortChannelID)
×
5390

×
5391
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5392
                        c.ShortChannelID)
5393
        }
6✔
5394

6✔
5395
        return closedSCIDs
3✔
5396
}
5397

5398
// getStartingBeat returns the current beat. This is used during the startup to
5399
// initialize blockbeat consumers.
UNCOV
5400
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
UNCOV
5401
        // beat is the current blockbeat.
×
UNCOV
5402
        var beat *chainio.Beat
×
UNCOV
5403

×
5404
        // If the node is configured with nochainbackend mode (remote signer),
5405
        // we will skip fetching the best block.
5406
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5407
                srvrLog.Info("Skipping block notification for nochainbackend " +
5408
                        "mode")
5409

5410
                return &chainio.Beat{}, nil
5411
        }
3✔
5412

3✔
5413
        // We should get a notification with the current best block immediately
3✔
5414
        // by passing a nil block.
3✔
5415
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5416
        if err != nil {
3✔
5417
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
3✔
5418
        }
×
UNCOV
5419
        defer blockEpochs.Cancel()
×
UNCOV
5420

×
UNCOV
5421
        // We registered for the block epochs with a nil request. The notifier
×
UNCOV
5422
        // should send us the current best block immediately. So we need to
×
5423
        // wait for it here because we need to know the current best height.
5424
        select {
5425
        case bestBlock := <-blockEpochs.Epochs:
5426
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5427
                        bestBlock.Hash, bestBlock.Height)
3✔
UNCOV
5428

×
UNCOV
5429
                // Update the current blockbeat.
×
5430
                beat = chainio.NewBeat(*bestBlock)
3✔
5431

3✔
5432
        case <-s.quit:
3✔
5433
                srvrLog.Debug("LND shutting down")
3✔
5434
        }
3✔
5435

3✔
5436
        return beat, nil
3✔
5437
}
3✔
5438

3✔
5439
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
3✔
5440
// point has an active RBF chan closer.
3✔
5441
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
3✔
5442
        chanPoint wire.OutPoint) bool {
UNCOV
5443

×
UNCOV
5444
        pubBytes := peerPub.SerializeCompressed()
×
5445

5446
        s.mu.RLock()
5447
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5448
        s.mu.RUnlock()
5449
        if !ok {
5450
                return false
5451
        }
5452

5453
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5454
}
3✔
5455

3✔
5456
// attemptCoopRbfFeeBump attempts to look up the active chan closer for a
3✔
5457
// channel given the outpoint. If found, we'll attempt to do a fee bump,
3✔
5458
// returning channels used for updates. If the channel isn't currently active
3✔
5459
// (p2p connection established), then his function will return an error.
3✔
5460
func (s *server) attemptCoopRbfFeeBump(ctx context.Context,
3✔
UNCOV
5461
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
×
UNCOV
5462
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
×
5463

5464
        // First, we'll attempt to look up the channel based on it's
3✔
5465
        // ChannelPoint.
5466
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
5467
        if err != nil {
5468
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
5469
        }
5470

5471
        // From the channel, we can now get the pubkey of the peer, then use
5472
        // that to eventually get the chan closer.
5473
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5474

3✔
5475
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5476
        s.mu.RLock()
3✔
5477
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5478
        s.mu.RUnlock()
3✔
UNCOV
5479
        if !ok {
×
5480
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5481
                        "not online", chanPoint)
5482
        }
5483

5484
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5485
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5486
        )
3✔
5487
        if err != nil {
3✔
5488
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
3✔
5489
                        "%w", err)
3✔
5490
        }
3✔
UNCOV
5491

×
UNCOV
5492
        return closeUpdates, nil
×
UNCOV
5493
}
×
5494

5495
// AttemptRBFCloseUpdate attempts to trigger a new RBF iteration for a co-op
3✔
5496
// close update. This route it to be used only if the target channel in question
3✔
5497
// is no longer active in the link. This can happen when we restart while we
3✔
5498
// already have done a single RBF co-op close iteration.
3✔
UNCOV
5499
func (s *server) AttemptRBFCloseUpdate(ctx context.Context,
×
UNCOV
5500
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
×
UNCOV
5501
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
×
5502

5503
        // If the channel is present in the switch, then the request should flow
3✔
5504
        // through the switch instead.
5505
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5506
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
5507
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
5508
                        "invalid request", chanPoint)
5509
        }
5510

5511
        // At this point, we know that the channel isn't present in the link, so
5512
        // we'll check to see if we have an entry in the active chan closer map.
3✔
5513
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5514
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5515
        )
3✔
5516
        if err != nil {
3✔
5517
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
3✔
5518
                        "ChannelPoint(%v)", chanPoint)
×
5519
        }
×
UNCOV
5520

×
5521
        return updates, nil
5522
}
5523

5524
// setSelfNode configures and sets the server's self node. It sets the node
3✔
5525
// announcement, signs it, and updates the source node in the graph. When
3✔
5526
// determining values such as color and alias, the method prioritizes values
3✔
5527
// set in the config, then values previously persisted on disk, and finally
3✔
UNCOV
5528
// falls back to the defaults.
×
UNCOV
5529
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
×
UNCOV
5530
        listenAddrs []net.Addr) error {
×
5531

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

6✔
5547
                        listenPorts = append(listenPorts, uint16(port))
3✔
5548
                }
3✔
5549

3✔
5550
                ips, err := s.configurePortForwarding(listenPorts...)
×
5551
                if err != nil {
×
5552
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5553
                                "forwarding using %s: %v",
×
5554
                                s.natTraversal.Name(), err)
×
5555
                } else {
×
5556
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5557
                                "using %s to advertise external IP",
×
5558
                                s.natTraversal.Name())
×
5559
                        externalIPStrings = append(externalIPStrings, ips...)
×
5560
                }
UNCOV
5561
        }
×
UNCOV
5562

×
UNCOV
5563
        // Normalize the external IP strings to net.Addr.
×
UNCOV
5564
        addrs, err := lncfg.NormalizeAddresses(
×
UNCOV
5565
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
5566
                s.cfg.net.ResolveTCPAddr,
×
UNCOV
5567
        )
×
UNCOV
5568
        if err != nil {
×
5569
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5570
        }
×
UNCOV
5571

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

3✔
UNCOV
5580
        var (
×
UNCOV
5581
                alias          = s.cfg.Alias
×
5582
                nodeLastUpdate = time.Now()
5583
        )
5584

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

3✔
5595
                // If the color is not changed from default, it means that we
3✔
5596
                // didn't specify a different color in the config. We'll use the
3✔
5597
                // source node's color.
3✔
5598
                if s.cfg.Color == defaultColor {
3✔
5599
                        srcNode.Color.WhenSome(func(rgba color.RGBA) {
3✔
5600
                                nodeColor = rgba
3✔
5601
                        })
3✔
5602
                }
6✔
5603

3✔
5604
                // If an alias is not specified in the config, we'll use the
3✔
5605
                // source node's alias.
5606
                if alias == "" {
5607
                        srcNode.Alias.WhenSome(func(s string) {
5608
                                alias = s
5609
                        })
6✔
5610
                }
6✔
5611

3✔
5612
                // If the `externalip` is not specified in the config, it means
3✔
5613
                // `addrs` will be empty, we'll use the source node's addresses.
5614
                if len(s.cfg.ExternalIPs) == 0 {
5615
                        addrs = srcNode.Addresses
5616
                }
5617

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

6✔
5626
        // If the above cases are not matched, then we have an unhandled non
3✔
5627
        // nil error.
3✔
5628
        default:
5629
                return fmt.Errorf("unable to fetch source node: %w", err)
3✔
5630
        }
3✔
5631

3✔
5632
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5633
        if err != nil {
6✔
5634
                return err
3✔
5635
        }
3✔
5636

5637
        // TODO(abdulkbk): potentially find a way to use the source node's
5638
        // features in the self node.
UNCOV
5639
        selfNode := models.NewV1Node(
×
UNCOV
5640
                nodePub, &models.NodeV1Fields{
×
5641
                        Alias:      nodeAlias.String(),
5642
                        Color:      nodeColor,
5643
                        LastUpdate: nodeLastUpdate,
3✔
5644
                        Addresses:  addrs,
3✔
UNCOV
5645
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
×
UNCOV
5646
                },
×
5647
        )
5648

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

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

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

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

3✔
5681
        s.currentNodeAnn = nodeAnn
3✔
5682

3✔
UNCOV
5683
        return nil
×
UNCOV
5684
}
×
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