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

lightningnetwork / lnd / 21485572389

29 Jan 2026 04:09PM UTC coverage: 65.247% (+0.2%) from 65.074%
21485572389

Pull #10089

github

web-flow
Merge 22d34d15e into 19b2ad797
Pull Request #10089: Onion message forwarding

1152 of 1448 new or added lines in 23 files covered. (79.56%)

4109 existing lines in 29 files now uncovered.

139515 of 213825 relevant lines covered (65.25%)

20529.09 hits per line

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

69.95
/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/actor"
31
        "github.com/lightningnetwork/lnd/aliasmgr"
32
        "github.com/lightningnetwork/lnd/autopilot"
33
        "github.com/lightningnetwork/lnd/brontide"
34
        "github.com/lightningnetwork/lnd/chainio"
35
        "github.com/lightningnetwork/lnd/chainreg"
36
        "github.com/lightningnetwork/lnd/chanacceptor"
37
        "github.com/lightningnetwork/lnd/chanbackup"
38
        "github.com/lightningnetwork/lnd/chanfitness"
39
        "github.com/lightningnetwork/lnd/channeldb"
40
        "github.com/lightningnetwork/lnd/channelnotifier"
41
        "github.com/lightningnetwork/lnd/clock"
42
        "github.com/lightningnetwork/lnd/cluster"
43
        "github.com/lightningnetwork/lnd/contractcourt"
44
        "github.com/lightningnetwork/lnd/discovery"
45
        "github.com/lightningnetwork/lnd/feature"
46
        "github.com/lightningnetwork/lnd/fn/v2"
47
        "github.com/lightningnetwork/lnd/funding"
48
        "github.com/lightningnetwork/lnd/graph"
49
        graphdb "github.com/lightningnetwork/lnd/graph/db"
50
        "github.com/lightningnetwork/lnd/graph/db/models"
51
        "github.com/lightningnetwork/lnd/healthcheck"
52
        "github.com/lightningnetwork/lnd/htlcswitch"
53
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
54
        "github.com/lightningnetwork/lnd/input"
55
        "github.com/lightningnetwork/lnd/invoices"
56
        "github.com/lightningnetwork/lnd/keychain"
57
        "github.com/lightningnetwork/lnd/lncfg"
58
        "github.com/lightningnetwork/lnd/lnencrypt"
59
        "github.com/lightningnetwork/lnd/lnpeer"
60
        "github.com/lightningnetwork/lnd/lnrpc"
61
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
62
        "github.com/lightningnetwork/lnd/lnutils"
63
        "github.com/lightningnetwork/lnd/lnwallet"
64
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
65
        chcl "github.com/lightningnetwork/lnd/lnwallet/chancloser"
66
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
67
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
68
        "github.com/lightningnetwork/lnd/lnwire"
69
        "github.com/lightningnetwork/lnd/nat"
70
        "github.com/lightningnetwork/lnd/netann"
71
        "github.com/lightningnetwork/lnd/onionmessage"
72
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
73
        "github.com/lightningnetwork/lnd/peer"
74
        "github.com/lightningnetwork/lnd/peernotifier"
75
        "github.com/lightningnetwork/lnd/pool"
76
        "github.com/lightningnetwork/lnd/queue"
77
        "github.com/lightningnetwork/lnd/routing"
78
        "github.com/lightningnetwork/lnd/routing/localchans"
79
        "github.com/lightningnetwork/lnd/routing/route"
80
        "github.com/lightningnetwork/lnd/subscribe"
81
        "github.com/lightningnetwork/lnd/sweep"
82
        "github.com/lightningnetwork/lnd/ticker"
83
        "github.com/lightningnetwork/lnd/tor"
84
        "github.com/lightningnetwork/lnd/walletunlocker"
85
        "github.com/lightningnetwork/lnd/watchtower/blob"
86
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
87
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
88
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
89
)
90

91
const (
92
        // defaultMinPeers is the minimum number of peers nodes should always be
93
        // connected to.
94
        defaultMinPeers = 3
95

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

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

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

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

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

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

129
        // ErrServerShuttingDown indicates that the server is in the process of
130
        // gracefully exiting.
131
        ErrServerShuttingDown = errors.New("server is shutting down")
132

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

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

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

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

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

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

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

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

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

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

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

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

203
        case peerStatusTemporary:
2✔
204
                return "temporary"
2✔
205

206
        case peerStatusProtected:
2✔
207
                return "protected"
2✔
208

209
        default:
×
210
                return "unknown"
×
211
        }
212
}
213

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

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

229
        start sync.Once
230
        stop  sync.Once
231

232
        cfg *Config
233

234
        implCfg *ImplementationCfg
235

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

240
        // identityKeyLoc is the key locator for the above wrapped identity key.
241
        identityKeyLoc keychain.KeyLocator
242

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

247
        chanStatusMgr *netann.ChanStatusManager
248

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

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

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

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

269
        mu sync.RWMutex
270

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

280
        inboundPeers  map[string]*peer.Brontide
281
        outboundPeers map[string]*peer.Brontide
282

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

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

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

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

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

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

321
        cc *chainreg.ChainControl
322

323
        fundingMgr *funding.Manager
324

325
        graphDB *graphdb.ChannelGraph
326

327
        chanStateDB *channeldb.ChannelStateDB
328

329
        addrSource channeldb.AddrSource
330

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

335
        invoicesDB invoices.InvoiceDB
336

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

341
        aliasMgr *aliasmgr.Manager
342

343
        htlcSwitch *htlcswitch.Switch
344

345
        interceptableSwitch *htlcswitch.InterceptableSwitch
346

347
        invoices *invoices.InvoiceRegistry
348

349
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
350

351
        channelNotifier *channelnotifier.ChannelNotifier
352

353
        peerNotifier *peernotifier.PeerNotifier
354

355
        htlcNotifier *htlcswitch.HtlcNotifier
356

357
        witnessBeacon contractcourt.WitnessBeacon
358

359
        breachArbitrator *contractcourt.BreachArbitrator
360

361
        missionController *routing.MissionController
362
        defaultMC         *routing.MissionControl
363

364
        graphBuilder *graph.Builder
365

366
        chanRouter *routing.ChannelRouter
367

368
        controlTower routing.ControlTower
369

370
        authGossiper *discovery.AuthenticatedGossiper
371

372
        localChanMgr *localchans.Manager
373

374
        utxoNursery *contractcourt.UtxoNursery
375

376
        sweeper *sweep.UtxoSweeper
377

378
        chainArb *contractcourt.ChainArbitrator
379

380
        sphinxPayment *hop.OnionProcessor
381

382
        sphinxOnionMsg *sphinx.Router
383

384
        towerClientMgr *wtclient.Manager
385

386
        connMgr *connmgr.ConnManager
387

388
        sigPool *lnwallet.SigPool
389

390
        writePool *pool.Write
391

392
        readPool *pool.Read
393

394
        tlsManager *TLSManager
395

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

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

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

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

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

418
        hostAnn *netann.HostAnnouncer
419

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

423
        customMessageServer *subscribe.Server
424

425
        onionMessageServer *subscribe.Server
426

427
        // onionEndpoint handles incoming onion messages and routes them to the
428
        // appropriate peer actor for forwarding or processes them locally.
429
        onionEndpoint *onionmessage.OnionEndpoint
430

431
        // actorSystem is the actor system tasked with handling actors that are
432
        // created for this server.
433
        actorSystem *actor.ActorSystem
434

435
        // txPublisher is a publisher with fee-bumping capability.
436
        txPublisher *sweep.TxPublisher
437

438
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
439
        // of new blocks.
440
        blockbeatDispatcher *chainio.BlockbeatDispatcher
441

442
        // peerAccessMan implements peer access controls.
443
        peerAccessMan *accessMan
444

445
        quit chan struct{}
446

447
        wg sync.WaitGroup
448
}
449

450
// updatePersistentPeerAddrs subscribes to topology changes and stores
451
// advertised addresses for any NodeAnnouncements from our persisted peers.
452
func (s *server) updatePersistentPeerAddrs() error {
2✔
453
        graphSub, err := s.graphDB.SubscribeTopology()
2✔
454
        if err != nil {
2✔
455
                return err
×
456
        }
×
457

458
        s.wg.Add(1)
2✔
459
        go func() {
4✔
460
                defer func() {
4✔
461
                        graphSub.Cancel()
2✔
462
                        s.wg.Done()
2✔
463
                }()
2✔
464

465
                for {
4✔
466
                        select {
2✔
467
                        case <-s.quit:
2✔
468
                                return
2✔
469

470
                        case topChange, ok := <-graphSub.TopologyChanges:
2✔
471
                                // If the router is shutting down, then we will
2✔
472
                                // as well.
2✔
473
                                if !ok {
2✔
474
                                        return
×
475
                                }
×
476

477
                                for _, update := range topChange.NodeUpdates {
4✔
478
                                        pubKeyStr := string(
2✔
479
                                                update.IdentityKey.
2✔
480
                                                        SerializeCompressed(),
2✔
481
                                        )
2✔
482

2✔
483
                                        // We only care about updates from
2✔
484
                                        // our persistentPeers.
2✔
485
                                        s.mu.RLock()
2✔
486
                                        _, ok := s.persistentPeers[pubKeyStr]
2✔
487
                                        s.mu.RUnlock()
2✔
488
                                        if !ok {
4✔
489
                                                continue
2✔
490
                                        }
491

492
                                        addrs := make([]*lnwire.NetAddress, 0,
2✔
493
                                                len(update.Addresses))
2✔
494

2✔
495
                                        for _, addr := range update.Addresses {
4✔
496
                                                addrs = append(addrs,
2✔
497
                                                        &lnwire.NetAddress{
2✔
498
                                                                IdentityKey: update.IdentityKey,
2✔
499
                                                                Address:     addr,
2✔
500
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
2✔
501
                                                        },
2✔
502
                                                )
2✔
503
                                        }
2✔
504

505
                                        s.mu.Lock()
2✔
506

2✔
507
                                        // Update the stored addresses for this
2✔
508
                                        // to peer to reflect the new set.
2✔
509
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
2✔
510

2✔
511
                                        // If there are no outstanding
2✔
512
                                        // connection requests for this peer
2✔
513
                                        // then our work is done since we are
2✔
514
                                        // not currently trying to connect to
2✔
515
                                        // them.
2✔
516
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
4✔
517
                                                s.mu.Unlock()
2✔
518
                                                continue
2✔
519
                                        }
520

521
                                        s.mu.Unlock()
2✔
522

2✔
523
                                        s.connectToPersistentPeer(pubKeyStr)
2✔
524
                                }
525
                        }
526
                }
527
        }()
528

529
        return nil
2✔
530
}
531

532
// CustomMessage is a custom message that is received from a peer.
533
type CustomMessage struct {
534
        // Peer is the peer pubkey
535
        Peer [33]byte
536

537
        // Msg is the custom wire message.
538
        Msg *lnwire.Custom
539
}
540

541
// parseAddr parses an address from its string format to a net.Addr.
542
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
2✔
543
        var (
2✔
544
                host string
2✔
545
                port int
2✔
546
        )
2✔
547

2✔
548
        // Split the address into its host and port components.
2✔
549
        h, p, err := net.SplitHostPort(address)
2✔
550
        if err != nil {
2✔
551
                // If a port wasn't specified, we'll assume the address only
×
552
                // contains the host so we'll use the default port.
×
553
                host = address
×
554
                port = defaultPeerPort
×
555
        } else {
2✔
556
                // Otherwise, we'll note both the host and ports.
2✔
557
                host = h
2✔
558
                portNum, err := strconv.Atoi(p)
2✔
559
                if err != nil {
2✔
560
                        return nil, err
×
561
                }
×
562
                port = portNum
2✔
563
        }
564

565
        if tor.IsOnionHost(host) {
2✔
566
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
567
        }
×
568

569
        // If the host is part of a TCP address, we'll use the network
570
        // specific ResolveTCPAddr function in order to resolve these
571
        // addresses over Tor in order to prevent leaking your real IP
572
        // address.
573
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
2✔
574
        return netCfg.ResolveTCPAddr("tcp", hostPort)
2✔
575
}
576

577
// noiseDial is a factory function which creates a connmgr compliant dialing
578
// function by returning a closure which includes the server's identity key.
579
func noiseDial(idKey keychain.SingleKeyECDH,
580
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
2✔
581

2✔
582
        return func(a net.Addr) (net.Conn, error) {
4✔
583
                lnAddr := a.(*lnwire.NetAddress)
2✔
584
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
2✔
585
        }
2✔
586
}
587

588
// newServer creates a new instance of the server which is to listen using the
589
// passed listener address.
590
//
591
//nolint:funlen
592
func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
593
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
594
        nodeKeyDesc *keychain.KeyDescriptor,
595
        chansToRestore walletunlocker.ChannelsToRecover,
596
        chanPredicate chanacceptor.ChannelAcceptor,
597
        torController *tor.Controller, tlsManager *TLSManager,
598
        leaderElector cluster.LeaderElector,
599
        implCfg *ImplementationCfg) (*server, error) {
2✔
600

2✔
601
        var (
2✔
602
                err         error
2✔
603
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
2✔
604

2✔
605
                // We just derived the full descriptor, so we know the public
2✔
606
                // key is set on it.
2✔
607
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
2✔
608
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
2✔
609
                )
2✔
610
        )
2✔
611

2✔
612
        netParams := cfg.ActiveNetParams.Params
2✔
613

2✔
614
        // Initialize the sphinx router.
2✔
615
        replayLog := htlcswitch.NewDecayedLog(
2✔
616
                dbs.DecayedLogDB, cc.ChainNotifier,
2✔
617
        )
2✔
618
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
2✔
619

2✔
620
        // TODO(gijs): remove the memory replay log once lightning-onion
2✔
621
        // supports it.
2✔
622
        sphinxOnionMsg := sphinx.NewRouter(
2✔
623
                nodeKeyECDH, sphinx.NewMemoryReplayLog(),
2✔
624
        )
2✔
625

2✔
626
        writeBufferPool := pool.NewWriteBuffer(
2✔
627
                pool.DefaultWriteBufferGCInterval,
2✔
628
                pool.DefaultWriteBufferExpiryInterval,
2✔
629
        )
2✔
630

2✔
631
        writePool := pool.NewWrite(
2✔
632
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
2✔
633
        )
2✔
634

2✔
635
        readBufferPool := pool.NewReadBuffer(
2✔
636
                pool.DefaultReadBufferGCInterval,
2✔
637
                pool.DefaultReadBufferExpiryInterval,
2✔
638
        )
2✔
639

2✔
640
        readPool := pool.NewRead(
2✔
641
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
2✔
642
        )
2✔
643

2✔
644
        // If the taproot overlay flag is set, but we don't have an aux funding
2✔
645
        // controller, then we'll exit as this is incompatible.
2✔
646
        if cfg.ProtocolOptions.TaprootOverlayChans &&
2✔
647
                implCfg.AuxFundingController.IsNone() {
2✔
648

×
649
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
650
                        "overlay channels are not supported " +
×
651
                        "in a standalone lnd build")
×
652
        }
×
653

654
        //nolint:ll
655
        featureMgr, err := feature.NewManager(feature.Config{
2✔
656
                NoTLVOnion:                   cfg.ProtocolOptions.LegacyOnion(),
2✔
657
                NoStaticRemoteKey:            cfg.ProtocolOptions.NoStaticRemoteKey(),
2✔
658
                NoAnchors:                    cfg.ProtocolOptions.NoAnchorCommitments(),
2✔
659
                NoWumbo:                      !cfg.ProtocolOptions.Wumbo(),
2✔
660
                NoScriptEnforcementLease:     cfg.ProtocolOptions.NoScriptEnforcementLease(),
2✔
661
                NoKeysend:                    !cfg.AcceptKeySend,
2✔
662
                NoOptionScidAlias:            !cfg.ProtocolOptions.ScidAlias(),
2✔
663
                NoZeroConf:                   !cfg.ProtocolOptions.ZeroConf(),
2✔
664
                NoAnySegwit:                  cfg.ProtocolOptions.NoAnySegwit(),
2✔
665
                CustomFeatures:               cfg.ProtocolOptions.CustomFeatures(),
2✔
666
                NoTaprootChans:               !cfg.ProtocolOptions.TaprootChans,
2✔
667
                NoTaprootOverlay:             !cfg.ProtocolOptions.TaprootOverlayChans,
2✔
668
                NoRouteBlinding:              cfg.ProtocolOptions.NoRouteBlinding(),
2✔
669
                NoOnionMessages:              cfg.ProtocolOptions.NoOnionMessages(),
2✔
670
                NoExperimentalAccountability: cfg.ProtocolOptions.NoExpAccountability(),
2✔
671
                NoQuiescence:                 cfg.ProtocolOptions.NoQuiescence(),
2✔
672
                NoRbfCoopClose:               !cfg.ProtocolOptions.RbfCoopClose,
2✔
673
        })
2✔
674
        if err != nil {
2✔
675
                return nil, err
×
676
        }
×
677

678
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
2✔
679
        registryConfig := invoices.RegistryConfig{
2✔
680
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
2✔
681
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
2✔
682
                Clock:                       clock.NewDefaultClock(),
2✔
683
                AcceptKeySend:               cfg.AcceptKeySend,
2✔
684
                AcceptAMP:                   cfg.AcceptAMP,
2✔
685
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
2✔
686
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
2✔
687
                KeysendHoldTime:             cfg.KeysendHoldTime,
2✔
688
                HtlcInterceptor:             invoiceHtlcModifier,
2✔
689
        }
2✔
690

2✔
691
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
2✔
692

2✔
693
        s := &server{
2✔
694
                cfg:            cfg,
2✔
695
                implCfg:        implCfg,
2✔
696
                graphDB:        dbs.GraphDB,
2✔
697
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
2✔
698
                addrSource:     addrSource,
2✔
699
                miscDB:         dbs.ChanStateDB,
2✔
700
                invoicesDB:     dbs.InvoiceDB,
2✔
701
                paymentsDB:     dbs.PaymentsDB,
2✔
702
                cc:             cc,
2✔
703
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
2✔
704
                writePool:      writePool,
2✔
705
                readPool:       readPool,
2✔
706
                chansToRestore: chansToRestore,
2✔
707

2✔
708
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
2✔
709
                        cc.ChainNotifier,
2✔
710
                ),
2✔
711
                channelNotifier: channelnotifier.New(
2✔
712
                        dbs.ChanStateDB.ChannelStateDB(),
2✔
713
                ),
2✔
714

2✔
715
                identityECDH:   nodeKeyECDH,
2✔
716
                identityKeyLoc: nodeKeyDesc.KeyLocator,
2✔
717
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
2✔
718

2✔
719
                listenAddrs: listenAddrs,
2✔
720

2✔
721
                // TODO(roasbeef): derive proper onion key based on rotation
2✔
722
                // schedule
2✔
723
                sphinxPayment:  hop.NewOnionProcessor(sphinxRouter),
2✔
724
                sphinxOnionMsg: sphinxOnionMsg,
2✔
725

2✔
726
                torController: torController,
2✔
727

2✔
728
                persistentPeers:         make(map[string]bool),
2✔
729
                persistentPeersBackoff:  make(map[string]time.Duration),
2✔
730
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
2✔
731
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
2✔
732
                persistentRetryCancels:  make(map[string]chan struct{}),
2✔
733
                peerErrors:              make(map[string]*queue.CircularBuffer),
2✔
734
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
2✔
735
                scheduledPeerConnection: make(map[string]func()),
2✔
736
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
2✔
737

2✔
738
                peersByPub:                make(map[string]*peer.Brontide),
2✔
739
                inboundPeers:              make(map[string]*peer.Brontide),
2✔
740
                outboundPeers:             make(map[string]*peer.Brontide),
2✔
741
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
2✔
742
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
2✔
743

2✔
744
                invoiceHtlcModifier: invoiceHtlcModifier,
2✔
745

2✔
746
                customMessageServer: subscribe.NewServer(),
2✔
747

2✔
748
                onionMessageServer: subscribe.NewServer(),
2✔
749

2✔
750
                actorSystem: actor.NewActorSystem(),
2✔
751

2✔
752
                tlsManager: tlsManager,
2✔
753

2✔
754
                featureMgr: featureMgr,
2✔
755
                quit:       make(chan struct{}),
2✔
756
        }
2✔
757

2✔
758
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
2✔
759
        if err != nil {
2✔
760
                return nil, err
×
761
        }
×
762

763
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
2✔
764
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
2✔
765
                uint32(currentHeight), currentHash, cc.ChainNotifier,
2✔
766
        )
2✔
767
        s.invoices = invoices.NewRegistry(
2✔
768
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
2✔
769
        )
2✔
770

2✔
771
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
2✔
772

2✔
773
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
2✔
774
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
2✔
775

2✔
776
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
4✔
777
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
2✔
778
                if err != nil {
2✔
779
                        return err
×
780
                }
×
781

782
                s.htlcSwitch.UpdateLinkAliases(link)
2✔
783

2✔
784
                return nil
2✔
785
        }
786

787
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
2✔
788
        if err != nil {
2✔
789
                return nil, err
×
790
        }
×
791

792
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
2✔
793
                DB:                   dbs.ChanStateDB,
2✔
794
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
2✔
795
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
2✔
796
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
2✔
797
                LocalChannelClose: func(pubKey []byte,
2✔
798
                        request *htlcswitch.ChanClose) {
4✔
799

2✔
800
                        peer, err := s.FindPeerByPubStr(string(pubKey))
2✔
801
                        if err != nil {
2✔
802
                                srvrLog.Errorf("unable to close channel, peer"+
×
803
                                        " with %v id can't be found: %v",
×
804
                                        pubKey, err,
×
805
                                )
×
806
                                return
×
807
                        }
×
808

809
                        peer.HandleLocalCloseChanReqs(request)
2✔
810
                },
811
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
812
                SwitchPackager:         channeldb.NewSwitchPackager(),
813
                ExtractErrorEncrypter:  s.sphinxPayment.ExtractErrorEncrypter,
814
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
815
                Notifier:               s.cc.ChainNotifier,
816
                HtlcNotifier:           s.htlcNotifier,
817
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
818
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
819
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
820
                AllowCircularRoute:     cfg.AllowCircularRoute,
821
                RejectHTLC:             cfg.RejectHTLC,
822
                Clock:                  clock.NewDefaultClock(),
823
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
824
                MaxFeeExposure:         thresholdMSats,
825
                SignAliasUpdate:        s.signAliasUpdate,
826
                IsAlias:                aliasmgr.IsAlias,
827
        }, uint32(currentHeight))
828
        if err != nil {
2✔
829
                return nil, err
×
830
        }
×
831
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
2✔
832
                &htlcswitch.InterceptableSwitchConfig{
2✔
833
                        Switch:             s.htlcSwitch,
2✔
834
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
2✔
835
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
2✔
836
                        RequireInterceptor: s.cfg.RequireInterceptor,
2✔
837
                        Notifier:           s.cc.ChainNotifier,
2✔
838
                },
2✔
839
        )
2✔
840
        if err != nil {
2✔
841
                return nil, err
×
842
        }
×
843

844
        s.witnessBeacon = newPreimageBeacon(
2✔
845
                dbs.ChanStateDB.NewWitnessCache(),
2✔
846
                s.interceptableSwitch.ForwardPacket,
2✔
847
        )
2✔
848

2✔
849
        chanStatusMgrCfg := &netann.ChanStatusConfig{
2✔
850
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
2✔
851
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
2✔
852
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
2✔
853
                OurPubKey:                nodeKeyDesc.PubKey,
2✔
854
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
2✔
855
                MessageSigner:            s.nodeSigner,
2✔
856
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
2✔
857
                ApplyChannelUpdate:       s.applyChannelUpdate,
2✔
858
                DB:                       s.chanStateDB,
2✔
859
                Graph:                    dbs.GraphDB,
2✔
860
        }
2✔
861

2✔
862
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
2✔
863
        if err != nil {
2✔
864
                return nil, err
×
865
        }
×
866
        s.chanStatusMgr = chanStatusMgr
2✔
867

2✔
868
        // If enabled, use either UPnP or NAT-PMP to automatically configure
2✔
869
        // port forwarding for users behind a NAT.
2✔
870
        if cfg.NAT {
2✔
871
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
872

×
873
                discoveryTimeout := time.Duration(10 * time.Second)
×
874

×
875
                ctx, cancel := context.WithTimeout(
×
876
                        context.Background(), discoveryTimeout,
×
877
                )
×
878
                defer cancel()
×
879
                upnp, err := nat.DiscoverUPnP(ctx)
×
880
                if err == nil {
×
881
                        s.natTraversal = upnp
×
882
                } else {
×
883
                        // If we were not able to discover a UPnP enabled device
×
884
                        // on the local network, we'll fall back to attempting
×
885
                        // to discover a NAT-PMP enabled device.
×
886
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
887
                                "device on the local network: %v", err)
×
888

×
889
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
890
                                "enabled device")
×
891

×
892
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
893
                        if err != nil {
×
894
                                err := fmt.Errorf("unable to discover a "+
×
895
                                        "NAT-PMP enabled device on the local "+
×
896
                                        "network: %v", err)
×
897
                                srvrLog.Error(err)
×
898
                                return nil, err
×
899
                        }
×
900

901
                        s.natTraversal = pmp
×
902
                }
903
        }
904

905
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
2✔
906
        // Set the self node which represents our node in the graph.
2✔
907
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
2✔
908
        if err != nil {
2✔
909
                return nil, err
×
910
        }
×
911

912
        // The router will get access to the payment ID sequencer, such that it
913
        // can generate unique payment IDs.
914
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
2✔
915
        if err != nil {
2✔
916
                return nil, err
×
917
        }
×
918

919
        // Instantiate mission control with config from the sub server.
920
        //
921
        // TODO(joostjager): When we are further in the process of moving to sub
922
        // servers, the mission control instance itself can be moved there too.
923
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
2✔
924

2✔
925
        // We only initialize a probability estimator if there's no custom one.
2✔
926
        var estimator routing.Estimator
2✔
927
        if cfg.Estimator != nil {
2✔
928
                estimator = cfg.Estimator
×
929
        } else {
2✔
930
                switch routingConfig.ProbabilityEstimatorType {
2✔
931
                case routing.AprioriEstimatorName:
2✔
932
                        aCfg := routingConfig.AprioriConfig
2✔
933
                        aprioriConfig := routing.AprioriConfig{
2✔
934
                                AprioriHopProbability: aCfg.HopProbability,
2✔
935
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
2✔
936
                                AprioriWeight:         aCfg.Weight,
2✔
937
                                CapacityFraction:      aCfg.CapacityFraction,
2✔
938
                        }
2✔
939

2✔
940
                        estimator, err = routing.NewAprioriEstimator(
2✔
941
                                aprioriConfig,
2✔
942
                        )
2✔
943
                        if err != nil {
2✔
944
                                return nil, err
×
945
                        }
×
946

947
                case routing.BimodalEstimatorName:
×
948
                        bCfg := routingConfig.BimodalConfig
×
949
                        bimodalConfig := routing.BimodalConfig{
×
950
                                BimodalNodeWeight: bCfg.NodeWeight,
×
951
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
952
                                        bCfg.Scale,
×
953
                                ),
×
954
                                BimodalDecayTime: bCfg.DecayTime,
×
955
                        }
×
956

×
957
                        estimator, err = routing.NewBimodalEstimator(
×
958
                                bimodalConfig,
×
959
                        )
×
960
                        if err != nil {
×
961
                                return nil, err
×
962
                        }
×
963

964
                default:
×
965
                        return nil, fmt.Errorf("unknown estimator type %v",
×
966
                                routingConfig.ProbabilityEstimatorType)
×
967
                }
968
        }
969

970
        mcCfg := &routing.MissionControlConfig{
2✔
971
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
2✔
972
                Estimator:               estimator,
2✔
973
                MaxMcHistory:            routingConfig.MaxMcHistory,
2✔
974
                McFlushInterval:         routingConfig.McFlushInterval,
2✔
975
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
2✔
976
        }
2✔
977

2✔
978
        s.missionController, err = routing.NewMissionController(
2✔
979
                dbs.ChanStateDB, nodePubKey, mcCfg,
2✔
980
        )
2✔
981
        if err != nil {
2✔
982
                return nil, fmt.Errorf("can't create mission control "+
×
983
                        "manager: %w", err)
×
984
        }
×
985
        s.defaultMC, err = s.missionController.GetNamespacedStore(
2✔
986
                routing.DefaultMissionControlNamespace,
2✔
987
        )
2✔
988
        if err != nil {
2✔
989
                return nil, fmt.Errorf("can't create mission control in the "+
×
990
                        "default namespace: %w", err)
×
991
        }
×
992

993
        srvrLog.Debugf("Instantiating payment session source with config: "+
2✔
994
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
2✔
995
                int64(routingConfig.AttemptCost),
2✔
996
                float64(routingConfig.AttemptCostPPM)/10000,
2✔
997
                routingConfig.MinRouteProbability)
2✔
998

2✔
999
        pathFindingConfig := routing.PathFindingConfig{
2✔
1000
                AttemptCost: lnwire.NewMSatFromSatoshis(
2✔
1001
                        routingConfig.AttemptCost,
2✔
1002
                ),
2✔
1003
                AttemptCostPPM: routingConfig.AttemptCostPPM,
2✔
1004
                MinProbability: routingConfig.MinRouteProbability,
2✔
1005
        }
2✔
1006

2✔
1007
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
2✔
1008
        if err != nil {
2✔
1009
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1010
        }
×
1011
        paymentSessionSource := &routing.SessionSource{
2✔
1012
                GraphSessionFactory: dbs.GraphDB,
2✔
1013
                SourceNode:          sourceNode,
2✔
1014
                MissionControl:      s.defaultMC,
2✔
1015
                GetLink:             s.htlcSwitch.GetLinkByShortID,
2✔
1016
                PathFindingConfig:   pathFindingConfig,
2✔
1017
        }
2✔
1018

2✔
1019
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
2✔
1020

2✔
1021
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
2✔
1022
                cfg.Routing.StrictZombiePruning
2✔
1023

2✔
1024
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
2✔
1025
                SelfNode:            nodePubKey,
2✔
1026
                Graph:               dbs.GraphDB,
2✔
1027
                Chain:               cc.ChainIO,
2✔
1028
                ChainView:           cc.ChainView,
2✔
1029
                Notifier:            cc.ChainNotifier,
2✔
1030
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
2✔
1031
                GraphPruneInterval:  time.Hour,
2✔
1032
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
2✔
1033
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
2✔
1034
                StrictZombiePruning: strictPruning,
2✔
1035
                IsAlias:             aliasmgr.IsAlias,
2✔
1036
        })
2✔
1037
        if err != nil {
2✔
1038
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1039
        }
×
1040

1041
        s.chanRouter, err = routing.New(routing.Config{
2✔
1042
                SelfNode:           nodePubKey,
2✔
1043
                RoutingGraph:       dbs.GraphDB,
2✔
1044
                Chain:              cc.ChainIO,
2✔
1045
                Payer:              s.htlcSwitch,
2✔
1046
                Control:            s.controlTower,
2✔
1047
                MissionControl:     s.defaultMC,
2✔
1048
                SessionSource:      paymentSessionSource,
2✔
1049
                GetLink:            s.htlcSwitch.GetLinkByShortID,
2✔
1050
                NextPaymentID:      sequencer.NextID,
2✔
1051
                PathFindingConfig:  pathFindingConfig,
2✔
1052
                Clock:              clock.NewDefaultClock(),
2✔
1053
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
2✔
1054
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
2✔
1055
                TrafficShaper:      implCfg.TrafficShaper,
2✔
1056
        })
2✔
1057
        if err != nil {
2✔
1058
                return nil, fmt.Errorf("can't create router: %w", err)
×
1059
        }
×
1060

1061
        chanSeries := discovery.NewChanSeries(s.graphDB)
2✔
1062
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
2✔
1063
        if err != nil {
2✔
1064
                return nil, err
×
1065
        }
×
1066
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
2✔
1067
        if err != nil {
2✔
1068
                return nil, err
×
1069
        }
×
1070

1071
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
2✔
1072

2✔
1073
        s.authGossiper = discovery.New(discovery.Config{
2✔
1074
                Graph:                 s.graphBuilder,
2✔
1075
                ChainIO:               s.cc.ChainIO,
2✔
1076
                Notifier:              s.cc.ChainNotifier,
2✔
1077
                ChainParams:           s.cfg.ActiveNetParams.Params,
2✔
1078
                Broadcast:             s.BroadcastMessage,
2✔
1079
                ChanSeries:            chanSeries,
2✔
1080
                NotifyWhenOnline:      s.NotifyWhenOnline,
2✔
1081
                NotifyWhenOffline:     s.NotifyWhenOffline,
2✔
1082
                FetchSelfAnnouncement: s.getNodeAnnouncement,
2✔
1083
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
2✔
1084
                        error) {
2✔
1085

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

1120
        accessCfg := &accessManConfig{
2✔
1121
                initAccessPerms: func() (map[string]channeldb.ChanCount,
2✔
1122
                        error) {
4✔
1123

2✔
1124
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
2✔
1125
                        return s.chanStateDB.FetchPermAndTempPeers(
2✔
1126
                                genesisHash[:],
2✔
1127
                        )
2✔
1128
                },
2✔
1129
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1130
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1131
        }
1132

1133
        peerAccessMan, err := newAccessMan(accessCfg)
2✔
1134
        if err != nil {
2✔
1135
                return nil, err
×
1136
        }
×
1137

1138
        s.peerAccessMan = peerAccessMan
2✔
1139

2✔
1140
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
2✔
1141
        //nolint:ll
2✔
1142
        s.localChanMgr = &localchans.Manager{
2✔
1143
                SelfPub:              nodeKeyDesc.PubKey,
2✔
1144
                DefaultRoutingPolicy: cc.RoutingPolicy,
2✔
1145
                ForAllOutgoingChannels: func(ctx context.Context,
2✔
1146
                        cb func(*models.ChannelEdgeInfo,
2✔
1147
                                *models.ChannelEdgePolicy) error,
2✔
1148
                        reset func()) error {
4✔
1149

2✔
1150
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
2✔
1151
                                func(c *models.ChannelEdgeInfo,
2✔
1152
                                        e *models.ChannelEdgePolicy,
2✔
1153
                                        _ *models.ChannelEdgePolicy) error {
4✔
1154

2✔
1155
                                        // NOTE: The invoked callback here may
2✔
1156
                                        // receive a nil channel policy.
2✔
1157
                                        return cb(c, e)
2✔
1158
                                }, reset,
2✔
1159
                        )
1160
                },
1161
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1162
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1163
                FetchChannel:              s.chanStateDB.FetchChannel,
1164
                AddEdge: func(ctx context.Context,
1165
                        edge *models.ChannelEdgeInfo) error {
×
1166

×
1167
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1168
                },
×
1169
        }
1170

1171
        utxnStore, err := contractcourt.NewNurseryStore(
2✔
1172
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
2✔
1173
        )
2✔
1174
        if err != nil {
2✔
1175
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1176
                return nil, err
×
1177
        }
×
1178

1179
        sweeperStore, err := sweep.NewSweeperStore(
2✔
1180
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
2✔
1181
        )
2✔
1182
        if err != nil {
2✔
1183
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1184
                return nil, err
×
1185
        }
×
1186

1187
        aggregator := sweep.NewBudgetAggregator(
2✔
1188
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
2✔
1189
                s.implCfg.AuxSweeper,
2✔
1190
        )
2✔
1191

2✔
1192
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
2✔
1193
                Signer:     cc.Wallet.Cfg.Signer,
2✔
1194
                Wallet:     cc.Wallet,
2✔
1195
                Estimator:  cc.FeeEstimator,
2✔
1196
                Notifier:   cc.ChainNotifier,
2✔
1197
                AuxSweeper: s.implCfg.AuxSweeper,
2✔
1198
        })
2✔
1199

2✔
1200
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
2✔
1201
                FeeEstimator: cc.FeeEstimator,
2✔
1202
                GenSweepScript: newSweepPkScriptGen(
2✔
1203
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
2✔
1204
                ),
2✔
1205
                Signer:               cc.Wallet.Cfg.Signer,
2✔
1206
                Wallet:               newSweeperWallet(cc.Wallet),
2✔
1207
                Mempool:              cc.MempoolNotifier,
2✔
1208
                Notifier:             cc.ChainNotifier,
2✔
1209
                Store:                sweeperStore,
2✔
1210
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
2✔
1211
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
2✔
1212
                Aggregator:           aggregator,
2✔
1213
                Publisher:            s.txPublisher,
2✔
1214
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
2✔
1215
        })
2✔
1216

2✔
1217
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
2✔
1218
                ChainIO:             cc.ChainIO,
2✔
1219
                ConfDepth:           1,
2✔
1220
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
2✔
1221
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
2✔
1222
                Notifier:            cc.ChainNotifier,
2✔
1223
                PublishTransaction:  cc.Wallet.PublishTransaction,
2✔
1224
                Store:               utxnStore,
2✔
1225
                SweepInput:          s.sweeper.SweepInput,
2✔
1226
                Budget:              s.cfg.Sweeper.Budget,
2✔
1227
        })
2✔
1228

2✔
1229
        // Construct a closure that wraps the htlcswitch's CloseLink method.
2✔
1230
        closeLink := func(chanPoint *wire.OutPoint,
2✔
1231
                closureType contractcourt.ChannelCloseType) {
4✔
1232
                // TODO(conner): Properly respect the update and error channels
2✔
1233
                // returned by CloseLink.
2✔
1234

2✔
1235
                // Instruct the switch to close the channel.  Provide no close out
2✔
1236
                // delivery script or target fee per kw because user input is not
2✔
1237
                // available when the remote peer closes the channel.
2✔
1238
                s.htlcSwitch.CloseLink(
2✔
1239
                        context.Background(), chanPoint, closureType, 0, 0, nil,
2✔
1240
                )
2✔
1241
        }
2✔
1242

1243
        // We will use the following channel to reliably hand off contract
1244
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1245
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
2✔
1246

2✔
1247
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
2✔
1248
                &contractcourt.BreachConfig{
2✔
1249
                        CloseLink: closeLink,
2✔
1250
                        DB:        s.chanStateDB,
2✔
1251
                        Estimator: s.cc.FeeEstimator,
2✔
1252
                        GenSweepScript: newSweepPkScriptGen(
2✔
1253
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
2✔
1254
                        ),
2✔
1255
                        Notifier:           cc.ChainNotifier,
2✔
1256
                        PublishTransaction: cc.Wallet.PublishTransaction,
2✔
1257
                        ContractBreaches:   contractBreaches,
2✔
1258
                        Signer:             cc.Wallet.Cfg.Signer,
2✔
1259
                        Store: contractcourt.NewRetributionStore(
2✔
1260
                                dbs.ChanStateDB,
2✔
1261
                        ),
2✔
1262
                        AuxSweeper: s.implCfg.AuxSweeper,
2✔
1263
                },
2✔
1264
        )
2✔
1265

2✔
1266
        //nolint:ll
2✔
1267
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
2✔
1268
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
2✔
1269
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
2✔
1270
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
2✔
1271
                NewSweepAddr: func() ([]byte, error) {
2✔
1272
                        addr, err := newSweepPkScriptGen(
×
1273
                                cc.Wallet, netParams,
×
1274
                        )().Unpack()
×
1275
                        if err != nil {
×
1276
                                return nil, err
×
1277
                        }
×
1278

1279
                        return addr.DeliveryAddress, nil
×
1280
                },
1281
                PublishTx: cc.Wallet.PublishTransaction,
1282
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
2✔
1283
                        for _, msg := range msgs {
4✔
1284
                                err := s.htlcSwitch.ProcessContractResolution(msg)
2✔
1285
                                if err != nil {
2✔
1286
                                        return err
×
1287
                                }
×
1288
                        }
1289
                        return nil
2✔
1290
                },
1291
                IncubateOutputs: func(chanPoint wire.OutPoint,
1292
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1293
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1294
                        broadcastHeight uint32,
1295
                        deadlineHeight fn.Option[int32]) error {
2✔
1296

2✔
1297
                        return s.utxoNursery.IncubateOutputs(
2✔
1298
                                chanPoint, outHtlcRes, inHtlcRes,
2✔
1299
                                broadcastHeight, deadlineHeight,
2✔
1300
                        )
2✔
1301
                },
2✔
1302
                PreimageDB:   s.witnessBeacon,
1303
                Notifier:     cc.ChainNotifier,
1304
                Mempool:      cc.MempoolNotifier,
1305
                Signer:       cc.Wallet.Cfg.Signer,
1306
                FeeEstimator: cc.FeeEstimator,
1307
                ChainIO:      cc.ChainIO,
1308
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
2✔
1309
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1310
                        s.htlcSwitch.RemoveLink(chanID)
2✔
1311
                        return nil
2✔
1312
                },
2✔
1313
                IsOurAddress: cc.Wallet.IsOurAddress,
1314
                ContractBreach: func(chanPoint wire.OutPoint,
1315
                        breachRet *lnwallet.BreachRetribution) error {
2✔
1316

2✔
1317
                        // processACK will handle the BreachArbitrator ACKing
2✔
1318
                        // the event.
2✔
1319
                        finalErr := make(chan error, 1)
2✔
1320
                        processACK := func(brarErr error) {
4✔
1321
                                if brarErr != nil {
2✔
1322
                                        finalErr <- brarErr
×
1323
                                        return
×
1324
                                }
×
1325

1326
                                // If the BreachArbitrator successfully handled
1327
                                // the event, we can signal that the handoff
1328
                                // was successful.
1329
                                finalErr <- nil
2✔
1330
                        }
1331

1332
                        event := &contractcourt.ContractBreachEvent{
2✔
1333
                                ChanPoint:         chanPoint,
2✔
1334
                                ProcessACK:        processACK,
2✔
1335
                                BreachRetribution: breachRet,
2✔
1336
                        }
2✔
1337

2✔
1338
                        // Send the contract breach event to the
2✔
1339
                        // BreachArbitrator.
2✔
1340
                        select {
2✔
1341
                        case contractBreaches <- event:
2✔
1342
                        case <-s.quit:
×
1343
                                return ErrServerShuttingDown
×
1344
                        }
1345

1346
                        // We'll wait for a final error to be available from
1347
                        // the BreachArbitrator.
1348
                        select {
2✔
1349
                        case err := <-finalErr:
2✔
1350
                                return err
2✔
1351
                        case <-s.quit:
×
1352
                                return ErrServerShuttingDown
×
1353
                        }
1354
                },
1355
                DisableChannel: func(chanPoint wire.OutPoint) error {
2✔
1356
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
2✔
1357
                },
2✔
1358
                Sweeper:                       s.sweeper,
1359
                Registry:                      s.invoices,
1360
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1361
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1362
                OnionProcessor:                s.sphinxPayment,
1363
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1364
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1365
                Clock:                         clock.NewDefaultClock(),
1366
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1367
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1368
                HtlcNotifier:                  s.htlcNotifier,
1369
                Budget:                        *s.cfg.Sweeper.Budget,
1370

1371
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1372
                QueryIncomingCircuit: func(
1373
                        circuit models.CircuitKey) *models.CircuitKey {
2✔
1374

2✔
1375
                        // Get the circuit map.
2✔
1376
                        circuits := s.htlcSwitch.CircuitLookup()
2✔
1377

2✔
1378
                        // Lookup the outgoing circuit.
2✔
1379
                        pc := circuits.LookupOpenCircuit(circuit)
2✔
1380
                        if pc == nil {
4✔
1381
                                return nil
2✔
1382
                        }
2✔
1383

1384
                        return &pc.Incoming
2✔
1385
                },
1386
                AuxLeafStore: implCfg.AuxLeafStore,
1387
                AuxSigner:    implCfg.AuxSigner,
1388
                AuxResolver:  implCfg.AuxContractResolver,
1389
                AuxCloser: fn.MapOption(
UNCOV
1390
                        func(c chcl.AuxChanCloser) contractcourt.AuxChanCloser {
×
UNCOV
1391
                                return c
×
UNCOV
1392
                        },
×
1393
                )(implCfg.AuxChanCloser),
1394
                ChannelCloseConfs: s.cfg.Dev.ChannelCloseConfs(),
1395
        }, dbs.ChanStateDB)
1396

1397
        // Select the configuration and funding parameters for Bitcoin.
1398
        chainCfg := cfg.Bitcoin
2✔
1399
        minRemoteDelay := funding.MinBtcRemoteDelay
2✔
1400
        maxRemoteDelay := funding.MaxBtcRemoteDelay
2✔
1401

2✔
1402
        var chanIDSeed [32]byte
2✔
1403
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
2✔
UNCOV
1404
                return nil, err
×
UNCOV
1405
        }
×
1406

1407
        // Wrap the DeleteChannelEdges method so that the funding manager can
1408
        // use it without depending on several layers of indirection.
1409
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
2✔
1410
                *models.ChannelEdgePolicy, error) {
4✔
1411

2✔
1412
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
2✔
1413
                        scid.ToUint64(),
2✔
1414
                )
2✔
1415
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
2✔
1416
                        // This is unlikely but there is a slim chance of this
×
1417
                        // being hit if lnd was killed via SIGKILL and the
×
UNCOV
1418
                        // funding manager was stepping through the delete
×
UNCOV
1419
                        // alias edge logic.
×
UNCOV
1420
                        return nil, nil
×
1421
                } else if err != nil {
2✔
UNCOV
1422
                        return nil, err
×
UNCOV
1423
                }
×
1424

1425
                // Grab our key to find our policy.
1426
                var ourKey [33]byte
2✔
1427
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
2✔
1428

2✔
1429
                var ourPolicy *models.ChannelEdgePolicy
2✔
1430
                if info != nil && info.NodeKey1Bytes == ourKey {
4✔
1431
                        ourPolicy = e1
2✔
1432
                } else {
4✔
1433
                        ourPolicy = e2
2✔
1434
                }
2✔
1435

1436
                if ourPolicy == nil {
2✔
UNCOV
1437
                        // Something is wrong, so return an error.
×
UNCOV
1438
                        return nil, fmt.Errorf("we don't have an edge")
×
UNCOV
1439
                }
×
1440

1441
                err = s.graphDB.DeleteChannelEdges(
2✔
1442
                        false, false, scid.ToUint64(),
2✔
1443
                )
2✔
1444
                return ourPolicy, err
2✔
1445
        }
1446

1447
        // For the reservationTimeout and the zombieSweeperInterval different
1448
        // values are set in case we are in a dev environment so enhance test
1449
        // capacilities.
1450
        reservationTimeout := chanfunding.DefaultReservationTimeout
2✔
1451
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
2✔
1452

2✔
1453
        // Get the development config for funding manager. If we are not in
2✔
1454
        // development mode, this would be nil.
2✔
1455
        var devCfg *funding.DevConfig
2✔
1456
        if lncfg.IsDevBuild() {
4✔
1457
                devCfg = &funding.DevConfig{
2✔
1458
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
2✔
1459
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
2✔
1460
                                GetMaxWaitNumBlocksFundingConf(),
2✔
1461
                }
2✔
1462

2✔
1463
                reservationTimeout = cfg.Dev.GetReservationTimeout()
2✔
1464
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
2✔
1465

2✔
1466
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
2✔
1467
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
2✔
1468
                        devCfg, reservationTimeout, zombieSweeperInterval)
2✔
1469
        }
2✔
1470

1471
        // Attempt to parse the provided upfront-shutdown address (if any).
1472
        script, err := chcl.ParseUpfrontShutdownAddress(
2✔
1473
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
2✔
1474
        )
2✔
1475
        if err != nil {
2✔
UNCOV
1476
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
UNCOV
1477
                        err)
×
UNCOV
1478
        }
×
1479

1480
        //nolint:ll
1481
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
2✔
1482
                Dev:                devCfg,
2✔
1483
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
2✔
1484
                IDKey:              nodeKeyDesc.PubKey,
2✔
1485
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
2✔
1486
                Wallet:             cc.Wallet,
2✔
1487
                PublishTransaction: cc.Wallet.PublishTransaction,
2✔
1488
                UpdateLabel: func(hash chainhash.Hash, label string) error {
4✔
1489
                        return cc.Wallet.LabelTransaction(hash, label, true)
2✔
1490
                },
2✔
1491
                Notifier:     cc.ChainNotifier,
1492
                ChannelDB:    s.chanStateDB,
1493
                FeeEstimator: cc.FeeEstimator,
1494
                SignMessage:  cc.MsgSigner.SignMessage,
1495
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
1496
                        error) {
2✔
1497

2✔
1498
                        return s.genNodeAnnouncement(nil)
2✔
1499
                },
2✔
1500
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1501
                NotifyWhenOnline:     s.NotifyWhenOnline,
1502
                TempChanIDSeed:       chanIDSeed,
1503
                FindChannel:          s.findChannel,
1504
                DefaultRoutingPolicy: cc.RoutingPolicy,
1505
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1506
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1507
                        pushAmt lnwire.MilliSatoshi) uint16 {
2✔
1508
                        // In case the user has explicitly specified
2✔
1509
                        // a default value for the number of
2✔
1510
                        // confirmations, we use it.
2✔
1511
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
2✔
1512
                        if defaultConf != 0 {
4✔
1513
                                return defaultConf
2✔
1514
                        }
2✔
1515

1516
                        // Otherwise, scale the number of confirmations based on
1517
                        // the channel amount and push amount. For large
1518
                        // channels we increase the number of
1519
                        // confirmations we require for the channel to be
1520
                        // considered open. As it is always the
1521
                        // responder that gets to choose value, the
1522
                        // pushAmt is value being pushed to us. This
1523
                        // means we have more to lose in the case this
1524
                        // gets re-orged out, and we will require more
1525
                        // confirmations before we consider it open.
1526
                        return lnwallet.FundingConfsForAmounts(chanAmt, pushAmt)
×
1527
                },
1528
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
2✔
1529
                        // We scale the remote CSV delay (the time the
2✔
1530
                        // remote have to claim funds in case of a unilateral
2✔
1531
                        // close) linearly from minRemoteDelay blocks
2✔
1532
                        // for small channels, to maxRemoteDelay blocks
2✔
1533
                        // for channels of size MaxFundingAmount.
2✔
1534

2✔
1535
                        // In case the user has explicitly specified
2✔
1536
                        // a default value for the remote delay, we
2✔
1537
                        // use it.
2✔
1538
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
2✔
1539
                        if defaultDelay > 0 {
4✔
1540
                                return defaultDelay
2✔
1541
                        }
2✔
1542

1543
                        // If this is a wumbo channel, then we'll require the
1544
                        // max value.
UNCOV
1545
                        if chanAmt > MaxFundingAmount {
×
UNCOV
1546
                                return maxRemoteDelay
×
UNCOV
1547
                        }
×
1548

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

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

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

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

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

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

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

1664
        // Assemble a peer notifier which will provide clients with subscriptions
1665
        // to peer online and offline events.
1666
        s.peerNotifier = peernotifier.New()
2✔
1667

2✔
1668
        // Create a channel event store which monitors all open channels.
2✔
1669
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
2✔
1670
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
4✔
1671
                        return s.channelNotifier.SubscribeChannelEvents()
2✔
1672
                },
2✔
1673
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
2✔
1674
                        return s.peerNotifier.SubscribePeerEvents()
2✔
1675
                },
2✔
1676
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1677
                Clock:           clock.NewDefaultClock(),
1678
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1679
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1680
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1681
        })
1682

1683
        if cfg.WtClient.Active {
4✔
1684
                policy := wtpolicy.DefaultPolicy()
2✔
1685
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
2✔
1686

2✔
1687
                // We expose the sweep fee rate in sat/vbyte, but the tower
2✔
1688
                // protocol operations on sat/kw.
2✔
1689
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
2✔
1690
                        1000 * cfg.WtClient.SweepFeeRate,
2✔
1691
                )
2✔
1692

2✔
1693
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
2✔
1694

2✔
1695
                if err := policy.Validate(); err != nil {
2✔
UNCOV
1696
                        return nil, err
×
UNCOV
1697
                }
×
1698

1699
                // authDial is the wrapper around the btrontide.Dial for the
1700
                // watchtower.
1701
                authDial := func(localKey keychain.SingleKeyECDH,
2✔
1702
                        netAddr *lnwire.NetAddress,
2✔
1703
                        dialer tor.DialFunc) (wtserver.Peer, error) {
4✔
1704

2✔
1705
                        return brontide.Dial(
2✔
1706
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
2✔
1707
                        )
2✔
1708
                }
2✔
1709

1710
                // buildBreachRetribution is a call-back that can be used to
1711
                // query the BreachRetribution info and channel type given a
1712
                // channel ID and commitment height.
1713
                buildBreachRetribution := func(chanID lnwire.ChannelID,
2✔
1714
                        commitHeight uint64) (*lnwallet.BreachRetribution,
2✔
1715
                        channeldb.ChannelType, error) {
4✔
1716

2✔
1717
                        channel, err := s.chanStateDB.FetchChannelByID(
2✔
1718
                                nil, chanID,
2✔
1719
                        )
2✔
1720
                        if err != nil {
2✔
UNCOV
1721
                                return nil, 0, err
×
UNCOV
1722
                        }
×
1723

1724
                        br, err := lnwallet.NewBreachRetribution(
2✔
1725
                                channel, commitHeight, 0, nil,
2✔
1726
                                implCfg.AuxLeafStore,
2✔
1727
                                implCfg.AuxContractResolver,
2✔
1728
                        )
2✔
1729
                        if err != nil {
2✔
UNCOV
1730
                                return nil, 0, err
×
UNCOV
1731
                        }
×
1732

1733
                        return br, channel.ChanType, nil
2✔
1734
                }
1735

1736
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
2✔
1737

2✔
1738
                // Copy the policy for legacy channels and set the blob flag
2✔
1739
                // signalling support for anchor channels.
2✔
1740
                anchorPolicy := policy
2✔
1741
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
2✔
1742

2✔
1743
                // Copy the policy for legacy channels and set the blob flag
2✔
1744
                // signalling support for taproot channels.
2✔
1745
                taprootPolicy := policy
2✔
1746
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
2✔
1747
                        blob.FlagTaprootChannel,
2✔
1748
                )
2✔
1749

2✔
1750
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
2✔
1751
                        FetchClosedChannel:     fetchClosedChannel,
2✔
1752
                        BuildBreachRetribution: buildBreachRetribution,
2✔
1753
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
2✔
1754
                        ChainNotifier:          s.cc.ChainNotifier,
2✔
1755
                        SubscribeChannelEvents: func() (subscribe.Subscription,
2✔
1756
                                error) {
4✔
1757

2✔
1758
                                return s.channelNotifier.
2✔
1759
                                        SubscribeChannelEvents()
2✔
1760
                        },
2✔
1761
                        Signer: cc.Wallet.Cfg.Signer,
1762
                        NewAddress: func() ([]byte, error) {
2✔
1763
                                addr, err := newSweepPkScriptGen(
2✔
1764
                                        cc.Wallet, netParams,
2✔
1765
                                )().Unpack()
2✔
1766
                                if err != nil {
2✔
UNCOV
1767
                                        return nil, err
×
UNCOV
1768
                                }
×
1769

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

1786
        if len(cfg.ExternalHosts) != 0 {
2✔
UNCOV
1787
                advertisedIPs := make(map[string]struct{})
×
UNCOV
1788
                for _, addr := range s.currentNodeAnn.Addresses {
×
UNCOV
1789
                        advertisedIPs[addr.String()] = struct{}{}
×
UNCOV
1790
                }
×
1791

UNCOV
1792
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
UNCOV
1793
                        Hosts:         cfg.ExternalHosts,
×
UNCOV
1794
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
UNCOV
1795
                        LookupHost: func(host string) (net.Addr, error) {
×
UNCOV
1796
                                return lncfg.ParseAddressString(
×
UNCOV
1797
                                        host, strconv.Itoa(defaultPeerPort),
×
1798
                                        cfg.net.ResolveTCPAddr,
×
1799
                                )
×
UNCOV
1800
                        },
×
1801
                        AdvertisedIPs: advertisedIPs,
1802
                        AnnounceNewIPs: netann.IPAnnouncer(
1803
                                func(modifier ...netann.NodeAnnModifier) (
1804
                                        lnwire.NodeAnnouncement1, error) {
×
1805

×
1806
                                        return s.genNodeAnnouncement(
×
UNCOV
1807
                                                nil, modifier...,
×
1808
                                        )
×
1809
                                }),
×
1810
                })
1811
        }
1812

1813
        // Create liveness monitor.
1814
        s.createLivenessMonitor(cfg, cc, leaderElector)
2✔
1815

2✔
1816
        listeners := make([]net.Listener, len(listenAddrs))
2✔
1817
        for i, listenAddr := range listenAddrs {
4✔
1818
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
2✔
1819
                // doesn't need to call the general lndResolveTCP function
2✔
1820
                // since we are resolving a local address.
2✔
1821

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

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

2✔
1853
        // Finally, register the subsystems in blockbeat.
2✔
1854
        s.registerBlockConsumers()
2✔
1855

2✔
1856
        return s, nil
2✔
1857
}
1858

1859
// UpdateRoutingConfig is a callback function to update the routing config
1860
// values in the main cfg.
1861
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
2✔
1862
        routerCfg := s.cfg.SubRPCServers.RouterRPC
2✔
1863

2✔
1864
        switch c := cfg.Estimator.Config().(type) {
2✔
1865
        case routing.AprioriConfig:
2✔
1866
                routerCfg.ProbabilityEstimatorType =
2✔
1867
                        routing.AprioriEstimatorName
2✔
1868

2✔
1869
                targetCfg := routerCfg.AprioriConfig
2✔
1870
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
2✔
1871
                targetCfg.Weight = c.AprioriWeight
2✔
1872
                targetCfg.CapacityFraction = c.CapacityFraction
2✔
1873
                targetCfg.HopProbability = c.AprioriHopProbability
2✔
1874

1875
        case routing.BimodalConfig:
2✔
1876
                routerCfg.ProbabilityEstimatorType =
2✔
1877
                        routing.BimodalEstimatorName
2✔
1878

2✔
1879
                targetCfg := routerCfg.BimodalConfig
2✔
1880
                targetCfg.Scale = int64(c.BimodalScaleMsat)
2✔
1881
                targetCfg.NodeWeight = c.BimodalNodeWeight
2✔
1882
                targetCfg.DecayTime = c.BimodalDecayTime
2✔
1883
        }
1884

1885
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
2✔
1886
}
1887

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

1907
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1908
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1909
// may differ from what is on disk.
1910
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1911
        error) {
2✔
1912

2✔
1913
        data, err := u.DataToSign()
2✔
1914
        if err != nil {
2✔
UNCOV
1915
                return nil, err
×
UNCOV
1916
        }
×
1917

1918
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
2✔
1919
}
1920

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

2✔
1934
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
2✔
1935
        if cfg.Bitcoin.Node == "nochainbackend" {
2✔
UNCOV
1936
                srvrLog.Info("Disabling chain backend checks for " +
×
UNCOV
1937
                        "nochainbackend mode")
×
UNCOV
1938

×
UNCOV
1939
                chainBackendAttempts = 0
×
UNCOV
1940
        }
×
1941

1942
        chainHealthCheck := healthcheck.NewObservation(
2✔
1943
                "chain backend",
2✔
1944
                cc.HealthCheck,
2✔
1945
                cfg.HealthChecks.ChainCheck.Interval,
2✔
1946
                cfg.HealthChecks.ChainCheck.Timeout,
2✔
1947
                cfg.HealthChecks.ChainCheck.Backoff,
2✔
1948
                chainBackendAttempts,
2✔
1949
        )
2✔
1950

2✔
1951
        diskCheck := healthcheck.NewObservation(
2✔
1952
                "disk space",
2✔
1953
                func() error {
2✔
1954
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1955
                                cfg.LndDir,
×
1956
                        )
×
UNCOV
1957
                        if err != nil {
×
UNCOV
1958
                                return err
×
UNCOV
1959
                        }
×
1960

1961
                        // If we have more free space than we require,
1962
                        // we return a nil error.
UNCOV
1963
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
UNCOV
1964
                                return nil
×
UNCOV
1965
                        }
×
1966

UNCOV
1967
                        return fmt.Errorf("require: %v free space, got: %v",
×
UNCOV
1968
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
UNCOV
1969
                                free)
×
1970
                },
1971
                cfg.HealthChecks.DiskCheck.Interval,
1972
                cfg.HealthChecks.DiskCheck.Timeout,
1973
                cfg.HealthChecks.DiskCheck.Backoff,
1974
                cfg.HealthChecks.DiskCheck.Attempts,
1975
        )
1976

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

1991
                        // If the certificate is not outdated, no error needs
1992
                        // to be returned
UNCOV
1993
                        return nil
×
1994
                },
1995
                cfg.HealthChecks.TLSCheck.Interval,
1996
                cfg.HealthChecks.TLSCheck.Timeout,
1997
                cfg.HealthChecks.TLSCheck.Backoff,
1998
                cfg.HealthChecks.TLSCheck.Attempts,
1999
        )
2000

2001
        checks := []*healthcheck.Observation{
2✔
2002
                chainHealthCheck, diskCheck, tlsHealthCheck,
2✔
2003
        }
2✔
2004

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

2027
        // If remote signing is enabled, add the healthcheck for the remote
2028
        // signing RPC interface.
2029
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
4✔
2030
                // Because we have two cascading timeouts here, we need to add
2✔
2031
                // some slack to the "outer" one of them in case the "inner"
2✔
2032
                // returns exactly on time.
2✔
2033
                overhead := time.Millisecond * 10
2✔
2034

2✔
2035
                remoteSignerConnectionCheck := healthcheck.NewObservation(
2✔
2036
                        "remote signer connection",
2✔
2037
                        rpcwallet.HealthCheck(
2✔
2038
                                s.cfg.RemoteSigner,
2✔
2039

2✔
2040
                                // For the health check we might to be even
2✔
2041
                                // stricter than the initial/normal connect, so
2✔
2042
                                // we use the health check timeout here.
2✔
2043
                                cfg.HealthChecks.RemoteSigner.Timeout,
2✔
2044
                        ),
2✔
2045
                        cfg.HealthChecks.RemoteSigner.Interval,
2✔
2046
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
2✔
2047
                        cfg.HealthChecks.RemoteSigner.Backoff,
2✔
2048
                        cfg.HealthChecks.RemoteSigner.Attempts,
2✔
2049
                )
2✔
2050
                checks = append(checks, remoteSignerConnectionCheck)
2✔
2051
        }
2✔
2052

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

×
UNCOV
2071
                                leader, err := leaderElector.IsLeader(
×
UNCOV
2072
                                        timeoutCtx,
×
UNCOV
2073
                                )
×
2074
                                if err != nil {
×
2075
                                        return fmt.Errorf("unable to check if "+
×
2076
                                                "still leader: %v", err)
×
2077
                                }
×
2078

2079
                                if !leader {
×
2080
                                        srvrLog.Debug("Not the current leader")
×
2081
                                        return fmt.Errorf("not the current " +
×
2082
                                                "leader")
×
2083
                                }
×
2084

2085
                                return nil
×
2086
                        },
2087
                        cfg.HealthChecks.LeaderCheck.Interval,
2088
                        cfg.HealthChecks.LeaderCheck.Timeout,
2089
                        cfg.HealthChecks.LeaderCheck.Backoff,
2090
                        cfg.HealthChecks.LeaderCheck.Attempts,
2091
                )
2092

2093
                checks = append(checks, leaderCheck)
×
2094
        }
2095

2096
        // If we have not disabled all of our health checks, we create a
2097
        // liveness monitor with our configured checks.
2098
        s.livenessMonitor = healthcheck.NewMonitor(
2✔
2099
                &healthcheck.Config{
2✔
2100
                        Checks:   checks,
2✔
2101
                        Shutdown: srvrLog.Criticalf,
2✔
2102
                },
2✔
2103
        )
2✔
2104
}
2105

2106
// Started returns true if the server has been started, and false otherwise.
2107
// NOTE: This function is safe for concurrent access.
2108
func (s *server) Started() bool {
2✔
2109
        return atomic.LoadInt32(&s.active) != 0
2✔
2110
}
2✔
2111

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

2118
// add is used to add a cleanup function to be called when
2119
// the run function is executed.
2120
func (c cleaner) add(cleanup func() error) cleaner {
2✔
2121
        return append(c, cleanup)
2✔
2122
}
2✔
2123

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

2133
// Start starts the main daemon server, all requested listeners, and any helper
2134
// goroutines.
2135
// NOTE: This function is safe for concurrent access.
2136
//
2137
//nolint:funlen
2138
func (s *server) Start(ctx context.Context) error {
2✔
2139
        var startErr error
2✔
2140

2✔
2141
        // If one sub system fails to start, the following code ensures that the
2✔
2142
        // previous started ones are stopped. It also ensures a proper wallet
2✔
2143
        // shutdown which is important for releasing its resources (boltdb, etc...)
2✔
2144
        cleanup := cleaner{}
2✔
2145

2✔
2146
        s.start.Do(func() {
4✔
2147
                // Before starting any subsystems, repair any link nodes that
2✔
2148
                // may have been incorrectly pruned due to the race condition
2✔
2149
                // that was fixed in the link node pruning logic. This must
2✔
2150
                // happen before the chain arbitrator and other subsystems load
2✔
2151
                // channels, to ensure the invariant "link node exists iff
2✔
2152
                // channels exist" is maintained.
2✔
2153
                err := s.chanStateDB.RepairLinkNodes(s.cfg.ActiveNetParams.Net)
2✔
2154
                if err != nil {
2✔
UNCOV
2155
                        srvrLog.Errorf("Failed to repair link nodes: %v", err)
×
UNCOV
2156

×
UNCOV
2157
                        startErr = err
×
UNCOV
2158

×
UNCOV
2159
                        return
×
UNCOV
2160
                }
×
2161

2162
                cleanup = cleanup.add(s.customMessageServer.Stop)
2✔
2163
                if err := s.customMessageServer.Start(); err != nil {
2✔
UNCOV
2164
                        startErr = err
×
UNCOV
2165
                        return
×
UNCOV
2166
                }
×
2167

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

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

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

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

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

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

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

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

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

2231
                cleanup = cleanup.add(func() error {
2✔
2232
                        return s.peerNotifier.Stop()
×
2233
                })
×
2234
                if err := s.peerNotifier.Start(); err != nil {
2✔
UNCOV
2235
                        startErr = err
×
UNCOV
2236
                        return
×
2237
                }
×
2238

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

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

2253
                beat, err := s.getStartingBeat()
2✔
2254
                if err != nil {
2✔
UNCOV
2255
                        startErr = err
×
UNCOV
2256
                        return
×
2257
                }
×
2258

2259
                cleanup = cleanup.add(s.txPublisher.Stop)
2✔
2260
                if err := s.txPublisher.Start(beat); err != nil {
2✔
UNCOV
2261
                        startErr = err
×
UNCOV
2262
                        return
×
UNCOV
2263
                }
×
2264

2265
                cleanup = cleanup.add(s.sweeper.Stop)
2✔
2266
                if err := s.sweeper.Start(beat); err != nil {
2✔
UNCOV
2267
                        startErr = err
×
UNCOV
2268
                        return
×
UNCOV
2269
                }
×
2270

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

2277
                cleanup = cleanup.add(s.breachArbitrator.Stop)
2✔
2278
                if err := s.breachArbitrator.Start(); err != nil {
2✔
2279
                        startErr = err
×
UNCOV
2280
                        return
×
UNCOV
2281
                }
×
2282

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

2289
                // htlcSwitch must be started before chainArb since the latter
2290
                // relies on htlcSwitch to deliver resolution message upon
2291
                // start.
2292
                cleanup = cleanup.add(s.htlcSwitch.Stop)
2✔
2293
                if err := s.htlcSwitch.Start(); err != nil {
2✔
UNCOV
2294
                        startErr = err
×
2295
                        return
×
2296
                }
×
2297

2298
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
2✔
2299
                if err := s.interceptableSwitch.Start(); err != nil {
2✔
UNCOV
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303

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

2310
                cleanup = cleanup.add(s.chainArb.Stop)
2✔
2311
                if err := s.chainArb.Start(beat); err != nil {
2✔
2312
                        startErr = err
×
UNCOV
2313
                        return
×
UNCOV
2314
                }
×
2315

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

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

2328
                cleanup = cleanup.add(s.chanRouter.Stop)
2✔
2329
                if err := s.chanRouter.Start(); err != nil {
2✔
2330
                        startErr = err
×
UNCOV
2331
                        return
×
UNCOV
2332
                }
×
2333
                // The authGossiper depends on the chanRouter and therefore
2334
                // should be started after it.
2335
                cleanup = cleanup.add(s.authGossiper.Stop)
2✔
2336
                if err := s.authGossiper.Start(); err != nil {
2✔
UNCOV
2337
                        startErr = err
×
UNCOV
2338
                        return
×
UNCOV
2339
                }
×
2340

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

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

2353
                cleanup = cleanup.add(func() error {
2✔
2354
                        s.sphinxOnionMsg.Stop()
×
2355
                        return nil
×
UNCOV
2356
                })
×
2357
                if err := s.sphinxOnionMsg.Start(); err != nil {
2✔
UNCOV
2358
                        startErr = err
×
2359
                        return
×
2360
                }
×
2361

2362
                // Create the onion message endpoint that handles incoming onion
2363
                // messages for all peers. This is shared across all peer
2364
                // connections and registered with each peer's message router.
2365
                // Skip if onion messaging is disabled via config.
2366
                if !s.cfg.ProtocolOptions.NoOnionMessages() {
4✔
2367
                        resolver := onionmessage.NewGraphNodeResolver(
2✔
2368
                                s.graphDB, s.identityECDH.PubKey(),
2✔
2369
                        )
2✔
2370
                        s.onionEndpoint, err = onionmessage.NewOnionEndpoint(
2✔
2371
                                s.actorSystem.Receptionist(),
2✔
2372
                                s.sphinxOnionMsg,
2✔
2373
                                resolver,
2✔
2374
                                onionmessage.WithMessageServer(
2✔
2375
                                        s.onionMessageServer,
2✔
2376
                                ),
2✔
2377
                        )
2✔
2378
                        if err != nil {
2✔
NEW
2379
                                startErr = fmt.Errorf("unable to create onion "+
×
NEW
2380
                                        "message endpoint: %w", err)
×
NEW
2381
                                return
×
NEW
2382
                        }
×
2383
                }
2384

2385
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
2✔
2386
                if err := s.chanStatusMgr.Start(); err != nil {
2✔
NEW
2387
                        startErr = err
×
NEW
2388
                        return
×
NEW
2389
                }
×
2390

2391
                cleanup = cleanup.add(s.chanEventStore.Stop)
2✔
2392
                if err := s.chanEventStore.Start(); err != nil {
2✔
NEW
2393
                        startErr = err
×
NEW
2394
                        return
×
NEW
2395
                }
×
2396

2397
                cleanup.add(func() error {
2✔
NEW
2398
                        s.missionController.StopStoreTickers()
×
NEW
2399
                        return nil
×
NEW
2400
                })
×
2401
                s.missionController.RunStoreTickers()
2✔
2402

2✔
2403
                // Before we start the connMgr, we'll check to see if we have
2✔
2404
                // any backups to recover. We do this now as we want to ensure
2✔
2405
                // that have all the information we need to handle channel
2✔
2406
                // recovery _before_ we even accept connections from any peers.
2✔
2407
                chanRestorer := &chanDBRestorer{
2✔
2408
                        db:         s.chanStateDB,
2✔
2409
                        secretKeys: s.cc.KeyRing,
2✔
2410
                        chainArb:   s.chainArb,
2✔
2411
                }
2✔
2412
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
2✔
UNCOV
2413
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2414
                                s.chansToRestore.PackedSingleChanBackups,
×
2415
                                s.cc.KeyRing, chanRestorer, s,
×
2416
                        )
×
UNCOV
2417
                        if err != nil {
×
UNCOV
2418
                                startErr = fmt.Errorf("unable to unpack single "+
×
UNCOV
2419
                                        "backups: %v", err)
×
UNCOV
2420
                                return
×
UNCOV
2421
                        }
×
2422
                }
2423
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
4✔
2424
                        _, err := chanbackup.UnpackAndRecoverMulti(
2✔
2425
                                s.chansToRestore.PackedMultiChanBackup,
2✔
2426
                                s.cc.KeyRing, chanRestorer, s,
2✔
2427
                        )
2✔
2428
                        if err != nil {
2✔
2429
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2430
                                        "backup: %v", err)
×
2431
                                return
×
2432
                        }
×
2433
                }
2434

2435
                // chanSubSwapper must be started after the `channelNotifier`
2436
                // because it depends on channel events as a synchronization
2437
                // point.
2438
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
2✔
2439
                if err := s.chanSubSwapper.Start(); err != nil {
2✔
UNCOV
2440
                        startErr = err
×
UNCOV
2441
                        return
×
UNCOV
2442
                }
×
2443

2444
                if s.torController != nil {
2✔
2445
                        cleanup = cleanup.add(s.torController.Stop)
×
2446
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2447
                                startErr = err
×
2448
                                return
×
UNCOV
2449
                        }
×
2450
                }
2451

2452
                if s.natTraversal != nil {
2✔
UNCOV
2453
                        s.wg.Add(1)
×
UNCOV
2454
                        go s.watchExternalIP()
×
UNCOV
2455
                }
×
2456

2457
                // Start connmgr last to prevent connections before init.
2458
                cleanup = cleanup.add(func() error {
2✔
UNCOV
2459
                        s.connMgr.Stop()
×
UNCOV
2460
                        return nil
×
2461
                })
×
2462

2463
                // RESOLVE: s.connMgr.Start() is called here, but
2464
                // brontide.NewListener() is called in newServer. This means
2465
                // that we are actually listening and partially accepting
2466
                // inbound connections even before the connMgr starts.
2467
                //
2468
                // TODO(yy): move the log into the connMgr's `Start` method.
2469
                srvrLog.Info("connMgr starting...")
2✔
2470
                s.connMgr.Start()
2✔
2471
                srvrLog.Debug("connMgr started")
2✔
2472

2✔
2473
                // If peers are specified as a config option, we'll add those
2✔
2474
                // peers first.
2✔
2475
                for _, peerAddrCfg := range s.cfg.AddPeers {
4✔
2476
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
2✔
2477
                                peerAddrCfg,
2✔
2478
                        )
2✔
2479
                        if err != nil {
2✔
UNCOV
2480
                                startErr = fmt.Errorf("unable to parse peer "+
×
UNCOV
2481
                                        "pubkey from config: %v", err)
×
UNCOV
2482
                                return
×
UNCOV
2483
                        }
×
2484
                        addr, err := parseAddr(parsedHost, s.cfg.net)
2✔
2485
                        if err != nil {
2✔
UNCOV
2486
                                startErr = fmt.Errorf("unable to parse peer "+
×
UNCOV
2487
                                        "address provided as a config option: "+
×
UNCOV
2488
                                        "%v", err)
×
UNCOV
2489
                                return
×
UNCOV
2490
                        }
×
2491

2492
                        peerAddr := &lnwire.NetAddress{
2✔
2493
                                IdentityKey: parsedPubkey,
2✔
2494
                                Address:     addr,
2✔
2495
                                ChainNet:    s.cfg.ActiveNetParams.Net,
2✔
2496
                        }
2✔
2497

2✔
2498
                        err = s.ConnectToPeer(
2✔
2499
                                peerAddr, true,
2✔
2500
                                s.cfg.ConnectionTimeout,
2✔
2501
                        )
2✔
2502
                        if err != nil {
2✔
2503
                                startErr = fmt.Errorf("unable to connect to "+
×
2504
                                        "peer address provided as a config "+
×
2505
                                        "option: %v", err)
×
2506
                                return
×
UNCOV
2507
                        }
×
2508
                }
2509

2510
                // Subscribe to NodeAnnouncements that advertise new addresses
2511
                // our persistent peers.
2512
                if err := s.updatePersistentPeerAddrs(); err != nil {
2✔
UNCOV
2513
                        srvrLog.Errorf("Failed to update persistent peer "+
×
UNCOV
2514
                                "addr: %v", err)
×
UNCOV
2515

×
UNCOV
2516
                        startErr = err
×
UNCOV
2517
                        return
×
UNCOV
2518
                }
×
2519

2520
                // With all the relevant sub-systems started, we'll now attempt
2521
                // to establish persistent connections to our direct channel
2522
                // collaborators within the network. Before doing so however,
2523
                // we'll prune our set of link nodes to ensure we don't
2524
                // reconnect to any nodes we no longer have open channels with.
2525
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
2✔
UNCOV
2526
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
UNCOV
2527

×
UNCOV
2528
                        startErr = err
×
2529
                        return
×
2530
                }
×
2531

2532
                if err := s.establishPersistentConnections(ctx); err != nil {
2✔
2533
                        srvrLog.Errorf("Failed to establish persistent "+
×
2534
                                "connections: %v", err)
×
UNCOV
2535
                }
×
2536

2537
                // setSeedList is a helper function that turns multiple DNS seed
2538
                // server tuples from the command line or config file into the
2539
                // data structure we need and does a basic formal sanity check
2540
                // in the process.
2541
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
2✔
2542
                        if len(tuples) == 0 {
×
2543
                                return
×
2544
                        }
×
2545

2546
                        result := make([][2]string, len(tuples))
×
UNCOV
2547
                        for idx, tuple := range tuples {
×
UNCOV
2548
                                tuple = strings.TrimSpace(tuple)
×
2549
                                if len(tuple) == 0 {
×
2550
                                        return
×
2551
                                }
×
2552

UNCOV
2553
                                servers := strings.Split(tuple, ",")
×
UNCOV
2554
                                if len(servers) > 2 || len(servers) == 0 {
×
UNCOV
2555
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
UNCOV
2556
                                                "seed tuple: %v", servers)
×
UNCOV
2557
                                        return
×
2558
                                }
×
2559

2560
                                copy(result[idx][:], servers)
×
2561
                        }
2562

2563
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2564
                }
2565

2566
                // Let users overwrite the DNS seed nodes. We only allow them
2567
                // for bitcoin mainnet/testnet/signet.
2568
                if s.cfg.Bitcoin.MainNet {
2✔
2569
                        setSeedList(
×
2570
                                s.cfg.Bitcoin.DNSSeeds,
×
2571
                                chainreg.BitcoinMainnetGenesis,
×
2572
                        )
×
2573
                }
×
2574
                if s.cfg.Bitcoin.TestNet3 {
2✔
UNCOV
2575
                        setSeedList(
×
2576
                                s.cfg.Bitcoin.DNSSeeds,
×
UNCOV
2577
                                chainreg.BitcoinTestnetGenesis,
×
UNCOV
2578
                        )
×
2579
                }
×
2580
                if s.cfg.Bitcoin.TestNet4 {
2✔
UNCOV
2581
                        setSeedList(
×
UNCOV
2582
                                s.cfg.Bitcoin.DNSSeeds,
×
UNCOV
2583
                                chainreg.BitcoinTestnet4Genesis,
×
UNCOV
2584
                        )
×
2585
                }
×
2586
                if s.cfg.Bitcoin.SigNet {
2✔
2587
                        setSeedList(
×
2588
                                s.cfg.Bitcoin.DNSSeeds,
×
2589
                                chainreg.BitcoinSignetGenesis,
×
UNCOV
2590
                        )
×
2591
                }
×
2592

2593
                // If network bootstrapping hasn't been disabled, then we'll
2594
                // configure the set of active bootstrappers, and launch a
2595
                // dedicated goroutine to maintain a set of persistent
2596
                // connections.
2597
                if !s.cfg.NoNetBootstrap {
4✔
2598
                        bootstrappers, err := initNetworkBootstrappers(s)
2✔
2599
                        if err != nil {
2✔
2600
                                startErr = err
×
2601
                                return
×
UNCOV
2602
                        }
×
2603

2604
                        s.wg.Add(1)
2✔
2605
                        go s.peerBootstrapper(
2✔
2606
                                ctx, defaultMinPeers, bootstrappers,
2✔
2607
                        )
2✔
2608
                } else {
2✔
2609
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
2✔
2610
                }
2✔
2611

2612
                // Start the blockbeat after all other subsystems have been
2613
                // started so they are ready to receive new blocks.
2614
                cleanup = cleanup.add(func() error {
2✔
UNCOV
2615
                        s.blockbeatDispatcher.Stop()
×
2616
                        return nil
×
2617
                })
×
2618
                if err := s.blockbeatDispatcher.Start(); err != nil {
2✔
UNCOV
2619
                        startErr = err
×
UNCOV
2620
                        return
×
UNCOV
2621
                }
×
2622

2623
                // Set the active flag now that we've completed the full
2624
                // startup.
2625
                atomic.StoreInt32(&s.active, 1)
2✔
2626
        })
2627

2628
        if startErr != nil {
2✔
UNCOV
2629
                cleanup.run()
×
UNCOV
2630
        }
×
2631
        return startErr
2✔
2632
}
2633

2634
// Stop gracefully shutsdown the main daemon server. This function will signal
2635
// any active goroutines, or helper objects to exit, then blocks until they've
2636
// all successfully exited. Additionally, any/all listeners are closed.
2637
// NOTE: This function is safe for concurrent access.
2638
func (s *server) Stop() error {
2✔
2639
        s.stop.Do(func() {
4✔
2640
                atomic.StoreInt32(&s.stopping, 1)
2✔
2641

2✔
2642
                ctx := context.Background()
2✔
2643

2✔
2644
                close(s.quit)
2✔
2645

2✔
2646
                // Shutdown connMgr first to prevent conns during shutdown.
2✔
2647
                s.connMgr.Stop()
2✔
2648

2✔
2649
                // Stop dispatching blocks to other systems immediately.
2✔
2650
                s.blockbeatDispatcher.Stop()
2✔
2651

2✔
2652
                // Shutdown the onion router for onion messaging.
2✔
2653
                s.sphinxOnionMsg.Stop()
2✔
2654

2✔
2655
                // Shutdown the actor system to stop all actors.
2✔
2656
                if err := s.actorSystem.Shutdown(); err != nil {
2✔
UNCOV
2657
                        srvrLog.Warnf("failed to stop actorSystem: %v", err)
×
UNCOV
2658
                }
×
2659

2660
                // Shutdown the wallet, funding manager, and the rpc server.
2661
                if err := s.chanStatusMgr.Stop(); err != nil {
2✔
UNCOV
2662
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
UNCOV
2663
                }
×
2664
                if err := s.htlcSwitch.Stop(); err != nil {
2✔
UNCOV
2665
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
UNCOV
2666
                }
×
2667
                if err := s.sphinxPayment.Stop(); err != nil {
2✔
NEW
2668
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
NEW
2669
                }
×
2670
                if err := s.invoices.Stop(); err != nil {
2✔
NEW
2671
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
NEW
2672
                }
×
2673
                if err := s.interceptableSwitch.Stop(); err != nil {
2✔
NEW
2674
                        srvrLog.Warnf("failed to stop interceptable "+
×
NEW
2675
                                "switch: %v", err)
×
UNCOV
2676
                }
×
2677
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
2✔
2678
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2679
                                "modifier: %v", err)
×
UNCOV
2680
                }
×
2681
                if err := s.chanRouter.Stop(); err != nil {
2✔
2682
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
NEW
2683
                }
×
2684
                if err := s.graphBuilder.Stop(); err != nil {
2✔
2685
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
UNCOV
2686
                }
×
2687
                if err := s.graphDB.Stop(); err != nil {
2✔
2688
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
UNCOV
2689
                }
×
2690
                if err := s.chainArb.Stop(); err != nil {
2✔
2691
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2692
                }
×
2693
                if err := s.fundingMgr.Stop(); err != nil {
2✔
2694
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2695
                }
×
2696
                if err := s.breachArbitrator.Stop(); err != nil {
2✔
UNCOV
2697
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2698
                                err)
×
2699
                }
×
2700
                if err := s.utxoNursery.Stop(); err != nil {
2✔
2701
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2702
                }
×
2703
                if err := s.authGossiper.Stop(); err != nil {
2✔
2704
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2705
                }
×
2706
                if err := s.sweeper.Stop(); err != nil {
2✔
2707
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2708
                }
×
2709
                if err := s.txPublisher.Stop(); err != nil {
2✔
2710
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2711
                }
×
2712
                if err := s.channelNotifier.Stop(); err != nil {
2✔
2713
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2714
                }
×
2715
                if err := s.peerNotifier.Stop(); err != nil {
2✔
UNCOV
2716
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2717
                }
×
2718
                if err := s.htlcNotifier.Stop(); err != nil {
2✔
UNCOV
2719
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2720
                }
×
2721

2722
                // Update channel.backup file. Make sure to do it before
2723
                // stopping chanSubSwapper.
2724
                singles, err := chanbackup.FetchStaticChanBackups(
2✔
2725
                        ctx, s.chanStateDB, s.addrSource,
2✔
2726
                )
2✔
2727
                if err != nil {
2✔
UNCOV
2728
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2729
                                err)
×
2730
                } else {
2✔
2731
                        err := s.chanSubSwapper.ManualUpdate(singles)
2✔
2732
                        if err != nil {
4✔
2733
                                srvrLog.Warnf("Manual update of channel "+
2✔
2734
                                        "backup failed: %v", err)
2✔
2735
                        }
2✔
2736
                }
2737

2738
                if err := s.chanSubSwapper.Stop(); err != nil {
2✔
UNCOV
2739
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
UNCOV
2740
                }
×
2741
                if err := s.cc.ChainNotifier.Stop(); err != nil {
2✔
UNCOV
2742
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
UNCOV
2743
                }
×
2744
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
2✔
2745
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
UNCOV
2746
                                err)
×
UNCOV
2747
                }
×
2748
                if err := s.chanEventStore.Stop(); err != nil {
2✔
UNCOV
2749
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
UNCOV
2750
                                err)
×
UNCOV
2751
                }
×
2752
                s.missionController.StopStoreTickers()
2✔
2753

2✔
2754
                // Disconnect from each active peers to ensure that
2✔
2755
                // peerTerminationWatchers signal completion to each peer.
2✔
2756
                for _, peer := range s.Peers() {
4✔
2757
                        err := s.DisconnectPeer(peer.IdentityKey())
2✔
2758
                        if err != nil {
2✔
2759
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
UNCOV
2760
                                        "received error: %v", peer.IdentityKey(),
×
2761
                                        err,
×
2762
                                )
×
2763
                        }
×
2764
                }
2765

2766
                // Now that all connections have been torn down, stop the tower
2767
                // client which will reliably flush all queued states to the
2768
                // tower. If this is halted for any reason, the force quit timer
2769
                // will kick in and abort to allow this method to return.
2770
                if s.towerClientMgr != nil {
4✔
2771
                        if err := s.towerClientMgr.Stop(); err != nil {
2✔
UNCOV
2772
                                srvrLog.Warnf("Unable to shut down tower "+
×
UNCOV
2773
                                        "client manager: %v", err)
×
UNCOV
2774
                        }
×
2775
                }
2776

2777
                if s.hostAnn != nil {
2✔
2778
                        if err := s.hostAnn.Stop(); err != nil {
×
2779
                                srvrLog.Warnf("unable to shut down host "+
×
UNCOV
2780
                                        "annoucner: %v", err)
×
UNCOV
2781
                        }
×
2782
                }
2783

2784
                if s.livenessMonitor != nil {
4✔
2785
                        if err := s.livenessMonitor.Stop(); err != nil {
2✔
UNCOV
2786
                                srvrLog.Warnf("unable to shutdown liveness "+
×
UNCOV
2787
                                        "monitor: %v", err)
×
2788
                        }
×
2789
                }
2790

2791
                // Wait for all lingering goroutines to quit.
2792
                srvrLog.Debug("Waiting for server to shutdown...")
2✔
2793
                s.wg.Wait()
2✔
2794

2✔
2795
                srvrLog.Debug("Stopping buffer pools...")
2✔
2796
                s.sigPool.Stop()
2✔
2797
                s.writePool.Stop()
2✔
2798
                s.readPool.Stop()
2✔
2799
        })
2800

2801
        return nil
2✔
2802
}
2803

2804
// Stopped returns true if the server has been instructed to shutdown.
2805
// NOTE: This function is safe for concurrent access.
2806
func (s *server) Stopped() bool {
2✔
2807
        return atomic.LoadInt32(&s.stopping) != 0
2✔
2808
}
2✔
2809

2810
// configurePortForwarding attempts to set up port forwarding for the different
2811
// ports that the server will be listening on.
2812
//
2813
// NOTE: This should only be used when using some kind of NAT traversal to
2814
// automatically set up forwarding rules.
UNCOV
2815
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
UNCOV
2816
        ip, err := s.natTraversal.ExternalIP()
×
UNCOV
2817
        if err != nil {
×
UNCOV
2818
                return nil, err
×
UNCOV
2819
        }
×
UNCOV
2820
        s.lastDetectedIP = ip
×
UNCOV
2821

×
UNCOV
2822
        externalIPs := make([]string, 0, len(ports))
×
UNCOV
2823
        for _, port := range ports {
×
UNCOV
2824
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
UNCOV
2825
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
UNCOV
2826
                        continue
×
2827
                }
2828

UNCOV
2829
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
UNCOV
2830
                externalIPs = append(externalIPs, hostIP)
×
2831
        }
2832

2833
        return externalIPs, nil
×
2834
}
2835

2836
// removePortForwarding attempts to clear the forwarding rules for the different
2837
// ports the server is currently listening on.
2838
//
2839
// NOTE: This should only be used when using some kind of NAT traversal to
2840
// automatically set up forwarding rules.
2841
func (s *server) removePortForwarding() {
×
2842
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
UNCOV
2843
        for _, port := range forwardedPorts {
×
UNCOV
2844
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2845
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2846
                                "port %d: %v", port, err)
×
UNCOV
2847
                }
×
2848
        }
2849
}
2850

2851
// watchExternalIP continuously checks for an updated external IP address every
2852
// 15 minutes. Once a new IP address has been detected, it will automatically
2853
// handle port forwarding rules and send updated node announcements to the
2854
// currently connected peers.
2855
//
2856
// NOTE: This MUST be run as a goroutine.
2857
func (s *server) watchExternalIP() {
×
2858
        defer s.wg.Done()
×
2859

×
2860
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2861
        // up by the server.
×
2862
        defer s.removePortForwarding()
×
2863

×
UNCOV
2864
        // Keep track of the external IPs set by the user to avoid replacing
×
UNCOV
2865
        // them when detecting a new IP.
×
UNCOV
2866
        ipsSetByUser := make(map[string]struct{})
×
UNCOV
2867
        for _, ip := range s.cfg.ExternalIPs {
×
UNCOV
2868
                ipsSetByUser[ip.String()] = struct{}{}
×
UNCOV
2869
        }
×
2870

UNCOV
2871
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
UNCOV
2872

×
2873
        ticker := time.NewTicker(15 * time.Minute)
×
2874
        defer ticker.Stop()
×
2875
out:
×
2876
        for {
×
2877
                select {
×
2878
                case <-ticker.C:
×
2879
                        // We'll start off by making sure a new IP address has
×
2880
                        // been detected.
×
2881
                        ip, err := s.natTraversal.ExternalIP()
×
2882
                        if err != nil {
×
2883
                                srvrLog.Debugf("Unable to retrieve the "+
×
2884
                                        "external IP address: %v", err)
×
2885
                                continue
×
2886
                        }
2887

2888
                        // Periodically renew the NAT port forwarding.
2889
                        for _, port := range forwardedPorts {
×
2890
                                err := s.natTraversal.AddPortMapping(port)
×
2891
                                if err != nil {
×
2892
                                        srvrLog.Warnf("Unable to automatically "+
×
2893
                                                "re-create port forwarding using %s: %v",
×
2894
                                                s.natTraversal.Name(), err)
×
2895
                                } else {
×
2896
                                        srvrLog.Debugf("Automatically re-created "+
×
2897
                                                "forwarding for port %d using %s to "+
×
2898
                                                "advertise external IP",
×
2899
                                                port, s.natTraversal.Name())
×
2900
                                }
×
2901
                        }
2902

UNCOV
2903
                        if ip.Equal(s.lastDetectedIP) {
×
UNCOV
2904
                                continue
×
2905
                        }
2906

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

×
2909
                        // Next, we'll craft the new addresses that will be
×
2910
                        // included in the new node announcement and advertised
×
2911
                        // to the network. Each address will consist of the new
×
2912
                        // IP detected and one of the currently advertised
×
2913
                        // ports.
×
2914
                        var newAddrs []net.Addr
×
2915
                        for _, port := range forwardedPorts {
×
2916
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
UNCOV
2917
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
UNCOV
2918
                                if err != nil {
×
2919
                                        srvrLog.Debugf("Unable to resolve "+
×
2920
                                                "host %v: %v", addr, err)
×
UNCOV
2921
                                        continue
×
2922
                                }
2923

2924
                                newAddrs = append(newAddrs, addr)
×
2925
                        }
2926

2927
                        // Skip the update if we weren't able to resolve any of
2928
                        // the new addresses.
2929
                        if len(newAddrs) == 0 {
×
2930
                                srvrLog.Debug("Skipping node announcement " +
×
2931
                                        "update due to not being able to " +
×
2932
                                        "resolve any new addresses")
×
2933
                                continue
×
2934
                        }
2935

2936
                        // Now, we'll need to update the addresses in our node's
2937
                        // announcement in order to propagate the update
2938
                        // throughout the network. We'll only include addresses
2939
                        // that have a different IP from the previous one, as
2940
                        // the previous IP is no longer valid.
UNCOV
2941
                        currentNodeAnn := s.getNodeAnnouncement()
×
UNCOV
2942

×
UNCOV
2943
                        for _, addr := range currentNodeAnn.Addresses {
×
UNCOV
2944
                                host, _, err := net.SplitHostPort(addr.String())
×
2945
                                if err != nil {
×
2946
                                        srvrLog.Debugf("Unable to determine "+
×
2947
                                                "host from address %v: %v",
×
2948
                                                addr, err)
×
2949
                                        continue
×
2950
                                }
2951

2952
                                // We'll also make sure to include external IPs
2953
                                // set manually by the user.
UNCOV
2954
                                _, setByUser := ipsSetByUser[addr.String()]
×
UNCOV
2955
                                if setByUser || host != s.lastDetectedIP.String() {
×
UNCOV
2956
                                        newAddrs = append(newAddrs, addr)
×
2957
                                }
×
2958
                        }
2959

2960
                        // Then, we'll generate a new timestamped node
2961
                        // announcement with the updated addresses and broadcast
2962
                        // it to our peers.
2963
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2964
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2965
                        )
×
UNCOV
2966
                        if err != nil {
×
UNCOV
2967
                                srvrLog.Debugf("Unable to generate new node "+
×
UNCOV
2968
                                        "announcement: %v", err)
×
UNCOV
2969
                                continue
×
2970
                        }
2971

2972
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2973
                        if err != nil {
×
UNCOV
2974
                                srvrLog.Debugf("Unable to broadcast new node "+
×
UNCOV
2975
                                        "announcement to peers: %v", err)
×
UNCOV
2976
                                continue
×
2977
                        }
2978

2979
                        // Finally, update the last IP seen to the current one.
2980
                        s.lastDetectedIP = ip
×
2981
                case <-s.quit:
×
2982
                        break out
×
2983
                }
2984
        }
2985
}
2986

2987
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2988
// based on the server, and currently active bootstrap mechanisms as defined
2989
// within the current configuration.
2990
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
2✔
2991
        srvrLog.Infof("Initializing peer network bootstrappers!")
2✔
2992

2✔
2993
        var bootStrappers []discovery.NetworkPeerBootstrapper
2✔
2994

2✔
2995
        // First, we'll create an instance of the ChannelGraphBootstrapper as
2✔
2996
        // this can be used by default if we've already partially seeded the
2✔
2997
        // network.
2✔
2998
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
2✔
2999
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
2✔
3000
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
2✔
3001
        )
2✔
3002
        if err != nil {
2✔
UNCOV
3003
                return nil, err
×
UNCOV
3004
        }
×
3005
        bootStrappers = append(bootStrappers, graphBootstrapper)
2✔
3006

2✔
3007
        // If this isn't using simnet or regtest mode, then one of our
2✔
3008
        // additional bootstrapping sources will be the set of running DNS
2✔
3009
        // seeds.
2✔
3010
        if !s.cfg.Bitcoin.IsLocalNetwork() {
2✔
UNCOV
3011
                //nolint:ll
×
UNCOV
3012
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
UNCOV
3013

×
UNCOV
3014
                // If we have a set of DNS seeds for this chain, then we'll add
×
UNCOV
3015
                // it as an additional bootstrapping source.
×
UNCOV
3016
                if ok {
×
UNCOV
3017
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
UNCOV
3018
                                "seeds: %v", dnsSeeds)
×
3019

×
3020
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
UNCOV
3021
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
3022
                        )
×
UNCOV
3023
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
UNCOV
3024
                }
×
3025
        }
3026

3027
        return bootStrappers, nil
2✔
3028
}
3029

3030
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3031
// needs to ignore, which is made of three parts,
3032
//   - the node itself needs to be skipped as it doesn't make sense to connect
3033
//     to itself.
3034
//   - the peers that already have connections with, as in s.peersByPub.
3035
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3036
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
2✔
3037
        s.mu.RLock()
2✔
3038
        defer s.mu.RUnlock()
2✔
3039

2✔
3040
        ignore := make(map[autopilot.NodeID]struct{})
2✔
3041

2✔
3042
        // We should ignore ourselves from bootstrapping.
2✔
3043
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
2✔
3044
        ignore[selfKey] = struct{}{}
2✔
3045

2✔
3046
        // Ignore all connected peers.
2✔
3047
        for _, peer := range s.peersByPub {
2✔
UNCOV
3048
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
UNCOV
3049
                ignore[nID] = struct{}{}
×
UNCOV
3050
        }
×
3051

3052
        // Ignore all persistent peers as they have a dedicated reconnecting
3053
        // process.
3054
        for pubKeyStr := range s.persistentPeers {
2✔
UNCOV
3055
                var nID autopilot.NodeID
×
UNCOV
3056
                copy(nID[:], []byte(pubKeyStr))
×
UNCOV
3057
                ignore[nID] = struct{}{}
×
UNCOV
3058
        }
×
3059

3060
        return ignore
2✔
3061
}
3062

3063
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3064
// and maintain a target minimum number of outbound connections. With this
3065
// invariant, we ensure that our node is connected to a diverse set of peers
3066
// and that nodes newly joining the network receive an up to date network view
3067
// as soon as possible.
3068
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3069
        bootstrappers []discovery.NetworkPeerBootstrapper) {
2✔
3070

2✔
3071
        defer s.wg.Done()
2✔
3072

2✔
3073
        // Before we continue, init the ignore peers map.
2✔
3074
        ignoreList := s.createBootstrapIgnorePeers()
2✔
3075

2✔
3076
        // We'll start off by aggressively attempting connections to peers in
2✔
3077
        // order to be a part of the network as soon as possible.
2✔
3078
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
2✔
3079

2✔
3080
        // Once done, we'll attempt to maintain our target minimum number of
2✔
3081
        // peers.
2✔
3082
        //
2✔
3083
        // We'll use a 15 second backoff, and double the time every time an
2✔
3084
        // epoch fails up to a ceiling.
2✔
3085
        backOff := time.Second * 15
2✔
3086

2✔
3087
        // We'll create a new ticker to wake us up every 15 seconds so we can
2✔
3088
        // see if we've reached our minimum number of peers.
2✔
3089
        sampleTicker := time.NewTicker(backOff)
2✔
3090
        defer sampleTicker.Stop()
2✔
3091

2✔
3092
        // We'll use the number of attempts and errors to determine if we need
2✔
3093
        // to increase the time between discovery epochs.
2✔
3094
        var epochErrors uint32 // To be used atomically.
2✔
3095
        var epochAttempts uint32
2✔
3096

2✔
3097
        for {
4✔
3098
                select {
2✔
3099
                // The ticker has just woken us up, so we'll need to check if
3100
                // we need to attempt to connect our to any more peers.
UNCOV
3101
                case <-sampleTicker.C:
×
UNCOV
3102
                        // Obtain the current number of peers, so we can gauge
×
UNCOV
3103
                        // if we need to sample more peers or not.
×
UNCOV
3104
                        s.mu.RLock()
×
UNCOV
3105
                        numActivePeers := uint32(len(s.peersByPub))
×
UNCOV
3106
                        s.mu.RUnlock()
×
UNCOV
3107

×
UNCOV
3108
                        // If we have enough peers, then we can loop back
×
UNCOV
3109
                        // around to the next round as we're done here.
×
UNCOV
3110
                        if numActivePeers >= numTargetPeers {
×
UNCOV
3111
                                continue
×
3112
                        }
3113

3114
                        // If all of our attempts failed during this last back
3115
                        // off period, then will increase our backoff to 5
3116
                        // minute ceiling to avoid an excessive number of
3117
                        // queries
3118
                        //
3119
                        // TODO(roasbeef): add reverse policy too?
3120

3121
                        if epochAttempts > 0 &&
×
3122
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3123

×
3124
                                sampleTicker.Stop()
×
3125

×
3126
                                backOff *= 2
×
3127
                                if backOff > bootstrapBackOffCeiling {
×
UNCOV
3128
                                        backOff = bootstrapBackOffCeiling
×
UNCOV
3129
                                }
×
3130

UNCOV
3131
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
UNCOV
3132
                                        "%v", backOff)
×
UNCOV
3133
                                sampleTicker = time.NewTicker(backOff)
×
UNCOV
3134
                                continue
×
3135
                        }
3136

3137
                        atomic.StoreUint32(&epochErrors, 0)
×
3138
                        epochAttempts = 0
×
3139

×
3140
                        // Since we know need more peers, we'll compute the
×
3141
                        // exact number we need to reach our threshold.
×
3142
                        numNeeded := numTargetPeers - numActivePeers
×
3143

×
3144
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3145
                                "peers", numNeeded)
×
UNCOV
3146

×
3147
                        // With the number of peers we need calculated, we'll
×
3148
                        // query the network bootstrappers to sample a set of
×
3149
                        // random addrs for us.
×
3150
                        //
×
UNCOV
3151
                        // Before we continue, get a copy of the ignore peers
×
UNCOV
3152
                        // map.
×
3153
                        ignoreList = s.createBootstrapIgnorePeers()
×
3154

×
3155
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3156
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3157
                        )
×
3158
                        if err != nil {
×
3159
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3160
                                        "peers: %v", err)
×
3161
                                continue
×
3162
                        }
3163

3164
                        // Finally, we'll launch a new goroutine for each
3165
                        // prospective peer candidates.
3166
                        for _, addr := range peerAddrs {
×
3167
                                epochAttempts++
×
3168

×
3169
                                go func(a *lnwire.NetAddress) {
×
3170
                                        // TODO(roasbeef): can do AS, subnet,
×
3171
                                        // country diversity, etc
×
3172
                                        errChan := make(chan error, 1)
×
3173
                                        s.connectToPeer(
×
3174
                                                a, errChan,
×
3175
                                                s.cfg.ConnectionTimeout,
×
3176
                                        )
×
3177
                                        select {
×
UNCOV
3178
                                        case err := <-errChan:
×
UNCOV
3179
                                                if err == nil {
×
UNCOV
3180
                                                        return
×
UNCOV
3181
                                                }
×
3182

3183
                                                srvrLog.Errorf("Unable to "+
×
3184
                                                        "connect to %v: %v",
×
3185
                                                        a, err)
×
3186
                                                atomic.AddUint32(&epochErrors, 1)
×
3187
                                        case <-s.quit:
×
3188
                                        }
3189
                                }(addr)
3190
                        }
3191
                case <-s.quit:
2✔
3192
                        return
2✔
3193
                }
3194
        }
3195
}
3196

3197
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3198
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3199
// query back off each time we encounter a failure.
3200
const bootstrapBackOffCeiling = time.Minute * 5
3201

3202
// initialPeerBootstrap attempts to continuously connect to peers on startup
3203
// until the target number of peers has been reached. This ensures that nodes
3204
// receive an up to date network view as soon as possible.
3205
func (s *server) initialPeerBootstrap(ctx context.Context,
3206
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3207
        bootstrappers []discovery.NetworkPeerBootstrapper) {
2✔
3208

2✔
3209
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
2✔
3210
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
2✔
3211

2✔
3212
        // We'll start off by waiting 2 seconds between failed attempts, then
2✔
3213
        // double each time we fail until we hit the bootstrapBackOffCeiling.
2✔
3214
        var delaySignal <-chan time.Time
2✔
3215
        delayTime := time.Second * 2
2✔
3216

2✔
3217
        // As want to be more aggressive, we'll use a lower back off celling
2✔
3218
        // then the main peer bootstrap logic.
2✔
3219
        backOffCeiling := bootstrapBackOffCeiling / 5
2✔
3220

2✔
3221
        for attempts := 0; ; attempts++ {
4✔
3222
                // Check if the server has been requested to shut down in order
2✔
3223
                // to prevent blocking.
2✔
3224
                if s.Stopped() {
2✔
UNCOV
3225
                        return
×
UNCOV
3226
                }
×
3227

3228
                // We can exit our aggressive initial peer bootstrapping stage
3229
                // if we've reached out target number of peers.
3230
                s.mu.RLock()
2✔
3231
                numActivePeers := uint32(len(s.peersByPub))
2✔
3232
                s.mu.RUnlock()
2✔
3233

2✔
3234
                if numActivePeers >= numTargetPeers {
4✔
3235
                        return
2✔
3236
                }
2✔
3237

3238
                if attempts > 0 {
3✔
3239
                        srvrLog.Debugf("Waiting %v before trying to locate "+
1✔
3240
                                "bootstrap peers (attempt #%v)", delayTime,
1✔
3241
                                attempts)
1✔
3242

1✔
3243
                        // We've completed at least one iterating and haven't
1✔
3244
                        // finished, so we'll start to insert a delay period
1✔
3245
                        // between each attempt.
1✔
3246
                        delaySignal = time.After(delayTime)
1✔
3247
                        select {
1✔
3248
                        case <-delaySignal:
1✔
UNCOV
3249
                        case <-s.quit:
×
UNCOV
3250
                                return
×
3251
                        }
3252

3253
                        // After our delay, we'll double the time we wait up to
3254
                        // the max back off period.
3255
                        delayTime *= 2
1✔
3256
                        if delayTime > backOffCeiling {
1✔
3257
                                delayTime = backOffCeiling
×
3258
                        }
×
3259
                }
3260

3261
                // Otherwise, we'll request for the remaining number of peers
3262
                // in order to reach our target.
3263
                peersNeeded := numTargetPeers - numActivePeers
2✔
3264
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
2✔
3265
                        ctx, ignore, peersNeeded, bootstrappers...,
2✔
3266
                )
2✔
3267
                if err != nil {
3✔
3268
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
1✔
3269
                                "peers: %v", err)
1✔
3270
                        continue
1✔
3271
                }
3272

3273
                // Then, we'll attempt to establish a connection to the
3274
                // different peer addresses retrieved by our bootstrappers.
3275
                var wg sync.WaitGroup
2✔
3276
                for _, bootstrapAddr := range bootstrapAddrs {
4✔
3277
                        wg.Add(1)
2✔
3278
                        go func(addr *lnwire.NetAddress) {
4✔
3279
                                defer wg.Done()
2✔
3280

2✔
3281
                                errChan := make(chan error, 1)
2✔
3282
                                go s.connectToPeer(
2✔
3283
                                        addr, errChan, s.cfg.ConnectionTimeout,
2✔
3284
                                )
2✔
3285

2✔
3286
                                // We'll only allow this connection attempt to
2✔
3287
                                // take up to 3 seconds. This allows us to move
2✔
3288
                                // quickly by discarding peers that are slowing
2✔
3289
                                // us down.
2✔
3290
                                select {
2✔
3291
                                case err := <-errChan:
2✔
3292
                                        if err == nil {
4✔
3293
                                                return
2✔
3294
                                        }
2✔
UNCOV
3295
                                        srvrLog.Errorf("Unable to connect to "+
×
UNCOV
3296
                                                "%v: %v", addr, err)
×
3297
                                // TODO: tune timeout? 3 seconds might be *too*
3298
                                // aggressive but works well.
UNCOV
3299
                                case <-time.After(3 * time.Second):
×
UNCOV
3300
                                        srvrLog.Tracef("Skipping peer %v due "+
×
UNCOV
3301
                                                "to not establishing a "+
×
UNCOV
3302
                                                "connection within 3 seconds",
×
UNCOV
3303
                                                addr)
×
UNCOV
3304
                                case <-s.quit:
×
3305
                                }
3306
                        }(bootstrapAddr)
3307
                }
3308

3309
                wg.Wait()
2✔
3310
        }
3311
}
3312

3313
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3314
// order to listen for inbound connections over Tor.
3315
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3316
        // Determine the different ports the server is listening on. The onion
×
3317
        // service's virtual port will map to these ports and one will be picked
×
3318
        // at random when the onion service is being accessed.
×
3319
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3320
        for _, listenAddr := range s.listenAddrs {
×
UNCOV
3321
                port := listenAddr.(*net.TCPAddr).Port
×
UNCOV
3322
                listenPorts = append(listenPorts, port)
×
UNCOV
3323
        }
×
3324

UNCOV
3325
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
UNCOV
3326
        if err != nil {
×
UNCOV
3327
                return err
×
UNCOV
3328
        }
×
3329

3330
        // Once the port mapping has been set, we can go ahead and automatically
3331
        // create our onion service. The service's private key will be saved to
3332
        // disk in order to regain access to this service when restarting `lnd`.
3333
        onionCfg := tor.AddOnionConfig{
×
3334
                VirtualPort: defaultPeerPort,
×
3335
                TargetPorts: listenPorts,
×
3336
                Store: tor.NewOnionFile(
×
3337
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3338
                        encrypter,
×
3339
                ),
×
UNCOV
3340
        }
×
3341

×
3342
        switch {
×
3343
        case s.cfg.Tor.V2:
×
3344
                onionCfg.Type = tor.V2
×
UNCOV
3345
        case s.cfg.Tor.V3:
×
UNCOV
3346
                onionCfg.Type = tor.V3
×
3347
        }
3348

3349
        addr, err := s.torController.AddOnion(onionCfg)
×
3350
        if err != nil {
×
3351
                return err
×
3352
        }
×
3353

3354
        // Now that the onion service has been created, we'll add the onion
3355
        // address it can be reached at to our list of advertised addresses.
3356
        newNodeAnn, err := s.genNodeAnnouncement(
×
3357
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3358
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3359
                },
×
3360
        )
3361
        if err != nil {
×
3362
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3363
                        "announcement: %v", err)
×
UNCOV
3364
        }
×
3365

3366
        // Finally, we'll update the on-disk version of our announcement so it
3367
        // will eventually propagate to nodes in the network.
3368
        selfNode := models.NewV1Node(
×
UNCOV
3369
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
UNCOV
3370
                        Addresses:    newNodeAnn.Addresses,
×
UNCOV
3371
                        Features:     newNodeAnn.Features,
×
3372
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3373
                        Color:        newNodeAnn.RGBColor,
×
3374
                        Alias:        newNodeAnn.Alias.String(),
×
3375
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
UNCOV
3376
                },
×
3377
        )
×
3378

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

UNCOV
3383
        return nil
×
3384
}
3385

3386
// findChannel finds a channel given a public key and ChannelID. It is an
3387
// optimization that is quicker than seeking for a channel given only the
3388
// ChannelID.
3389
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3390
        *channeldb.OpenChannel, error) {
2✔
3391

2✔
3392
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
2✔
3393
        if err != nil {
2✔
3394
                return nil, err
×
3395
        }
×
3396

3397
        for _, channel := range nodeChans {
4✔
3398
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
4✔
3399
                        return channel, nil
2✔
3400
                }
2✔
3401
        }
3402

3403
        return nil, fmt.Errorf("unable to find channel")
2✔
3404
}
3405

3406
// getNodeAnnouncement fetches the current, fully signed node announcement.
3407
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
2✔
3408
        s.mu.Lock()
2✔
3409
        defer s.mu.Unlock()
2✔
3410

2✔
3411
        return *s.currentNodeAnn
2✔
3412
}
2✔
3413

3414
// genNodeAnnouncement generates and returns the current fully signed node
3415
// announcement. The time stamp of the announcement will be updated in order
3416
// to ensure it propagates through the network.
3417
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3418
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
2✔
3419

2✔
3420
        s.mu.Lock()
2✔
3421
        defer s.mu.Unlock()
2✔
3422

2✔
3423
        // Create a shallow copy of the current node announcement to work on.
2✔
3424
        // This ensures the original announcement remains unchanged
2✔
3425
        // until the new announcement is fully signed and valid.
2✔
3426
        newNodeAnn := *s.currentNodeAnn
2✔
3427

2✔
3428
        // First, try to update our feature manager with the updated set of
2✔
3429
        // features.
2✔
3430
        if features != nil {
4✔
3431
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
2✔
3432
                        feature.SetNodeAnn: features,
2✔
3433
                }
2✔
3434
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
2✔
3435
                if err != nil {
4✔
3436
                        return lnwire.NodeAnnouncement1{}, err
2✔
3437
                }
2✔
3438

3439
                // If we could successfully update our feature manager, add
3440
                // an update modifier to include these new features to our
3441
                // set.
3442
                modifiers = append(
2✔
3443
                        modifiers, netann.NodeAnnSetFeatures(features),
2✔
3444
                )
2✔
3445
        }
3446

3447
        // Always update the timestamp when refreshing to ensure the update
3448
        // propagates.
3449
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
2✔
3450

2✔
3451
        // Apply the requested changes to the node announcement.
2✔
3452
        for _, modifier := range modifiers {
4✔
3453
                modifier(&newNodeAnn)
2✔
3454
        }
2✔
3455

3456
        // The modifiers may have added duplicate addresses, so we need to
3457
        // de-duplicate them here.
3458
        uniqueAddrs := map[string]struct{}{}
2✔
3459
        dedupedAddrs := make([]net.Addr, 0)
2✔
3460
        for _, addr := range newNodeAnn.Addresses {
4✔
3461
                if _, ok := uniqueAddrs[addr.String()]; !ok {
4✔
3462
                        uniqueAddrs[addr.String()] = struct{}{}
2✔
3463
                        dedupedAddrs = append(dedupedAddrs, addr)
2✔
3464
                }
2✔
3465
        }
3466
        newNodeAnn.Addresses = dedupedAddrs
2✔
3467

2✔
3468
        // Sign a new update after applying all of the passed modifiers.
2✔
3469
        err := netann.SignNodeAnnouncement(
2✔
3470
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
2✔
3471
        )
2✔
3472
        if err != nil {
2✔
UNCOV
3473
                return lnwire.NodeAnnouncement1{}, err
×
UNCOV
3474
        }
×
3475

3476
        // If signing succeeds, update the current announcement.
3477
        *s.currentNodeAnn = newNodeAnn
2✔
3478

2✔
3479
        return *s.currentNodeAnn, nil
2✔
3480
}
3481

3482
// updateAndBroadcastSelfNode generates a new node announcement
3483
// applying the giving modifiers and updating the time stamp
3484
// to ensure it propagates through the network. Then it broadcasts
3485
// it to the network.
3486
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3487
        features *lnwire.RawFeatureVector,
3488
        modifiers ...netann.NodeAnnModifier) error {
2✔
3489

2✔
3490
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
2✔
3491
        if err != nil {
4✔
3492
                return fmt.Errorf("unable to generate new node "+
2✔
3493
                        "announcement: %v", err)
2✔
3494
        }
2✔
3495

3496
        // Update the on-disk version of our announcement.
3497
        // Load and modify self node istead of creating anew instance so we
3498
        // don't risk overwriting any existing values.
3499
        selfNode, err := s.graphDB.SourceNode(ctx)
2✔
3500
        if err != nil {
2✔
UNCOV
3501
                return fmt.Errorf("unable to get current source node: %w", err)
×
UNCOV
3502
        }
×
3503

3504
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
2✔
3505
        selfNode.Addresses = newNodeAnn.Addresses
2✔
3506
        selfNode.Alias = fn.Some(newNodeAnn.Alias.String())
2✔
3507
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
2✔
3508
        selfNode.Color = fn.Some(newNodeAnn.RGBColor)
2✔
3509
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
2✔
3510

2✔
3511
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
2✔
3512

2✔
3513
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
2✔
UNCOV
3514
                return fmt.Errorf("can't set self node: %w", err)
×
UNCOV
3515
        }
×
3516

3517
        // Finally, propagate it to the nodes in the network.
3518
        err = s.BroadcastMessage(nil, &newNodeAnn)
2✔
3519
        if err != nil {
2✔
UNCOV
3520
                rpcsLog.Debugf("Unable to broadcast new node "+
×
UNCOV
3521
                        "announcement to peers: %v", err)
×
UNCOV
3522
                return err
×
UNCOV
3523
        }
×
3524

3525
        return nil
2✔
3526
}
3527

3528
type nodeAddresses struct {
3529
        pubKey    *btcec.PublicKey
3530
        addresses []net.Addr
3531
}
3532

3533
// establishPersistentConnections attempts to establish persistent connections
3534
// to all our direct channel collaborators. In order to promote liveness of our
3535
// active channels, we instruct the connection manager to attempt to establish
3536
// and maintain persistent connections to all our direct channel counterparties.
3537
func (s *server) establishPersistentConnections(ctx context.Context) error {
2✔
3538
        // nodeAddrsMap stores the combination of node public keys and addresses
2✔
3539
        // that we'll attempt to reconnect to. PubKey strings are used as keys
2✔
3540
        // since other PubKey forms can't be compared.
2✔
3541
        nodeAddrsMap := make(map[string]*nodeAddresses)
2✔
3542

2✔
3543
        // Iterate through the list of LinkNodes to find addresses we should
2✔
3544
        // attempt to connect to based on our set of previous connections. Set
2✔
3545
        // the reconnection port to the default peer port.
2✔
3546
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
2✔
3547
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
2✔
UNCOV
3548
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
UNCOV
3549
        }
×
3550

3551
        for _, node := range linkNodes {
4✔
3552
                pubStr := string(node.IdentityPub.SerializeCompressed())
2✔
3553
                nodeAddrs := &nodeAddresses{
2✔
3554
                        pubKey:    node.IdentityPub,
2✔
3555
                        addresses: node.Addresses,
2✔
3556
                }
2✔
3557
                nodeAddrsMap[pubStr] = nodeAddrs
2✔
3558
        }
2✔
3559

3560
        // After checking our previous connections for addresses to connect to,
3561
        // iterate through the nodes in our channel graph to find addresses
3562
        // that have been added via NodeAnnouncement1 messages.
3563
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3564
        // each of the nodes.
3565
        graphAddrs := make(map[string]*nodeAddresses)
2✔
3566
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
2✔
3567
                havePolicy bool, channelPeer *models.Node) error {
4✔
3568

2✔
3569
                // If the remote party has announced the channel to us, but we
2✔
3570
                // haven't yet, then we won't have a policy. However, we don't
2✔
3571
                // need this to connect to the peer, so we'll log it and move on.
2✔
3572
                if !havePolicy {
2✔
UNCOV
3573
                        srvrLog.Warnf("No channel policy found for "+
×
UNCOV
3574
                                "ChannelPoint(%v): ", chanPoint)
×
UNCOV
3575
                }
×
3576

3577
                pubStr := string(channelPeer.PubKeyBytes[:])
2✔
3578

2✔
3579
                // Add all unique addresses from channel
2✔
3580
                // graph/NodeAnnouncements to the list of addresses we'll
2✔
3581
                // connect to for this peer.
2✔
3582
                addrSet := make(map[string]net.Addr)
2✔
3583
                for _, addr := range channelPeer.Addresses {
4✔
3584
                        switch addr.(type) {
2✔
3585
                        case *net.TCPAddr:
2✔
3586
                                addrSet[addr.String()] = addr
2✔
3587

3588
                        // We'll only attempt to connect to Tor addresses if Tor
3589
                        // outbound support is enabled.
3590
                        case *tor.OnionAddr:
×
3591
                                if s.cfg.Tor.Active {
×
UNCOV
3592
                                        addrSet[addr.String()] = addr
×
UNCOV
3593
                                }
×
3594
                        }
3595
                }
3596

3597
                // If this peer is also recorded as a link node, we'll add any
3598
                // additional addresses that have not already been selected.
3599
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
2✔
3600
                if ok {
4✔
3601
                        for _, lnAddress := range linkNodeAddrs.addresses {
4✔
3602
                                switch lnAddress.(type) {
2✔
3603
                                case *net.TCPAddr:
2✔
3604
                                        addrSet[lnAddress.String()] = lnAddress
2✔
3605

3606
                                // We'll only attempt to connect to Tor
3607
                                // addresses if Tor outbound support is enabled.
3608
                                case *tor.OnionAddr:
×
3609
                                        if s.cfg.Tor.Active {
×
UNCOV
3610
                                                //nolint:ll
×
UNCOV
3611
                                                addrSet[lnAddress.String()] = lnAddress
×
UNCOV
3612
                                        }
×
3613
                                }
3614
                        }
3615
                }
3616

3617
                // Construct a slice of the deduped addresses.
3618
                var addrs []net.Addr
2✔
3619
                for _, addr := range addrSet {
4✔
3620
                        addrs = append(addrs, addr)
2✔
3621
                }
2✔
3622

3623
                n := &nodeAddresses{
2✔
3624
                        addresses: addrs,
2✔
3625
                }
2✔
3626
                n.pubKey, err = channelPeer.PubKey()
2✔
3627
                if err != nil {
2✔
3628
                        return err
×
UNCOV
3629
                }
×
3630

3631
                graphAddrs[pubStr] = n
2✔
3632
                return nil
2✔
3633
        }
3634
        err = s.graphDB.ForEachSourceNodeChannel(
2✔
3635
                ctx, forEachSrcNodeChan, func() {
4✔
3636
                        clear(graphAddrs)
2✔
3637
                },
2✔
3638
        )
3639
        if err != nil {
2✔
UNCOV
3640
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
UNCOV
3641
                        "%v", err)
×
UNCOV
3642

×
UNCOV
3643
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3644
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3645

×
UNCOV
3646
                        return err
×
UNCOV
3647
                }
×
3648
        }
3649

3650
        // Combine the addresses from the link nodes and the channel graph.
3651
        for pubStr, nodeAddr := range graphAddrs {
4✔
3652
                nodeAddrsMap[pubStr] = nodeAddr
2✔
3653
        }
2✔
3654

3655
        srvrLog.Debugf("Establishing %v persistent connections on start",
2✔
3656
                len(nodeAddrsMap))
2✔
3657

2✔
3658
        // Acquire and hold server lock until all persistent connection requests
2✔
3659
        // have been recorded and sent to the connection manager.
2✔
3660
        s.mu.Lock()
2✔
3661
        defer s.mu.Unlock()
2✔
3662

2✔
3663
        // Iterate through the combined list of addresses from prior links and
2✔
3664
        // node announcements and attempt to reconnect to each node.
2✔
3665
        var numOutboundConns int
2✔
3666
        for pubStr, nodeAddr := range nodeAddrsMap {
4✔
3667
                // Add this peer to the set of peers we should maintain a
2✔
3668
                // persistent connection with. We set the value to false to
2✔
3669
                // indicate that we should not continue to reconnect if the
2✔
3670
                // number of channels returns to zero, since this peer has not
2✔
3671
                // been requested as perm by the user.
2✔
3672
                s.persistentPeers[pubStr] = false
2✔
3673
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
4✔
3674
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
2✔
3675
                }
2✔
3676

3677
                for _, address := range nodeAddr.addresses {
4✔
3678
                        // Create a wrapper address which couples the IP and
2✔
3679
                        // the pubkey so the brontide authenticated connection
2✔
3680
                        // can be established.
2✔
3681
                        lnAddr := &lnwire.NetAddress{
2✔
3682
                                IdentityKey: nodeAddr.pubKey,
2✔
3683
                                Address:     address,
2✔
3684
                        }
2✔
3685

2✔
3686
                        s.persistentPeerAddrs[pubStr] = append(
2✔
3687
                                s.persistentPeerAddrs[pubStr], lnAddr)
2✔
3688
                }
2✔
3689

3690
                // We'll connect to the first 10 peers immediately, then
3691
                // randomly stagger any remaining connections if the
3692
                // stagger initial reconnect flag is set. This ensures
3693
                // that mobile nodes or nodes with a small number of
3694
                // channels obtain connectivity quickly, but larger
3695
                // nodes are able to disperse the costs of connecting to
3696
                // all peers at once.
3697
                if numOutboundConns < numInstantInitReconnect ||
2✔
3698
                        !s.cfg.StaggerInitialReconnect {
4✔
3699

2✔
3700
                        go s.connectToPersistentPeer(pubStr)
2✔
3701
                } else {
2✔
UNCOV
3702
                        go s.delayInitialReconnect(pubStr)
×
UNCOV
3703
                }
×
3704

3705
                numOutboundConns++
2✔
3706
        }
3707

3708
        return nil
2✔
3709
}
3710

3711
// delayInitialReconnect will attempt a reconnection to the given peer after
3712
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3713
//
3714
// NOTE: This method MUST be run as a goroutine.
UNCOV
3715
func (s *server) delayInitialReconnect(pubStr string) {
×
UNCOV
3716
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
UNCOV
3717
        select {
×
3718
        case <-time.After(delay):
×
3719
                s.connectToPersistentPeer(pubStr)
×
UNCOV
3720
        case <-s.quit:
×
3721
        }
3722
}
3723

3724
// prunePersistentPeerConnection removes all internal state related to
3725
// persistent connections to a peer within the server. This is used to avoid
3726
// persistent connection retries to peers we do not have any open channels with.
3727
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
2✔
3728
        pubKeyStr := string(compressedPubKey[:])
2✔
3729

2✔
3730
        s.mu.Lock()
2✔
3731
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
4✔
3732
                delete(s.persistentPeers, pubKeyStr)
2✔
3733
                delete(s.persistentPeersBackoff, pubKeyStr)
2✔
3734
                delete(s.persistentPeerAddrs, pubKeyStr)
2✔
3735
                s.cancelConnReqs(pubKeyStr, nil)
2✔
3736
                s.mu.Unlock()
2✔
3737

2✔
3738
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
2✔
3739
                        "peer has no open channels", compressedPubKey)
2✔
3740

2✔
3741
                return
2✔
3742
        }
2✔
3743
        s.mu.Unlock()
2✔
3744
}
3745

3746
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3747
// is instead used to remove persistent peer state for a peer that has been
3748
// disconnected for good cause by the server. Currently, a gossip ban from
3749
// sending garbage and the server running out of restricted-access
3750
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3751
// future, this function may expand when more ban criteria is added.
3752
//
3753
// NOTE: The server's write lock MUST be held when this is called.
UNCOV
3754
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
UNCOV
3755
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
UNCOV
3756
                delete(s.persistentPeers, remotePub)
×
UNCOV
3757
                delete(s.persistentPeersBackoff, remotePub)
×
UNCOV
3758
                delete(s.persistentPeerAddrs, remotePub)
×
UNCOV
3759
                s.cancelConnReqs(remotePub, nil)
×
UNCOV
3760
        }
×
3761
}
3762

3763
// BroadcastMessage sends a request to the server to broadcast a set of
3764
// messages to all peers other than the one specified by the `skips` parameter.
3765
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3766
// the target peers.
3767
//
3768
// NOTE: This function is safe for concurrent access.
3769
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3770
        msgs ...lnwire.Message) error {
2✔
3771

2✔
3772
        // Filter out peers found in the skips map. We synchronize access to
2✔
3773
        // peersByPub throughout this process to ensure we deliver messages to
2✔
3774
        // exact set of peers present at the time of invocation.
2✔
3775
        s.mu.RLock()
2✔
3776
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
2✔
3777
        for pubStr, sPeer := range s.peersByPub {
4✔
3778
                if skips != nil {
4✔
3779
                        if _, ok := skips[sPeer.PubKey()]; ok {
4✔
3780
                                srvrLog.Tracef("Skipping %x in broadcast with "+
2✔
3781
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
2✔
3782
                                continue
2✔
3783
                        }
3784
                }
3785

3786
                peers = append(peers, sPeer)
2✔
3787
        }
3788
        s.mu.RUnlock()
2✔
3789

2✔
3790
        // Iterate over all known peers, dispatching a go routine to enqueue
2✔
3791
        // all messages to each of peers.
2✔
3792
        var wg sync.WaitGroup
2✔
3793
        for _, sPeer := range peers {
4✔
3794
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
2✔
3795
                        sPeer.PubKey())
2✔
3796

2✔
3797
                // Dispatch a go routine to enqueue all messages to this peer.
2✔
3798
                wg.Add(1)
2✔
3799
                s.wg.Add(1)
2✔
3800
                go func(p lnpeer.Peer) {
4✔
3801
                        defer s.wg.Done()
2✔
3802
                        defer wg.Done()
2✔
3803

2✔
3804
                        p.SendMessageLazy(false, msgs...)
2✔
3805
                }(sPeer)
2✔
3806
        }
3807

3808
        // Wait for all messages to have been dispatched before returning to
3809
        // caller.
3810
        wg.Wait()
2✔
3811

2✔
3812
        return nil
2✔
3813
}
3814

3815
// NotifyWhenOnline can be called by other subsystems to get notified when a
3816
// particular peer comes online. The peer itself is sent across the peerChan.
3817
//
3818
// NOTE: This function is safe for concurrent access.
3819
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3820
        peerChan chan<- lnpeer.Peer) {
2✔
3821

2✔
3822
        s.mu.Lock()
2✔
3823

2✔
3824
        // Compute the target peer's identifier.
2✔
3825
        pubStr := string(peerKey[:])
2✔
3826

2✔
3827
        // Check if peer is connected.
2✔
3828
        peer, ok := s.peersByPub[pubStr]
2✔
3829
        if ok {
4✔
3830
                // Unlock here so that the mutex isn't held while we are
2✔
3831
                // waiting for the peer to become active.
2✔
3832
                s.mu.Unlock()
2✔
3833

2✔
3834
                // Wait until the peer signals that it is actually active
2✔
3835
                // rather than only in the server's maps.
2✔
3836
                select {
2✔
3837
                case <-peer.ActiveSignal():
2✔
UNCOV
3838
                case <-peer.QuitSignal():
×
UNCOV
3839
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3840
                        // and return.
×
UNCOV
3841
                        s.mu.Lock()
×
UNCOV
3842
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3843
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3844
                        )
×
UNCOV
3845
                        s.mu.Unlock()
×
UNCOV
3846
                        return
×
3847
                }
3848

3849
                // Connected, can return early.
3850
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
2✔
3851

2✔
3852
                select {
2✔
3853
                case peerChan <- peer:
2✔
UNCOV
3854
                case <-s.quit:
×
3855
                }
3856

3857
                return
2✔
3858
        }
3859

3860
        // Not connected, store this listener such that it can be notified when
3861
        // the peer comes online.
3862
        s.peerConnectedListeners[pubStr] = append(
2✔
3863
                s.peerConnectedListeners[pubStr], peerChan,
2✔
3864
        )
2✔
3865
        s.mu.Unlock()
2✔
3866
}
3867

3868
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3869
// the given public key has been disconnected. The notification is signaled by
3870
// closing the channel returned.
3871
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
2✔
3872
        s.mu.Lock()
2✔
3873
        defer s.mu.Unlock()
2✔
3874

2✔
3875
        c := make(chan struct{})
2✔
3876

2✔
3877
        // If the peer is already offline, we can immediately trigger the
2✔
3878
        // notification.
2✔
3879
        peerPubKeyStr := string(peerPubKey[:])
2✔
3880
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
2✔
UNCOV
3881
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
UNCOV
3882
                close(c)
×
UNCOV
3883
                return c
×
UNCOV
3884
        }
×
3885

3886
        // Otherwise, the peer is online, so we'll keep track of the channel to
3887
        // trigger the notification once the server detects the peer
3888
        // disconnects.
3889
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
2✔
3890
                s.peerDisconnectedListeners[peerPubKeyStr], c,
2✔
3891
        )
2✔
3892

2✔
3893
        return c
2✔
3894
}
3895

3896
// FindPeer will return the peer that corresponds to the passed in public key.
3897
// This function is used by the funding manager, allowing it to update the
3898
// daemon's local representation of the remote peer.
3899
//
3900
// NOTE: This function is safe for concurrent access.
3901
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
2✔
3902
        s.mu.RLock()
2✔
3903
        defer s.mu.RUnlock()
2✔
3904

2✔
3905
        pubStr := string(peerKey.SerializeCompressed())
2✔
3906

2✔
3907
        return s.findPeerByPubStr(pubStr)
2✔
3908
}
2✔
3909

3910
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3911
// which should be a string representation of the peer's serialized, compressed
3912
// public key.
3913
//
3914
// NOTE: This function is safe for concurrent access.
3915
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
2✔
3916
        s.mu.RLock()
2✔
3917
        defer s.mu.RUnlock()
2✔
3918

2✔
3919
        return s.findPeerByPubStr(pubStr)
2✔
3920
}
2✔
3921

3922
// findPeerByPubStr is an internal method that retrieves the specified peer from
3923
// the server's internal state using.
3924
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
2✔
3925
        peer, ok := s.peersByPub[pubStr]
2✔
3926
        if !ok {
4✔
3927
                return nil, ErrPeerNotConnected
2✔
3928
        }
2✔
3929

3930
        return peer, nil
2✔
3931
}
3932

3933
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3934
// exponential backoff. If no previous backoff was known, the default is
3935
// returned.
3936
func (s *server) nextPeerBackoff(pubStr string,
3937
        startTime time.Time) time.Duration {
2✔
3938

2✔
3939
        // Now, determine the appropriate backoff to use for the retry.
2✔
3940
        backoff, ok := s.persistentPeersBackoff[pubStr]
2✔
3941
        if !ok {
4✔
3942
                // If an existing backoff was unknown, use the default.
2✔
3943
                return s.cfg.MinBackoff
2✔
3944
        }
2✔
3945

3946
        // If the peer failed to start properly, we'll just use the previous
3947
        // backoff to compute the subsequent randomized exponential backoff
3948
        // duration. This will roughly double on average.
3949
        if startTime.IsZero() {
2✔
UNCOV
3950
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3951
        }
×
3952

3953
        // The peer succeeded in starting. If the connection didn't last long
3954
        // enough to be considered stable, we'll continue to back off retries
3955
        // with this peer.
3956
        connDuration := time.Since(startTime)
2✔
3957
        if connDuration < defaultStableConnDuration {
4✔
3958
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
2✔
3959
        }
2✔
3960

3961
        // The peer succeed in starting and this was stable peer, so we'll
3962
        // reduce the timeout duration by the length of the connection after
3963
        // applying randomized exponential backoff. We'll only apply this in the
3964
        // case that:
3965
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3966
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3967
        if relaxedBackoff > s.cfg.MinBackoff {
×
UNCOV
3968
                return relaxedBackoff
×
UNCOV
3969
        }
×
3970

3971
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3972
        // the stable connection lasted much longer than our previous backoff.
3973
        // To reward such good behavior, we'll reconnect after the default
3974
        // timeout.
UNCOV
3975
        return s.cfg.MinBackoff
×
3976
}
3977

3978
// shouldDropLocalConnection determines if our local connection to a remote peer
3979
// should be dropped in the case of concurrent connection establishment. In
3980
// order to deterministically decide which connection should be dropped, we'll
3981
// utilize the ordering of the local and remote public key. If we didn't use
3982
// such a tie breaker, then we risk _both_ connections erroneously being
3983
// dropped.
3984
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3985
        localPubBytes := local.SerializeCompressed()
×
UNCOV
3986
        remotePubPbytes := remote.SerializeCompressed()
×
UNCOV
3987

×
UNCOV
3988
        // The connection that comes from the node with a "smaller" pubkey
×
UNCOV
3989
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
UNCOV
3990
        // should drop our established connection.
×
3991
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
UNCOV
3992
}
×
3993

3994
// InboundPeerConnected initializes a new peer in response to a new inbound
3995
// connection.
3996
//
3997
// NOTE: This function is safe for concurrent access.
3998
func (s *server) InboundPeerConnected(conn net.Conn) {
2✔
3999
        // Exit early if we have already been instructed to shutdown, this
2✔
4000
        // prevents any delayed callbacks from accidentally registering peers.
2✔
4001
        if s.Stopped() {
2✔
4002
                return
×
4003
        }
×
4004

4005
        nodePub := conn.(*brontide.Conn).RemotePub()
2✔
4006
        pubSer := nodePub.SerializeCompressed()
2✔
4007
        pubStr := string(pubSer)
2✔
4008

2✔
4009
        var pubBytes [33]byte
2✔
4010
        copy(pubBytes[:], pubSer)
2✔
4011

2✔
4012
        s.mu.Lock()
2✔
4013
        defer s.mu.Unlock()
2✔
4014

2✔
4015
        // If we already have an outbound connection to this peer, then ignore
2✔
4016
        // this new connection.
2✔
4017
        if p, ok := s.outboundPeers[pubStr]; ok {
4✔
4018
                srvrLog.Debugf("Already have outbound connection for %v, "+
2✔
4019
                        "ignoring inbound connection from local=%v, remote=%v",
2✔
4020
                        p, conn.LocalAddr(), conn.RemoteAddr())
2✔
4021

2✔
4022
                conn.Close()
2✔
4023
                return
2✔
4024
        }
2✔
4025

4026
        // If we already have a valid connection that is scheduled to take
4027
        // precedence once the prior peer has finished disconnecting, we'll
4028
        // ignore this connection.
4029
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
2✔
UNCOV
4030
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
UNCOV
4031
                        "scheduled", conn.RemoteAddr(), p)
×
UNCOV
4032
                conn.Close()
×
UNCOV
4033
                return
×
UNCOV
4034
        }
×
4035

4036
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
2✔
4037

2✔
4038
        // Check to see if we already have a connection with this peer. If so,
2✔
4039
        // we may need to drop our existing connection. This prevents us from
2✔
4040
        // having duplicate connections to the same peer. We forgo adding a
2✔
4041
        // default case as we expect these to be the only error values returned
2✔
4042
        // from findPeerByPubStr.
2✔
4043
        connectedPeer, err := s.findPeerByPubStr(pubStr)
2✔
4044
        switch err {
2✔
4045
        case ErrPeerNotConnected:
2✔
4046
                // We were unable to locate an existing connection with the
2✔
4047
                // target peer, proceed to connect.
2✔
4048
                s.cancelConnReqs(pubStr, nil)
2✔
4049
                s.peerConnected(conn, nil, true)
2✔
4050

4051
        case nil:
2✔
4052
                ctx := btclog.WithCtx(
2✔
4053
                        context.TODO(),
2✔
4054
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
2✔
4055
                )
2✔
4056

2✔
4057
                // We already have a connection with the incoming peer. If the
2✔
4058
                // connection we've already established should be kept and is
2✔
4059
                // not of the same type of the new connection (inbound), then
2✔
4060
                // we'll close out the new connection s.t there's only a single
2✔
4061
                // connection between us.
2✔
4062
                localPub := s.identityECDH.PubKey()
2✔
4063
                if !connectedPeer.Inbound() &&
2✔
4064
                        !shouldDropLocalConnection(localPub, nodePub) {
2✔
UNCOV
4065

×
UNCOV
4066
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
UNCOV
4067
                                "peer, but already have outbound "+
×
UNCOV
4068
                                "connection, dropping conn",
×
UNCOV
4069
                                fmt.Errorf("already have outbound conn"))
×
UNCOV
4070
                        conn.Close()
×
UNCOV
4071
                        return
×
UNCOV
4072
                }
×
4073

4074
                // Otherwise, if we should drop the connection, then we'll
4075
                // disconnect our already connected peer.
4076
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
2✔
4077

2✔
4078
                s.cancelConnReqs(pubStr, nil)
2✔
4079

2✔
4080
                // Remove the current peer from the server's internal state and
2✔
4081
                // signal that the peer termination watcher does not need to
2✔
4082
                // execute for this peer.
2✔
4083
                s.removePeerUnsafe(ctx, connectedPeer)
2✔
4084
                s.ignorePeerTermination[connectedPeer] = struct{}{}
2✔
4085
                s.scheduledPeerConnection[pubStr] = func() {
4✔
4086
                        s.peerConnected(conn, nil, true)
2✔
4087
                }
2✔
4088
        }
4089
}
4090

4091
// OutboundPeerConnected initializes a new peer in response to a new outbound
4092
// connection.
4093
// NOTE: This function is safe for concurrent access.
4094
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
2✔
4095
        // Exit early if we have already been instructed to shutdown, this
2✔
4096
        // prevents any delayed callbacks from accidentally registering peers.
2✔
4097
        if s.Stopped() {
2✔
UNCOV
4098
                return
×
UNCOV
4099
        }
×
4100

4101
        nodePub := conn.(*brontide.Conn).RemotePub()
2✔
4102
        pubSer := nodePub.SerializeCompressed()
2✔
4103
        pubStr := string(pubSer)
2✔
4104

2✔
4105
        var pubBytes [33]byte
2✔
4106
        copy(pubBytes[:], pubSer)
2✔
4107

2✔
4108
        s.mu.Lock()
2✔
4109
        defer s.mu.Unlock()
2✔
4110

2✔
4111
        // If we already have an inbound connection to this peer, then ignore
2✔
4112
        // this new connection.
2✔
4113
        if p, ok := s.inboundPeers[pubStr]; ok {
4✔
4114
                srvrLog.Debugf("Already have inbound connection for %v, "+
2✔
4115
                        "ignoring outbound connection from local=%v, remote=%v",
2✔
4116
                        p, conn.LocalAddr(), conn.RemoteAddr())
2✔
4117

2✔
4118
                if connReq != nil {
4✔
4119
                        s.connMgr.Remove(connReq.ID())
2✔
4120
                }
2✔
4121
                conn.Close()
2✔
4122
                return
2✔
4123
        }
4124
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
2✔
UNCOV
4125
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
UNCOV
4126
                s.connMgr.Remove(connReq.ID())
×
UNCOV
4127
                conn.Close()
×
UNCOV
4128
                return
×
UNCOV
4129
        }
×
4130

4131
        // If we already have a valid connection that is scheduled to take
4132
        // precedence once the prior peer has finished disconnecting, we'll
4133
        // ignore this connection.
4134
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
2✔
UNCOV
4135
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
UNCOV
4136

×
UNCOV
4137
                if connReq != nil {
×
UNCOV
4138
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4139
                }
×
4140

4141
                conn.Close()
×
4142
                return
×
4143
        }
4144

4145
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
2✔
4146
                conn.RemoteAddr())
2✔
4147

2✔
4148
        if connReq != nil {
4✔
4149
                // A successful connection was returned by the connmgr.
2✔
4150
                // Immediately cancel all pending requests, excluding the
2✔
4151
                // outbound connection we just established.
2✔
4152
                ignore := connReq.ID()
2✔
4153
                s.cancelConnReqs(pubStr, &ignore)
2✔
4154
        } else {
4✔
4155
                // This was a successful connection made by some other
2✔
4156
                // subsystem. Remove all requests being managed by the connmgr.
2✔
4157
                s.cancelConnReqs(pubStr, nil)
2✔
4158
        }
2✔
4159

4160
        // If we already have a connection with this peer, decide whether or not
4161
        // we need to drop the stale connection. We forgo adding a default case
4162
        // as we expect these to be the only error values returned from
4163
        // findPeerByPubStr.
4164
        connectedPeer, err := s.findPeerByPubStr(pubStr)
2✔
4165
        switch err {
2✔
4166
        case ErrPeerNotConnected:
2✔
4167
                // We were unable to locate an existing connection with the
2✔
4168
                // target peer, proceed to connect.
2✔
4169
                s.peerConnected(conn, connReq, false)
2✔
4170

4171
        case nil:
2✔
4172
                ctx := btclog.WithCtx(
2✔
4173
                        context.TODO(),
2✔
4174
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
2✔
4175
                )
2✔
4176

2✔
4177
                // We already have a connection with the incoming peer. If the
2✔
4178
                // connection we've already established should be kept and is
2✔
4179
                // not of the same type of the new connection (outbound), then
2✔
4180
                // we'll close out the new connection s.t there's only a single
2✔
4181
                // connection between us.
2✔
4182
                localPub := s.identityECDH.PubKey()
2✔
4183
                if connectedPeer.Inbound() &&
2✔
4184
                        shouldDropLocalConnection(localPub, nodePub) {
2✔
UNCOV
4185

×
UNCOV
4186
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
UNCOV
4187
                                "to peer, but already have inbound "+
×
UNCOV
4188
                                "connection, dropping conn",
×
UNCOV
4189
                                fmt.Errorf("already have inbound conn"))
×
UNCOV
4190
                        if connReq != nil {
×
UNCOV
4191
                                s.connMgr.Remove(connReq.ID())
×
UNCOV
4192
                        }
×
UNCOV
4193
                        conn.Close()
×
UNCOV
4194
                        return
×
4195
                }
4196

4197
                // Otherwise, _their_ connection should be dropped. So we'll
4198
                // disconnect the peer and send the now obsolete peer to the
4199
                // server for garbage collection.
4200
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
2✔
4201

2✔
4202
                // Remove the current peer from the server's internal state and
2✔
4203
                // signal that the peer termination watcher does not need to
2✔
4204
                // execute for this peer.
2✔
4205
                s.removePeerUnsafe(ctx, connectedPeer)
2✔
4206
                s.ignorePeerTermination[connectedPeer] = struct{}{}
2✔
4207
                s.scheduledPeerConnection[pubStr] = func() {
4✔
4208
                        s.peerConnected(conn, connReq, false)
2✔
4209
                }
2✔
4210
        }
4211
}
4212

4213
// UnassignedConnID is the default connection ID that a request can have before
4214
// it actually is submitted to the connmgr.
4215
// TODO(conner): move into connmgr package, or better, add connmgr method for
4216
// generating atomic IDs
4217
const UnassignedConnID uint64 = 0
4218

4219
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4220
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4221
// Afterwards, each connection request removed from the connmgr. The caller can
4222
// optionally specify a connection ID to ignore, which prevents us from
4223
// canceling a successful request. All persistent connreqs for the provided
4224
// pubkey are discarded after the operationjw.
4225
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
2✔
4226
        // First, cancel any lingering persistent retry attempts, which will
2✔
4227
        // prevent retries for any with backoffs that are still maturing.
2✔
4228
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
4✔
4229
                close(cancelChan)
2✔
4230
                delete(s.persistentRetryCancels, pubStr)
2✔
4231
        }
2✔
4232

4233
        // Next, check to see if we have any outstanding persistent connection
4234
        // requests to this peer. If so, then we'll remove all of these
4235
        // connection requests, and also delete the entry from the map.
4236
        connReqs, ok := s.persistentConnReqs[pubStr]
2✔
4237
        if !ok {
4✔
4238
                return
2✔
4239
        }
2✔
4240

4241
        for _, connReq := range connReqs {
4✔
4242
                srvrLog.Tracef("Canceling %s:", connReqs)
2✔
4243

2✔
4244
                // Atomically capture the current request identifier.
2✔
4245
                connID := connReq.ID()
2✔
4246

2✔
4247
                // Skip any zero IDs, this indicates the request has not
2✔
4248
                // yet been schedule.
2✔
4249
                if connID == UnassignedConnID {
2✔
UNCOV
4250
                        continue
×
4251
                }
4252

4253
                // Skip a particular connection ID if instructed.
4254
                if skip != nil && connID == *skip {
4✔
4255
                        continue
2✔
4256
                }
4257

4258
                s.connMgr.Remove(connID)
2✔
4259
        }
4260

4261
        delete(s.persistentConnReqs, pubStr)
2✔
4262
}
4263

4264
// handleCustomMessage dispatches an incoming custom peers message to
4265
// subscribers.
4266
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
2✔
4267
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
2✔
4268
                peer, msg.Type)
2✔
4269

2✔
4270
        return s.customMessageServer.SendUpdate(&CustomMessage{
2✔
4271
                Peer: peer,
2✔
4272
                Msg:  msg,
2✔
4273
        })
2✔
4274
}
2✔
4275

4276
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4277
// messages.
4278
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
2✔
4279
        return s.customMessageServer.Subscribe()
2✔
4280
}
2✔
4281

4282
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4283
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
2✔
4284
        return s.onionMessageServer.Subscribe()
2✔
4285
}
2✔
4286

4287
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4288
// the channelNotifier's NotifyOpenChannelEvent.
4289
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4290
        remotePub *btcec.PublicKey) {
2✔
4291

2✔
4292
        // Call newOpenChan to update the access manager's maps for this peer.
2✔
4293
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
4✔
4294
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
2✔
4295
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
2✔
4296
        }
2✔
4297

4298
        // Notify subscribers about this open channel event.
4299
        s.channelNotifier.NotifyOpenChannelEvent(op)
2✔
4300
}
4301

4302
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4303
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4304
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4305
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
2✔
4306

2✔
4307
        // Call newPendingOpenChan to update the access manager's maps for this
2✔
4308
        // peer.
2✔
4309
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
2✔
UNCOV
4310
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4311
                        "channel[%v] pending open",
×
UNCOV
4312
                        remotePub.SerializeCompressed(), op)
×
UNCOV
4313
        }
×
4314

4315
        // Notify subscribers about this event.
4316
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
2✔
4317
}
4318

4319
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4320
// calls the channelNotifier's NotifyFundingTimeout.
4321
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4322
        remotePub *btcec.PublicKey) {
2✔
4323

2✔
4324
        // Call newPendingCloseChan to potentially demote the peer.
2✔
4325
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
2✔
4326
        if err != nil {
2✔
4327
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4328
                        "channel[%v] pending close",
×
4329
                        remotePub.SerializeCompressed(), op)
×
UNCOV
4330
        }
×
4331

4332
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
2✔
UNCOV
4333
                // If we encounter an error while attempting to disconnect the
×
UNCOV
4334
                // peer, log the error.
×
UNCOV
4335
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
UNCOV
4336
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
UNCOV
4337
                }
×
4338
        }
4339

4340
        // Notify subscribers about this event.
4341
        s.channelNotifier.NotifyFundingTimeout(op)
2✔
4342
}
4343

4344
// peerConnected is a function that handles initialization a newly connected
4345
// peer by adding it to the server's global list of all active peers, and
4346
// starting all the goroutines the peer needs to function properly. The inbound
4347
// boolean should be true if the peer initiated the connection to us.
4348
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4349
        inbound bool) {
2✔
4350

2✔
4351
        brontideConn := conn.(*brontide.Conn)
2✔
4352
        addr := conn.RemoteAddr()
2✔
4353
        pubKey := brontideConn.RemotePub()
2✔
4354

2✔
4355
        // Only restrict access for inbound connections, which means if the
2✔
4356
        // remote node's public key is banned or the restricted slots are used
2✔
4357
        // up, we will drop the connection.
2✔
4358
        //
2✔
4359
        // TODO(yy): Consider perform this check in
2✔
4360
        // `peerAccessMan.addPeerAccess`.
2✔
4361
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
2✔
4362
        if inbound && err != nil {
2✔
UNCOV
4363
                pubSer := pubKey.SerializeCompressed()
×
UNCOV
4364

×
UNCOV
4365
                // Clean up the persistent peer maps if we're dropping this
×
UNCOV
4366
                // connection.
×
UNCOV
4367
                s.bannedPersistentPeerConnection(string(pubSer))
×
UNCOV
4368

×
UNCOV
4369
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
UNCOV
4370
                        "of restricted-access connection slots: %v.", pubSer,
×
UNCOV
4371
                        err)
×
UNCOV
4372

×
UNCOV
4373
                conn.Close()
×
UNCOV
4374

×
UNCOV
4375
                return
×
UNCOV
4376
        }
×
4377

4378
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
2✔
4379
                pubKey.SerializeCompressed(), addr, inbound)
2✔
4380

2✔
4381
        peerAddr := &lnwire.NetAddress{
2✔
4382
                IdentityKey: pubKey,
2✔
4383
                Address:     addr,
2✔
4384
                ChainNet:    s.cfg.ActiveNetParams.Net,
2✔
4385
        }
2✔
4386

2✔
4387
        // With the brontide connection established, we'll now craft the feature
2✔
4388
        // vectors to advertise to the remote node.
2✔
4389
        initFeatures := s.featureMgr.Get(feature.SetInit)
2✔
4390
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
2✔
4391

2✔
4392
        // Lookup past error caches for the peer in the server. If no buffer is
2✔
4393
        // found, create a fresh buffer.
2✔
4394
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
2✔
4395
        errBuffer, ok := s.peerErrors[pkStr]
2✔
4396
        if !ok {
4✔
4397
                var err error
2✔
4398
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
2✔
4399
                if err != nil {
2✔
UNCOV
4400
                        srvrLog.Errorf("unable to create peer %v", err)
×
UNCOV
4401
                        return
×
UNCOV
4402
                }
×
4403
        }
4404

4405
        // If we directly set the peer.Config TowerClient member to the
4406
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4407
        // the peer.Config's TowerClient member will not evaluate to nil even
4408
        // though the underlying value is nil. To avoid this gotcha which can
4409
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4410
        // TowerClient if needed.
4411
        var towerClient wtclient.ClientManager
2✔
4412
        if s.towerClientMgr != nil {
4✔
4413
                towerClient = s.towerClientMgr
2✔
4414
        }
2✔
4415

4416
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
2✔
4417
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
2✔
4418

2✔
4419
        // Now that we've established a connection, create a peer, and it to the
2✔
4420
        // set of currently active peers. Configure the peer with the incoming
2✔
4421
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
2✔
4422
        // offered that would trigger channel closure. In case of outgoing
2✔
4423
        // htlcs, an extra block is added to prevent the channel from being
2✔
4424
        // closed when the htlc is outstanding and a new block comes in.
2✔
4425
        pCfg := peer.Config{
2✔
4426
                Conn:                    brontideConn,
2✔
4427
                ConnReq:                 connReq,
2✔
4428
                Addr:                    peerAddr,
2✔
4429
                Inbound:                 inbound,
2✔
4430
                Features:                initFeatures,
2✔
4431
                LegacyFeatures:          legacyFeatures,
2✔
4432
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
2✔
4433
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
2✔
4434
                ErrorBuffer:             errBuffer,
2✔
4435
                WritePool:               s.writePool,
2✔
4436
                ReadPool:                s.readPool,
2✔
4437
                Switch:                  s.htlcSwitch,
2✔
4438
                InterceptSwitch:         s.interceptableSwitch,
2✔
4439
                ChannelDB:               s.chanStateDB,
2✔
4440
                ChannelGraph:            s.graphDB,
2✔
4441
                ChainArb:                s.chainArb,
2✔
4442
                AuthGossiper:            s.authGossiper,
2✔
4443
                ChanStatusMgr:           s.chanStatusMgr,
2✔
4444
                ChainIO:                 s.cc.ChainIO,
2✔
4445
                FeeEstimator:            s.cc.FeeEstimator,
2✔
4446
                Signer:                  s.cc.Wallet.Cfg.Signer,
2✔
4447
                SigPool:                 s.sigPool,
2✔
4448
                Wallet:                  s.cc.Wallet,
2✔
4449
                ChainNotifier:           s.cc.ChainNotifier,
2✔
4450
                BestBlockView:           s.cc.BestBlockTracker,
2✔
4451
                RoutingPolicy:           s.cc.RoutingPolicy,
2✔
4452
                SphinxPayment:           s.sphinxPayment,
2✔
4453
                OnionEndpoint:           s.onionEndpoint,
2✔
4454
                WitnessBeacon:           s.witnessBeacon,
2✔
4455
                Invoices:                s.invoices,
2✔
4456
                ChannelNotifier:         s.channelNotifier,
2✔
4457
                HtlcNotifier:            s.htlcNotifier,
2✔
4458
                TowerClient:             towerClient,
2✔
4459
                DisconnectPeer:          s.DisconnectPeer,
2✔
4460
                ActorSystem:             s.actorSystem,
2✔
4461
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
2✔
4462
                        lnwire.NodeAnnouncement1, error) {
4✔
4463

2✔
4464
                        return s.genNodeAnnouncement(nil)
2✔
4465
                },
2✔
4466

4467
                PongBuf: s.pongBuf,
4468

4469
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4470

4471
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4472

4473
                FundingManager: s.fundingMgr,
4474

4475
                Hodl:                    s.cfg.Hodl,
4476
                UnsafeReplay:            s.cfg.UnsafeReplay,
4477
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4478
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4479
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4480
                ChannelCloseConfs:       s.cfg.Dev.ChannelCloseConfs(),
4481
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4482
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4483
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4484
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4485
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4486
                HandleCustomMessage:    s.handleCustomMessage,
4487
                GetAliases:             s.aliasMgr.GetAliases,
4488
                RequestAlias:           s.aliasMgr.RequestAlias,
4489
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4490
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4491
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4492
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4493
                MaxFeeExposure:         thresholdMSats,
4494
                Quit:                   s.quit,
4495
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4496
                AuxSigner:              s.implCfg.AuxSigner,
4497
                MsgRouter:              s.implCfg.MsgRouter,
4498
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4499
                AuxResolver:            s.implCfg.AuxContractResolver,
4500
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4501
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4502
                ShouldFwdExpAccountability: func() bool {
2✔
4503
                        return !s.cfg.ProtocolOptions.NoExpAccountability()
2✔
4504
                },
2✔
4505
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4506
        }
4507

4508
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
2✔
4509
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
2✔
4510

2✔
4511
        p := peer.NewBrontide(pCfg)
2✔
4512

2✔
4513
        // Update the access manager with the access permission for this peer.
2✔
4514
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
2✔
4515

2✔
4516
        // TODO(roasbeef): update IP address for link-node
2✔
4517
        //  * also mark last-seen, do it one single transaction?
2✔
4518

2✔
4519
        s.addPeer(p)
2✔
4520

2✔
4521
        // Once we have successfully added the peer to the server, we can
2✔
4522
        // delete the previous error buffer from the server's map of error
2✔
4523
        // buffers.
2✔
4524
        delete(s.peerErrors, pkStr)
2✔
4525

2✔
4526
        // Dispatch a goroutine to asynchronously start the peer. This process
2✔
4527
        // includes sending and receiving Init messages, which would be a DOS
2✔
4528
        // vector if we held the server's mutex throughout the procedure.
2✔
4529
        s.wg.Add(1)
2✔
4530
        go s.peerInitializer(p)
2✔
4531
}
4532

4533
// addPeer adds the passed peer to the server's global state of all active
4534
// peers.
4535
func (s *server) addPeer(p *peer.Brontide) {
2✔
4536
        if p == nil {
2✔
UNCOV
4537
                return
×
UNCOV
4538
        }
×
4539

4540
        pubBytes := p.IdentityKey().SerializeCompressed()
2✔
4541

2✔
4542
        // Ignore new peers if we're shutting down.
2✔
4543
        if s.Stopped() {
2✔
UNCOV
4544
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
UNCOV
4545
                        pubBytes)
×
UNCOV
4546
                p.Disconnect(ErrServerShuttingDown)
×
UNCOV
4547

×
UNCOV
4548
                return
×
UNCOV
4549
        }
×
4550

4551
        // Track the new peer in our indexes so we can quickly look it up either
4552
        // according to its public key, or its peer ID.
4553
        // TODO(roasbeef): pipe all requests through to the
4554
        // queryHandler/peerManager
4555

4556
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4557
        // be human-readable.
4558
        pubStr := string(pubBytes)
2✔
4559

2✔
4560
        s.peersByPub[pubStr] = p
2✔
4561

2✔
4562
        if p.Inbound() {
4✔
4563
                s.inboundPeers[pubStr] = p
2✔
4564
        } else {
4✔
4565
                s.outboundPeers[pubStr] = p
2✔
4566
        }
2✔
4567

4568
        // Inform the peer notifier of a peer online event so that it can be reported
4569
        // to clients listening for peer events.
4570
        var pubKey [33]byte
2✔
4571
        copy(pubKey[:], pubBytes)
2✔
4572
}
4573

4574
// peerInitializer asynchronously starts a newly connected peer after it has
4575
// been added to the server's peer map. This method sets up a
4576
// peerTerminationWatcher for the given peer, and ensures that it executes even
4577
// if the peer failed to start. In the event of a successful connection, this
4578
// method reads the negotiated, local feature-bits and spawns the appropriate
4579
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4580
// be signaled of the new peer once the method returns.
4581
//
4582
// NOTE: This MUST be launched as a goroutine.
4583
func (s *server) peerInitializer(p *peer.Brontide) {
2✔
4584
        defer s.wg.Done()
2✔
4585

2✔
4586
        pubBytes := p.IdentityKey().SerializeCompressed()
2✔
4587

2✔
4588
        // Avoid initializing peers while the server is exiting.
2✔
4589
        if s.Stopped() {
2✔
UNCOV
4590
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
UNCOV
4591
                        pubBytes)
×
UNCOV
4592
                return
×
UNCOV
4593
        }
×
4594

4595
        // Create a channel that will be used to signal a successful start of
4596
        // the link. This prevents the peer termination watcher from beginning
4597
        // its duty too early.
4598
        ready := make(chan struct{})
2✔
4599

2✔
4600
        // Before starting the peer, launch a goroutine to watch for the
2✔
4601
        // unexpected termination of this peer, which will ensure all resources
2✔
4602
        // are properly cleaned up, and re-establish persistent connections when
2✔
4603
        // necessary. The peer termination watcher will be short circuited if
2✔
4604
        // the peer is ever added to the ignorePeerTermination map, indicating
2✔
4605
        // that the server has already handled the removal of this peer.
2✔
4606
        s.wg.Add(1)
2✔
4607
        go s.peerTerminationWatcher(p, ready)
2✔
4608

2✔
4609
        // Start the peer! If an error occurs, we Disconnect the peer, which
2✔
4610
        // will unblock the peerTerminationWatcher.
2✔
4611
        if err := p.Start(); err != nil {
4✔
4612
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
2✔
4613

2✔
4614
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4615
                return
2✔
4616
        }
2✔
4617

4618
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4619
        // was successful, and to begin watching the peer's wait group.
4620
        close(ready)
2✔
4621

2✔
4622
        s.mu.Lock()
2✔
4623
        defer s.mu.Unlock()
2✔
4624

2✔
4625
        // Check if there are listeners waiting for this peer to come online.
2✔
4626
        srvrLog.Debugf("Notifying that peer %v is online", p)
2✔
4627

2✔
4628
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
2✔
4629
        // route.Vertex as the key type of peerConnectedListeners.
2✔
4630
        pubStr := string(pubBytes)
2✔
4631
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
4✔
4632
                select {
2✔
4633
                case peerChan <- p:
2✔
UNCOV
4634
                case <-s.quit:
×
UNCOV
4635
                        return
×
4636
                }
4637
        }
4638
        delete(s.peerConnectedListeners, pubStr)
2✔
4639

2✔
4640
        // Since the peer has been fully initialized, now it's time to notify
2✔
4641
        // the RPC about the peer online event.
2✔
4642
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
2✔
4643
}
4644

4645
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4646
// and then cleans up all resources allocated to the peer, notifies relevant
4647
// sub-systems of its demise, and finally handles re-connecting to the peer if
4648
// it's persistent. If the server intentionally disconnects a peer, it should
4649
// have a corresponding entry in the ignorePeerTermination map which will cause
4650
// the cleanup routine to exit early. The passed `ready` chan is used to
4651
// synchronize when WaitForDisconnect should begin watching on the peer's
4652
// waitgroup. The ready chan should only be signaled if the peer starts
4653
// successfully, otherwise the peer should be disconnected instead.
4654
//
4655
// NOTE: This MUST be launched as a goroutine.
4656
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
2✔
4657
        defer s.wg.Done()
2✔
4658

2✔
4659
        ctx := btclog.WithCtx(
2✔
4660
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
2✔
4661
        )
2✔
4662

2✔
4663
        p.WaitForDisconnect(ready)
2✔
4664

2✔
4665
        srvrLog.DebugS(ctx, "Peer has been disconnected")
2✔
4666

2✔
4667
        // If the server is exiting then we can bail out early ourselves as all
2✔
4668
        // the other sub-systems will already be shutting down.
2✔
4669
        if s.Stopped() {
4✔
4670
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
2✔
4671
                return
2✔
4672
        }
2✔
4673

4674
        // Next, we'll cancel all pending funding reservations with this node.
4675
        // If we tried to initiate any funding flows that haven't yet finished,
4676
        // then we need to unlock those committed outputs so they're still
4677
        // available for use.
4678
        s.fundingMgr.CancelPeerReservations(p.PubKey())
2✔
4679

2✔
4680
        pubKey := p.IdentityKey()
2✔
4681

2✔
4682
        // We'll also inform the gossiper that this peer is no longer active,
2✔
4683
        // so we don't need to maintain sync state for it any longer.
2✔
4684
        s.authGossiper.PruneSyncState(p.PubKey())
2✔
4685

2✔
4686
        // Tell the switch to remove all links associated with this peer.
2✔
4687
        // Passing nil as the target link indicates that all links associated
2✔
4688
        // with this interface should be closed.
2✔
4689
        //
2✔
4690
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
2✔
4691
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
2✔
4692
        if err != nil && err != htlcswitch.ErrNoLinksFound {
2✔
UNCOV
4693
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
UNCOV
4694
        }
×
4695

4696
        for _, link := range links {
4✔
4697
                s.htlcSwitch.RemoveLink(link.ChanID())
2✔
4698
        }
2✔
4699

4700
        s.mu.Lock()
2✔
4701
        defer s.mu.Unlock()
2✔
4702

2✔
4703
        // If there were any notification requests for when this peer
2✔
4704
        // disconnected, we can trigger them now.
2✔
4705
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
2✔
4706
        pubStr := string(pubKey.SerializeCompressed())
2✔
4707
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
4✔
4708
                close(offlineChan)
2✔
4709
        }
2✔
4710
        delete(s.peerDisconnectedListeners, pubStr)
2✔
4711

2✔
4712
        // If the server has already removed this peer, we can short circuit the
2✔
4713
        // peer termination watcher and skip cleanup.
2✔
4714
        if _, ok := s.ignorePeerTermination[p]; ok {
4✔
4715
                delete(s.ignorePeerTermination, p)
2✔
4716

2✔
4717
                pubKey := p.PubKey()
2✔
4718
                pubStr := string(pubKey[:])
2✔
4719

2✔
4720
                // If a connection callback is present, we'll go ahead and
2✔
4721
                // execute it now that previous peer has fully disconnected. If
2✔
4722
                // the callback is not present, this likely implies the peer was
2✔
4723
                // purposefully disconnected via RPC, and that no reconnect
2✔
4724
                // should be attempted.
2✔
4725
                connCallback, ok := s.scheduledPeerConnection[pubStr]
2✔
4726
                if ok {
4✔
4727
                        delete(s.scheduledPeerConnection, pubStr)
2✔
4728
                        connCallback()
2✔
4729
                }
2✔
4730
                return
2✔
4731
        }
4732

4733
        // First, cleanup any remaining state the server has regarding the peer
4734
        // in question.
4735
        s.removePeerUnsafe(ctx, p)
2✔
4736

2✔
4737
        // Next, check to see if this is a persistent peer or not.
2✔
4738
        if _, ok := s.persistentPeers[pubStr]; !ok {
4✔
4739
                return
2✔
4740
        }
2✔
4741

4742
        // Get the last address that we used to connect to the peer.
4743
        addrs := []net.Addr{
2✔
4744
                p.NetAddress().Address,
2✔
4745
        }
2✔
4746

2✔
4747
        // We'll ensure that we locate all the peers advertised addresses for
2✔
4748
        // reconnection purposes.
2✔
4749
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
2✔
4750
        switch {
2✔
4751
        // We found advertised addresses, so use them.
4752
        case err == nil:
2✔
4753
                addrs = advertisedAddrs
2✔
4754

4755
        // The peer doesn't have an advertised address.
4756
        case err == errNoAdvertisedAddr:
2✔
4757
                // If it is an outbound peer then we fall back to the existing
2✔
4758
                // peer address.
2✔
4759
                if !p.Inbound() {
4✔
4760
                        break
2✔
4761
                }
4762

4763
                // Fall back to the existing peer address if
4764
                // we're not accepting connections over Tor.
4765
                if s.torController == nil {
4✔
4766
                        break
2✔
4767
                }
4768

4769
                // If we are, the peer's address won't be known
4770
                // to us (we'll see a private address, which is
4771
                // the address used by our onion service to dial
4772
                // to lnd), so we don't have enough information
4773
                // to attempt a reconnect.
UNCOV
4774
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
UNCOV
4775
                        "to inbound peer without advertised address")
×
UNCOV
4776
                return
×
4777

4778
        // We came across an error retrieving an advertised
4779
        // address, log it, and fall back to the existing peer
4780
        // address.
4781
        default:
2✔
4782
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
2✔
4783
                        "address for peer", err)
2✔
4784
        }
4785

4786
        // Make an easy lookup map so that we can check if an address
4787
        // is already in the address list that we have stored for this peer.
4788
        existingAddrs := make(map[string]bool)
2✔
4789
        for _, addr := range s.persistentPeerAddrs[pubStr] {
4✔
4790
                existingAddrs[addr.String()] = true
2✔
4791
        }
2✔
4792

4793
        // Add any missing addresses for this peer to persistentPeerAddr.
4794
        for _, addr := range addrs {
4✔
4795
                if existingAddrs[addr.String()] {
2✔
UNCOV
4796
                        continue
×
4797
                }
4798

4799
                s.persistentPeerAddrs[pubStr] = append(
2✔
4800
                        s.persistentPeerAddrs[pubStr],
2✔
4801
                        &lnwire.NetAddress{
2✔
4802
                                IdentityKey: p.IdentityKey(),
2✔
4803
                                Address:     addr,
2✔
4804
                                ChainNet:    p.NetAddress().ChainNet,
2✔
4805
                        },
2✔
4806
                )
2✔
4807
        }
4808

4809
        // Record the computed backoff in the backoff map.
4810
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
2✔
4811
        s.persistentPeersBackoff[pubStr] = backoff
2✔
4812

2✔
4813
        // Initialize a retry canceller for this peer if one does not
2✔
4814
        // exist.
2✔
4815
        cancelChan, ok := s.persistentRetryCancels[pubStr]
2✔
4816
        if !ok {
4✔
4817
                cancelChan = make(chan struct{})
2✔
4818
                s.persistentRetryCancels[pubStr] = cancelChan
2✔
4819
        }
2✔
4820

4821
        // We choose not to wait group this go routine since the Connect
4822
        // call can stall for arbitrarily long if we shutdown while an
4823
        // outbound connection attempt is being made.
4824
        go func() {
4✔
4825
                srvrLog.DebugS(ctx, "Scheduling connection "+
2✔
4826
                        "re-establishment to persistent peer",
2✔
4827
                        "reconnecting_in", backoff)
2✔
4828

2✔
4829
                select {
2✔
4830
                case <-time.After(backoff):
2✔
4831
                case <-cancelChan:
2✔
4832
                        return
2✔
4833
                case <-s.quit:
2✔
4834
                        return
2✔
4835
                }
4836

4837
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
2✔
4838
                        "connection")
2✔
4839

2✔
4840
                s.connectToPersistentPeer(pubStr)
2✔
4841
        }()
4842
}
4843

4844
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4845
// to connect to the peer. It creates connection requests if there are
4846
// currently none for a given address and it removes old connection requests
4847
// if the associated address is no longer in the latest address list for the
4848
// peer.
4849
func (s *server) connectToPersistentPeer(pubKeyStr string) {
2✔
4850
        s.mu.Lock()
2✔
4851
        defer s.mu.Unlock()
2✔
4852

2✔
4853
        // Create an easy lookup map of the addresses we have stored for the
2✔
4854
        // peer. We will remove entries from this map if we have existing
2✔
4855
        // connection requests for the associated address and then any leftover
2✔
4856
        // entries will indicate which addresses we should create new
2✔
4857
        // connection requests for.
2✔
4858
        addrMap := make(map[string]*lnwire.NetAddress)
2✔
4859
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
4✔
4860
                addrMap[addr.String()] = addr
2✔
4861
        }
2✔
4862

4863
        // Go through each of the existing connection requests and
4864
        // check if they correspond to the latest set of addresses. If
4865
        // there is a connection requests that does not use one of the latest
4866
        // advertised addresses then remove that connection request.
4867
        var updatedConnReqs []*connmgr.ConnReq
2✔
4868
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
4✔
4869
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
2✔
4870

2✔
4871
                switch _, ok := addrMap[lnAddr]; ok {
2✔
4872
                // If the existing connection request is using one of the
4873
                // latest advertised addresses for the peer then we add it to
4874
                // updatedConnReqs and remove the associated address from
4875
                // addrMap so that we don't recreate this connReq later on.
UNCOV
4876
                case true:
×
UNCOV
4877
                        updatedConnReqs = append(
×
UNCOV
4878
                                updatedConnReqs, connReq,
×
UNCOV
4879
                        )
×
UNCOV
4880
                        delete(addrMap, lnAddr)
×
4881

4882
                // If the existing connection request is using an address that
4883
                // is not one of the latest advertised addresses for the peer
4884
                // then we remove the connecting request from the connection
4885
                // manager.
4886
                case false:
2✔
4887
                        srvrLog.Info(
2✔
4888
                                "Removing conn req:", connReq.Addr.String(),
2✔
4889
                        )
2✔
4890
                        s.connMgr.Remove(connReq.ID())
2✔
4891
                }
4892
        }
4893

4894
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
2✔
4895

2✔
4896
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
2✔
4897
        if !ok {
4✔
4898
                cancelChan = make(chan struct{})
2✔
4899
                s.persistentRetryCancels[pubKeyStr] = cancelChan
2✔
4900
        }
2✔
4901

4902
        // Any addresses left in addrMap are new ones that we have not made
4903
        // connection requests for. So create new connection requests for those.
4904
        // If there is more than one address in the address map, stagger the
4905
        // creation of the connection requests for those.
4906
        go func() {
4✔
4907
                ticker := time.NewTicker(multiAddrConnectionStagger)
2✔
4908
                defer ticker.Stop()
2✔
4909

2✔
4910
                for _, addr := range addrMap {
4✔
4911
                        // Send the persistent connection request to the
2✔
4912
                        // connection manager, saving the request itself so we
2✔
4913
                        // can cancel/restart the process as needed.
2✔
4914
                        connReq := &connmgr.ConnReq{
2✔
4915
                                Addr:      addr,
2✔
4916
                                Permanent: true,
2✔
4917
                        }
2✔
4918

2✔
4919
                        s.mu.Lock()
2✔
4920
                        s.persistentConnReqs[pubKeyStr] = append(
2✔
4921
                                s.persistentConnReqs[pubKeyStr], connReq,
2✔
4922
                        )
2✔
4923
                        s.mu.Unlock()
2✔
4924

2✔
4925
                        srvrLog.Debugf("Attempting persistent connection to "+
2✔
4926
                                "channel peer %v", addr)
2✔
4927

2✔
4928
                        go s.connMgr.Connect(connReq)
2✔
4929

2✔
4930
                        select {
2✔
4931
                        case <-s.quit:
2✔
4932
                                return
2✔
4933
                        case <-cancelChan:
2✔
4934
                                return
2✔
4935
                        case <-ticker.C:
2✔
4936
                        }
4937
                }
4938
        }()
4939
}
4940

4941
// removePeerUnsafe removes the passed peer from the server's state of all
4942
// active peers.
4943
//
4944
// NOTE: Server mutex must be held when calling this function.
4945
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
2✔
4946
        if p == nil {
2✔
UNCOV
4947
                return
×
UNCOV
4948
        }
×
4949

4950
        srvrLog.DebugS(ctx, "Removing peer")
2✔
4951

2✔
4952
        // Exit early if we have already been instructed to shutdown, the peers
2✔
4953
        // will be disconnected in the server shutdown process.
2✔
4954
        if s.Stopped() {
2✔
UNCOV
4955
                return
×
UNCOV
4956
        }
×
4957

4958
        // Capture the peer's public key and string representation.
4959
        pKey := p.PubKey()
2✔
4960
        pubSer := pKey[:]
2✔
4961
        pubStr := string(pubSer)
2✔
4962

2✔
4963
        delete(s.peersByPub, pubStr)
2✔
4964

2✔
4965
        if p.Inbound() {
4✔
4966
                delete(s.inboundPeers, pubStr)
2✔
4967
        } else {
4✔
4968
                delete(s.outboundPeers, pubStr)
2✔
4969
        }
2✔
4970

4971
        // When removing the peer we make sure to disconnect it asynchronously
4972
        // to avoid blocking the main server goroutine because it is holding the
4973
        // server's mutex. Disconnecting the peer might block and wait until the
4974
        // peer has fully started up. This can happen if an inbound and outbound
4975
        // race condition occurs.
4976
        s.wg.Add(1)
2✔
4977
        go func() {
4✔
4978
                defer s.wg.Done()
2✔
4979

2✔
4980
                p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
2✔
4981

2✔
4982
                // If this peer had an active persistent connection request,
2✔
4983
                // remove it.
2✔
4984
                if p.ConnReq() != nil {
4✔
4985
                        s.connMgr.Remove(p.ConnReq().ID())
2✔
4986
                }
2✔
4987

4988
                // Remove the peer's access permission from the access manager.
4989
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
2✔
4990
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
2✔
4991

2✔
4992
                // Copy the peer's error buffer across to the server if it has
2✔
4993
                // any items in it so that we can restore peer errors across
2✔
4994
                // connections. We need to look up the error after the peer has
2✔
4995
                // been disconnected because we write the error in the
2✔
4996
                // `Disconnect` method.
2✔
4997
                s.mu.Lock()
2✔
4998
                if p.ErrorBuffer().Total() > 0 {
4✔
4999
                        s.peerErrors[pubStr] = p.ErrorBuffer()
2✔
5000
                }
2✔
5001
                s.mu.Unlock()
2✔
5002

2✔
5003
                // Inform the peer notifier of a peer offline event so that it
2✔
5004
                // can be reported to clients listening for peer events.
2✔
5005
                var pubKey [33]byte
2✔
5006
                copy(pubKey[:], pubSer)
2✔
5007

2✔
5008
                s.peerNotifier.NotifyPeerOffline(pubKey)
2✔
5009
        }()
5010
}
5011

5012
// ConnectToPeer requests that the server connect to a Lightning Network peer
5013
// at the specified address. This function will *block* until either a
5014
// connection is established, or the initial handshake process fails.
5015
//
5016
// NOTE: This function is safe for concurrent access.
5017
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5018
        perm bool, timeout time.Duration) error {
2✔
5019

2✔
5020
        targetPub := string(addr.IdentityKey.SerializeCompressed())
2✔
5021

2✔
5022
        // Acquire mutex, but use explicit unlocking instead of defer for
2✔
5023
        // better granularity.  In certain conditions, this method requires
2✔
5024
        // making an outbound connection to a remote peer, which requires the
2✔
5025
        // lock to be released, and subsequently reacquired.
2✔
5026
        s.mu.Lock()
2✔
5027

2✔
5028
        // Ensure we're not already connected to this peer.
2✔
5029
        peer, err := s.findPeerByPubStr(targetPub)
2✔
5030

2✔
5031
        // When there's no error it means we already have a connection with this
2✔
5032
        // peer. If this is a dev environment with the `--unsafeconnect` flag
2✔
5033
        // set, we will ignore the existing connection and continue.
2✔
5034
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
4✔
5035
                s.mu.Unlock()
2✔
5036
                return &errPeerAlreadyConnected{peer: peer}
2✔
5037
        }
2✔
5038

5039
        // Peer was not found, continue to pursue connection with peer.
5040

5041
        // If there's already a pending connection request for this pubkey,
5042
        // then we ignore this request to ensure we don't create a redundant
5043
        // connection.
5044
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
4✔
5045
                srvrLog.Warnf("Already have %d persistent connection "+
2✔
5046
                        "requests for %v, connecting anyway.", len(reqs), addr)
2✔
5047
        }
2✔
5048

5049
        // If there's not already a pending or active connection to this node,
5050
        // then instruct the connection manager to attempt to establish a
5051
        // persistent connection to the peer.
5052
        srvrLog.Debugf("Connecting to %v", addr)
2✔
5053
        if perm {
4✔
5054
                connReq := &connmgr.ConnReq{
2✔
5055
                        Addr:      addr,
2✔
5056
                        Permanent: true,
2✔
5057
                }
2✔
5058

2✔
5059
                // Since the user requested a permanent connection, we'll set
2✔
5060
                // the entry to true which will tell the server to continue
2✔
5061
                // reconnecting even if the number of channels with this peer is
2✔
5062
                // zero.
2✔
5063
                s.persistentPeers[targetPub] = true
2✔
5064
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
4✔
5065
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
2✔
5066
                }
2✔
5067
                s.persistentConnReqs[targetPub] = append(
2✔
5068
                        s.persistentConnReqs[targetPub], connReq,
2✔
5069
                )
2✔
5070
                s.mu.Unlock()
2✔
5071

2✔
5072
                go s.connMgr.Connect(connReq)
2✔
5073

2✔
5074
                return nil
2✔
5075
        }
5076
        s.mu.Unlock()
2✔
5077

2✔
5078
        // If we're not making a persistent connection, then we'll attempt to
2✔
5079
        // connect to the target peer. If the we can't make the connection, or
2✔
5080
        // the crypto negotiation breaks down, then return an error to the
2✔
5081
        // caller.
2✔
5082
        errChan := make(chan error, 1)
2✔
5083
        s.connectToPeer(addr, errChan, timeout)
2✔
5084

2✔
5085
        select {
2✔
5086
        case err := <-errChan:
2✔
5087
                return err
2✔
UNCOV
5088
        case <-s.quit:
×
UNCOV
5089
                return ErrServerShuttingDown
×
5090
        }
5091
}
5092

5093
// connectToPeer establishes a connection to a remote peer. errChan is used to
5094
// notify the caller if the connection attempt has failed. Otherwise, it will be
5095
// closed.
5096
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5097
        errChan chan<- error, timeout time.Duration) {
2✔
5098

2✔
5099
        conn, err := brontide.Dial(
2✔
5100
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
2✔
5101
        )
2✔
5102
        if err != nil {
4✔
5103
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
2✔
5104
                select {
2✔
5105
                case errChan <- err:
2✔
UNCOV
5106
                case <-s.quit:
×
5107
                }
5108
                return
2✔
5109
        }
5110

5111
        close(errChan)
2✔
5112

2✔
5113
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
2✔
5114
                conn.LocalAddr(), conn.RemoteAddr())
2✔
5115

2✔
5116
        s.OutboundPeerConnected(nil, conn)
2✔
5117
}
5118

5119
// DisconnectPeer sends the request to server to close the connection with peer
5120
// identified by public key.
5121
//
5122
// NOTE: This function is safe for concurrent access.
5123
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
2✔
5124
        pubBytes := pubKey.SerializeCompressed()
2✔
5125
        pubStr := string(pubBytes)
2✔
5126

2✔
5127
        s.mu.Lock()
2✔
5128
        defer s.mu.Unlock()
2✔
5129

2✔
5130
        // Check that were actually connected to this peer. If not, then we'll
2✔
5131
        // exit in an error as we can't disconnect from a peer that we're not
2✔
5132
        // currently connected to.
2✔
5133
        peer, err := s.findPeerByPubStr(pubStr)
2✔
5134
        if err == ErrPeerNotConnected {
4✔
5135
                return fmt.Errorf("peer %x is not connected", pubBytes)
2✔
5136
        }
2✔
5137

5138
        srvrLog.Infof("Disconnecting from %v", peer)
2✔
5139

2✔
5140
        s.cancelConnReqs(pubStr, nil)
2✔
5141

2✔
5142
        // If this peer was formerly a persistent connection, then we'll remove
2✔
5143
        // them from this map so we don't attempt to re-connect after we
2✔
5144
        // disconnect.
2✔
5145
        delete(s.persistentPeers, pubStr)
2✔
5146
        delete(s.persistentPeersBackoff, pubStr)
2✔
5147

2✔
5148
        // Remove the peer by calling Disconnect. Previously this was done with
2✔
5149
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
2✔
5150
        //
2✔
5151
        // NOTE: We call it in a goroutine to avoid blocking the main server
2✔
5152
        // goroutine because we might hold the server's mutex.
2✔
5153
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
2✔
5154

2✔
5155
        return nil
2✔
5156
}
5157

5158
// OpenChannel sends a request to the server to open a channel to the specified
5159
// peer identified by nodeKey with the passed channel funding parameters.
5160
//
5161
// NOTE: This function is safe for concurrent access.
5162
func (s *server) OpenChannel(
5163
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
2✔
5164

2✔
5165
        // The updateChan will have a buffer of 2, since we expect a ChanPending
2✔
5166
        // + a ChanOpen update, and we want to make sure the funding process is
2✔
5167
        // not blocked if the caller is not reading the updates.
2✔
5168
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
2✔
5169
        req.Err = make(chan error, 1)
2✔
5170

2✔
5171
        // First attempt to locate the target peer to open a channel with, if
2✔
5172
        // we're unable to locate the peer then this request will fail.
2✔
5173
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
2✔
5174
        s.mu.RLock()
2✔
5175
        peer, ok := s.peersByPub[string(pubKeyBytes)]
2✔
5176
        if !ok {
2✔
UNCOV
5177
                s.mu.RUnlock()
×
UNCOV
5178

×
UNCOV
5179
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
UNCOV
5180
                return req.Updates, req.Err
×
UNCOV
5181
        }
×
5182
        req.Peer = peer
2✔
5183
        s.mu.RUnlock()
2✔
5184

2✔
5185
        // We'll wait until the peer is active before beginning the channel
2✔
5186
        // opening process.
2✔
5187
        select {
2✔
5188
        case <-peer.ActiveSignal():
2✔
UNCOV
5189
        case <-peer.QuitSignal():
×
UNCOV
5190
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
UNCOV
5191
                return req.Updates, req.Err
×
5192
        case <-s.quit:
×
5193
                req.Err <- ErrServerShuttingDown
×
5194
                return req.Updates, req.Err
×
5195
        }
5196

5197
        // If the fee rate wasn't specified at this point we fail the funding
5198
        // because of the missing fee rate information. The caller of the
5199
        // `OpenChannel` method needs to make sure that default values for the
5200
        // fee rate are set beforehand.
5201
        if req.FundingFeePerKw == 0 {
2✔
UNCOV
5202
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
UNCOV
5203
                        "the channel opening transaction")
×
5204

×
5205
                return req.Updates, req.Err
×
5206
        }
×
5207

5208
        // Spawn a goroutine to send the funding workflow request to the funding
5209
        // manager. This allows the server to continue handling queries instead
5210
        // of blocking on this request which is exported as a synchronous
5211
        // request to the outside world.
5212
        go s.fundingMgr.InitFundingWorkflow(req)
2✔
5213

2✔
5214
        return req.Updates, req.Err
2✔
5215
}
5216

5217
// Peers returns a slice of all active peers.
5218
//
5219
// NOTE: This function is safe for concurrent access.
5220
func (s *server) Peers() []*peer.Brontide {
2✔
5221
        s.mu.RLock()
2✔
5222
        defer s.mu.RUnlock()
2✔
5223

2✔
5224
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
2✔
5225
        for _, peer := range s.peersByPub {
4✔
5226
                peers = append(peers, peer)
2✔
5227
        }
2✔
5228

5229
        return peers
2✔
5230
}
5231

5232
// computeNextBackoff uses a truncated exponential backoff to compute the next
5233
// backoff using the value of the exiting backoff. The returned duration is
5234
// randomized in either direction by 1/20 to prevent tight loops from
5235
// stabilizing.
5236
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
2✔
5237
        // Double the current backoff, truncating if it exceeds our maximum.
2✔
5238
        nextBackoff := 2 * currBackoff
2✔
5239
        if nextBackoff > maxBackoff {
4✔
5240
                nextBackoff = maxBackoff
2✔
5241
        }
2✔
5242

5243
        // Using 1/10 of our duration as a margin, compute a random offset to
5244
        // avoid the nodes entering connection cycles.
5245
        margin := nextBackoff / 10
2✔
5246

2✔
5247
        var wiggle big.Int
2✔
5248
        wiggle.SetUint64(uint64(margin))
2✔
5249
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
2✔
UNCOV
5250
                // Randomizing is not mission critical, so we'll just return the
×
UNCOV
5251
                // current backoff.
×
UNCOV
5252
                return nextBackoff
×
UNCOV
5253
        }
×
5254

5255
        // Otherwise add in our wiggle, but subtract out half of the margin so
5256
        // that the backoff can tweaked by 1/20 in either direction.
5257
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
2✔
5258
}
5259

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

5264
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5265
func (s *server) fetchNodeAdvertisedAddrs(ctx context.Context,
5266
        pub *btcec.PublicKey) ([]net.Addr, error) {
2✔
5267

2✔
5268
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
2✔
5269
        if err != nil {
2✔
UNCOV
5270
                return nil, err
×
UNCOV
5271
        }
×
5272

5273
        node, err := s.graphDB.FetchNode(ctx, vertex)
2✔
5274
        if err != nil {
4✔
5275
                return nil, err
2✔
5276
        }
2✔
5277

5278
        if len(node.Addresses) == 0 {
4✔
5279
                return nil, errNoAdvertisedAddr
2✔
5280
        }
2✔
5281

5282
        return node.Addresses, nil
2✔
5283
}
5284

5285
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5286
// channel update for a target channel.
5287
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5288
        *lnwire.ChannelUpdate1, error) {
2✔
5289

2✔
5290
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
2✔
5291
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
4✔
5292
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
2✔
5293
                if err != nil {
4✔
5294
                        return nil, err
2✔
5295
                }
2✔
5296

5297
                return netann.ExtractChannelUpdate(
2✔
5298
                        ourPubKey[:], info, edge1, edge2,
2✔
5299
                )
2✔
5300
        }
5301
}
5302

5303
// applyChannelUpdate applies the channel update to the different sub-systems of
5304
// the server. The useAlias boolean denotes whether or not to send an alias in
5305
// place of the real SCID.
5306
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5307
        op *wire.OutPoint, useAlias bool) error {
2✔
5308

2✔
5309
        var (
2✔
5310
                peerAlias    *lnwire.ShortChannelID
2✔
5311
                defaultAlias lnwire.ShortChannelID
2✔
5312
        )
2✔
5313

2✔
5314
        chanID := lnwire.NewChanIDFromOutPoint(*op)
2✔
5315

2✔
5316
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
2✔
5317
        // in the ChannelUpdate if it hasn't been announced yet.
2✔
5318
        if useAlias {
4✔
5319
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
2✔
5320
                if foundAlias != defaultAlias {
4✔
5321
                        peerAlias = &foundAlias
2✔
5322
                }
2✔
5323
        }
5324

5325
        errChan := s.authGossiper.ProcessLocalAnnouncement(
2✔
5326
                update, discovery.RemoteAlias(peerAlias),
2✔
5327
        )
2✔
5328
        select {
2✔
5329
        case err := <-errChan:
2✔
5330
                return err
2✔
UNCOV
5331
        case <-s.quit:
×
UNCOV
5332
                return ErrServerShuttingDown
×
5333
        }
5334
}
5335

5336
// SendCustomMessage sends a custom message to the peer with the specified
5337
// pubkey.
5338
func (s *server) SendCustomMessage(ctx context.Context, peerPub [33]byte,
5339
        msgType lnwire.MessageType, data []byte) error {
2✔
5340

2✔
5341
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
2✔
5342
        if err != nil {
4✔
5343
                return err
2✔
5344
        }
2✔
5345

5346
        // We'll wait until the peer is active, but also listen for
5347
        // cancellation.
5348
        select {
2✔
5349
        case <-peer.ActiveSignal():
2✔
UNCOV
5350
        case <-peer.QuitSignal():
×
UNCOV
5351
                return fmt.Errorf("peer %x disconnected", peerPub)
×
UNCOV
5352
        case <-s.quit:
×
UNCOV
5353
                return ErrServerShuttingDown
×
UNCOV
5354
        case <-ctx.Done():
×
UNCOV
5355
                return ctx.Err()
×
5356
        }
5357

5358
        msg, err := lnwire.NewCustom(msgType, data)
2✔
5359
        if err != nil {
4✔
5360
                return err
2✔
5361
        }
2✔
5362

5363
        // Send the message as low-priority. For now we assume that all
5364
        // application-defined message are low priority.
5365
        return peer.SendMessageLazy(true, msg)
2✔
5366
}
5367

5368
// SendOnionMessage sends a custom message to the peer with the specified
5369
// pubkey.
5370
// TODO(gijs): change this message to include path finding.
5371
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
5372
        pathKey *btcec.PublicKey, onion []byte) error {
2✔
5373

2✔
5374
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
2✔
5375
        if err != nil {
2✔
UNCOV
5376
                return err
×
UNCOV
5377
        }
×
5378

5379
        // We'll wait until the peer is active, but also listen for
5380
        // cancellation.
5381
        select {
2✔
5382
        case <-peer.ActiveSignal():
2✔
UNCOV
5383
        case <-peer.QuitSignal():
×
UNCOV
5384
                return fmt.Errorf("peer %x disconnected", peerPub)
×
UNCOV
5385
        case <-s.quit:
×
UNCOV
5386
                return ErrServerShuttingDown
×
UNCOV
5387
        case <-ctx.Done():
×
UNCOV
5388
                return ctx.Err()
×
5389
        }
5390

5391
        msg := lnwire.NewOnionMessage(pathKey, onion)
2✔
5392

2✔
5393
        // Send the message as low-priority. For now we assume that all
2✔
5394
        // application-defined message are low priority.
2✔
5395
        return peer.SendMessageLazy(true, msg)
2✔
5396
}
5397

5398
// newSweepPkScriptGen creates closure that generates a new public key script
5399
// which should be used to sweep any funds into the on-chain wallet.
5400
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5401
// (p2wkh) output.
5402
func newSweepPkScriptGen(
5403
        wallet lnwallet.WalletController,
5404
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
2✔
5405

2✔
5406
        return func() fn.Result[lnwallet.AddrWithKey] {
4✔
5407
                sweepAddr, err := wallet.NewAddress(
2✔
5408
                        lnwallet.TaprootPubkey, false,
2✔
5409
                        lnwallet.DefaultAccountName,
2✔
5410
                )
2✔
5411
                if err != nil {
2✔
UNCOV
5412
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5413
                }
×
5414

5415
                addr, err := txscript.PayToAddrScript(sweepAddr)
2✔
5416
                if err != nil {
2✔
UNCOV
5417
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5418
                }
×
5419

5420
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
2✔
5421
                        wallet, netParams, addr,
2✔
5422
                )
2✔
5423
                if err != nil {
2✔
UNCOV
5424
                        return fn.Err[lnwallet.AddrWithKey](err)
×
UNCOV
5425
                }
×
5426

5427
                return fn.Ok(lnwallet.AddrWithKey{
2✔
5428
                        DeliveryAddress: addr,
2✔
5429
                        InternalKey:     internalKeyDesc,
2✔
5430
                })
2✔
5431
        }
5432
}
5433

5434
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5435
// finished.
5436
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
2✔
5437
        // Get a list of closed channels.
2✔
5438
        channels, err := s.chanStateDB.FetchClosedChannels(false)
2✔
5439
        if err != nil {
2✔
5440
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
UNCOV
5441
                return nil
×
UNCOV
5442
        }
×
5443

5444
        // Save the SCIDs in a map.
5445
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
2✔
5446
        for _, c := range channels {
4✔
5447
                // If the channel is not pending, its FC has been finalized.
2✔
5448
                if !c.IsPending {
4✔
5449
                        closedSCIDs[c.ShortChanID] = struct{}{}
2✔
5450
                }
2✔
5451
        }
5452

5453
        // Double check whether the reported closed channel has indeed finished
5454
        // closing.
5455
        //
5456
        // NOTE: There are misalignments regarding when a channel's FC is
5457
        // marked as finalized. We double check the pending channels to make
5458
        // sure the returned SCIDs are indeed terminated.
5459
        //
5460
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5461
        pendings, err := s.chanStateDB.FetchPendingChannels()
2✔
5462
        if err != nil {
2✔
UNCOV
5463
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
UNCOV
5464
                return nil
×
UNCOV
5465
        }
×
5466

5467
        for _, c := range pendings {
4✔
5468
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
4✔
5469
                        continue
2✔
5470
                }
5471

5472
                // If the channel is still reported as pending, remove it from
5473
                // the map.
UNCOV
5474
                delete(closedSCIDs, c.ShortChannelID)
×
UNCOV
5475

×
UNCOV
5476
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
UNCOV
5477
                        c.ShortChannelID)
×
5478
        }
5479

5480
        return closedSCIDs
2✔
5481
}
5482

5483
// getStartingBeat returns the current beat. This is used during the startup to
5484
// initialize blockbeat consumers.
5485
func (s *server) getStartingBeat() (*chainio.Beat, error) {
2✔
5486
        // beat is the current blockbeat.
2✔
5487
        var beat *chainio.Beat
2✔
5488

2✔
5489
        // If the node is configured with nochainbackend mode (remote signer),
2✔
5490
        // we will skip fetching the best block.
2✔
5491
        if s.cfg.Bitcoin.Node == "nochainbackend" {
2✔
5492
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
UNCOV
5493
                        "mode")
×
UNCOV
5494

×
UNCOV
5495
                return &chainio.Beat{}, nil
×
UNCOV
5496
        }
×
5497

5498
        // We should get a notification with the current best block immediately
5499
        // by passing a nil block.
5500
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
2✔
5501
        if err != nil {
2✔
UNCOV
5502
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
UNCOV
5503
        }
×
5504
        defer blockEpochs.Cancel()
2✔
5505

2✔
5506
        // We registered for the block epochs with a nil request. The notifier
2✔
5507
        // should send us the current best block immediately. So we need to
2✔
5508
        // wait for it here because we need to know the current best height.
2✔
5509
        select {
2✔
5510
        case bestBlock := <-blockEpochs.Epochs:
2✔
5511
                srvrLog.Infof("Received initial block %v at height %d",
2✔
5512
                        bestBlock.Hash, bestBlock.Height)
2✔
5513

2✔
5514
                // Update the current blockbeat.
2✔
5515
                beat = chainio.NewBeat(*bestBlock)
2✔
5516

5517
        case <-s.quit:
×
5518
                srvrLog.Debug("LND shutting down")
×
5519
        }
5520

5521
        return beat, nil
2✔
5522
}
5523

5524
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5525
// point has an active RBF chan closer.
5526
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5527
        chanPoint wire.OutPoint) bool {
2✔
5528

2✔
5529
        pubBytes := peerPub.SerializeCompressed()
2✔
5530

2✔
5531
        s.mu.RLock()
2✔
5532
        targetPeer, ok := s.peersByPub[string(pubBytes)]
2✔
5533
        s.mu.RUnlock()
2✔
5534
        if !ok {
2✔
UNCOV
5535
                return false
×
UNCOV
5536
        }
×
5537

5538
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
2✔
5539
}
5540

5541
// attemptCoopRbfFeeBump attempts to look up the active chan closer for a
5542
// channel given the outpoint. If found, we'll attempt to do a fee bump,
5543
// returning channels used for updates. If the channel isn't currently active
5544
// (p2p connection established), then his function will return an error.
5545
func (s *server) attemptCoopRbfFeeBump(ctx context.Context,
5546
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5547
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
2✔
5548

2✔
5549
        // First, we'll attempt to look up the channel based on it's
2✔
5550
        // ChannelPoint.
2✔
5551
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
2✔
5552
        if err != nil {
2✔
UNCOV
5553
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
UNCOV
5554
        }
×
5555

5556
        // From the channel, we can now get the pubkey of the peer, then use
5557
        // that to eventually get the chan closer.
5558
        peerPub := channel.IdentityPub.SerializeCompressed()
2✔
5559

2✔
5560
        // Now that we have the peer pub, we can look up the peer itself.
2✔
5561
        s.mu.RLock()
2✔
5562
        targetPeer, ok := s.peersByPub[string(peerPub)]
2✔
5563
        s.mu.RUnlock()
2✔
5564
        if !ok {
2✔
UNCOV
5565
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
UNCOV
5566
                        "not online", chanPoint)
×
UNCOV
5567
        }
×
5568

5569
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
2✔
5570
                ctx, chanPoint, feeRate, deliveryScript,
2✔
5571
        )
2✔
5572
        if err != nil {
2✔
UNCOV
5573
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
UNCOV
5574
                        "%w", err)
×
UNCOV
5575
        }
×
5576

5577
        return closeUpdates, nil
2✔
5578
}
5579

5580
// AttemptRBFCloseUpdate attempts to trigger a new RBF iteration for a co-op
5581
// close update. This route it to be used only if the target channel in question
5582
// is no longer active in the link. This can happen when we restart while we
5583
// already have done a single RBF co-op close iteration.
5584
func (s *server) AttemptRBFCloseUpdate(ctx context.Context,
5585
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5586
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
2✔
5587

2✔
5588
        // If the channel is present in the switch, then the request should flow
2✔
5589
        // through the switch instead.
2✔
5590
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5591
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
2✔
UNCOV
5592
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
UNCOV
5593
                        "invalid request", chanPoint)
×
UNCOV
5594
        }
×
5595

5596
        // At this point, we know that the channel isn't present in the link, so
5597
        // we'll check to see if we have an entry in the active chan closer map.
5598
        updates, err := s.attemptCoopRbfFeeBump(
2✔
5599
                ctx, chanPoint, feeRate, deliveryScript,
2✔
5600
        )
2✔
5601
        if err != nil {
2✔
UNCOV
5602
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
UNCOV
5603
                        "ChannelPoint(%v)", chanPoint)
×
UNCOV
5604
        }
×
5605

5606
        return updates, nil
2✔
5607
}
5608

5609
// calculateNodeAnnouncementTimestamp returns the timestamp to use for a node
5610
// announcement, ensuring it's at least one second after the previously
5611
// persisted timestamp. This ensures BOLT-07 compliance, which requires node
5612
// announcements to have strictly increasing timestamps.
5613
func calculateNodeAnnouncementTimestamp(persistedTime,
5614
        currentTime time.Time) time.Time {
11✔
5615

11✔
5616
        if persistedTime.Unix() >= currentTime.Unix() {
19✔
5617
                return persistedTime.Add(time.Second)
8✔
5618
        }
8✔
5619

5620
        return currentTime
5✔
5621
}
5622

5623
// setSelfNode configures and sets the server's self node. It sets the node
5624
// announcement, signs it, and updates the source node in the graph. When
5625
// determining values such as color and alias, the method prioritizes values
5626
// set in the config, then values previously persisted on disk, and finally
5627
// falls back to the defaults.
5628
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5629
        listenAddrs []net.Addr) error {
2✔
5630

2✔
5631
        // If we were requested to automatically configure port forwarding,
2✔
5632
        // we'll use the ports that the server will be listening on.
2✔
5633
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
2✔
5634
        for _, ip := range s.cfg.ExternalIPs {
4✔
5635
                externalIPStrings = append(externalIPStrings, ip.String())
2✔
5636
        }
2✔
5637
        if s.natTraversal != nil {
2✔
UNCOV
5638
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
UNCOV
5639
                for _, listenAddr := range listenAddrs {
×
UNCOV
5640
                        // At this point, the listen addresses should have
×
UNCOV
5641
                        // already been normalized, so it's safe to ignore the
×
UNCOV
5642
                        // errors.
×
UNCOV
5643
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
UNCOV
5644
                        port, _ := strconv.Atoi(portStr)
×
UNCOV
5645

×
UNCOV
5646
                        listenPorts = append(listenPorts, uint16(port))
×
UNCOV
5647
                }
×
5648

UNCOV
5649
                ips, err := s.configurePortForwarding(listenPorts...)
×
UNCOV
5650
                if err != nil {
×
UNCOV
5651
                        srvrLog.Errorf("Unable to automatically set up port "+
×
UNCOV
5652
                                "forwarding using %s: %v",
×
5653
                                s.natTraversal.Name(), err)
×
5654
                } else {
×
5655
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5656
                                "using %s to advertise external IP",
×
5657
                                s.natTraversal.Name())
×
5658
                        externalIPStrings = append(externalIPStrings, ips...)
×
5659
                }
×
5660
        }
5661

5662
        // Normalize the external IP strings to net.Addr.
5663
        addrs, err := lncfg.NormalizeAddresses(
2✔
5664
                externalIPStrings, strconv.Itoa(defaultPeerPort),
2✔
5665
                s.cfg.net.ResolveTCPAddr,
2✔
5666
        )
2✔
5667
        if err != nil {
2✔
5668
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5669
        }
×
5670

5671
        // Parse the color from config. We will update this later if the config
5672
        // color is not changed from default (#3399FF) and we have a value in
5673
        // the source node.
5674
        nodeColor, err := lncfg.ParseHexColor(s.cfg.Color)
2✔
5675
        if err != nil {
2✔
UNCOV
5676
                return fmt.Errorf("unable to parse color: %w", err)
×
UNCOV
5677
        }
×
5678

5679
        var (
2✔
5680
                alias          = s.cfg.Alias
2✔
5681
                nodeLastUpdate = time.Now()
2✔
5682
        )
2✔
5683

2✔
5684
        srcNode, err := s.graphDB.SourceNode(ctx)
2✔
5685
        switch {
2✔
5686
        case err == nil:
2✔
5687
                // If we have a source node persisted in the DB already, then we
2✔
5688
                // just need to make sure that the new LastUpdate time is at
2✔
5689
                // least one second after the last update time.
2✔
5690
                nodeLastUpdate = calculateNodeAnnouncementTimestamp(
2✔
5691
                        srcNode.LastUpdate, nodeLastUpdate,
2✔
5692
                )
2✔
5693

2✔
5694
                // If the color is not changed from default, it means that we
2✔
5695
                // didn't specify a different color in the config. We'll use the
2✔
5696
                // source node's color.
2✔
5697
                if s.cfg.Color == defaultColor {
4✔
5698
                        srcNode.Color.WhenSome(func(rgba color.RGBA) {
4✔
5699
                                nodeColor = rgba
2✔
5700
                        })
2✔
5701
                }
5702

5703
                // If an alias is not specified in the config, we'll use the
5704
                // source node's alias.
5705
                if alias == "" {
4✔
5706
                        srcNode.Alias.WhenSome(func(s string) {
4✔
5707
                                alias = s
2✔
5708
                        })
2✔
5709
                }
5710

5711
                // If the `externalip` is not specified in the config, it means
5712
                // `addrs` will be empty, we'll use the source node's addresses.
5713
                if len(s.cfg.ExternalIPs) == 0 {
4✔
5714
                        addrs = srcNode.Addresses
2✔
5715
                }
2✔
5716

5717
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
2✔
5718
                // If an alias is not specified in the config, we'll use the
2✔
5719
                // default, which is the first 10 bytes of the serialized
2✔
5720
                // pubkey.
2✔
5721
                if alias == "" {
4✔
5722
                        alias = hex.EncodeToString(nodePub[:10])
2✔
5723
                }
2✔
5724

5725
        // If the above cases are not matched, then we have an unhandled non
5726
        // nil error.
UNCOV
5727
        default:
×
UNCOV
5728
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5729
        }
5730

5731
        nodeAlias, err := lnwire.NewNodeAlias(alias)
2✔
5732
        if err != nil {
2✔
UNCOV
5733
                return err
×
UNCOV
5734
        }
×
5735

5736
        // TODO(abdulkbk): potentially find a way to use the source node's
5737
        // features in the self node.
5738
        selfNode := models.NewV1Node(
2✔
5739
                nodePub, &models.NodeV1Fields{
2✔
5740
                        Alias:      nodeAlias.String(),
2✔
5741
                        Color:      nodeColor,
2✔
5742
                        LastUpdate: nodeLastUpdate,
2✔
5743
                        Addresses:  addrs,
2✔
5744
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
2✔
5745
                },
2✔
5746
        )
2✔
5747

2✔
5748
        // Based on the disk representation of the node announcement generated
2✔
5749
        // above, we'll generate a node announcement that can go out on the
2✔
5750
        // network so we can properly sign it.
2✔
5751
        nodeAnn, err := selfNode.NodeAnnouncement(false)
2✔
5752
        if err != nil {
2✔
UNCOV
5753
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
UNCOV
5754
        }
×
5755

5756
        // With the announcement generated, we'll sign it to properly
5757
        // authenticate the message on the network.
5758
        authSig, err := netann.SignAnnouncement(
2✔
5759
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
2✔
5760
        )
2✔
5761
        if err != nil {
2✔
UNCOV
5762
                return fmt.Errorf("unable to generate signature for self node "+
×
UNCOV
5763
                        "announcement: %v", err)
×
UNCOV
5764
        }
×
5765

5766
        selfNode.AuthSigBytes = authSig.Serialize()
2✔
5767
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
2✔
5768
                selfNode.AuthSigBytes,
2✔
5769
        )
2✔
5770
        if err != nil {
2✔
UNCOV
5771
                return err
×
UNCOV
5772
        }
×
5773

5774
        // Finally, we'll update the representation on disk, and update our
5775
        // cached in-memory version as well.
5776
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
2✔
5777
                return fmt.Errorf("can't set self node: %w", err)
×
5778
        }
×
5779

5780
        s.currentNodeAnn = nodeAnn
2✔
5781

2✔
5782
        return nil
2✔
5783
}
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

© 2026 Coveralls, Inc