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

lightningnetwork / lnd / 16181619122

09 Jul 2025 10:33PM UTC coverage: 55.326% (-2.3%) from 57.611%
16181619122

Pull #10060

github

web-flow
Merge d15e8671f into 0e830da9d
Pull Request #10060: sweep: fix expected spending events being missed

9 of 26 new or added lines in 2 files covered. (34.62%)

23695 existing lines in 280 files now uncovered.

108518 of 196143 relevant lines covered (55.33%)

22354.81 hits per line

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

0.0
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

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

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

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

248
        chanStatusMgr *netann.ChanStatusManager
249

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

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

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

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

270
        mu sync.RWMutex
271

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

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

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

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

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

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

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

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

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

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

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

413
        hostAnn *netann.HostAnnouncer
414

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

418
        customMessageServer *subscribe.Server
419

420
        // txPublisher is a publisher with fee-bumping capability.
421
        txPublisher *sweep.TxPublisher
422

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

427
        // peerAccessMan implements peer access controls.
428
        peerAccessMan *accessMan
429

430
        quit chan struct{}
431

432
        wg sync.WaitGroup
433
}
434

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

UNCOV
443
        s.wg.Add(1)
×
UNCOV
444
        go func() {
×
UNCOV
445
                defer func() {
×
UNCOV
446
                        graphSub.Cancel()
×
UNCOV
447
                        s.wg.Done()
×
UNCOV
448
                }()
×
449

UNCOV
450
                for {
×
UNCOV
451
                        select {
×
UNCOV
452
                        case <-s.quit:
×
UNCOV
453
                                return
×
454

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

UNCOV
462
                                for _, update := range topChange.NodeUpdates {
×
UNCOV
463
                                        pubKeyStr := string(
×
UNCOV
464
                                                update.IdentityKey.
×
UNCOV
465
                                                        SerializeCompressed(),
×
UNCOV
466
                                        )
×
UNCOV
467

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

UNCOV
477
                                        addrs := make([]*lnwire.NetAddress, 0,
×
UNCOV
478
                                                len(update.Addresses))
×
UNCOV
479

×
UNCOV
480
                                        for _, addr := range update.Addresses {
×
UNCOV
481
                                                addrs = append(addrs,
×
UNCOV
482
                                                        &lnwire.NetAddress{
×
UNCOV
483
                                                                IdentityKey: update.IdentityKey,
×
UNCOV
484
                                                                Address:     addr,
×
UNCOV
485
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
486
                                                        },
×
UNCOV
487
                                                )
×
UNCOV
488
                                        }
×
489

UNCOV
490
                                        s.mu.Lock()
×
UNCOV
491

×
UNCOV
492
                                        // Update the stored addresses for this
×
UNCOV
493
                                        // to peer to reflect the new set.
×
UNCOV
494
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
×
UNCOV
495

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

UNCOV
506
                                        s.mu.Unlock()
×
UNCOV
507

×
UNCOV
508
                                        s.connectToPersistentPeer(pubKeyStr)
×
509
                                }
510
                        }
511
                }
512
        }()
513

UNCOV
514
        return nil
×
515
}
516

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

522
        // Msg is the custom wire message.
523
        Msg *lnwire.Custom
524
}
525

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

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

UNCOV
550
        if tor.IsOnionHost(host) {
×
551
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
552
        }
×
553

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

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

×
UNCOV
567
        return func(a net.Addr) (net.Conn, error) {
×
UNCOV
568
                lnAddr := a.(*lnwire.NetAddress)
×
UNCOV
569
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
UNCOV
570
        }
×
571
}
572

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

×
UNCOV
586
        var (
×
UNCOV
587
                err         error
×
UNCOV
588
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
UNCOV
589

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

×
UNCOV
597
        var serializedPubKey [33]byte
×
UNCOV
598
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
599

×
UNCOV
600
        netParams := cfg.ActiveNetParams.Params
×
UNCOV
601

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

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

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

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

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

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

×
631
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
632
                        "aux controllers")
×
633
        }
×
634

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

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

×
UNCOV
671
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
UNCOV
672

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

×
UNCOV
687
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
×
UNCOV
688
                        cc.ChainNotifier,
×
UNCOV
689
                ),
×
UNCOV
690
                channelNotifier: channelnotifier.New(
×
UNCOV
691
                        dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
692
                ),
×
UNCOV
693

×
UNCOV
694
                identityECDH:   nodeKeyECDH,
×
UNCOV
695
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
UNCOV
696
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
UNCOV
697

×
UNCOV
698
                listenAddrs: listenAddrs,
×
UNCOV
699

×
UNCOV
700
                // TODO(roasbeef): derive proper onion key based on rotation
×
UNCOV
701
                // schedule
×
UNCOV
702
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
UNCOV
703

×
UNCOV
704
                torController: torController,
×
UNCOV
705

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

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

×
UNCOV
722
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
723

×
UNCOV
724
                customMessageServer: subscribe.NewServer(),
×
UNCOV
725

×
UNCOV
726
                tlsManager: tlsManager,
×
UNCOV
727

×
UNCOV
728
                featureMgr: featureMgr,
×
UNCOV
729
                quit:       make(chan struct{}),
×
UNCOV
730
        }
×
UNCOV
731

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

UNCOV
743
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
744
        if err != nil {
×
745
                return nil, err
×
746
        }
×
747

UNCOV
748
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
UNCOV
749
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
UNCOV
750
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
UNCOV
751
        )
×
UNCOV
752
        s.invoices = invoices.NewRegistry(
×
UNCOV
753
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
UNCOV
754
        )
×
UNCOV
755

×
UNCOV
756
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
757

×
UNCOV
758
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
759
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
760

×
UNCOV
761
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
UNCOV
762
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
UNCOV
763
                if err != nil {
×
764
                        return err
×
765
                }
×
766

UNCOV
767
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
768

×
UNCOV
769
                return nil
×
770
        }
771

UNCOV
772
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
773
        if err != nil {
×
774
                return nil, err
×
775
        }
×
776

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

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

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

UNCOV
829
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
830
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
831
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
832
        )
×
UNCOV
833

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

×
UNCOV
847
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
848
        if err != nil {
×
849
                return nil, err
×
850
        }
×
UNCOV
851
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
852

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

×
858
                discoveryTimeout := time.Duration(10 * time.Second)
×
859

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

×
874
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
875
                                "enabled device")
×
876

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

886
                        s.natTraversal = pmp
×
887
                }
888
        }
889

890
        // If we were requested to automatically configure port forwarding,
891
        // we'll use the ports that the server will be listening on.
UNCOV
892
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
×
UNCOV
893
        for idx, ip := range cfg.ExternalIPs {
×
UNCOV
894
                externalIPStrings[idx] = ip.String()
×
UNCOV
895
        }
×
UNCOV
896
        if s.natTraversal != nil {
×
897
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
898
                for _, listenAddr := range listenAddrs {
×
899
                        // At this point, the listen addresses should have
×
900
                        // already been normalized, so it's safe to ignore the
×
901
                        // errors.
×
902
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
903
                        port, _ := strconv.Atoi(portStr)
×
904

×
905
                        listenPorts = append(listenPorts, uint16(port))
×
906
                }
×
907

908
                ips, err := s.configurePortForwarding(listenPorts...)
×
909
                if err != nil {
×
910
                        srvrLog.Errorf("Unable to automatically set up port "+
×
911
                                "forwarding using %s: %v",
×
912
                                s.natTraversal.Name(), err)
×
913
                } else {
×
914
                        srvrLog.Infof("Automatically set up port forwarding "+
×
915
                                "using %s to advertise external IP",
×
916
                                s.natTraversal.Name())
×
917
                        externalIPStrings = append(externalIPStrings, ips...)
×
918
                }
×
919
        }
920

921
        // If external IP addresses have been specified, add those to the list
922
        // of this server's addresses.
UNCOV
923
        externalIPs, err := lncfg.NormalizeAddresses(
×
UNCOV
924
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
925
                cfg.net.ResolveTCPAddr,
×
UNCOV
926
        )
×
UNCOV
927
        if err != nil {
×
928
                return nil, err
×
929
        }
×
930

UNCOV
931
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
UNCOV
932
        selfAddrs = append(selfAddrs, externalIPs...)
×
UNCOV
933

×
UNCOV
934
        // We'll now reconstruct a node announcement based on our current
×
UNCOV
935
        // configuration so we can send it out as a sort of heart beat within
×
UNCOV
936
        // the network.
×
UNCOV
937
        //
×
UNCOV
938
        // We'll start by parsing the node color from configuration.
×
UNCOV
939
        color, err := lncfg.ParseHexColor(cfg.Color)
×
UNCOV
940
        if err != nil {
×
941
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
942
                return nil, err
×
943
        }
×
944

945
        // If no alias is provided, default to first 10 characters of public
946
        // key.
UNCOV
947
        alias := cfg.Alias
×
UNCOV
948
        if alias == "" {
×
UNCOV
949
                alias = hex.EncodeToString(serializedPubKey[:10])
×
UNCOV
950
        }
×
UNCOV
951
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
952
        if err != nil {
×
953
                return nil, err
×
954
        }
×
955

956
        // TODO(elle): All previously persisted node announcement fields (ie,
957
        //  not just LastUpdate) should be consulted here to ensure that we
958
        //  aren't overwriting any fields that may have been set during the
959
        //  last run of lnd.
UNCOV
960
        nodeLastUpdate := time.Now()
×
UNCOV
961
        srcNode, err := dbs.GraphDB.SourceNode(ctx)
×
UNCOV
962
        switch {
×
963
        // If we have a source node persisted in the DB already, then we just
964
        // need to make sure that the new LastUpdate time is at least one
965
        // second after the last update time.
UNCOV
966
        case err == nil:
×
UNCOV
967
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
×
UNCOV
968
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
×
UNCOV
969
                }
×
970

971
        // If we don't have a source node persisted in the DB, then we'll
972
        // create a new one with the current time as the LastUpdate.
UNCOV
973
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
×
974

975
        // If the above cases are not matched, then we have an unhandled non
976
        // nil error.
977
        default:
×
978
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
979
        }
980

UNCOV
981
        selfNode := &models.LightningNode{
×
UNCOV
982
                HaveNodeAnnouncement: true,
×
UNCOV
983
                LastUpdate:           nodeLastUpdate,
×
UNCOV
984
                Addresses:            selfAddrs,
×
UNCOV
985
                Alias:                nodeAlias.String(),
×
UNCOV
986
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
987
                Color:                color,
×
UNCOV
988
        }
×
UNCOV
989
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
990

×
UNCOV
991
        // Based on the disk representation of the node announcement generated
×
UNCOV
992
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
993
        // network so we can properly sign it.
×
UNCOV
994
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
995
        if err != nil {
×
996
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
997
        }
×
998

999
        // With the announcement generated, we'll sign it to properly
1000
        // authenticate the message on the network.
UNCOV
1001
        authSig, err := netann.SignAnnouncement(
×
UNCOV
1002
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
UNCOV
1003
        )
×
UNCOV
1004
        if err != nil {
×
1005
                return nil, fmt.Errorf("unable to generate signature for "+
×
1006
                        "self node announcement: %v", err)
×
1007
        }
×
UNCOV
1008
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
1009
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
1010
                selfNode.AuthSigBytes,
×
UNCOV
1011
        )
×
UNCOV
1012
        if err != nil {
×
1013
                return nil, err
×
1014
        }
×
1015

1016
        // Finally, we'll update the representation on disk, and update our
1017
        // cached in-memory version as well.
UNCOV
1018
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
×
1019
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1020
        }
×
UNCOV
1021
        s.currentNodeAnn = nodeAnn
×
UNCOV
1022

×
UNCOV
1023
        // The router will get access to the payment ID sequencer, such that it
×
UNCOV
1024
        // can generate unique payment IDs.
×
UNCOV
1025
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
1026
        if err != nil {
×
1027
                return nil, err
×
1028
        }
×
1029

1030
        // Instantiate mission control with config from the sub server.
1031
        //
1032
        // TODO(joostjager): When we are further in the process of moving to sub
1033
        // servers, the mission control instance itself can be moved there too.
UNCOV
1034
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
1035

×
UNCOV
1036
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
1037
        var estimator routing.Estimator
×
UNCOV
1038
        if cfg.Estimator != nil {
×
1039
                estimator = cfg.Estimator
×
UNCOV
1040
        } else {
×
UNCOV
1041
                switch routingConfig.ProbabilityEstimatorType {
×
UNCOV
1042
                case routing.AprioriEstimatorName:
×
UNCOV
1043
                        aCfg := routingConfig.AprioriConfig
×
UNCOV
1044
                        aprioriConfig := routing.AprioriConfig{
×
UNCOV
1045
                                AprioriHopProbability: aCfg.HopProbability,
×
UNCOV
1046
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
UNCOV
1047
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
1048
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
1049
                        }
×
UNCOV
1050

×
UNCOV
1051
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
1052
                                aprioriConfig,
×
UNCOV
1053
                        )
×
UNCOV
1054
                        if err != nil {
×
1055
                                return nil, err
×
1056
                        }
×
1057

1058
                case routing.BimodalEstimatorName:
×
1059
                        bCfg := routingConfig.BimodalConfig
×
1060
                        bimodalConfig := routing.BimodalConfig{
×
1061
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1062
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1063
                                        bCfg.Scale,
×
1064
                                ),
×
1065
                                BimodalDecayTime: bCfg.DecayTime,
×
1066
                        }
×
1067

×
1068
                        estimator, err = routing.NewBimodalEstimator(
×
1069
                                bimodalConfig,
×
1070
                        )
×
1071
                        if err != nil {
×
1072
                                return nil, err
×
1073
                        }
×
1074

1075
                default:
×
1076
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1077
                                routingConfig.ProbabilityEstimatorType)
×
1078
                }
1079
        }
1080

UNCOV
1081
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
1082
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
UNCOV
1083
                Estimator:               estimator,
×
UNCOV
1084
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
1085
                McFlushInterval:         routingConfig.McFlushInterval,
×
UNCOV
1086
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
UNCOV
1087
        }
×
UNCOV
1088

×
UNCOV
1089
        s.missionController, err = routing.NewMissionController(
×
UNCOV
1090
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
UNCOV
1091
        )
×
UNCOV
1092
        if err != nil {
×
1093
                return nil, fmt.Errorf("can't create mission control "+
×
1094
                        "manager: %w", err)
×
1095
        }
×
UNCOV
1096
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
1097
                routing.DefaultMissionControlNamespace,
×
UNCOV
1098
        )
×
UNCOV
1099
        if err != nil {
×
1100
                return nil, fmt.Errorf("can't create mission control in the "+
×
1101
                        "default namespace: %w", err)
×
1102
        }
×
1103

UNCOV
1104
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
UNCOV
1105
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
UNCOV
1106
                int64(routingConfig.AttemptCost),
×
UNCOV
1107
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
1108
                routingConfig.MinRouteProbability)
×
UNCOV
1109

×
UNCOV
1110
        pathFindingConfig := routing.PathFindingConfig{
×
UNCOV
1111
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
UNCOV
1112
                        routingConfig.AttemptCost,
×
UNCOV
1113
                ),
×
UNCOV
1114
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
1115
                MinProbability: routingConfig.MinRouteProbability,
×
UNCOV
1116
        }
×
UNCOV
1117

×
UNCOV
1118
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
×
UNCOV
1119
        if err != nil {
×
1120
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1121
        }
×
UNCOV
1122
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
1123
                GraphSessionFactory: dbs.GraphDB,
×
UNCOV
1124
                SourceNode:          sourceNode,
×
UNCOV
1125
                MissionControl:      s.defaultMC,
×
UNCOV
1126
                GetLink:             s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1127
                PathFindingConfig:   pathFindingConfig,
×
UNCOV
1128
        }
×
UNCOV
1129

×
UNCOV
1130
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
UNCOV
1131

×
UNCOV
1132
        s.controlTower = routing.NewControlTower(paymentControl)
×
UNCOV
1133

×
UNCOV
1134
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1135
                cfg.Routing.StrictZombiePruning
×
UNCOV
1136

×
UNCOV
1137
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1138
                SelfNode:            selfNode.PubKeyBytes,
×
UNCOV
1139
                Graph:               dbs.GraphDB,
×
UNCOV
1140
                Chain:               cc.ChainIO,
×
UNCOV
1141
                ChainView:           cc.ChainView,
×
UNCOV
1142
                Notifier:            cc.ChainNotifier,
×
UNCOV
1143
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1144
                GraphPruneInterval:  time.Hour,
×
UNCOV
1145
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1146
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1147
                StrictZombiePruning: strictPruning,
×
UNCOV
1148
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1149
        })
×
UNCOV
1150
        if err != nil {
×
1151
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1152
        }
×
1153

UNCOV
1154
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1155
                SelfNode:           selfNode.PubKeyBytes,
×
UNCOV
1156
                RoutingGraph:       dbs.GraphDB,
×
UNCOV
1157
                Chain:              cc.ChainIO,
×
UNCOV
1158
                Payer:              s.htlcSwitch,
×
UNCOV
1159
                Control:            s.controlTower,
×
UNCOV
1160
                MissionControl:     s.defaultMC,
×
UNCOV
1161
                SessionSource:      paymentSessionSource,
×
UNCOV
1162
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1163
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1164
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1165
                Clock:              clock.NewDefaultClock(),
×
UNCOV
1166
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
UNCOV
1167
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1168
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1169
        })
×
UNCOV
1170
        if err != nil {
×
1171
                return nil, fmt.Errorf("can't create router: %w", err)
×
1172
        }
×
1173

UNCOV
1174
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1175
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1176
        if err != nil {
×
1177
                return nil, err
×
1178
        }
×
UNCOV
1179
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1180
        if err != nil {
×
1181
                return nil, err
×
1182
        }
×
1183

UNCOV
1184
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1185

×
UNCOV
1186
        s.authGossiper = discovery.New(discovery.Config{
×
UNCOV
1187
                Graph:                 s.graphBuilder,
×
UNCOV
1188
                ChainIO:               s.cc.ChainIO,
×
UNCOV
1189
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1190
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1191
                Broadcast:             s.BroadcastMessage,
×
UNCOV
1192
                ChanSeries:            chanSeries,
×
UNCOV
1193
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1194
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1195
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
UNCOV
1196
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
UNCOV
1197
                        error) {
×
1198

×
1199
                        return s.genNodeAnnouncement(nil)
×
1200
                },
×
1201
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1202
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1203
                RetransmitTicker:        ticker.New(time.Minute * 30),
1204
                RebroadcastInterval:     time.Hour * 24,
1205
                WaitingProofStore:       waitingProofStore,
1206
                MessageStore:            gossipMessageStore,
1207
                AnnSigner:               s.nodeSigner,
1208
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1209
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1210
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1211
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1212
                MinimumBatchSize:        10,
1213
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1214
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1215
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1216
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1217
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1218
                IsAlias:                 aliasmgr.IsAlias,
1219
                SignAliasUpdate:         s.signAliasUpdate,
1220
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1221
                GetAlias:                s.aliasMgr.GetPeerAlias,
1222
                FindChannel:             s.findChannel,
1223
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1224
                ScidCloser:              scidCloserMan,
1225
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1226
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1227
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1228
        }, nodeKeyDesc)
1229

UNCOV
1230
        accessCfg := &accessManConfig{
×
UNCOV
1231
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
UNCOV
1232
                        error) {
×
UNCOV
1233

×
UNCOV
1234
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
×
UNCOV
1235
                        return s.chanStateDB.FetchPermAndTempPeers(
×
UNCOV
1236
                                genesisHash[:],
×
UNCOV
1237
                        )
×
UNCOV
1238
                },
×
1239
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1240
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1241
        }
1242

UNCOV
1243
        peerAccessMan, err := newAccessMan(accessCfg)
×
UNCOV
1244
        if err != nil {
×
1245
                return nil, err
×
1246
        }
×
1247

UNCOV
1248
        s.peerAccessMan = peerAccessMan
×
UNCOV
1249

×
UNCOV
1250
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1251
        //nolint:ll
×
UNCOV
1252
        s.localChanMgr = &localchans.Manager{
×
UNCOV
1253
                SelfPub:              nodeKeyDesc.PubKey,
×
UNCOV
1254
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
UNCOV
1255
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
×
UNCOV
1256
                        *models.ChannelEdgePolicy) error) error {
×
UNCOV
1257

×
UNCOV
1258
                        return s.graphDB.ForEachNodeChannel(selfVertex,
×
UNCOV
1259
                                func(c *models.ChannelEdgeInfo,
×
UNCOV
1260
                                        e *models.ChannelEdgePolicy,
×
UNCOV
1261
                                        _ *models.ChannelEdgePolicy) error {
×
UNCOV
1262

×
UNCOV
1263
                                        // NOTE: The invoked callback here may
×
UNCOV
1264
                                        // receive a nil channel policy.
×
UNCOV
1265
                                        return cb(c, e)
×
UNCOV
1266
                                },
×
1267
                        )
1268
                },
1269
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1270
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1271
                FetchChannel:              s.chanStateDB.FetchChannel,
1272
                AddEdge: func(ctx context.Context,
1273
                        edge *models.ChannelEdgeInfo) error {
×
1274

×
1275
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1276
                },
×
1277
        }
1278

UNCOV
1279
        utxnStore, err := contractcourt.NewNurseryStore(
×
UNCOV
1280
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
UNCOV
1281
        )
×
UNCOV
1282
        if err != nil {
×
1283
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1284
                return nil, err
×
1285
        }
×
1286

UNCOV
1287
        sweeperStore, err := sweep.NewSweeperStore(
×
UNCOV
1288
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1289
        )
×
UNCOV
1290
        if err != nil {
×
1291
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1292
                return nil, err
×
1293
        }
×
1294

UNCOV
1295
        aggregator := sweep.NewBudgetAggregator(
×
UNCOV
1296
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1297
                s.implCfg.AuxSweeper,
×
UNCOV
1298
        )
×
UNCOV
1299

×
UNCOV
1300
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
UNCOV
1301
                Signer:     cc.Wallet.Cfg.Signer,
×
UNCOV
1302
                Wallet:     cc.Wallet,
×
UNCOV
1303
                Estimator:  cc.FeeEstimator,
×
UNCOV
1304
                Notifier:   cc.ChainNotifier,
×
UNCOV
1305
                AuxSweeper: s.implCfg.AuxSweeper,
×
NEW
1306
                ChainIO:    cc.ChainIO,
×
UNCOV
1307
        })
×
UNCOV
1308

×
UNCOV
1309
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
UNCOV
1310
                FeeEstimator: cc.FeeEstimator,
×
UNCOV
1311
                GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1312
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1313
                ),
×
UNCOV
1314
                Signer:               cc.Wallet.Cfg.Signer,
×
UNCOV
1315
                Wallet:               newSweeperWallet(cc.Wallet),
×
UNCOV
1316
                Mempool:              cc.MempoolNotifier,
×
UNCOV
1317
                Notifier:             cc.ChainNotifier,
×
UNCOV
1318
                Store:                sweeperStore,
×
UNCOV
1319
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
UNCOV
1320
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
UNCOV
1321
                Aggregator:           aggregator,
×
UNCOV
1322
                Publisher:            s.txPublisher,
×
UNCOV
1323
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
UNCOV
1324
        })
×
UNCOV
1325

×
UNCOV
1326
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
UNCOV
1327
                ChainIO:             cc.ChainIO,
×
UNCOV
1328
                ConfDepth:           1,
×
UNCOV
1329
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
UNCOV
1330
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
UNCOV
1331
                Notifier:            cc.ChainNotifier,
×
UNCOV
1332
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
UNCOV
1333
                Store:               utxnStore,
×
UNCOV
1334
                SweepInput:          s.sweeper.SweepInput,
×
UNCOV
1335
                Budget:              s.cfg.Sweeper.Budget,
×
UNCOV
1336
        })
×
UNCOV
1337

×
UNCOV
1338
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
UNCOV
1339
        closeLink := func(chanPoint *wire.OutPoint,
×
UNCOV
1340
                closureType contractcourt.ChannelCloseType) {
×
UNCOV
1341
                // TODO(conner): Properly respect the update and error channels
×
UNCOV
1342
                // returned by CloseLink.
×
UNCOV
1343

×
UNCOV
1344
                // Instruct the switch to close the channel.  Provide no close out
×
UNCOV
1345
                // delivery script or target fee per kw because user input is not
×
UNCOV
1346
                // available when the remote peer closes the channel.
×
UNCOV
1347
                s.htlcSwitch.CloseLink(
×
UNCOV
1348
                        context.Background(), chanPoint, closureType, 0, 0, nil,
×
UNCOV
1349
                )
×
UNCOV
1350
        }
×
1351

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

×
UNCOV
1356
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
UNCOV
1357
                &contractcourt.BreachConfig{
×
UNCOV
1358
                        CloseLink: closeLink,
×
UNCOV
1359
                        DB:        s.chanStateDB,
×
UNCOV
1360
                        Estimator: s.cc.FeeEstimator,
×
UNCOV
1361
                        GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1362
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1363
                        ),
×
UNCOV
1364
                        Notifier:           cc.ChainNotifier,
×
UNCOV
1365
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1366
                        ContractBreaches:   contractBreaches,
×
UNCOV
1367
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1368
                        Store: contractcourt.NewRetributionStore(
×
UNCOV
1369
                                dbs.ChanStateDB,
×
UNCOV
1370
                        ),
×
UNCOV
1371
                        AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1372
                },
×
UNCOV
1373
        )
×
UNCOV
1374

×
UNCOV
1375
        //nolint:ll
×
UNCOV
1376
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
UNCOV
1377
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1378
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
UNCOV
1379
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
UNCOV
1380
                NewSweepAddr: func() ([]byte, error) {
×
1381
                        addr, err := newSweepPkScriptGen(
×
1382
                                cc.Wallet, netParams,
×
1383
                        )().Unpack()
×
1384
                        if err != nil {
×
1385
                                return nil, err
×
1386
                        }
×
1387

1388
                        return addr.DeliveryAddress, nil
×
1389
                },
1390
                PublishTx: cc.Wallet.PublishTransaction,
UNCOV
1391
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
UNCOV
1392
                        for _, msg := range msgs {
×
UNCOV
1393
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
UNCOV
1394
                                if err != nil {
×
1395
                                        return err
×
1396
                                }
×
1397
                        }
UNCOV
1398
                        return nil
×
1399
                },
1400
                IncubateOutputs: func(chanPoint wire.OutPoint,
1401
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1402
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1403
                        broadcastHeight uint32,
UNCOV
1404
                        deadlineHeight fn.Option[int32]) error {
×
UNCOV
1405

×
UNCOV
1406
                        return s.utxoNursery.IncubateOutputs(
×
UNCOV
1407
                                chanPoint, outHtlcRes, inHtlcRes,
×
UNCOV
1408
                                broadcastHeight, deadlineHeight,
×
UNCOV
1409
                        )
×
UNCOV
1410
                },
×
1411
                PreimageDB:   s.witnessBeacon,
1412
                Notifier:     cc.ChainNotifier,
1413
                Mempool:      cc.MempoolNotifier,
1414
                Signer:       cc.Wallet.Cfg.Signer,
1415
                FeeEstimator: cc.FeeEstimator,
1416
                ChainIO:      cc.ChainIO,
UNCOV
1417
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
UNCOV
1418
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1419
                        s.htlcSwitch.RemoveLink(chanID)
×
UNCOV
1420
                        return nil
×
UNCOV
1421
                },
×
1422
                IsOurAddress: cc.Wallet.IsOurAddress,
1423
                ContractBreach: func(chanPoint wire.OutPoint,
UNCOV
1424
                        breachRet *lnwallet.BreachRetribution) error {
×
UNCOV
1425

×
UNCOV
1426
                        // processACK will handle the BreachArbitrator ACKing
×
UNCOV
1427
                        // the event.
×
UNCOV
1428
                        finalErr := make(chan error, 1)
×
UNCOV
1429
                        processACK := func(brarErr error) {
×
UNCOV
1430
                                if brarErr != nil {
×
1431
                                        finalErr <- brarErr
×
1432
                                        return
×
1433
                                }
×
1434

1435
                                // If the BreachArbitrator successfully handled
1436
                                // the event, we can signal that the handoff
1437
                                // was successful.
UNCOV
1438
                                finalErr <- nil
×
1439
                        }
1440

UNCOV
1441
                        event := &contractcourt.ContractBreachEvent{
×
UNCOV
1442
                                ChanPoint:         chanPoint,
×
UNCOV
1443
                                ProcessACK:        processACK,
×
UNCOV
1444
                                BreachRetribution: breachRet,
×
UNCOV
1445
                        }
×
UNCOV
1446

×
UNCOV
1447
                        // Send the contract breach event to the
×
UNCOV
1448
                        // BreachArbitrator.
×
UNCOV
1449
                        select {
×
UNCOV
1450
                        case contractBreaches <- event:
×
1451
                        case <-s.quit:
×
1452
                                return ErrServerShuttingDown
×
1453
                        }
1454

1455
                        // We'll wait for a final error to be available from
1456
                        // the BreachArbitrator.
UNCOV
1457
                        select {
×
UNCOV
1458
                        case err := <-finalErr:
×
UNCOV
1459
                                return err
×
1460
                        case <-s.quit:
×
1461
                                return ErrServerShuttingDown
×
1462
                        }
1463
                },
UNCOV
1464
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
UNCOV
1465
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
UNCOV
1466
                },
×
1467
                Sweeper:                       s.sweeper,
1468
                Registry:                      s.invoices,
1469
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1470
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1471
                OnionProcessor:                s.sphinx,
1472
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1473
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1474
                Clock:                         clock.NewDefaultClock(),
1475
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1476
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1477
                HtlcNotifier:                  s.htlcNotifier,
1478
                Budget:                        *s.cfg.Sweeper.Budget,
1479

1480
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1481
                QueryIncomingCircuit: func(
UNCOV
1482
                        circuit models.CircuitKey) *models.CircuitKey {
×
UNCOV
1483

×
UNCOV
1484
                        // Get the circuit map.
×
UNCOV
1485
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1486

×
UNCOV
1487
                        // Lookup the outgoing circuit.
×
UNCOV
1488
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1489
                        if pc == nil {
×
UNCOV
1490
                                return nil
×
UNCOV
1491
                        }
×
1492

UNCOV
1493
                        return &pc.Incoming
×
1494
                },
1495
                AuxLeafStore: implCfg.AuxLeafStore,
1496
                AuxSigner:    implCfg.AuxSigner,
1497
                AuxResolver:  implCfg.AuxContractResolver,
1498
        }, dbs.ChanStateDB)
1499

1500
        // Select the configuration and funding parameters for Bitcoin.
UNCOV
1501
        chainCfg := cfg.Bitcoin
×
UNCOV
1502
        minRemoteDelay := funding.MinBtcRemoteDelay
×
UNCOV
1503
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
UNCOV
1504

×
UNCOV
1505
        var chanIDSeed [32]byte
×
UNCOV
1506
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1507
                return nil, err
×
1508
        }
×
1509

1510
        // Wrap the DeleteChannelEdges method so that the funding manager can
1511
        // use it without depending on several layers of indirection.
UNCOV
1512
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
UNCOV
1513
                *models.ChannelEdgePolicy, error) {
×
UNCOV
1514

×
UNCOV
1515
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
UNCOV
1516
                        scid.ToUint64(),
×
UNCOV
1517
                )
×
UNCOV
1518
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1519
                        // This is unlikely but there is a slim chance of this
×
1520
                        // being hit if lnd was killed via SIGKILL and the
×
1521
                        // funding manager was stepping through the delete
×
1522
                        // alias edge logic.
×
1523
                        return nil, nil
×
UNCOV
1524
                } else if err != nil {
×
1525
                        return nil, err
×
1526
                }
×
1527

1528
                // Grab our key to find our policy.
UNCOV
1529
                var ourKey [33]byte
×
UNCOV
1530
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1531

×
UNCOV
1532
                var ourPolicy *models.ChannelEdgePolicy
×
UNCOV
1533
                if info != nil && info.NodeKey1Bytes == ourKey {
×
UNCOV
1534
                        ourPolicy = e1
×
UNCOV
1535
                } else {
×
UNCOV
1536
                        ourPolicy = e2
×
UNCOV
1537
                }
×
1538

UNCOV
1539
                if ourPolicy == nil {
×
1540
                        // Something is wrong, so return an error.
×
1541
                        return nil, fmt.Errorf("we don't have an edge")
×
1542
                }
×
1543

UNCOV
1544
                err = s.graphDB.DeleteChannelEdges(
×
UNCOV
1545
                        false, false, scid.ToUint64(),
×
UNCOV
1546
                )
×
UNCOV
1547
                return ourPolicy, err
×
1548
        }
1549

1550
        // For the reservationTimeout and the zombieSweeperInterval different
1551
        // values are set in case we are in a dev environment so enhance test
1552
        // capacilities.
UNCOV
1553
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1554
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1555

×
UNCOV
1556
        // Get the development config for funding manager. If we are not in
×
UNCOV
1557
        // development mode, this would be nil.
×
UNCOV
1558
        var devCfg *funding.DevConfig
×
UNCOV
1559
        if lncfg.IsDevBuild() {
×
UNCOV
1560
                devCfg = &funding.DevConfig{
×
UNCOV
1561
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1562
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
×
UNCOV
1563
                                GetMaxWaitNumBlocksFundingConf(),
×
UNCOV
1564
                }
×
UNCOV
1565

×
UNCOV
1566
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1567
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1568

×
UNCOV
1569
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1570
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1571
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1572
        }
×
1573

1574
        //nolint:ll
UNCOV
1575
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1576
                Dev:                devCfg,
×
UNCOV
1577
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1578
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1579
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1580
                Wallet:             cc.Wallet,
×
UNCOV
1581
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1582
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1583
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1584
                },
×
1585
                Notifier:     cc.ChainNotifier,
1586
                ChannelDB:    s.chanStateDB,
1587
                FeeEstimator: cc.FeeEstimator,
1588
                SignMessage:  cc.MsgSigner.SignMessage,
1589
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1590
                        error) {
×
UNCOV
1591

×
UNCOV
1592
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1593
                },
×
1594
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1595
                NotifyWhenOnline:     s.NotifyWhenOnline,
1596
                TempChanIDSeed:       chanIDSeed,
1597
                FindChannel:          s.findChannel,
1598
                DefaultRoutingPolicy: cc.RoutingPolicy,
1599
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1600
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1601
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1602
                        // For large channels we increase the number
×
UNCOV
1603
                        // of confirmations we require for the
×
UNCOV
1604
                        // channel to be considered open. As it is
×
UNCOV
1605
                        // always the responder that gets to choose
×
UNCOV
1606
                        // value, the pushAmt is value being pushed
×
UNCOV
1607
                        // to us. This means we have more to lose
×
UNCOV
1608
                        // in the case this gets re-orged out, and
×
UNCOV
1609
                        // we will require more confirmations before
×
UNCOV
1610
                        // we consider it open.
×
UNCOV
1611

×
UNCOV
1612
                        // In case the user has explicitly specified
×
UNCOV
1613
                        // a default value for the number of
×
UNCOV
1614
                        // confirmations, we use it.
×
UNCOV
1615
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1616
                        if defaultConf != 0 {
×
UNCOV
1617
                                return defaultConf
×
UNCOV
1618
                        }
×
1619

1620
                        minConf := uint64(3)
×
1621
                        maxConf := uint64(6)
×
1622

×
1623
                        // If this is a wumbo channel, then we'll require the
×
1624
                        // max amount of confirmations.
×
1625
                        if chanAmt > MaxFundingAmount {
×
1626
                                return uint16(maxConf)
×
1627
                        }
×
1628

1629
                        // If not we return a value scaled linearly
1630
                        // between 3 and 6, depending on channel size.
1631
                        // TODO(halseth): Use 1 as minimum?
1632
                        maxChannelSize := uint64(
×
1633
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1634
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1635
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1636
                        if conf < minConf {
×
1637
                                conf = minConf
×
1638
                        }
×
1639
                        if conf > maxConf {
×
1640
                                conf = maxConf
×
1641
                        }
×
1642
                        return uint16(conf)
×
1643
                },
UNCOV
1644
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1645
                        // We scale the remote CSV delay (the time the
×
UNCOV
1646
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1647
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1648
                        // for small channels, to maxRemoteDelay blocks
×
UNCOV
1649
                        // for channels of size MaxFundingAmount.
×
UNCOV
1650

×
UNCOV
1651
                        // In case the user has explicitly specified
×
UNCOV
1652
                        // a default value for the remote delay, we
×
UNCOV
1653
                        // use it.
×
UNCOV
1654
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1655
                        if defaultDelay > 0 {
×
UNCOV
1656
                                return defaultDelay
×
UNCOV
1657
                        }
×
1658

1659
                        // If this is a wumbo channel, then we'll require the
1660
                        // max value.
1661
                        if chanAmt > MaxFundingAmount {
×
1662
                                return maxRemoteDelay
×
1663
                        }
×
1664

1665
                        // If not we scale according to channel size.
1666
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1667
                                chanAmt / MaxFundingAmount)
×
1668
                        if delay < minRemoteDelay {
×
1669
                                delay = minRemoteDelay
×
1670
                        }
×
1671
                        if delay > maxRemoteDelay {
×
1672
                                delay = maxRemoteDelay
×
1673
                        }
×
1674
                        return delay
×
1675
                },
1676
                WatchNewChannel: func(channel *channeldb.OpenChannel,
UNCOV
1677
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1678

×
UNCOV
1679
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1680
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1681
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1682
                        // we'll set false to prevent the server from continuing
×
UNCOV
1683
                        // to connect to this peer even if the number of
×
UNCOV
1684
                        // channels with this peer is zero.
×
UNCOV
1685
                        s.mu.Lock()
×
UNCOV
1686
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1687
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1688
                                s.persistentPeers[pubStr] = false
×
UNCOV
1689
                        }
×
UNCOV
1690
                        s.mu.Unlock()
×
UNCOV
1691

×
UNCOV
1692
                        // With that taken care of, we'll send this channel to
×
UNCOV
1693
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1694
                        return s.chainArb.WatchNewChannel(channel)
×
1695
                },
UNCOV
1696
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1697
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1698
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1699
                },
×
1700
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1701
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1702

×
UNCOV
1703
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1704
                        // at least 1% of the total channel capacity at all
×
UNCOV
1705
                        // times. If this value ends up dipping below the dust
×
UNCOV
1706
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1707
                        // reserve as required by BOLT #2.
×
UNCOV
1708
                        reserve := chanAmt / 100
×
UNCOV
1709
                        if reserve < dustLimit {
×
UNCOV
1710
                                reserve = dustLimit
×
UNCOV
1711
                        }
×
1712

UNCOV
1713
                        return reserve
×
1714
                },
UNCOV
1715
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1716
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1717
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1718
                        // required reserve.
×
UNCOV
1719
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1720
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1721
                },
×
UNCOV
1722
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1723
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1724
                                return cfg.DefaultRemoteMaxHtlcs
×
UNCOV
1725
                        }
×
1726

1727
                        // By default, we'll permit them to utilize the full
1728
                        // channel bandwidth.
1729
                        return uint16(input.MaxHTLCNumber / 2)
×
1730
                },
1731
                ZombieSweeperInterval:         zombieSweeperInterval,
1732
                ReservationTimeout:            reservationTimeout,
1733
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1734
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1735
                MaxPendingChannels:            cfg.MaxPendingChannels,
1736
                RejectPush:                    cfg.RejectPush,
1737
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1738
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1739
                OpenChannelPredicate:          chanPredicate,
1740
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1741
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1742
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1743
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1744
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1745
                DeleteAliasEdge:      deleteAliasEdge,
1746
                AliasManager:         s.aliasMgr,
1747
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1748
                AuxFundingController: implCfg.AuxFundingController,
1749
                AuxSigner:            implCfg.AuxSigner,
1750
                AuxResolver:          implCfg.AuxContractResolver,
1751
        })
UNCOV
1752
        if err != nil {
×
1753
                return nil, err
×
1754
        }
×
1755

1756
        // Next, we'll assemble the sub-system that will maintain an on-disk
1757
        // static backup of the latest channel state.
UNCOV
1758
        chanNotifier := &channelNotifier{
×
UNCOV
1759
                chanNotifier: s.channelNotifier,
×
UNCOV
1760
                addrs:        s.addrSource,
×
UNCOV
1761
        }
×
UNCOV
1762
        backupFile := chanbackup.NewMultiFile(
×
UNCOV
1763
                cfg.BackupFilePath, cfg.NoBackupArchive,
×
UNCOV
1764
        )
×
UNCOV
1765
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1766
                ctx, s.chanStateDB, s.addrSource,
×
UNCOV
1767
        )
×
UNCOV
1768
        if err != nil {
×
1769
                return nil, err
×
1770
        }
×
UNCOV
1771
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1772
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1773
        )
×
UNCOV
1774
        if err != nil {
×
1775
                return nil, err
×
1776
        }
×
1777

1778
        // Assemble a peer notifier which will provide clients with subscriptions
1779
        // to peer online and offline events.
UNCOV
1780
        s.peerNotifier = peernotifier.New()
×
UNCOV
1781

×
UNCOV
1782
        // Create a channel event store which monitors all open channels.
×
UNCOV
1783
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1784
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1785
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1786
                },
×
UNCOV
1787
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1788
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1789
                },
×
1790
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1791
                Clock:           clock.NewDefaultClock(),
1792
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1793
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1794
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1795
        })
1796

UNCOV
1797
        if cfg.WtClient.Active {
×
UNCOV
1798
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1799
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1800

×
UNCOV
1801
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1802
                // protocol operations on sat/kw.
×
UNCOV
1803
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1804
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1805
                )
×
UNCOV
1806

×
UNCOV
1807
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1808

×
UNCOV
1809
                if err := policy.Validate(); err != nil {
×
1810
                        return nil, err
×
1811
                }
×
1812

1813
                // authDial is the wrapper around the btrontide.Dial for the
1814
                // watchtower.
UNCOV
1815
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1816
                        netAddr *lnwire.NetAddress,
×
UNCOV
1817
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1818

×
UNCOV
1819
                        return brontide.Dial(
×
UNCOV
1820
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1821
                        )
×
UNCOV
1822
                }
×
1823

1824
                // buildBreachRetribution is a call-back that can be used to
1825
                // query the BreachRetribution info and channel type given a
1826
                // channel ID and commitment height.
UNCOV
1827
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1828
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1829
                        channeldb.ChannelType, error) {
×
UNCOV
1830

×
UNCOV
1831
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1832
                                nil, chanID,
×
UNCOV
1833
                        )
×
UNCOV
1834
                        if err != nil {
×
1835
                                return nil, 0, err
×
1836
                        }
×
1837

UNCOV
1838
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1839
                                channel, commitHeight, 0, nil,
×
UNCOV
1840
                                implCfg.AuxLeafStore,
×
UNCOV
1841
                                implCfg.AuxContractResolver,
×
UNCOV
1842
                        )
×
UNCOV
1843
                        if err != nil {
×
1844
                                return nil, 0, err
×
1845
                        }
×
1846

UNCOV
1847
                        return br, channel.ChanType, nil
×
1848
                }
1849

UNCOV
1850
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1851

×
UNCOV
1852
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1853
                // signalling support for anchor channels.
×
UNCOV
1854
                anchorPolicy := policy
×
UNCOV
1855
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1856

×
UNCOV
1857
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1858
                // signalling support for taproot channels.
×
UNCOV
1859
                taprootPolicy := policy
×
UNCOV
1860
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1861
                        blob.FlagTaprootChannel,
×
UNCOV
1862
                )
×
UNCOV
1863

×
UNCOV
1864
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1865
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1866
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1867
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1868
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1869
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1870
                                error) {
×
UNCOV
1871

×
UNCOV
1872
                                return s.channelNotifier.
×
UNCOV
1873
                                        SubscribeChannelEvents()
×
UNCOV
1874
                        },
×
1875
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1876
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1877
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1878
                                        cc.Wallet, netParams,
×
UNCOV
1879
                                )().Unpack()
×
UNCOV
1880
                                if err != nil {
×
1881
                                        return nil, err
×
1882
                                }
×
1883

UNCOV
1884
                                return addr.DeliveryAddress, nil
×
1885
                        },
1886
                        SecretKeyRing:      s.cc.KeyRing,
1887
                        Dial:               cfg.net.Dial,
1888
                        AuthDial:           authDial,
1889
                        DB:                 dbs.TowerClientDB,
1890
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1891
                        MinBackoff:         10 * time.Second,
1892
                        MaxBackoff:         5 * time.Minute,
1893
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1894
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1895
                if err != nil {
×
1896
                        return nil, err
×
1897
                }
×
1898
        }
1899

UNCOV
1900
        if len(cfg.ExternalHosts) != 0 {
×
1901
                advertisedIPs := make(map[string]struct{})
×
1902
                for _, addr := range s.currentNodeAnn.Addresses {
×
1903
                        advertisedIPs[addr.String()] = struct{}{}
×
1904
                }
×
1905

1906
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1907
                        Hosts:         cfg.ExternalHosts,
×
1908
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1909
                        LookupHost: func(host string) (net.Addr, error) {
×
1910
                                return lncfg.ParseAddressString(
×
1911
                                        host, strconv.Itoa(defaultPeerPort),
×
1912
                                        cfg.net.ResolveTCPAddr,
×
1913
                                )
×
1914
                        },
×
1915
                        AdvertisedIPs: advertisedIPs,
1916
                        AnnounceNewIPs: netann.IPAnnouncer(
1917
                                func(modifier ...netann.NodeAnnModifier) (
1918
                                        lnwire.NodeAnnouncement, error) {
×
1919

×
1920
                                        return s.genNodeAnnouncement(
×
1921
                                                nil, modifier...,
×
1922
                                        )
×
1923
                                }),
×
1924
                })
1925
        }
1926

1927
        // Create liveness monitor.
UNCOV
1928
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1929

×
UNCOV
1930
        listeners := make([]net.Listener, len(listenAddrs))
×
UNCOV
1931
        for i, listenAddr := range listenAddrs {
×
UNCOV
1932
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
UNCOV
1933
                // doesn't need to call the general lndResolveTCP function
×
UNCOV
1934
                // since we are resolving a local address.
×
UNCOV
1935

×
UNCOV
1936
                // RESOLVE: We are actually partially accepting inbound
×
UNCOV
1937
                // connection requests when we call NewListener.
×
UNCOV
1938
                listeners[i], err = brontide.NewListener(
×
UNCOV
1939
                        nodeKeyECDH, listenAddr.String(),
×
UNCOV
1940
                        // TODO(yy): remove this check and unify the inbound
×
UNCOV
1941
                        // connection check inside `InboundPeerConnected`.
×
UNCOV
1942
                        s.peerAccessMan.checkAcceptIncomingConn,
×
UNCOV
1943
                )
×
UNCOV
1944
                if err != nil {
×
1945
                        return nil, err
×
1946
                }
×
1947
        }
1948

1949
        // Create the connection manager which will be responsible for
1950
        // maintaining persistent outbound connections and also accepting new
1951
        // incoming connections
UNCOV
1952
        cmgr, err := connmgr.New(&connmgr.Config{
×
UNCOV
1953
                Listeners:      listeners,
×
UNCOV
1954
                OnAccept:       s.InboundPeerConnected,
×
UNCOV
1955
                RetryDuration:  time.Second * 5,
×
UNCOV
1956
                TargetOutbound: 100,
×
UNCOV
1957
                Dial: noiseDial(
×
UNCOV
1958
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
1959
                ),
×
UNCOV
1960
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
1961
        })
×
UNCOV
1962
        if err != nil {
×
1963
                return nil, err
×
1964
        }
×
UNCOV
1965
        s.connMgr = cmgr
×
UNCOV
1966

×
UNCOV
1967
        // Finally, register the subsystems in blockbeat.
×
UNCOV
1968
        s.registerBlockConsumers()
×
UNCOV
1969

×
UNCOV
1970
        return s, nil
×
1971
}
1972

1973
// UpdateRoutingConfig is a callback function to update the routing config
1974
// values in the main cfg.
UNCOV
1975
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
1976
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
1977

×
UNCOV
1978
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
1979
        case routing.AprioriConfig:
×
UNCOV
1980
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1981
                        routing.AprioriEstimatorName
×
UNCOV
1982

×
UNCOV
1983
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1984
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1985
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1986
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1987
                targetCfg.HopProbability = c.AprioriHopProbability
×
1988

UNCOV
1989
        case routing.BimodalConfig:
×
UNCOV
1990
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1991
                        routing.BimodalEstimatorName
×
UNCOV
1992

×
UNCOV
1993
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1994
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1995
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1996
                targetCfg.DecayTime = c.BimodalDecayTime
×
1997
        }
1998

UNCOV
1999
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
2000
}
2001

2002
// registerBlockConsumers registers the subsystems that consume block events.
2003
// By calling `RegisterQueue`, a list of subsystems are registered in the
2004
// blockbeat for block notifications. When a new block arrives, the subsystems
2005
// in the same queue are notified sequentially, and different queues are
2006
// notified concurrently.
2007
//
2008
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
2009
// a new `RegisterQueue` call.
UNCOV
2010
func (s *server) registerBlockConsumers() {
×
UNCOV
2011
        // In this queue, when a new block arrives, it will be received and
×
UNCOV
2012
        // processed in this order: chainArb -> sweeper -> txPublisher.
×
UNCOV
2013
        consumers := []chainio.Consumer{
×
UNCOV
2014
                s.chainArb,
×
UNCOV
2015
                s.sweeper,
×
UNCOV
2016
                s.txPublisher,
×
UNCOV
2017
        }
×
UNCOV
2018
        s.blockbeatDispatcher.RegisterQueue(consumers)
×
UNCOV
2019
}
×
2020

2021
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2022
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2023
// may differ from what is on disk.
2024
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
2025
        error) {
×
UNCOV
2026

×
UNCOV
2027
        data, err := u.DataToSign()
×
UNCOV
2028
        if err != nil {
×
2029
                return nil, err
×
2030
        }
×
2031

UNCOV
2032
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
2033
}
2034

2035
// createLivenessMonitor creates a set of health checks using our configured
2036
// values and uses these checks to create a liveness monitor. Available
2037
// health checks,
2038
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2039
//   - diskCheck
2040
//   - tlsHealthCheck
2041
//   - torController, only created when tor is enabled.
2042
//
2043
// If a health check has been disabled by setting attempts to 0, our monitor
2044
// will not run it.
2045
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
UNCOV
2046
        leaderElector cluster.LeaderElector) {
×
UNCOV
2047

×
UNCOV
2048
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
2049
        if cfg.Bitcoin.Node == "nochainbackend" {
×
2050
                srvrLog.Info("Disabling chain backend checks for " +
×
2051
                        "nochainbackend mode")
×
2052

×
2053
                chainBackendAttempts = 0
×
2054
        }
×
2055

UNCOV
2056
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
2057
                "chain backend",
×
UNCOV
2058
                cc.HealthCheck,
×
UNCOV
2059
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
2060
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
2061
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
2062
                chainBackendAttempts,
×
UNCOV
2063
        )
×
UNCOV
2064

×
UNCOV
2065
        diskCheck := healthcheck.NewObservation(
×
UNCOV
2066
                "disk space",
×
UNCOV
2067
                func() error {
×
2068
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2069
                                cfg.LndDir,
×
2070
                        )
×
2071
                        if err != nil {
×
2072
                                return err
×
2073
                        }
×
2074

2075
                        // If we have more free space than we require,
2076
                        // we return a nil error.
2077
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2078
                                return nil
×
2079
                        }
×
2080

2081
                        return fmt.Errorf("require: %v free space, got: %v",
×
2082
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2083
                                free)
×
2084
                },
2085
                cfg.HealthChecks.DiskCheck.Interval,
2086
                cfg.HealthChecks.DiskCheck.Timeout,
2087
                cfg.HealthChecks.DiskCheck.Backoff,
2088
                cfg.HealthChecks.DiskCheck.Attempts,
2089
        )
2090

UNCOV
2091
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
2092
                "tls",
×
UNCOV
2093
                func() error {
×
2094
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2095
                                s.cc.KeyRing,
×
2096
                        )
×
2097
                        if err != nil {
×
2098
                                return err
×
2099
                        }
×
2100
                        if expired {
×
2101
                                return fmt.Errorf("TLS certificate is "+
×
2102
                                        "expired as of %v", expTime)
×
2103
                        }
×
2104

2105
                        // If the certificate is not outdated, no error needs
2106
                        // to be returned
2107
                        return nil
×
2108
                },
2109
                cfg.HealthChecks.TLSCheck.Interval,
2110
                cfg.HealthChecks.TLSCheck.Timeout,
2111
                cfg.HealthChecks.TLSCheck.Backoff,
2112
                cfg.HealthChecks.TLSCheck.Attempts,
2113
        )
2114

UNCOV
2115
        checks := []*healthcheck.Observation{
×
UNCOV
2116
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
2117
        }
×
UNCOV
2118

×
UNCOV
2119
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
2120
        if s.torController != nil {
×
2121
                torConnectionCheck := healthcheck.NewObservation(
×
2122
                        "tor connection",
×
2123
                        func() error {
×
2124
                                return healthcheck.CheckTorServiceStatus(
×
2125
                                        s.torController,
×
2126
                                        func() error {
×
2127
                                                return s.createNewHiddenService(
×
2128
                                                        context.TODO(),
×
2129
                                                )
×
2130
                                        },
×
2131
                                )
2132
                        },
2133
                        cfg.HealthChecks.TorConnection.Interval,
2134
                        cfg.HealthChecks.TorConnection.Timeout,
2135
                        cfg.HealthChecks.TorConnection.Backoff,
2136
                        cfg.HealthChecks.TorConnection.Attempts,
2137
                )
2138
                checks = append(checks, torConnectionCheck)
×
2139
        }
2140

2141
        // If remote signing is enabled, add the healthcheck for the remote
2142
        // signing RPC interface.
UNCOV
2143
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
2144
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
2145
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
2146
                // returns exactly on time.
×
UNCOV
2147
                overhead := time.Millisecond * 10
×
UNCOV
2148

×
UNCOV
2149
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
2150
                        "remote signer connection",
×
UNCOV
2151
                        rpcwallet.HealthCheck(
×
UNCOV
2152
                                s.cfg.RemoteSigner,
×
UNCOV
2153

×
UNCOV
2154
                                // For the health check we might to be even
×
UNCOV
2155
                                // stricter than the initial/normal connect, so
×
UNCOV
2156
                                // we use the health check timeout here.
×
UNCOV
2157
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
2158
                        ),
×
UNCOV
2159
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
2160
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
2161
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
2162
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
2163
                )
×
UNCOV
2164
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
2165
        }
×
2166

2167
        // If we have a leader elector, we add a health check to ensure we are
2168
        // still the leader. During normal operation, we should always be the
2169
        // leader, but there are circumstances where this may change, such as
2170
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
2171
        if leaderElector != nil {
×
2172
                leaderCheck := healthcheck.NewObservation(
×
2173
                        "leader status",
×
2174
                        func() error {
×
2175
                                // Check if we are still the leader. Note that
×
2176
                                // we don't need to use a timeout context here
×
2177
                                // as the healthcheck observer will handle the
×
2178
                                // timeout case for us.
×
2179
                                timeoutCtx, cancel := context.WithTimeout(
×
2180
                                        context.Background(),
×
2181
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2182
                                )
×
2183
                                defer cancel()
×
2184

×
2185
                                leader, err := leaderElector.IsLeader(
×
2186
                                        timeoutCtx,
×
2187
                                )
×
2188
                                if err != nil {
×
2189
                                        return fmt.Errorf("unable to check if "+
×
2190
                                                "still leader: %v", err)
×
2191
                                }
×
2192

2193
                                if !leader {
×
2194
                                        srvrLog.Debug("Not the current leader")
×
2195
                                        return fmt.Errorf("not the current " +
×
2196
                                                "leader")
×
2197
                                }
×
2198

2199
                                return nil
×
2200
                        },
2201
                        cfg.HealthChecks.LeaderCheck.Interval,
2202
                        cfg.HealthChecks.LeaderCheck.Timeout,
2203
                        cfg.HealthChecks.LeaderCheck.Backoff,
2204
                        cfg.HealthChecks.LeaderCheck.Attempts,
2205
                )
2206

2207
                checks = append(checks, leaderCheck)
×
2208
        }
2209

2210
        // If we have not disabled all of our health checks, we create a
2211
        // liveness monitor with our configured checks.
UNCOV
2212
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2213
                &healthcheck.Config{
×
UNCOV
2214
                        Checks:   checks,
×
UNCOV
2215
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2216
                },
×
UNCOV
2217
        )
×
2218
}
2219

2220
// Started returns true if the server has been started, and false otherwise.
2221
// NOTE: This function is safe for concurrent access.
UNCOV
2222
func (s *server) Started() bool {
×
UNCOV
2223
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2224
}
×
2225

2226
// cleaner is used to aggregate "cleanup" functions during an operation that
2227
// starts several subsystems. In case one of the subsystem fails to start
2228
// and a proper resource cleanup is required, the "run" method achieves this
2229
// by running all these added "cleanup" functions.
2230
type cleaner []func() error
2231

2232
// add is used to add a cleanup function to be called when
2233
// the run function is executed.
UNCOV
2234
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2235
        return append(c, cleanup)
×
UNCOV
2236
}
×
2237

2238
// run is used to run all the previousely added cleanup functions.
2239
func (c cleaner) run() {
×
2240
        for i := len(c) - 1; i >= 0; i-- {
×
2241
                if err := c[i](); err != nil {
×
2242
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2243
                }
×
2244
        }
2245
}
2246

2247
// startLowLevelServices starts the low-level services of the server. These
2248
// services must be started successfully before running the main server. The
2249
// services are,
2250
// 1. the chain notifier.
2251
//
2252
// TODO(yy): identify and add more low-level services here.
UNCOV
2253
func (s *server) startLowLevelServices() error {
×
UNCOV
2254
        var startErr error
×
UNCOV
2255

×
UNCOV
2256
        cleanup := cleaner{}
×
UNCOV
2257

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

UNCOV
2263
        if startErr != nil {
×
2264
                cleanup.run()
×
2265
        }
×
2266

UNCOV
2267
        return startErr
×
2268
}
2269

2270
// Start starts the main daemon server, all requested listeners, and any helper
2271
// goroutines.
2272
// NOTE: This function is safe for concurrent access.
2273
//
2274
//nolint:funlen
UNCOV
2275
func (s *server) Start(ctx context.Context) error {
×
UNCOV
2276
        // Get the current blockbeat.
×
UNCOV
2277
        beat, err := s.getStartingBeat()
×
UNCOV
2278
        if err != nil {
×
2279
                return err
×
2280
        }
×
2281

UNCOV
2282
        var startErr error
×
UNCOV
2283

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

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

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

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

2312
                // Start the notification server. This is used so channel
2313
                // management goroutines can be notified when a funding
2314
                // transaction reaches a sufficient number of confirmations, or
2315
                // when the input for the funding transaction is spent in an
2316
                // attempt at an uncooperative close by the counterparty.
UNCOV
2317
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2318
                if err := s.sigPool.Start(); err != nil {
×
2319
                        startErr = err
×
2320
                        return
×
2321
                }
×
2322

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

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

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

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

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

UNCOV
2355
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
UNCOV
2356
                if err := s.htlcNotifier.Start(); err != nil {
×
2357
                        startErr = err
×
2358
                        return
×
2359
                }
×
2360

UNCOV
2361
                if s.towerClientMgr != nil {
×
UNCOV
2362
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
×
UNCOV
2363
                        if err := s.towerClientMgr.Start(); err != nil {
×
2364
                                startErr = err
×
2365
                                return
×
2366
                        }
×
2367
                }
2368

UNCOV
2369
                cleanup = cleanup.add(s.txPublisher.Stop)
×
UNCOV
2370
                if err := s.txPublisher.Start(beat); err != nil {
×
2371
                        startErr = err
×
2372
                        return
×
2373
                }
×
2374

UNCOV
2375
                cleanup = cleanup.add(s.sweeper.Stop)
×
UNCOV
2376
                if err := s.sweeper.Start(beat); err != nil {
×
2377
                        startErr = err
×
2378
                        return
×
2379
                }
×
2380

UNCOV
2381
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
UNCOV
2382
                if err := s.utxoNursery.Start(); err != nil {
×
2383
                        startErr = err
×
2384
                        return
×
2385
                }
×
2386

UNCOV
2387
                cleanup = cleanup.add(s.breachArbitrator.Stop)
×
UNCOV
2388
                if err := s.breachArbitrator.Start(); err != nil {
×
2389
                        startErr = err
×
2390
                        return
×
2391
                }
×
2392

UNCOV
2393
                cleanup = cleanup.add(s.fundingMgr.Stop)
×
UNCOV
2394
                if err := s.fundingMgr.Start(); err != nil {
×
2395
                        startErr = err
×
2396
                        return
×
2397
                }
×
2398

2399
                // htlcSwitch must be started before chainArb since the latter
2400
                // relies on htlcSwitch to deliver resolution message upon
2401
                // start.
UNCOV
2402
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2403
                if err := s.htlcSwitch.Start(); err != nil {
×
2404
                        startErr = err
×
2405
                        return
×
2406
                }
×
2407

UNCOV
2408
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
×
UNCOV
2409
                if err := s.interceptableSwitch.Start(); err != nil {
×
2410
                        startErr = err
×
2411
                        return
×
2412
                }
×
2413

UNCOV
2414
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
×
UNCOV
2415
                if err := s.invoiceHtlcModifier.Start(); err != nil {
×
2416
                        startErr = err
×
2417
                        return
×
2418
                }
×
2419

UNCOV
2420
                cleanup = cleanup.add(s.chainArb.Stop)
×
UNCOV
2421
                if err := s.chainArb.Start(beat); err != nil {
×
2422
                        startErr = err
×
2423
                        return
×
2424
                }
×
2425

UNCOV
2426
                cleanup = cleanup.add(s.graphDB.Stop)
×
UNCOV
2427
                if err := s.graphDB.Start(); err != nil {
×
2428
                        startErr = err
×
2429
                        return
×
2430
                }
×
2431

UNCOV
2432
                cleanup = cleanup.add(s.graphBuilder.Stop)
×
UNCOV
2433
                if err := s.graphBuilder.Start(); err != nil {
×
2434
                        startErr = err
×
2435
                        return
×
2436
                }
×
2437

UNCOV
2438
                cleanup = cleanup.add(s.chanRouter.Stop)
×
UNCOV
2439
                if err := s.chanRouter.Start(); err != nil {
×
2440
                        startErr = err
×
2441
                        return
×
2442
                }
×
2443
                // The authGossiper depends on the chanRouter and therefore
2444
                // should be started after it.
UNCOV
2445
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2446
                if err := s.authGossiper.Start(); err != nil {
×
2447
                        startErr = err
×
2448
                        return
×
2449
                }
×
2450

UNCOV
2451
                cleanup = cleanup.add(s.invoices.Stop)
×
UNCOV
2452
                if err := s.invoices.Start(); err != nil {
×
2453
                        startErr = err
×
2454
                        return
×
2455
                }
×
2456

UNCOV
2457
                cleanup = cleanup.add(s.sphinx.Stop)
×
UNCOV
2458
                if err := s.sphinx.Start(); err != nil {
×
2459
                        startErr = err
×
2460
                        return
×
2461
                }
×
2462

UNCOV
2463
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
×
UNCOV
2464
                if err := s.chanStatusMgr.Start(); err != nil {
×
2465
                        startErr = err
×
2466
                        return
×
2467
                }
×
2468

UNCOV
2469
                cleanup = cleanup.add(s.chanEventStore.Stop)
×
UNCOV
2470
                if err := s.chanEventStore.Start(); err != nil {
×
2471
                        startErr = err
×
2472
                        return
×
2473
                }
×
2474

UNCOV
2475
                cleanup.add(func() error {
×
2476
                        s.missionController.StopStoreTickers()
×
2477
                        return nil
×
2478
                })
×
UNCOV
2479
                s.missionController.RunStoreTickers()
×
UNCOV
2480

×
UNCOV
2481
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2482
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2483
                // that have all the information we need to handle channel
×
UNCOV
2484
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2485
                chanRestorer := &chanDBRestorer{
×
UNCOV
2486
                        db:         s.chanStateDB,
×
UNCOV
2487
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2488
                        chainArb:   s.chainArb,
×
UNCOV
2489
                }
×
UNCOV
2490
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2491
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2492
                                s.chansToRestore.PackedSingleChanBackups,
×
2493
                                s.cc.KeyRing, chanRestorer, s,
×
2494
                        )
×
2495
                        if err != nil {
×
2496
                                startErr = fmt.Errorf("unable to unpack single "+
×
2497
                                        "backups: %v", err)
×
2498
                                return
×
2499
                        }
×
2500
                }
UNCOV
2501
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2502
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2503
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2504
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2505
                        )
×
UNCOV
2506
                        if err != nil {
×
2507
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2508
                                        "backup: %v", err)
×
2509
                                return
×
2510
                        }
×
2511
                }
2512

2513
                // chanSubSwapper must be started after the `channelNotifier`
2514
                // because it depends on channel events as a synchronization
2515
                // point.
UNCOV
2516
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2517
                if err := s.chanSubSwapper.Start(); err != nil {
×
2518
                        startErr = err
×
2519
                        return
×
2520
                }
×
2521

UNCOV
2522
                if s.torController != nil {
×
2523
                        cleanup = cleanup.add(s.torController.Stop)
×
2524
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2525
                                startErr = err
×
2526
                                return
×
2527
                        }
×
2528
                }
2529

UNCOV
2530
                if s.natTraversal != nil {
×
2531
                        s.wg.Add(1)
×
2532
                        go s.watchExternalIP()
×
2533
                }
×
2534

2535
                // Start connmgr last to prevent connections before init.
UNCOV
2536
                cleanup = cleanup.add(func() error {
×
2537
                        s.connMgr.Stop()
×
2538
                        return nil
×
2539
                })
×
2540

2541
                // RESOLVE: s.connMgr.Start() is called here, but
2542
                // brontide.NewListener() is called in newServer. This means
2543
                // that we are actually listening and partially accepting
2544
                // inbound connections even before the connMgr starts.
2545
                //
2546
                // TODO(yy): move the log into the connMgr's `Start` method.
UNCOV
2547
                srvrLog.Info("connMgr starting...")
×
UNCOV
2548
                s.connMgr.Start()
×
UNCOV
2549
                srvrLog.Debug("connMgr started")
×
UNCOV
2550

×
UNCOV
2551
                // If peers are specified as a config option, we'll add those
×
UNCOV
2552
                // peers first.
×
UNCOV
2553
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
UNCOV
2554
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
UNCOV
2555
                                peerAddrCfg,
×
UNCOV
2556
                        )
×
UNCOV
2557
                        if err != nil {
×
2558
                                startErr = fmt.Errorf("unable to parse peer "+
×
2559
                                        "pubkey from config: %v", err)
×
2560
                                return
×
2561
                        }
×
UNCOV
2562
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
UNCOV
2563
                        if err != nil {
×
2564
                                startErr = fmt.Errorf("unable to parse peer "+
×
2565
                                        "address provided as a config option: "+
×
2566
                                        "%v", err)
×
2567
                                return
×
2568
                        }
×
2569

UNCOV
2570
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2571
                                IdentityKey: parsedPubkey,
×
UNCOV
2572
                                Address:     addr,
×
UNCOV
2573
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2574
                        }
×
UNCOV
2575

×
UNCOV
2576
                        err = s.ConnectToPeer(
×
UNCOV
2577
                                peerAddr, true,
×
UNCOV
2578
                                s.cfg.ConnectionTimeout,
×
UNCOV
2579
                        )
×
UNCOV
2580
                        if err != nil {
×
2581
                                startErr = fmt.Errorf("unable to connect to "+
×
2582
                                        "peer address provided as a config "+
×
2583
                                        "option: %v", err)
×
2584
                                return
×
2585
                        }
×
2586
                }
2587

2588
                // Subscribe to NodeAnnouncements that advertise new addresses
2589
                // our persistent peers.
UNCOV
2590
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2591
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2592
                                "addr: %v", err)
×
2593

×
2594
                        startErr = err
×
2595
                        return
×
2596
                }
×
2597

2598
                // With all the relevant sub-systems started, we'll now attempt
2599
                // to establish persistent connections to our direct channel
2600
                // collaborators within the network. Before doing so however,
2601
                // we'll prune our set of link nodes found within the database
2602
                // to ensure we don't reconnect to any nodes we no longer have
2603
                // open channels with.
UNCOV
2604
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2605
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2606

×
2607
                        startErr = err
×
2608
                        return
×
2609
                }
×
2610

UNCOV
2611
                if err := s.establishPersistentConnections(); err != nil {
×
2612
                        srvrLog.Errorf("Failed to establish persistent "+
×
2613
                                "connections: %v", err)
×
2614
                }
×
2615

2616
                // setSeedList is a helper function that turns multiple DNS seed
2617
                // server tuples from the command line or config file into the
2618
                // data structure we need and does a basic formal sanity check
2619
                // in the process.
UNCOV
2620
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2621
                        if len(tuples) == 0 {
×
2622
                                return
×
2623
                        }
×
2624

2625
                        result := make([][2]string, len(tuples))
×
2626
                        for idx, tuple := range tuples {
×
2627
                                tuple = strings.TrimSpace(tuple)
×
2628
                                if len(tuple) == 0 {
×
2629
                                        return
×
2630
                                }
×
2631

2632
                                servers := strings.Split(tuple, ",")
×
2633
                                if len(servers) > 2 || len(servers) == 0 {
×
2634
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2635
                                                "seed tuple: %v", servers)
×
2636
                                        return
×
2637
                                }
×
2638

2639
                                copy(result[idx][:], servers)
×
2640
                        }
2641

2642
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2643
                }
2644

2645
                // Let users overwrite the DNS seed nodes. We only allow them
2646
                // for bitcoin mainnet/testnet/signet.
UNCOV
2647
                if s.cfg.Bitcoin.MainNet {
×
2648
                        setSeedList(
×
2649
                                s.cfg.Bitcoin.DNSSeeds,
×
2650
                                chainreg.BitcoinMainnetGenesis,
×
2651
                        )
×
2652
                }
×
UNCOV
2653
                if s.cfg.Bitcoin.TestNet3 {
×
2654
                        setSeedList(
×
2655
                                s.cfg.Bitcoin.DNSSeeds,
×
2656
                                chainreg.BitcoinTestnetGenesis,
×
2657
                        )
×
2658
                }
×
UNCOV
2659
                if s.cfg.Bitcoin.TestNet4 {
×
2660
                        setSeedList(
×
2661
                                s.cfg.Bitcoin.DNSSeeds,
×
2662
                                chainreg.BitcoinTestnet4Genesis,
×
2663
                        )
×
2664
                }
×
UNCOV
2665
                if s.cfg.Bitcoin.SigNet {
×
2666
                        setSeedList(
×
2667
                                s.cfg.Bitcoin.DNSSeeds,
×
2668
                                chainreg.BitcoinSignetGenesis,
×
2669
                        )
×
2670
                }
×
2671

2672
                // If network bootstrapping hasn't been disabled, then we'll
2673
                // configure the set of active bootstrappers, and launch a
2674
                // dedicated goroutine to maintain a set of persistent
2675
                // connections.
UNCOV
2676
                if !s.cfg.NoNetBootstrap {
×
UNCOV
2677
                        bootstrappers, err := initNetworkBootstrappers(s)
×
UNCOV
2678
                        if err != nil {
×
2679
                                startErr = err
×
2680
                                return
×
2681
                        }
×
2682

UNCOV
2683
                        s.wg.Add(1)
×
UNCOV
2684
                        go s.peerBootstrapper(
×
UNCOV
2685
                                ctx, defaultMinPeers, bootstrappers,
×
UNCOV
2686
                        )
×
UNCOV
2687
                } else {
×
UNCOV
2688
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2689
                }
×
2690

2691
                // Start the blockbeat after all other subsystems have been
2692
                // started so they are ready to receive new blocks.
UNCOV
2693
                cleanup = cleanup.add(func() error {
×
2694
                        s.blockbeatDispatcher.Stop()
×
2695
                        return nil
×
2696
                })
×
UNCOV
2697
                if err := s.blockbeatDispatcher.Start(); err != nil {
×
2698
                        startErr = err
×
2699
                        return
×
2700
                }
×
2701

2702
                // Set the active flag now that we've completed the full
2703
                // startup.
UNCOV
2704
                atomic.StoreInt32(&s.active, 1)
×
2705
        })
2706

UNCOV
2707
        if startErr != nil {
×
2708
                cleanup.run()
×
2709
        }
×
UNCOV
2710
        return startErr
×
2711
}
2712

2713
// Stop gracefully shutsdown the main daemon server. This function will signal
2714
// any active goroutines, or helper objects to exit, then blocks until they've
2715
// all successfully exited. Additionally, any/all listeners are closed.
2716
// NOTE: This function is safe for concurrent access.
UNCOV
2717
func (s *server) Stop() error {
×
UNCOV
2718
        s.stop.Do(func() {
×
UNCOV
2719
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2720

×
UNCOV
2721
                ctx := context.Background()
×
UNCOV
2722

×
UNCOV
2723
                close(s.quit)
×
UNCOV
2724

×
UNCOV
2725
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2726
                s.connMgr.Stop()
×
UNCOV
2727

×
UNCOV
2728
                // Stop dispatching blocks to other systems immediately.
×
UNCOV
2729
                s.blockbeatDispatcher.Stop()
×
UNCOV
2730

×
UNCOV
2731
                // Shutdown the wallet, funding manager, and the rpc server.
×
UNCOV
2732
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2733
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2734
                }
×
UNCOV
2735
                if err := s.htlcSwitch.Stop(); err != nil {
×
2736
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2737
                }
×
UNCOV
2738
                if err := s.sphinx.Stop(); err != nil {
×
2739
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2740
                }
×
UNCOV
2741
                if err := s.invoices.Stop(); err != nil {
×
2742
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2743
                }
×
UNCOV
2744
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2745
                        srvrLog.Warnf("failed to stop interceptable "+
×
2746
                                "switch: %v", err)
×
2747
                }
×
UNCOV
2748
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2749
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2750
                                "modifier: %v", err)
×
2751
                }
×
UNCOV
2752
                if err := s.chanRouter.Stop(); err != nil {
×
2753
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2754
                }
×
UNCOV
2755
                if err := s.graphBuilder.Stop(); err != nil {
×
2756
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2757
                }
×
UNCOV
2758
                if err := s.graphDB.Stop(); err != nil {
×
2759
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2760
                }
×
UNCOV
2761
                if err := s.chainArb.Stop(); err != nil {
×
2762
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2763
                }
×
UNCOV
2764
                if err := s.fundingMgr.Stop(); err != nil {
×
2765
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2766
                }
×
UNCOV
2767
                if err := s.breachArbitrator.Stop(); err != nil {
×
2768
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2769
                                err)
×
2770
                }
×
UNCOV
2771
                if err := s.utxoNursery.Stop(); err != nil {
×
2772
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2773
                }
×
UNCOV
2774
                if err := s.authGossiper.Stop(); err != nil {
×
2775
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2776
                }
×
UNCOV
2777
                if err := s.sweeper.Stop(); err != nil {
×
2778
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2779
                }
×
UNCOV
2780
                if err := s.txPublisher.Stop(); err != nil {
×
2781
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2782
                }
×
UNCOV
2783
                if err := s.channelNotifier.Stop(); err != nil {
×
2784
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2785
                }
×
UNCOV
2786
                if err := s.peerNotifier.Stop(); err != nil {
×
2787
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2788
                }
×
UNCOV
2789
                if err := s.htlcNotifier.Stop(); err != nil {
×
2790
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2791
                }
×
2792

2793
                // Update channel.backup file. Make sure to do it before
2794
                // stopping chanSubSwapper.
UNCOV
2795
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2796
                        ctx, s.chanStateDB, s.addrSource,
×
UNCOV
2797
                )
×
UNCOV
2798
                if err != nil {
×
2799
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2800
                                err)
×
UNCOV
2801
                } else {
×
UNCOV
2802
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
UNCOV
2803
                        if err != nil {
×
UNCOV
2804
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2805
                                        "backup failed: %v", err)
×
UNCOV
2806
                        }
×
2807
                }
2808

UNCOV
2809
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2810
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2811
                }
×
UNCOV
2812
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2813
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2814
                }
×
UNCOV
2815
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2816
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2817
                                err)
×
2818
                }
×
UNCOV
2819
                if err := s.chanEventStore.Stop(); err != nil {
×
2820
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2821
                                err)
×
2822
                }
×
UNCOV
2823
                s.missionController.StopStoreTickers()
×
UNCOV
2824

×
UNCOV
2825
                // Disconnect from each active peers to ensure that
×
UNCOV
2826
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2827
                for _, peer := range s.Peers() {
×
UNCOV
2828
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2829
                        if err != nil {
×
2830
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2831
                                        "received error: %v", peer.IdentityKey(),
×
2832
                                        err,
×
2833
                                )
×
2834
                        }
×
2835
                }
2836

2837
                // Now that all connections have been torn down, stop the tower
2838
                // client which will reliably flush all queued states to the
2839
                // tower. If this is halted for any reason, the force quit timer
2840
                // will kick in and abort to allow this method to return.
UNCOV
2841
                if s.towerClientMgr != nil {
×
UNCOV
2842
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2843
                                srvrLog.Warnf("Unable to shut down tower "+
×
2844
                                        "client manager: %v", err)
×
2845
                        }
×
2846
                }
2847

UNCOV
2848
                if s.hostAnn != nil {
×
2849
                        if err := s.hostAnn.Stop(); err != nil {
×
2850
                                srvrLog.Warnf("unable to shut down host "+
×
2851
                                        "annoucner: %v", err)
×
2852
                        }
×
2853
                }
2854

UNCOV
2855
                if s.livenessMonitor != nil {
×
UNCOV
2856
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2857
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2858
                                        "monitor: %v", err)
×
2859
                        }
×
2860
                }
2861

2862
                // Wait for all lingering goroutines to quit.
UNCOV
2863
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2864
                s.wg.Wait()
×
UNCOV
2865

×
UNCOV
2866
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2867
                s.sigPool.Stop()
×
UNCOV
2868
                s.writePool.Stop()
×
UNCOV
2869
                s.readPool.Stop()
×
2870
        })
2871

UNCOV
2872
        return nil
×
2873
}
2874

2875
// Stopped returns true if the server has been instructed to shutdown.
2876
// NOTE: This function is safe for concurrent access.
UNCOV
2877
func (s *server) Stopped() bool {
×
UNCOV
2878
        return atomic.LoadInt32(&s.stopping) != 0
×
UNCOV
2879
}
×
2880

2881
// configurePortForwarding attempts to set up port forwarding for the different
2882
// ports that the server will be listening on.
2883
//
2884
// NOTE: This should only be used when using some kind of NAT traversal to
2885
// automatically set up forwarding rules.
2886
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2887
        ip, err := s.natTraversal.ExternalIP()
×
2888
        if err != nil {
×
2889
                return nil, err
×
2890
        }
×
2891
        s.lastDetectedIP = ip
×
2892

×
2893
        externalIPs := make([]string, 0, len(ports))
×
2894
        for _, port := range ports {
×
2895
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2896
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2897
                        continue
×
2898
                }
2899

2900
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2901
                externalIPs = append(externalIPs, hostIP)
×
2902
        }
2903

2904
        return externalIPs, nil
×
2905
}
2906

2907
// removePortForwarding attempts to clear the forwarding rules for the different
2908
// ports the server is currently listening on.
2909
//
2910
// NOTE: This should only be used when using some kind of NAT traversal to
2911
// automatically set up forwarding rules.
2912
func (s *server) removePortForwarding() {
×
2913
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2914
        for _, port := range forwardedPorts {
×
2915
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2916
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2917
                                "port %d: %v", port, err)
×
2918
                }
×
2919
        }
2920
}
2921

2922
// watchExternalIP continuously checks for an updated external IP address every
2923
// 15 minutes. Once a new IP address has been detected, it will automatically
2924
// handle port forwarding rules and send updated node announcements to the
2925
// currently connected peers.
2926
//
2927
// NOTE: This MUST be run as a goroutine.
2928
func (s *server) watchExternalIP() {
×
2929
        defer s.wg.Done()
×
2930

×
2931
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2932
        // up by the server.
×
2933
        defer s.removePortForwarding()
×
2934

×
2935
        // Keep track of the external IPs set by the user to avoid replacing
×
2936
        // them when detecting a new IP.
×
2937
        ipsSetByUser := make(map[string]struct{})
×
2938
        for _, ip := range s.cfg.ExternalIPs {
×
2939
                ipsSetByUser[ip.String()] = struct{}{}
×
2940
        }
×
2941

2942
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2943

×
2944
        ticker := time.NewTicker(15 * time.Minute)
×
2945
        defer ticker.Stop()
×
2946
out:
×
2947
        for {
×
2948
                select {
×
2949
                case <-ticker.C:
×
2950
                        // We'll start off by making sure a new IP address has
×
2951
                        // been detected.
×
2952
                        ip, err := s.natTraversal.ExternalIP()
×
2953
                        if err != nil {
×
2954
                                srvrLog.Debugf("Unable to retrieve the "+
×
2955
                                        "external IP address: %v", err)
×
2956
                                continue
×
2957
                        }
2958

2959
                        // Periodically renew the NAT port forwarding.
2960
                        for _, port := range forwardedPorts {
×
2961
                                err := s.natTraversal.AddPortMapping(port)
×
2962
                                if err != nil {
×
2963
                                        srvrLog.Warnf("Unable to automatically "+
×
2964
                                                "re-create port forwarding using %s: %v",
×
2965
                                                s.natTraversal.Name(), err)
×
2966
                                } else {
×
2967
                                        srvrLog.Debugf("Automatically re-created "+
×
2968
                                                "forwarding for port %d using %s to "+
×
2969
                                                "advertise external IP",
×
2970
                                                port, s.natTraversal.Name())
×
2971
                                }
×
2972
                        }
2973

2974
                        if ip.Equal(s.lastDetectedIP) {
×
2975
                                continue
×
2976
                        }
2977

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

×
2980
                        // Next, we'll craft the new addresses that will be
×
2981
                        // included in the new node announcement and advertised
×
2982
                        // to the network. Each address will consist of the new
×
2983
                        // IP detected and one of the currently advertised
×
2984
                        // ports.
×
2985
                        var newAddrs []net.Addr
×
2986
                        for _, port := range forwardedPorts {
×
2987
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2988
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2989
                                if err != nil {
×
2990
                                        srvrLog.Debugf("Unable to resolve "+
×
2991
                                                "host %v: %v", addr, err)
×
2992
                                        continue
×
2993
                                }
2994

2995
                                newAddrs = append(newAddrs, addr)
×
2996
                        }
2997

2998
                        // Skip the update if we weren't able to resolve any of
2999
                        // the new addresses.
3000
                        if len(newAddrs) == 0 {
×
3001
                                srvrLog.Debug("Skipping node announcement " +
×
3002
                                        "update due to not being able to " +
×
3003
                                        "resolve any new addresses")
×
3004
                                continue
×
3005
                        }
3006

3007
                        // Now, we'll need to update the addresses in our node's
3008
                        // announcement in order to propagate the update
3009
                        // throughout the network. We'll only include addresses
3010
                        // that have a different IP from the previous one, as
3011
                        // the previous IP is no longer valid.
3012
                        currentNodeAnn := s.getNodeAnnouncement()
×
3013

×
3014
                        for _, addr := range currentNodeAnn.Addresses {
×
3015
                                host, _, err := net.SplitHostPort(addr.String())
×
3016
                                if err != nil {
×
3017
                                        srvrLog.Debugf("Unable to determine "+
×
3018
                                                "host from address %v: %v",
×
3019
                                                addr, err)
×
3020
                                        continue
×
3021
                                }
3022

3023
                                // We'll also make sure to include external IPs
3024
                                // set manually by the user.
3025
                                _, setByUser := ipsSetByUser[addr.String()]
×
3026
                                if setByUser || host != s.lastDetectedIP.String() {
×
3027
                                        newAddrs = append(newAddrs, addr)
×
3028
                                }
×
3029
                        }
3030

3031
                        // Then, we'll generate a new timestamped node
3032
                        // announcement with the updated addresses and broadcast
3033
                        // it to our peers.
3034
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3035
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3036
                        )
×
3037
                        if err != nil {
×
3038
                                srvrLog.Debugf("Unable to generate new node "+
×
3039
                                        "announcement: %v", err)
×
3040
                                continue
×
3041
                        }
3042

3043
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3044
                        if err != nil {
×
3045
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3046
                                        "announcement to peers: %v", err)
×
3047
                                continue
×
3048
                        }
3049

3050
                        // Finally, update the last IP seen to the current one.
3051
                        s.lastDetectedIP = ip
×
3052
                case <-s.quit:
×
3053
                        break out
×
3054
                }
3055
        }
3056
}
3057

3058
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3059
// based on the server, and currently active bootstrap mechanisms as defined
3060
// within the current configuration.
UNCOV
3061
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
UNCOV
3062
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
UNCOV
3063

×
UNCOV
3064
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
UNCOV
3065

×
UNCOV
3066
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
UNCOV
3067
        // this can be used by default if we've already partially seeded the
×
UNCOV
3068
        // network.
×
UNCOV
3069
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
UNCOV
3070
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
×
UNCOV
3071
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
×
UNCOV
3072
        )
×
UNCOV
3073
        if err != nil {
×
3074
                return nil, err
×
3075
        }
×
UNCOV
3076
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
UNCOV
3077

×
UNCOV
3078
        // If this isn't using simnet or regtest mode, then one of our
×
UNCOV
3079
        // additional bootstrapping sources will be the set of running DNS
×
UNCOV
3080
        // seeds.
×
UNCOV
3081
        if !s.cfg.Bitcoin.IsLocalNetwork() {
×
3082
                //nolint:ll
×
3083
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3084

×
3085
                // If we have a set of DNS seeds for this chain, then we'll add
×
3086
                // it as an additional bootstrapping source.
×
3087
                if ok {
×
3088
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3089
                                "seeds: %v", dnsSeeds)
×
3090

×
3091
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3092
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3093
                        )
×
3094
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3095
                }
×
3096
        }
3097

UNCOV
3098
        return bootStrappers, nil
×
3099
}
3100

3101
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3102
// needs to ignore, which is made of three parts,
3103
//   - the node itself needs to be skipped as it doesn't make sense to connect
3104
//     to itself.
3105
//   - the peers that already have connections with, as in s.peersByPub.
3106
//   - the peers that we are attempting to connect, as in s.persistentPeers.
UNCOV
3107
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
UNCOV
3108
        s.mu.RLock()
×
UNCOV
3109
        defer s.mu.RUnlock()
×
UNCOV
3110

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

×
UNCOV
3113
        // We should ignore ourselves from bootstrapping.
×
UNCOV
3114
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
UNCOV
3115
        ignore[selfKey] = struct{}{}
×
UNCOV
3116

×
UNCOV
3117
        // Ignore all connected peers.
×
UNCOV
3118
        for _, peer := range s.peersByPub {
×
3119
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3120
                ignore[nID] = struct{}{}
×
3121
        }
×
3122

3123
        // Ignore all persistent peers as they have a dedicated reconnecting
3124
        // process.
UNCOV
3125
        for pubKeyStr := range s.persistentPeers {
×
3126
                var nID autopilot.NodeID
×
3127
                copy(nID[:], []byte(pubKeyStr))
×
3128
                ignore[nID] = struct{}{}
×
3129
        }
×
3130

UNCOV
3131
        return ignore
×
3132
}
3133

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

×
UNCOV
3142
        defer s.wg.Done()
×
UNCOV
3143

×
UNCOV
3144
        // Before we continue, init the ignore peers map.
×
UNCOV
3145
        ignoreList := s.createBootstrapIgnorePeers()
×
UNCOV
3146

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

×
UNCOV
3151
        // Once done, we'll attempt to maintain our target minimum number of
×
UNCOV
3152
        // peers.
×
UNCOV
3153
        //
×
UNCOV
3154
        // We'll use a 15 second backoff, and double the time every time an
×
UNCOV
3155
        // epoch fails up to a ceiling.
×
UNCOV
3156
        backOff := time.Second * 15
×
UNCOV
3157

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

×
UNCOV
3163
        // We'll use the number of attempts and errors to determine if we need
×
UNCOV
3164
        // to increase the time between discovery epochs.
×
UNCOV
3165
        var epochErrors uint32 // To be used atomically.
×
UNCOV
3166
        var epochAttempts uint32
×
UNCOV
3167

×
UNCOV
3168
        for {
×
UNCOV
3169
                select {
×
3170
                // The ticker has just woken us up, so we'll need to check if
3171
                // we need to attempt to connect our to any more peers.
3172
                case <-sampleTicker.C:
×
3173
                        // Obtain the current number of peers, so we can gauge
×
3174
                        // if we need to sample more peers or not.
×
3175
                        s.mu.RLock()
×
3176
                        numActivePeers := uint32(len(s.peersByPub))
×
3177
                        s.mu.RUnlock()
×
3178

×
3179
                        // If we have enough peers, then we can loop back
×
3180
                        // around to the next round as we're done here.
×
3181
                        if numActivePeers >= numTargetPeers {
×
3182
                                continue
×
3183
                        }
3184

3185
                        // If all of our attempts failed during this last back
3186
                        // off period, then will increase our backoff to 5
3187
                        // minute ceiling to avoid an excessive number of
3188
                        // queries
3189
                        //
3190
                        // TODO(roasbeef): add reverse policy too?
3191

3192
                        if epochAttempts > 0 &&
×
3193
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3194

×
3195
                                sampleTicker.Stop()
×
3196

×
3197
                                backOff *= 2
×
3198
                                if backOff > bootstrapBackOffCeiling {
×
3199
                                        backOff = bootstrapBackOffCeiling
×
3200
                                }
×
3201

3202
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3203
                                        "%v", backOff)
×
3204
                                sampleTicker = time.NewTicker(backOff)
×
3205
                                continue
×
3206
                        }
3207

3208
                        atomic.StoreUint32(&epochErrors, 0)
×
3209
                        epochAttempts = 0
×
3210

×
3211
                        // Since we know need more peers, we'll compute the
×
3212
                        // exact number we need to reach our threshold.
×
3213
                        numNeeded := numTargetPeers - numActivePeers
×
3214

×
3215
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3216
                                "peers", numNeeded)
×
3217

×
3218
                        // With the number of peers we need calculated, we'll
×
3219
                        // query the network bootstrappers to sample a set of
×
3220
                        // random addrs for us.
×
3221
                        //
×
3222
                        // Before we continue, get a copy of the ignore peers
×
3223
                        // map.
×
3224
                        ignoreList = s.createBootstrapIgnorePeers()
×
3225

×
3226
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3227
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3228
                        )
×
3229
                        if err != nil {
×
3230
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3231
                                        "peers: %v", err)
×
3232
                                continue
×
3233
                        }
3234

3235
                        // Finally, we'll launch a new goroutine for each
3236
                        // prospective peer candidates.
3237
                        for _, addr := range peerAddrs {
×
3238
                                epochAttempts++
×
3239

×
3240
                                go func(a *lnwire.NetAddress) {
×
3241
                                        // TODO(roasbeef): can do AS, subnet,
×
3242
                                        // country diversity, etc
×
3243
                                        errChan := make(chan error, 1)
×
3244
                                        s.connectToPeer(
×
3245
                                                a, errChan,
×
3246
                                                s.cfg.ConnectionTimeout,
×
3247
                                        )
×
3248
                                        select {
×
3249
                                        case err := <-errChan:
×
3250
                                                if err == nil {
×
3251
                                                        return
×
3252
                                                }
×
3253

3254
                                                srvrLog.Errorf("Unable to "+
×
3255
                                                        "connect to %v: %v",
×
3256
                                                        a, err)
×
3257
                                                atomic.AddUint32(&epochErrors, 1)
×
3258
                                        case <-s.quit:
×
3259
                                        }
3260
                                }(addr)
3261
                        }
UNCOV
3262
                case <-s.quit:
×
UNCOV
3263
                        return
×
3264
                }
3265
        }
3266
}
3267

3268
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3269
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3270
// query back off each time we encounter a failure.
3271
const bootstrapBackOffCeiling = time.Minute * 5
3272

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

×
UNCOV
3280
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
UNCOV
3281
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
UNCOV
3282

×
UNCOV
3283
        // We'll start off by waiting 2 seconds between failed attempts, then
×
UNCOV
3284
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
UNCOV
3285
        var delaySignal <-chan time.Time
×
UNCOV
3286
        delayTime := time.Second * 2
×
UNCOV
3287

×
UNCOV
3288
        // As want to be more aggressive, we'll use a lower back off celling
×
UNCOV
3289
        // then the main peer bootstrap logic.
×
UNCOV
3290
        backOffCeiling := bootstrapBackOffCeiling / 5
×
UNCOV
3291

×
UNCOV
3292
        for attempts := 0; ; attempts++ {
×
UNCOV
3293
                // Check if the server has been requested to shut down in order
×
UNCOV
3294
                // to prevent blocking.
×
UNCOV
3295
                if s.Stopped() {
×
3296
                        return
×
3297
                }
×
3298

3299
                // We can exit our aggressive initial peer bootstrapping stage
3300
                // if we've reached out target number of peers.
UNCOV
3301
                s.mu.RLock()
×
UNCOV
3302
                numActivePeers := uint32(len(s.peersByPub))
×
UNCOV
3303
                s.mu.RUnlock()
×
UNCOV
3304

×
UNCOV
3305
                if numActivePeers >= numTargetPeers {
×
UNCOV
3306
                        return
×
UNCOV
3307
                }
×
3308

UNCOV
3309
                if attempts > 0 {
×
3310
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3311
                                "bootstrap peers (attempt #%v)", delayTime,
×
3312
                                attempts)
×
3313

×
3314
                        // We've completed at least one iterating and haven't
×
3315
                        // finished, so we'll start to insert a delay period
×
3316
                        // between each attempt.
×
3317
                        delaySignal = time.After(delayTime)
×
3318
                        select {
×
3319
                        case <-delaySignal:
×
3320
                        case <-s.quit:
×
3321
                                return
×
3322
                        }
3323

3324
                        // After our delay, we'll double the time we wait up to
3325
                        // the max back off period.
3326
                        delayTime *= 2
×
3327
                        if delayTime > backOffCeiling {
×
3328
                                delayTime = backOffCeiling
×
3329
                        }
×
3330
                }
3331

3332
                // Otherwise, we'll request for the remaining number of peers
3333
                // in order to reach our target.
UNCOV
3334
                peersNeeded := numTargetPeers - numActivePeers
×
UNCOV
3335
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
UNCOV
3336
                        ctx, ignore, peersNeeded, bootstrappers...,
×
UNCOV
3337
                )
×
UNCOV
3338
                if err != nil {
×
3339
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3340
                                "peers: %v", err)
×
3341
                        continue
×
3342
                }
3343

3344
                // Then, we'll attempt to establish a connection to the
3345
                // different peer addresses retrieved by our bootstrappers.
UNCOV
3346
                var wg sync.WaitGroup
×
UNCOV
3347
                for _, bootstrapAddr := range bootstrapAddrs {
×
UNCOV
3348
                        wg.Add(1)
×
UNCOV
3349
                        go func(addr *lnwire.NetAddress) {
×
UNCOV
3350
                                defer wg.Done()
×
UNCOV
3351

×
UNCOV
3352
                                errChan := make(chan error, 1)
×
UNCOV
3353
                                go s.connectToPeer(
×
UNCOV
3354
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
UNCOV
3355
                                )
×
UNCOV
3356

×
UNCOV
3357
                                // We'll only allow this connection attempt to
×
UNCOV
3358
                                // take up to 3 seconds. This allows us to move
×
UNCOV
3359
                                // quickly by discarding peers that are slowing
×
UNCOV
3360
                                // us down.
×
UNCOV
3361
                                select {
×
UNCOV
3362
                                case err := <-errChan:
×
UNCOV
3363
                                        if err == nil {
×
UNCOV
3364
                                                return
×
UNCOV
3365
                                        }
×
3366
                                        srvrLog.Errorf("Unable to connect to "+
×
3367
                                                "%v: %v", addr, err)
×
3368
                                // TODO: tune timeout? 3 seconds might be *too*
3369
                                // aggressive but works well.
3370
                                case <-time.After(3 * time.Second):
×
3371
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3372
                                                "to not establishing a "+
×
3373
                                                "connection within 3 seconds",
×
3374
                                                addr)
×
3375
                                case <-s.quit:
×
3376
                                }
3377
                        }(bootstrapAddr)
3378
                }
3379

UNCOV
3380
                wg.Wait()
×
3381
        }
3382
}
3383

3384
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3385
// order to listen for inbound connections over Tor.
3386
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3387
        // Determine the different ports the server is listening on. The onion
×
3388
        // service's virtual port will map to these ports and one will be picked
×
3389
        // at random when the onion service is being accessed.
×
3390
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3391
        for _, listenAddr := range s.listenAddrs {
×
3392
                port := listenAddr.(*net.TCPAddr).Port
×
3393
                listenPorts = append(listenPorts, port)
×
3394
        }
×
3395

3396
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3397
        if err != nil {
×
3398
                return err
×
3399
        }
×
3400

3401
        // Once the port mapping has been set, we can go ahead and automatically
3402
        // create our onion service. The service's private key will be saved to
3403
        // disk in order to regain access to this service when restarting `lnd`.
3404
        onionCfg := tor.AddOnionConfig{
×
3405
                VirtualPort: defaultPeerPort,
×
3406
                TargetPorts: listenPorts,
×
3407
                Store: tor.NewOnionFile(
×
3408
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3409
                        encrypter,
×
3410
                ),
×
3411
        }
×
3412

×
3413
        switch {
×
3414
        case s.cfg.Tor.V2:
×
3415
                onionCfg.Type = tor.V2
×
3416
        case s.cfg.Tor.V3:
×
3417
                onionCfg.Type = tor.V3
×
3418
        }
3419

3420
        addr, err := s.torController.AddOnion(onionCfg)
×
3421
        if err != nil {
×
3422
                return err
×
3423
        }
×
3424

3425
        // Now that the onion service has been created, we'll add the onion
3426
        // address it can be reached at to our list of advertised addresses.
3427
        newNodeAnn, err := s.genNodeAnnouncement(
×
3428
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3429
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3430
                },
×
3431
        )
3432
        if err != nil {
×
3433
                return fmt.Errorf("unable to generate new node "+
×
3434
                        "announcement: %v", err)
×
3435
        }
×
3436

3437
        // Finally, we'll update the on-disk version of our announcement so it
3438
        // will eventually propagate to nodes in the network.
3439
        selfNode := &models.LightningNode{
×
3440
                HaveNodeAnnouncement: true,
×
3441
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3442
                Addresses:            newNodeAnn.Addresses,
×
3443
                Alias:                newNodeAnn.Alias.String(),
×
3444
                Features: lnwire.NewFeatureVector(
×
3445
                        newNodeAnn.Features, lnwire.Features,
×
3446
                ),
×
3447
                Color:        newNodeAnn.RGBColor,
×
3448
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3449
        }
×
3450
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3451
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3452
                return fmt.Errorf("can't set self node: %w", err)
×
3453
        }
×
3454

3455
        return nil
×
3456
}
3457

3458
// findChannel finds a channel given a public key and ChannelID. It is an
3459
// optimization that is quicker than seeking for a channel given only the
3460
// ChannelID.
3461
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
UNCOV
3462
        *channeldb.OpenChannel, error) {
×
UNCOV
3463

×
UNCOV
3464
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3465
        if err != nil {
×
3466
                return nil, err
×
3467
        }
×
3468

UNCOV
3469
        for _, channel := range nodeChans {
×
UNCOV
3470
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3471
                        return channel, nil
×
UNCOV
3472
                }
×
3473
        }
3474

UNCOV
3475
        return nil, fmt.Errorf("unable to find channel")
×
3476
}
3477

3478
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3479
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3480
        s.mu.Lock()
×
UNCOV
3481
        defer s.mu.Unlock()
×
UNCOV
3482

×
UNCOV
3483
        return *s.currentNodeAnn
×
UNCOV
3484
}
×
3485

3486
// genNodeAnnouncement generates and returns the current fully signed node
3487
// announcement. The time stamp of the announcement will be updated in order
3488
// to ensure it propagates through the network.
3489
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3490
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3491

×
UNCOV
3492
        s.mu.Lock()
×
UNCOV
3493
        defer s.mu.Unlock()
×
UNCOV
3494

×
UNCOV
3495
        // Create a shallow copy of the current node announcement to work on.
×
UNCOV
3496
        // This ensures the original announcement remains unchanged
×
UNCOV
3497
        // until the new announcement is fully signed and valid.
×
UNCOV
3498
        newNodeAnn := *s.currentNodeAnn
×
UNCOV
3499

×
UNCOV
3500
        // First, try to update our feature manager with the updated set of
×
UNCOV
3501
        // features.
×
UNCOV
3502
        if features != nil {
×
UNCOV
3503
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3504
                        feature.SetNodeAnn: features,
×
UNCOV
3505
                }
×
UNCOV
3506
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3507
                if err != nil {
×
UNCOV
3508
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3509
                }
×
3510

3511
                // If we could successfully update our feature manager, add
3512
                // an update modifier to include these new features to our
3513
                // set.
UNCOV
3514
                modifiers = append(
×
UNCOV
3515
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3516
                )
×
3517
        }
3518

3519
        // Always update the timestamp when refreshing to ensure the update
3520
        // propagates.
UNCOV
3521
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3522

×
UNCOV
3523
        // Apply the requested changes to the node announcement.
×
UNCOV
3524
        for _, modifier := range modifiers {
×
UNCOV
3525
                modifier(&newNodeAnn)
×
UNCOV
3526
        }
×
3527

3528
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3529
        err := netann.SignNodeAnnouncement(
×
UNCOV
3530
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
UNCOV
3531
        )
×
UNCOV
3532
        if err != nil {
×
3533
                return lnwire.NodeAnnouncement{}, err
×
3534
        }
×
3535

3536
        // If signing succeeds, update the current announcement.
UNCOV
3537
        *s.currentNodeAnn = newNodeAnn
×
UNCOV
3538

×
UNCOV
3539
        return *s.currentNodeAnn, nil
×
3540
}
3541

3542
// updateAndBroadcastSelfNode generates a new node announcement
3543
// applying the giving modifiers and updating the time stamp
3544
// to ensure it propagates through the network. Then it broadcasts
3545
// it to the network.
3546
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3547
        features *lnwire.RawFeatureVector,
UNCOV
3548
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3549

×
UNCOV
3550
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3551
        if err != nil {
×
UNCOV
3552
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3553
                        "announcement: %v", err)
×
UNCOV
3554
        }
×
3555

3556
        // Update the on-disk version of our announcement.
3557
        // Load and modify self node istead of creating anew instance so we
3558
        // don't risk overwriting any existing values.
UNCOV
3559
        selfNode, err := s.graphDB.SourceNode(ctx)
×
UNCOV
3560
        if err != nil {
×
3561
                return fmt.Errorf("unable to get current source node: %w", err)
×
3562
        }
×
3563

UNCOV
3564
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3565
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3566
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3567
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3568
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3569
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3570
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3571

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

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

3578
        // Finally, propagate it to the nodes in the network.
UNCOV
3579
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3580
        if err != nil {
×
3581
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3582
                        "announcement to peers: %v", err)
×
3583
                return err
×
3584
        }
×
3585

UNCOV
3586
        return nil
×
3587
}
3588

3589
type nodeAddresses struct {
3590
        pubKey    *btcec.PublicKey
3591
        addresses []net.Addr
3592
}
3593

3594
// establishPersistentConnections attempts to establish persistent connections
3595
// to all our direct channel collaborators. In order to promote liveness of our
3596
// active channels, we instruct the connection manager to attempt to establish
3597
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3598
func (s *server) establishPersistentConnections() error {
×
UNCOV
3599
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3600
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3601
        // since other PubKey forms can't be compared.
×
UNCOV
3602
        nodeAddrsMap := map[string]*nodeAddresses{}
×
UNCOV
3603

×
UNCOV
3604
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3605
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3606
        // the reconnection port to the default peer port.
×
UNCOV
3607
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3608
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3609
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3610
        }
×
3611

UNCOV
3612
        for _, node := range linkNodes {
×
UNCOV
3613
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3614
                nodeAddrs := &nodeAddresses{
×
UNCOV
3615
                        pubKey:    node.IdentityPub,
×
UNCOV
3616
                        addresses: node.Addresses,
×
UNCOV
3617
                }
×
UNCOV
3618
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3619
        }
×
3620

3621
        // After checking our previous connections for addresses to connect to,
3622
        // iterate through the nodes in our channel graph to find addresses
3623
        // that have been added via NodeAnnouncement messages.
3624
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3625
        // each of the nodes.
UNCOV
3626
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
×
UNCOV
3627
                havePolicy bool, channelPeer *models.LightningNode) error {
×
UNCOV
3628

×
UNCOV
3629
                // If the remote party has announced the channel to us, but we
×
UNCOV
3630
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3631
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3632
                if !havePolicy {
×
3633
                        srvrLog.Warnf("No channel policy found for "+
×
3634
                                "ChannelPoint(%v): ", chanPoint)
×
3635
                }
×
3636

UNCOV
3637
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3638

×
UNCOV
3639
                // Add all unique addresses from channel
×
UNCOV
3640
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3641
                // connect to for this peer.
×
UNCOV
3642
                addrSet := make(map[string]net.Addr)
×
UNCOV
3643
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3644
                        switch addr.(type) {
×
UNCOV
3645
                        case *net.TCPAddr:
×
UNCOV
3646
                                addrSet[addr.String()] = addr
×
3647

3648
                        // We'll only attempt to connect to Tor addresses if Tor
3649
                        // outbound support is enabled.
3650
                        case *tor.OnionAddr:
×
3651
                                if s.cfg.Tor.Active {
×
3652
                                        addrSet[addr.String()] = addr
×
3653
                                }
×
3654
                        }
3655
                }
3656

3657
                // If this peer is also recorded as a link node, we'll add any
3658
                // additional addresses that have not already been selected.
UNCOV
3659
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3660
                if ok {
×
UNCOV
3661
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3662
                                switch lnAddress.(type) {
×
UNCOV
3663
                                case *net.TCPAddr:
×
UNCOV
3664
                                        addrSet[lnAddress.String()] = lnAddress
×
3665

3666
                                // We'll only attempt to connect to Tor
3667
                                // addresses if Tor outbound support is enabled.
3668
                                case *tor.OnionAddr:
×
3669
                                        if s.cfg.Tor.Active {
×
3670
                                                addrSet[lnAddress.String()] = lnAddress
×
3671
                                        }
×
3672
                                }
3673
                        }
3674
                }
3675

3676
                // Construct a slice of the deduped addresses.
UNCOV
3677
                var addrs []net.Addr
×
UNCOV
3678
                for _, addr := range addrSet {
×
UNCOV
3679
                        addrs = append(addrs, addr)
×
UNCOV
3680
                }
×
3681

UNCOV
3682
                n := &nodeAddresses{
×
UNCOV
3683
                        addresses: addrs,
×
UNCOV
3684
                }
×
UNCOV
3685
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3686
                if err != nil {
×
3687
                        return err
×
3688
                }
×
3689

UNCOV
3690
                nodeAddrsMap[pubStr] = n
×
UNCOV
3691
                return nil
×
3692
        })
UNCOV
3693
        if err != nil {
×
3694
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3695
                        "%v", err)
×
3696

×
3697
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3698
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3699

×
3700
                        return err
×
3701
                }
×
3702
        }
3703

UNCOV
3704
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3705
                len(nodeAddrsMap))
×
UNCOV
3706

×
UNCOV
3707
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3708
        // have been recorded and sent to the connection manager.
×
UNCOV
3709
        s.mu.Lock()
×
UNCOV
3710
        defer s.mu.Unlock()
×
UNCOV
3711

×
UNCOV
3712
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3713
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3714
        var numOutboundConns int
×
UNCOV
3715
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3716
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3717
                // persistent connection with. We set the value to false to
×
UNCOV
3718
                // indicate that we should not continue to reconnect if the
×
UNCOV
3719
                // number of channels returns to zero, since this peer has not
×
UNCOV
3720
                // been requested as perm by the user.
×
UNCOV
3721
                s.persistentPeers[pubStr] = false
×
UNCOV
3722
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
UNCOV
3723
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
UNCOV
3724
                }
×
3725

UNCOV
3726
                for _, address := range nodeAddr.addresses {
×
UNCOV
3727
                        // Create a wrapper address which couples the IP and
×
UNCOV
3728
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3729
                        // can be established.
×
UNCOV
3730
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3731
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3732
                                Address:     address,
×
UNCOV
3733
                        }
×
UNCOV
3734

×
UNCOV
3735
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3736
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3737
                }
×
3738

3739
                // We'll connect to the first 10 peers immediately, then
3740
                // randomly stagger any remaining connections if the
3741
                // stagger initial reconnect flag is set. This ensures
3742
                // that mobile nodes or nodes with a small number of
3743
                // channels obtain connectivity quickly, but larger
3744
                // nodes are able to disperse the costs of connecting to
3745
                // all peers at once.
UNCOV
3746
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3747
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3748

×
UNCOV
3749
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3750
                } else {
×
3751
                        go s.delayInitialReconnect(pubStr)
×
3752
                }
×
3753

UNCOV
3754
                numOutboundConns++
×
3755
        }
3756

UNCOV
3757
        return nil
×
3758
}
3759

3760
// delayInitialReconnect will attempt a reconnection to the given peer after
3761
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3762
//
3763
// NOTE: This method MUST be run as a goroutine.
3764
func (s *server) delayInitialReconnect(pubStr string) {
×
3765
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3766
        select {
×
3767
        case <-time.After(delay):
×
3768
                s.connectToPersistentPeer(pubStr)
×
3769
        case <-s.quit:
×
3770
        }
3771
}
3772

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

×
UNCOV
3779
        s.mu.Lock()
×
UNCOV
3780
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3781
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3782
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3783
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3784
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3785
                s.mu.Unlock()
×
UNCOV
3786

×
UNCOV
3787
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3788
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3789

×
UNCOV
3790
                return
×
UNCOV
3791
        }
×
UNCOV
3792
        s.mu.Unlock()
×
3793
}
3794

3795
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3796
// is instead used to remove persistent peer state for a peer that has been
3797
// disconnected for good cause by the server. Currently, a gossip ban from
3798
// sending garbage and the server running out of restricted-access
3799
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3800
// future, this function may expand when more ban criteria is added.
3801
//
3802
// NOTE: The server's write lock MUST be held when this is called.
3803
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3804
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3805
                delete(s.persistentPeers, remotePub)
×
3806
                delete(s.persistentPeersBackoff, remotePub)
×
3807
                delete(s.persistentPeerAddrs, remotePub)
×
3808
                s.cancelConnReqs(remotePub, nil)
×
3809
        }
×
3810
}
3811

3812
// BroadcastMessage sends a request to the server to broadcast a set of
3813
// messages to all peers other than the one specified by the `skips` parameter.
3814
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3815
// the target peers.
3816
//
3817
// NOTE: This function is safe for concurrent access.
3818
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3819
        msgs ...lnwire.Message) error {
×
UNCOV
3820

×
UNCOV
3821
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3822
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3823
        // exact set of peers present at the time of invocation.
×
UNCOV
3824
        s.mu.RLock()
×
UNCOV
3825
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3826
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3827
                if skips != nil {
×
UNCOV
3828
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3829
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3830
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
UNCOV
3831
                                continue
×
3832
                        }
3833
                }
3834

UNCOV
3835
                peers = append(peers, sPeer)
×
3836
        }
UNCOV
3837
        s.mu.RUnlock()
×
UNCOV
3838

×
UNCOV
3839
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3840
        // all messages to each of peers.
×
UNCOV
3841
        var wg sync.WaitGroup
×
UNCOV
3842
        for _, sPeer := range peers {
×
UNCOV
3843
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3844
                        sPeer.PubKey())
×
UNCOV
3845

×
UNCOV
3846
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3847
                wg.Add(1)
×
UNCOV
3848
                s.wg.Add(1)
×
UNCOV
3849
                go func(p lnpeer.Peer) {
×
UNCOV
3850
                        defer s.wg.Done()
×
UNCOV
3851
                        defer wg.Done()
×
UNCOV
3852

×
UNCOV
3853
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3854
                }(sPeer)
×
3855
        }
3856

3857
        // Wait for all messages to have been dispatched before returning to
3858
        // caller.
UNCOV
3859
        wg.Wait()
×
UNCOV
3860

×
UNCOV
3861
        return nil
×
3862
}
3863

3864
// NotifyWhenOnline can be called by other subsystems to get notified when a
3865
// particular peer comes online. The peer itself is sent across the peerChan.
3866
//
3867
// NOTE: This function is safe for concurrent access.
3868
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3869
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3870

×
UNCOV
3871
        s.mu.Lock()
×
UNCOV
3872

×
UNCOV
3873
        // Compute the target peer's identifier.
×
UNCOV
3874
        pubStr := string(peerKey[:])
×
UNCOV
3875

×
UNCOV
3876
        // Check if peer is connected.
×
UNCOV
3877
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3878
        if ok {
×
UNCOV
3879
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3880
                // waiting for the peer to become active.
×
UNCOV
3881
                s.mu.Unlock()
×
UNCOV
3882

×
UNCOV
3883
                // Wait until the peer signals that it is actually active
×
UNCOV
3884
                // rather than only in the server's maps.
×
UNCOV
3885
                select {
×
UNCOV
3886
                case <-peer.ActiveSignal():
×
UNCOV
3887
                case <-peer.QuitSignal():
×
UNCOV
3888
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3889
                        // and return.
×
UNCOV
3890
                        s.mu.Lock()
×
UNCOV
3891
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3892
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3893
                        )
×
UNCOV
3894
                        s.mu.Unlock()
×
UNCOV
3895
                        return
×
3896
                }
3897

3898
                // Connected, can return early.
UNCOV
3899
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3900

×
UNCOV
3901
                select {
×
UNCOV
3902
                case peerChan <- peer:
×
UNCOV
3903
                case <-s.quit:
×
3904
                }
3905

UNCOV
3906
                return
×
3907
        }
3908

3909
        // Not connected, store this listener such that it can be notified when
3910
        // the peer comes online.
UNCOV
3911
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3912
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3913
        )
×
UNCOV
3914
        s.mu.Unlock()
×
3915
}
3916

3917
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3918
// the given public key has been disconnected. The notification is signaled by
3919
// closing the channel returned.
UNCOV
3920
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3921
        s.mu.Lock()
×
UNCOV
3922
        defer s.mu.Unlock()
×
UNCOV
3923

×
UNCOV
3924
        c := make(chan struct{})
×
UNCOV
3925

×
UNCOV
3926
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3927
        // notification.
×
UNCOV
3928
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3929
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3930
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3931
                close(c)
×
3932
                return c
×
3933
        }
×
3934

3935
        // Otherwise, the peer is online, so we'll keep track of the channel to
3936
        // trigger the notification once the server detects the peer
3937
        // disconnects.
UNCOV
3938
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
3939
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
3940
        )
×
UNCOV
3941

×
UNCOV
3942
        return c
×
3943
}
3944

3945
// FindPeer will return the peer that corresponds to the passed in public key.
3946
// This function is used by the funding manager, allowing it to update the
3947
// daemon's local representation of the remote peer.
3948
//
3949
// NOTE: This function is safe for concurrent access.
UNCOV
3950
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
3951
        s.mu.RLock()
×
UNCOV
3952
        defer s.mu.RUnlock()
×
UNCOV
3953

×
UNCOV
3954
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3955

×
UNCOV
3956
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3957
}
×
3958

3959
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3960
// which should be a string representation of the peer's serialized, compressed
3961
// public key.
3962
//
3963
// NOTE: This function is safe for concurrent access.
UNCOV
3964
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3965
        s.mu.RLock()
×
UNCOV
3966
        defer s.mu.RUnlock()
×
UNCOV
3967

×
UNCOV
3968
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3969
}
×
3970

3971
// findPeerByPubStr is an internal method that retrieves the specified peer from
3972
// the server's internal state using.
UNCOV
3973
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3974
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3975
        if !ok {
×
UNCOV
3976
                return nil, ErrPeerNotConnected
×
UNCOV
3977
        }
×
3978

UNCOV
3979
        return peer, nil
×
3980
}
3981

3982
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3983
// exponential backoff. If no previous backoff was known, the default is
3984
// returned.
3985
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
3986
        startTime time.Time) time.Duration {
×
UNCOV
3987

×
UNCOV
3988
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
3989
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
3990
        if !ok {
×
UNCOV
3991
                // If an existing backoff was unknown, use the default.
×
UNCOV
3992
                return s.cfg.MinBackoff
×
UNCOV
3993
        }
×
3994

3995
        // If the peer failed to start properly, we'll just use the previous
3996
        // backoff to compute the subsequent randomized exponential backoff
3997
        // duration. This will roughly double on average.
UNCOV
3998
        if startTime.IsZero() {
×
3999
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4000
        }
×
4001

4002
        // The peer succeeded in starting. If the connection didn't last long
4003
        // enough to be considered stable, we'll continue to back off retries
4004
        // with this peer.
UNCOV
4005
        connDuration := time.Since(startTime)
×
UNCOV
4006
        if connDuration < defaultStableConnDuration {
×
UNCOV
4007
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
4008
        }
×
4009

4010
        // The peer succeed in starting and this was stable peer, so we'll
4011
        // reduce the timeout duration by the length of the connection after
4012
        // applying randomized exponential backoff. We'll only apply this in the
4013
        // case that:
4014
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4015
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4016
        if relaxedBackoff > s.cfg.MinBackoff {
×
4017
                return relaxedBackoff
×
4018
        }
×
4019

4020
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4021
        // the stable connection lasted much longer than our previous backoff.
4022
        // To reward such good behavior, we'll reconnect after the default
4023
        // timeout.
4024
        return s.cfg.MinBackoff
×
4025
}
4026

4027
// shouldDropLocalConnection determines if our local connection to a remote peer
4028
// should be dropped in the case of concurrent connection establishment. In
4029
// order to deterministically decide which connection should be dropped, we'll
4030
// utilize the ordering of the local and remote public key. If we didn't use
4031
// such a tie breaker, then we risk _both_ connections erroneously being
4032
// dropped.
4033
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4034
        localPubBytes := local.SerializeCompressed()
×
4035
        remotePubPbytes := remote.SerializeCompressed()
×
4036

×
4037
        // The connection that comes from the node with a "smaller" pubkey
×
4038
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4039
        // should drop our established connection.
×
4040
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4041
}
×
4042

4043
// InboundPeerConnected initializes a new peer in response to a new inbound
4044
// connection.
4045
//
4046
// NOTE: This function is safe for concurrent access.
UNCOV
4047
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
4048
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
4049
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
4050
        if s.Stopped() {
×
4051
                return
×
4052
        }
×
4053

UNCOV
4054
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4055
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4056
        pubStr := string(pubSer)
×
UNCOV
4057

×
UNCOV
4058
        var pubBytes [33]byte
×
UNCOV
4059
        copy(pubBytes[:], pubSer)
×
UNCOV
4060

×
UNCOV
4061
        s.mu.Lock()
×
UNCOV
4062
        defer s.mu.Unlock()
×
UNCOV
4063

×
UNCOV
4064
        // If we already have an outbound connection to this peer, then ignore
×
UNCOV
4065
        // this new connection.
×
UNCOV
4066
        if p, ok := s.outboundPeers[pubStr]; ok {
×
UNCOV
4067
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
UNCOV
4068
                        "ignoring inbound connection from local=%v, remote=%v",
×
UNCOV
4069
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4070

×
UNCOV
4071
                conn.Close()
×
UNCOV
4072
                return
×
UNCOV
4073
        }
×
4074

4075
        // If we already have a valid connection that is scheduled to take
4076
        // precedence once the prior peer has finished disconnecting, we'll
4077
        // ignore this connection.
UNCOV
4078
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4079
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4080
                        "scheduled", conn.RemoteAddr(), p)
×
4081
                conn.Close()
×
4082
                return
×
4083
        }
×
4084

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

×
UNCOV
4087
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
4088
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
4089
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
4090
        // default case as we expect these to be the only error values returned
×
UNCOV
4091
        // from findPeerByPubStr.
×
UNCOV
4092
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4093
        switch err {
×
UNCOV
4094
        case ErrPeerNotConnected:
×
UNCOV
4095
                // We were unable to locate an existing connection with the
×
UNCOV
4096
                // target peer, proceed to connect.
×
UNCOV
4097
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4098
                s.peerConnected(conn, nil, true)
×
4099

UNCOV
4100
        case nil:
×
UNCOV
4101
                ctx := btclog.WithCtx(
×
UNCOV
4102
                        context.TODO(),
×
UNCOV
4103
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
4104
                )
×
UNCOV
4105

×
UNCOV
4106
                // We already have a connection with the incoming peer. If the
×
UNCOV
4107
                // connection we've already established should be kept and is
×
UNCOV
4108
                // not of the same type of the new connection (inbound), then
×
UNCOV
4109
                // we'll close out the new connection s.t there's only a single
×
UNCOV
4110
                // connection between us.
×
UNCOV
4111
                localPub := s.identityECDH.PubKey()
×
UNCOV
4112
                if !connectedPeer.Inbound() &&
×
UNCOV
4113
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4114

×
4115
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4116
                                "peer, but already have outbound "+
×
4117
                                "connection, dropping conn",
×
4118
                                fmt.Errorf("already have outbound conn"))
×
4119
                        conn.Close()
×
4120
                        return
×
4121
                }
×
4122

4123
                // Otherwise, if we should drop the connection, then we'll
4124
                // disconnect our already connected peer.
UNCOV
4125
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
4126

×
UNCOV
4127
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4128

×
UNCOV
4129
                // Remove the current peer from the server's internal state and
×
UNCOV
4130
                // signal that the peer termination watcher does not need to
×
UNCOV
4131
                // execute for this peer.
×
UNCOV
4132
                s.removePeerUnsafe(ctx, connectedPeer)
×
UNCOV
4133
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
4134
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
4135
                        s.peerConnected(conn, nil, true)
×
UNCOV
4136
                }
×
4137
        }
4138
}
4139

4140
// OutboundPeerConnected initializes a new peer in response to a new outbound
4141
// connection.
4142
// NOTE: This function is safe for concurrent access.
UNCOV
4143
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
UNCOV
4144
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
4145
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
4146
        if s.Stopped() {
×
4147
                return
×
4148
        }
×
4149

UNCOV
4150
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4151
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4152
        pubStr := string(pubSer)
×
UNCOV
4153

×
UNCOV
4154
        var pubBytes [33]byte
×
UNCOV
4155
        copy(pubBytes[:], pubSer)
×
UNCOV
4156

×
UNCOV
4157
        s.mu.Lock()
×
UNCOV
4158
        defer s.mu.Unlock()
×
UNCOV
4159

×
UNCOV
4160
        // If we already have an inbound connection to this peer, then ignore
×
UNCOV
4161
        // this new connection.
×
UNCOV
4162
        if p, ok := s.inboundPeers[pubStr]; ok {
×
UNCOV
4163
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
UNCOV
4164
                        "ignoring outbound connection from local=%v, remote=%v",
×
UNCOV
4165
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4166

×
UNCOV
4167
                if connReq != nil {
×
UNCOV
4168
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4169
                }
×
UNCOV
4170
                conn.Close()
×
UNCOV
4171
                return
×
4172
        }
UNCOV
4173
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4174
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4175
                s.connMgr.Remove(connReq.ID())
×
4176
                conn.Close()
×
4177
                return
×
4178
        }
×
4179

4180
        // If we already have a valid connection that is scheduled to take
4181
        // precedence once the prior peer has finished disconnecting, we'll
4182
        // ignore this connection.
UNCOV
4183
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4184
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4185

×
4186
                if connReq != nil {
×
4187
                        s.connMgr.Remove(connReq.ID())
×
4188
                }
×
4189

4190
                conn.Close()
×
4191
                return
×
4192
        }
4193

UNCOV
4194
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
UNCOV
4195
                conn.RemoteAddr())
×
UNCOV
4196

×
UNCOV
4197
        if connReq != nil {
×
UNCOV
4198
                // A successful connection was returned by the connmgr.
×
UNCOV
4199
                // Immediately cancel all pending requests, excluding the
×
UNCOV
4200
                // outbound connection we just established.
×
UNCOV
4201
                ignore := connReq.ID()
×
UNCOV
4202
                s.cancelConnReqs(pubStr, &ignore)
×
UNCOV
4203
        } else {
×
UNCOV
4204
                // This was a successful connection made by some other
×
UNCOV
4205
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
4206
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4207
        }
×
4208

4209
        // If we already have a connection with this peer, decide whether or not
4210
        // we need to drop the stale connection. We forgo adding a default case
4211
        // as we expect these to be the only error values returned from
4212
        // findPeerByPubStr.
UNCOV
4213
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4214
        switch err {
×
UNCOV
4215
        case ErrPeerNotConnected:
×
UNCOV
4216
                // We were unable to locate an existing connection with the
×
UNCOV
4217
                // target peer, proceed to connect.
×
UNCOV
4218
                s.peerConnected(conn, connReq, false)
×
4219

UNCOV
4220
        case nil:
×
UNCOV
4221
                ctx := btclog.WithCtx(
×
UNCOV
4222
                        context.TODO(),
×
UNCOV
4223
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
4224
                )
×
UNCOV
4225

×
UNCOV
4226
                // We already have a connection with the incoming peer. If the
×
UNCOV
4227
                // connection we've already established should be kept and is
×
UNCOV
4228
                // not of the same type of the new connection (outbound), then
×
UNCOV
4229
                // we'll close out the new connection s.t there's only a single
×
UNCOV
4230
                // connection between us.
×
UNCOV
4231
                localPub := s.identityECDH.PubKey()
×
UNCOV
4232
                if connectedPeer.Inbound() &&
×
UNCOV
4233
                        shouldDropLocalConnection(localPub, nodePub) {
×
4234

×
4235
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4236
                                "to peer, but already have inbound "+
×
4237
                                "connection, dropping conn",
×
4238
                                fmt.Errorf("already have inbound conn"))
×
4239
                        if connReq != nil {
×
4240
                                s.connMgr.Remove(connReq.ID())
×
4241
                        }
×
4242
                        conn.Close()
×
4243
                        return
×
4244
                }
4245

4246
                // Otherwise, _their_ connection should be dropped. So we'll
4247
                // disconnect the peer and send the now obsolete peer to the
4248
                // server for garbage collection.
UNCOV
4249
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
4250

×
UNCOV
4251
                // Remove the current peer from the server's internal state and
×
UNCOV
4252
                // signal that the peer termination watcher does not need to
×
UNCOV
4253
                // execute for this peer.
×
UNCOV
4254
                s.removePeerUnsafe(ctx, connectedPeer)
×
UNCOV
4255
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
4256
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
4257
                        s.peerConnected(conn, connReq, false)
×
UNCOV
4258
                }
×
4259
        }
4260
}
4261

4262
// UnassignedConnID is the default connection ID that a request can have before
4263
// it actually is submitted to the connmgr.
4264
// TODO(conner): move into connmgr package, or better, add connmgr method for
4265
// generating atomic IDs
4266
const UnassignedConnID uint64 = 0
4267

4268
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4269
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4270
// Afterwards, each connection request removed from the connmgr. The caller can
4271
// optionally specify a connection ID to ignore, which prevents us from
4272
// canceling a successful request. All persistent connreqs for the provided
4273
// pubkey are discarded after the operationjw.
UNCOV
4274
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
4275
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
4276
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
4277
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
4278
                close(cancelChan)
×
UNCOV
4279
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
4280
        }
×
4281

4282
        // Next, check to see if we have any outstanding persistent connection
4283
        // requests to this peer. If so, then we'll remove all of these
4284
        // connection requests, and also delete the entry from the map.
UNCOV
4285
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4286
        if !ok {
×
UNCOV
4287
                return
×
UNCOV
4288
        }
×
4289

UNCOV
4290
        for _, connReq := range connReqs {
×
UNCOV
4291
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4292

×
UNCOV
4293
                // Atomically capture the current request identifier.
×
UNCOV
4294
                connID := connReq.ID()
×
UNCOV
4295

×
UNCOV
4296
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4297
                // yet been schedule.
×
UNCOV
4298
                if connID == UnassignedConnID {
×
4299
                        continue
×
4300
                }
4301

4302
                // Skip a particular connection ID if instructed.
UNCOV
4303
                if skip != nil && connID == *skip {
×
UNCOV
4304
                        continue
×
4305
                }
4306

UNCOV
4307
                s.connMgr.Remove(connID)
×
4308
        }
4309

UNCOV
4310
        delete(s.persistentConnReqs, pubStr)
×
4311
}
4312

4313
// handleCustomMessage dispatches an incoming custom peers message to
4314
// subscribers.
UNCOV
4315
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4316
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4317
                peer, msg.Type)
×
UNCOV
4318

×
UNCOV
4319
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4320
                Peer: peer,
×
UNCOV
4321
                Msg:  msg,
×
UNCOV
4322
        })
×
UNCOV
4323
}
×
4324

4325
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4326
// messages.
UNCOV
4327
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4328
        return s.customMessageServer.Subscribe()
×
UNCOV
4329
}
×
4330

4331
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4332
// the channelNotifier's NotifyOpenChannelEvent.
4333
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
UNCOV
4334
        remotePub *btcec.PublicKey) {
×
UNCOV
4335

×
UNCOV
4336
        // Call newOpenChan to update the access manager's maps for this peer.
×
UNCOV
4337
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
×
UNCOV
4338
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4339
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
×
UNCOV
4340
        }
×
4341

4342
        // Notify subscribers about this open channel event.
UNCOV
4343
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4344
}
4345

4346
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4347
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4348
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
UNCOV
4349
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
×
UNCOV
4350

×
UNCOV
4351
        // Call newPendingOpenChan to update the access manager's maps for this
×
UNCOV
4352
        // peer.
×
UNCOV
4353
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
×
4354
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4355
                        "channel[%v] pending open",
×
4356
                        remotePub.SerializeCompressed(), op)
×
4357
        }
×
4358

4359
        // Notify subscribers about this event.
UNCOV
4360
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4361
}
4362

4363
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4364
// calls the channelNotifier's NotifyFundingTimeout.
4365
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
UNCOV
4366
        remotePub *btcec.PublicKey) {
×
UNCOV
4367

×
UNCOV
4368
        // Call newPendingCloseChan to potentially demote the peer.
×
UNCOV
4369
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
UNCOV
4370
        if err != nil {
×
4371
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4372
                        "channel[%v] pending close",
×
4373
                        remotePub.SerializeCompressed(), op)
×
4374
        }
×
4375

UNCOV
4376
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
×
4377
                // If we encounter an error while attempting to disconnect the
×
4378
                // peer, log the error.
×
4379
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4380
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4381
                }
×
4382
        }
4383

4384
        // Notify subscribers about this event.
UNCOV
4385
        s.channelNotifier.NotifyFundingTimeout(op)
×
4386
}
4387

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

×
UNCOV
4395
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4396
        addr := conn.RemoteAddr()
×
UNCOV
4397
        pubKey := brontideConn.RemotePub()
×
UNCOV
4398

×
UNCOV
4399
        // Only restrict access for inbound connections, which means if the
×
UNCOV
4400
        // remote node's public key is banned or the restricted slots are used
×
UNCOV
4401
        // up, we will drop the connection.
×
UNCOV
4402
        //
×
UNCOV
4403
        // TODO(yy): Consider perform this check in
×
UNCOV
4404
        // `peerAccessMan.addPeerAccess`.
×
UNCOV
4405
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
×
UNCOV
4406
        if inbound && err != nil {
×
4407
                pubSer := pubKey.SerializeCompressed()
×
4408

×
4409
                // Clean up the persistent peer maps if we're dropping this
×
4410
                // connection.
×
4411
                s.bannedPersistentPeerConnection(string(pubSer))
×
4412

×
4413
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4414
                        "of restricted-access connection slots: %v.", pubSer,
×
4415
                        err)
×
4416

×
4417
                conn.Close()
×
4418

×
4419
                return
×
4420
        }
×
4421

UNCOV
4422
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4423
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4424

×
UNCOV
4425
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4426
                IdentityKey: pubKey,
×
UNCOV
4427
                Address:     addr,
×
UNCOV
4428
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4429
        }
×
UNCOV
4430

×
UNCOV
4431
        // With the brontide connection established, we'll now craft the feature
×
UNCOV
4432
        // vectors to advertise to the remote node.
×
UNCOV
4433
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
UNCOV
4434
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
UNCOV
4435

×
UNCOV
4436
        // Lookup past error caches for the peer in the server. If no buffer is
×
UNCOV
4437
        // found, create a fresh buffer.
×
UNCOV
4438
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4439
        errBuffer, ok := s.peerErrors[pkStr]
×
UNCOV
4440
        if !ok {
×
UNCOV
4441
                var err error
×
UNCOV
4442
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
UNCOV
4443
                if err != nil {
×
4444
                        srvrLog.Errorf("unable to create peer %v", err)
×
4445
                        return
×
4446
                }
×
4447
        }
4448

4449
        // If we directly set the peer.Config TowerClient member to the
4450
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4451
        // the peer.Config's TowerClient member will not evaluate to nil even
4452
        // though the underlying value is nil. To avoid this gotcha which can
4453
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4454
        // TowerClient if needed.
UNCOV
4455
        var towerClient wtclient.ClientManager
×
UNCOV
4456
        if s.towerClientMgr != nil {
×
UNCOV
4457
                towerClient = s.towerClientMgr
×
UNCOV
4458
        }
×
4459

UNCOV
4460
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4461
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4462

×
UNCOV
4463
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4464
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4465
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4466
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4467
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4468
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4469
        pCfg := peer.Config{
×
UNCOV
4470
                Conn:                    brontideConn,
×
UNCOV
4471
                ConnReq:                 connReq,
×
UNCOV
4472
                Addr:                    peerAddr,
×
UNCOV
4473
                Inbound:                 inbound,
×
UNCOV
4474
                Features:                initFeatures,
×
UNCOV
4475
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4476
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4477
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4478
                ErrorBuffer:             errBuffer,
×
UNCOV
4479
                WritePool:               s.writePool,
×
UNCOV
4480
                ReadPool:                s.readPool,
×
UNCOV
4481
                Switch:                  s.htlcSwitch,
×
UNCOV
4482
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4483
                ChannelDB:               s.chanStateDB,
×
UNCOV
4484
                ChannelGraph:            s.graphDB,
×
UNCOV
4485
                ChainArb:                s.chainArb,
×
UNCOV
4486
                AuthGossiper:            s.authGossiper,
×
UNCOV
4487
                ChanStatusMgr:           s.chanStatusMgr,
×
UNCOV
4488
                ChainIO:                 s.cc.ChainIO,
×
UNCOV
4489
                FeeEstimator:            s.cc.FeeEstimator,
×
UNCOV
4490
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
UNCOV
4491
                SigPool:                 s.sigPool,
×
UNCOV
4492
                Wallet:                  s.cc.Wallet,
×
UNCOV
4493
                ChainNotifier:           s.cc.ChainNotifier,
×
UNCOV
4494
                BestBlockView:           s.cc.BestBlockTracker,
×
UNCOV
4495
                RoutingPolicy:           s.cc.RoutingPolicy,
×
UNCOV
4496
                Sphinx:                  s.sphinx,
×
UNCOV
4497
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4498
                Invoices:                s.invoices,
×
UNCOV
4499
                ChannelNotifier:         s.channelNotifier,
×
UNCOV
4500
                HtlcNotifier:            s.htlcNotifier,
×
UNCOV
4501
                TowerClient:             towerClient,
×
UNCOV
4502
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4503
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4504
                        lnwire.NodeAnnouncement, error) {
×
UNCOV
4505

×
UNCOV
4506
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4507
                },
×
4508

4509
                PongBuf: s.pongBuf,
4510

4511
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4512

4513
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4514

4515
                FundingManager: s.fundingMgr,
4516

4517
                Hodl:                    s.cfg.Hodl,
4518
                UnsafeReplay:            s.cfg.UnsafeReplay,
4519
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4520
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4521
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4522
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4523
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4524
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4525
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4526
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4527
                HandleCustomMessage:    s.handleCustomMessage,
4528
                GetAliases:             s.aliasMgr.GetAliases,
4529
                RequestAlias:           s.aliasMgr.RequestAlias,
4530
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4531
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4532
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4533
                MaxFeeExposure:         thresholdMSats,
4534
                Quit:                   s.quit,
4535
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4536
                AuxSigner:              s.implCfg.AuxSigner,
4537
                MsgRouter:              s.implCfg.MsgRouter,
4538
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4539
                AuxResolver:            s.implCfg.AuxContractResolver,
4540
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
UNCOV
4541
                ShouldFwdExpEndorsement: func() bool {
×
UNCOV
4542
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
UNCOV
4543
                                return false
×
UNCOV
4544
                        }
×
4545

UNCOV
4546
                        return clock.NewDefaultClock().Now().Before(
×
UNCOV
4547
                                EndorsementExperimentEnd,
×
UNCOV
4548
                        )
×
4549
                },
4550
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4551
        }
4552

UNCOV
4553
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4554
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4555

×
UNCOV
4556
        p := peer.NewBrontide(pCfg)
×
UNCOV
4557

×
UNCOV
4558
        // Update the access manager with the access permission for this peer.
×
UNCOV
4559
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
UNCOV
4560

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

×
UNCOV
4564
        s.addPeer(p)
×
UNCOV
4565

×
UNCOV
4566
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4567
        // delete the previous error buffer from the server's map of error
×
UNCOV
4568
        // buffers.
×
UNCOV
4569
        delete(s.peerErrors, pkStr)
×
UNCOV
4570

×
UNCOV
4571
        // Dispatch a goroutine to asynchronously start the peer. This process
×
UNCOV
4572
        // includes sending and receiving Init messages, which would be a DOS
×
UNCOV
4573
        // vector if we held the server's mutex throughout the procedure.
×
UNCOV
4574
        s.wg.Add(1)
×
UNCOV
4575
        go s.peerInitializer(p)
×
4576
}
4577

4578
// addPeer adds the passed peer to the server's global state of all active
4579
// peers.
UNCOV
4580
func (s *server) addPeer(p *peer.Brontide) {
×
UNCOV
4581
        if p == nil {
×
4582
                return
×
4583
        }
×
4584

UNCOV
4585
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4586

×
UNCOV
4587
        // Ignore new peers if we're shutting down.
×
UNCOV
4588
        if s.Stopped() {
×
4589
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4590
                        pubBytes)
×
4591
                p.Disconnect(ErrServerShuttingDown)
×
4592

×
4593
                return
×
4594
        }
×
4595

4596
        // Track the new peer in our indexes so we can quickly look it up either
4597
        // according to its public key, or its peer ID.
4598
        // TODO(roasbeef): pipe all requests through to the
4599
        // queryHandler/peerManager
4600

4601
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4602
        // be human-readable.
UNCOV
4603
        pubStr := string(pubBytes)
×
UNCOV
4604

×
UNCOV
4605
        s.peersByPub[pubStr] = p
×
UNCOV
4606

×
UNCOV
4607
        if p.Inbound() {
×
UNCOV
4608
                s.inboundPeers[pubStr] = p
×
UNCOV
4609
        } else {
×
UNCOV
4610
                s.outboundPeers[pubStr] = p
×
UNCOV
4611
        }
×
4612

4613
        // Inform the peer notifier of a peer online event so that it can be reported
4614
        // to clients listening for peer events.
UNCOV
4615
        var pubKey [33]byte
×
UNCOV
4616
        copy(pubKey[:], pubBytes)
×
UNCOV
4617

×
UNCOV
4618
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
4619
}
4620

4621
// peerInitializer asynchronously starts a newly connected peer after it has
4622
// been added to the server's peer map. This method sets up a
4623
// peerTerminationWatcher for the given peer, and ensures that it executes even
4624
// if the peer failed to start. In the event of a successful connection, this
4625
// method reads the negotiated, local feature-bits and spawns the appropriate
4626
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4627
// be signaled of the new peer once the method returns.
4628
//
4629
// NOTE: This MUST be launched as a goroutine.
UNCOV
4630
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4631
        defer s.wg.Done()
×
UNCOV
4632

×
UNCOV
4633
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4634

×
UNCOV
4635
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4636
        if s.Stopped() {
×
4637
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4638
                        pubBytes)
×
4639
                return
×
4640
        }
×
4641

4642
        // Create a channel that will be used to signal a successful start of
4643
        // the link. This prevents the peer termination watcher from beginning
4644
        // its duty too early.
UNCOV
4645
        ready := make(chan struct{})
×
UNCOV
4646

×
UNCOV
4647
        // Before starting the peer, launch a goroutine to watch for the
×
UNCOV
4648
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4649
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4650
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4651
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4652
        // that the server has already handled the removal of this peer.
×
UNCOV
4653
        s.wg.Add(1)
×
UNCOV
4654
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4655

×
UNCOV
4656
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4657
        // will unblock the peerTerminationWatcher.
×
UNCOV
4658
        if err := p.Start(); err != nil {
×
UNCOV
4659
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4660

×
UNCOV
4661
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4662
                return
×
UNCOV
4663
        }
×
4664

4665
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4666
        // was successful, and to begin watching the peer's wait group.
UNCOV
4667
        close(ready)
×
UNCOV
4668

×
UNCOV
4669
        s.mu.Lock()
×
UNCOV
4670
        defer s.mu.Unlock()
×
UNCOV
4671

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

×
UNCOV
4675
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4676
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4677
        pubStr := string(pubBytes)
×
UNCOV
4678
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4679
                select {
×
UNCOV
4680
                case peerChan <- p:
×
4681
                case <-s.quit:
×
4682
                        return
×
4683
                }
4684
        }
UNCOV
4685
        delete(s.peerConnectedListeners, pubStr)
×
4686
}
4687

4688
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4689
// and then cleans up all resources allocated to the peer, notifies relevant
4690
// sub-systems of its demise, and finally handles re-connecting to the peer if
4691
// it's persistent. If the server intentionally disconnects a peer, it should
4692
// have a corresponding entry in the ignorePeerTermination map which will cause
4693
// the cleanup routine to exit early. The passed `ready` chan is used to
4694
// synchronize when WaitForDisconnect should begin watching on the peer's
4695
// waitgroup. The ready chan should only be signaled if the peer starts
4696
// successfully, otherwise the peer should be disconnected instead.
4697
//
4698
// NOTE: This MUST be launched as a goroutine.
UNCOV
4699
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4700
        defer s.wg.Done()
×
UNCOV
4701

×
UNCOV
4702
        ctx := btclog.WithCtx(
×
UNCOV
4703
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
UNCOV
4704
        )
×
UNCOV
4705

×
UNCOV
4706
        p.WaitForDisconnect(ready)
×
UNCOV
4707

×
UNCOV
4708
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
UNCOV
4709

×
UNCOV
4710
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4711
        // the other sub-systems will already be shutting down.
×
UNCOV
4712
        if s.Stopped() {
×
UNCOV
4713
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
×
UNCOV
4714
                return
×
UNCOV
4715
        }
×
4716

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

×
UNCOV
4723
        pubKey := p.IdentityKey()
×
UNCOV
4724

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

×
UNCOV
4729
        // Tell the switch to remove all links associated with this peer.
×
UNCOV
4730
        // Passing nil as the target link indicates that all links associated
×
UNCOV
4731
        // with this interface should be closed.
×
UNCOV
4732
        //
×
UNCOV
4733
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
UNCOV
4734
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
UNCOV
4735
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4736
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4737
        }
×
4738

UNCOV
4739
        for _, link := range links {
×
UNCOV
4740
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4741
        }
×
4742

UNCOV
4743
        s.mu.Lock()
×
UNCOV
4744
        defer s.mu.Unlock()
×
UNCOV
4745

×
UNCOV
4746
        // If there were any notification requests for when this peer
×
UNCOV
4747
        // disconnected, we can trigger them now.
×
UNCOV
4748
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
UNCOV
4749
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4750
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4751
                close(offlineChan)
×
UNCOV
4752
        }
×
UNCOV
4753
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4754

×
UNCOV
4755
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4756
        // peer termination watcher and skip cleanup.
×
UNCOV
4757
        if _, ok := s.ignorePeerTermination[p]; ok {
×
UNCOV
4758
                delete(s.ignorePeerTermination, p)
×
UNCOV
4759

×
UNCOV
4760
                pubKey := p.PubKey()
×
UNCOV
4761
                pubStr := string(pubKey[:])
×
UNCOV
4762

×
UNCOV
4763
                // If a connection callback is present, we'll go ahead and
×
UNCOV
4764
                // execute it now that previous peer has fully disconnected. If
×
UNCOV
4765
                // the callback is not present, this likely implies the peer was
×
UNCOV
4766
                // purposefully disconnected via RPC, and that no reconnect
×
UNCOV
4767
                // should be attempted.
×
UNCOV
4768
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
UNCOV
4769
                if ok {
×
UNCOV
4770
                        delete(s.scheduledPeerConnection, pubStr)
×
UNCOV
4771
                        connCallback()
×
UNCOV
4772
                }
×
UNCOV
4773
                return
×
4774
        }
4775

4776
        // First, cleanup any remaining state the server has regarding the peer
4777
        // in question.
UNCOV
4778
        s.removePeerUnsafe(ctx, p)
×
UNCOV
4779

×
UNCOV
4780
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4781
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4782
                return
×
UNCOV
4783
        }
×
4784

4785
        // Get the last address that we used to connect to the peer.
UNCOV
4786
        addrs := []net.Addr{
×
UNCOV
4787
                p.NetAddress().Address,
×
UNCOV
4788
        }
×
UNCOV
4789

×
UNCOV
4790
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4791
        // reconnection purposes.
×
UNCOV
4792
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
×
UNCOV
4793
        switch {
×
4794
        // We found advertised addresses, so use them.
UNCOV
4795
        case err == nil:
×
UNCOV
4796
                addrs = advertisedAddrs
×
4797

4798
        // The peer doesn't have an advertised address.
UNCOV
4799
        case err == errNoAdvertisedAddr:
×
UNCOV
4800
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4801
                // peer address.
×
UNCOV
4802
                if !p.Inbound() {
×
UNCOV
4803
                        break
×
4804
                }
4805

4806
                // Fall back to the existing peer address if
4807
                // we're not accepting connections over Tor.
UNCOV
4808
                if s.torController == nil {
×
UNCOV
4809
                        break
×
4810
                }
4811

4812
                // If we are, the peer's address won't be known
4813
                // to us (we'll see a private address, which is
4814
                // the address used by our onion service to dial
4815
                // to lnd), so we don't have enough information
4816
                // to attempt a reconnect.
4817
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4818
                        "to inbound peer without advertised address")
×
4819
                return
×
4820

4821
        // We came across an error retrieving an advertised
4822
        // address, log it, and fall back to the existing peer
4823
        // address.
UNCOV
4824
        default:
×
UNCOV
4825
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
UNCOV
4826
                        "address for peer", err)
×
4827
        }
4828

4829
        // Make an easy lookup map so that we can check if an address
4830
        // is already in the address list that we have stored for this peer.
UNCOV
4831
        existingAddrs := make(map[string]bool)
×
UNCOV
4832
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4833
                existingAddrs[addr.String()] = true
×
UNCOV
4834
        }
×
4835

4836
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4837
        for _, addr := range addrs {
×
UNCOV
4838
                if existingAddrs[addr.String()] {
×
4839
                        continue
×
4840
                }
4841

UNCOV
4842
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4843
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4844
                        &lnwire.NetAddress{
×
UNCOV
4845
                                IdentityKey: p.IdentityKey(),
×
UNCOV
4846
                                Address:     addr,
×
UNCOV
4847
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4848
                        },
×
UNCOV
4849
                )
×
4850
        }
4851

4852
        // Record the computed backoff in the backoff map.
UNCOV
4853
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4854
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4855

×
UNCOV
4856
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4857
        // exist.
×
UNCOV
4858
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4859
        if !ok {
×
UNCOV
4860
                cancelChan = make(chan struct{})
×
UNCOV
4861
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4862
        }
×
4863

4864
        // We choose not to wait group this go routine since the Connect
4865
        // call can stall for arbitrarily long if we shutdown while an
4866
        // outbound connection attempt is being made.
UNCOV
4867
        go func() {
×
UNCOV
4868
                srvrLog.DebugS(ctx, "Scheduling connection "+
×
UNCOV
4869
                        "re-establishment to persistent peer",
×
UNCOV
4870
                        "reconnecting_in", backoff)
×
UNCOV
4871

×
UNCOV
4872
                select {
×
UNCOV
4873
                case <-time.After(backoff):
×
UNCOV
4874
                case <-cancelChan:
×
UNCOV
4875
                        return
×
UNCOV
4876
                case <-s.quit:
×
UNCOV
4877
                        return
×
4878
                }
4879

UNCOV
4880
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
UNCOV
4881
                        "connection")
×
UNCOV
4882

×
UNCOV
4883
                s.connectToPersistentPeer(pubStr)
×
4884
        }()
4885
}
4886

4887
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4888
// to connect to the peer. It creates connection requests if there are
4889
// currently none for a given address and it removes old connection requests
4890
// if the associated address is no longer in the latest address list for the
4891
// peer.
UNCOV
4892
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
UNCOV
4893
        s.mu.Lock()
×
UNCOV
4894
        defer s.mu.Unlock()
×
UNCOV
4895

×
UNCOV
4896
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4897
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4898
        // connection requests for the associated address and then any leftover
×
UNCOV
4899
        // entries will indicate which addresses we should create new
×
UNCOV
4900
        // connection requests for.
×
UNCOV
4901
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4902
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4903
                addrMap[addr.String()] = addr
×
UNCOV
4904
        }
×
4905

4906
        // Go through each of the existing connection requests and
4907
        // check if they correspond to the latest set of addresses. If
4908
        // there is a connection requests that does not use one of the latest
4909
        // advertised addresses then remove that connection request.
UNCOV
4910
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4911
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4912
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4913

×
UNCOV
4914
                switch _, ok := addrMap[lnAddr]; ok {
×
4915
                // If the existing connection request is using one of the
4916
                // latest advertised addresses for the peer then we add it to
4917
                // updatedConnReqs and remove the associated address from
4918
                // addrMap so that we don't recreate this connReq later on.
4919
                case true:
×
4920
                        updatedConnReqs = append(
×
4921
                                updatedConnReqs, connReq,
×
4922
                        )
×
4923
                        delete(addrMap, lnAddr)
×
4924

4925
                // If the existing connection request is using an address that
4926
                // is not one of the latest advertised addresses for the peer
4927
                // then we remove the connecting request from the connection
4928
                // manager.
UNCOV
4929
                case false:
×
UNCOV
4930
                        srvrLog.Info(
×
UNCOV
4931
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4932
                        )
×
UNCOV
4933
                        s.connMgr.Remove(connReq.ID())
×
4934
                }
4935
        }
4936

UNCOV
4937
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4938

×
UNCOV
4939
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4940
        if !ok {
×
UNCOV
4941
                cancelChan = make(chan struct{})
×
UNCOV
4942
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4943
        }
×
4944

4945
        // Any addresses left in addrMap are new ones that we have not made
4946
        // connection requests for. So create new connection requests for those.
4947
        // If there is more than one address in the address map, stagger the
4948
        // creation of the connection requests for those.
UNCOV
4949
        go func() {
×
UNCOV
4950
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
UNCOV
4951
                defer ticker.Stop()
×
UNCOV
4952

×
UNCOV
4953
                for _, addr := range addrMap {
×
UNCOV
4954
                        // Send the persistent connection request to the
×
UNCOV
4955
                        // connection manager, saving the request itself so we
×
UNCOV
4956
                        // can cancel/restart the process as needed.
×
UNCOV
4957
                        connReq := &connmgr.ConnReq{
×
UNCOV
4958
                                Addr:      addr,
×
UNCOV
4959
                                Permanent: true,
×
UNCOV
4960
                        }
×
UNCOV
4961

×
UNCOV
4962
                        s.mu.Lock()
×
UNCOV
4963
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4964
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4965
                        )
×
UNCOV
4966
                        s.mu.Unlock()
×
UNCOV
4967

×
UNCOV
4968
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4969
                                "channel peer %v", addr)
×
UNCOV
4970

×
UNCOV
4971
                        go s.connMgr.Connect(connReq)
×
UNCOV
4972

×
UNCOV
4973
                        select {
×
UNCOV
4974
                        case <-s.quit:
×
UNCOV
4975
                                return
×
UNCOV
4976
                        case <-cancelChan:
×
UNCOV
4977
                                return
×
UNCOV
4978
                        case <-ticker.C:
×
4979
                        }
4980
                }
4981
        }()
4982
}
4983

4984
// removePeerUnsafe removes the passed peer from the server's state of all
4985
// active peers.
4986
//
4987
// NOTE: Server mutex must be held when calling this function.
UNCOV
4988
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
×
UNCOV
4989
        if p == nil {
×
4990
                return
×
4991
        }
×
4992

UNCOV
4993
        srvrLog.DebugS(ctx, "Removing peer")
×
UNCOV
4994

×
UNCOV
4995
        // Exit early if we have already been instructed to shutdown, the peers
×
UNCOV
4996
        // will be disconnected in the server shutdown process.
×
UNCOV
4997
        if s.Stopped() {
×
4998
                return
×
4999
        }
×
5000

5001
        // Capture the peer's public key and string representation.
UNCOV
5002
        pKey := p.PubKey()
×
UNCOV
5003
        pubSer := pKey[:]
×
UNCOV
5004
        pubStr := string(pubSer)
×
UNCOV
5005

×
UNCOV
5006
        delete(s.peersByPub, pubStr)
×
UNCOV
5007

×
UNCOV
5008
        if p.Inbound() {
×
UNCOV
5009
                delete(s.inboundPeers, pubStr)
×
UNCOV
5010
        } else {
×
UNCOV
5011
                delete(s.outboundPeers, pubStr)
×
UNCOV
5012
        }
×
5013

5014
        // When removing the peer we make sure to disconnect it asynchronously
5015
        // to avoid blocking the main server goroutine because it is holding the
5016
        // server's mutex. Disconnecting the peer might block and wait until the
5017
        // peer has fully started up. This can happen if an inbound and outbound
5018
        // race condition occurs.
UNCOV
5019
        s.wg.Add(1)
×
UNCOV
5020
        go func() {
×
UNCOV
5021
                defer s.wg.Done()
×
UNCOV
5022

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

×
UNCOV
5025
                // If this peer had an active persistent connection request,
×
UNCOV
5026
                // remove it.
×
UNCOV
5027
                if p.ConnReq() != nil {
×
UNCOV
5028
                        s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
5029
                }
×
5030

5031
                // Remove the peer's access permission from the access manager.
UNCOV
5032
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
UNCOV
5033
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
UNCOV
5034

×
UNCOV
5035
                // Copy the peer's error buffer across to the server if it has
×
UNCOV
5036
                // any items in it so that we can restore peer errors across
×
UNCOV
5037
                // connections. We need to look up the error after the peer has
×
UNCOV
5038
                // been disconnected because we write the error in the
×
UNCOV
5039
                // `Disconnect` method.
×
UNCOV
5040
                s.mu.Lock()
×
UNCOV
5041
                if p.ErrorBuffer().Total() > 0 {
×
UNCOV
5042
                        s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
5043
                }
×
UNCOV
5044
                s.mu.Unlock()
×
UNCOV
5045

×
UNCOV
5046
                // Inform the peer notifier of a peer offline event so that it
×
UNCOV
5047
                // can be reported to clients listening for peer events.
×
UNCOV
5048
                var pubKey [33]byte
×
UNCOV
5049
                copy(pubKey[:], pubSer)
×
UNCOV
5050

×
UNCOV
5051
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
5052
        }()
5053
}
5054

5055
// ConnectToPeer requests that the server connect to a Lightning Network peer
5056
// at the specified address. This function will *block* until either a
5057
// connection is established, or the initial handshake process fails.
5058
//
5059
// NOTE: This function is safe for concurrent access.
5060
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
5061
        perm bool, timeout time.Duration) error {
×
UNCOV
5062

×
UNCOV
5063
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
5064

×
UNCOV
5065
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
5066
        // better granularity.  In certain conditions, this method requires
×
UNCOV
5067
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
5068
        // lock to be released, and subsequently reacquired.
×
UNCOV
5069
        s.mu.Lock()
×
UNCOV
5070

×
UNCOV
5071
        // Ensure we're not already connected to this peer.
×
UNCOV
5072
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
5073

×
UNCOV
5074
        // When there's no error it means we already have a connection with this
×
UNCOV
5075
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
UNCOV
5076
        // set, we will ignore the existing connection and continue.
×
UNCOV
5077
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
UNCOV
5078
                s.mu.Unlock()
×
UNCOV
5079
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
5080
        }
×
5081

5082
        // Peer was not found, continue to pursue connection with peer.
5083

5084
        // If there's already a pending connection request for this pubkey,
5085
        // then we ignore this request to ensure we don't create a redundant
5086
        // connection.
UNCOV
5087
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
5088
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
5089
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
5090
        }
×
5091

5092
        // If there's not already a pending or active connection to this node,
5093
        // then instruct the connection manager to attempt to establish a
5094
        // persistent connection to the peer.
UNCOV
5095
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
5096
        if perm {
×
UNCOV
5097
                connReq := &connmgr.ConnReq{
×
UNCOV
5098
                        Addr:      addr,
×
UNCOV
5099
                        Permanent: true,
×
UNCOV
5100
                }
×
UNCOV
5101

×
UNCOV
5102
                // Since the user requested a permanent connection, we'll set
×
UNCOV
5103
                // the entry to true which will tell the server to continue
×
UNCOV
5104
                // reconnecting even if the number of channels with this peer is
×
UNCOV
5105
                // zero.
×
UNCOV
5106
                s.persistentPeers[targetPub] = true
×
UNCOV
5107
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
5108
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
5109
                }
×
UNCOV
5110
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
5111
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
5112
                )
×
UNCOV
5113
                s.mu.Unlock()
×
UNCOV
5114

×
UNCOV
5115
                go s.connMgr.Connect(connReq)
×
UNCOV
5116

×
UNCOV
5117
                return nil
×
5118
        }
UNCOV
5119
        s.mu.Unlock()
×
UNCOV
5120

×
UNCOV
5121
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
5122
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
5123
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
5124
        // caller.
×
UNCOV
5125
        errChan := make(chan error, 1)
×
UNCOV
5126
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
5127

×
UNCOV
5128
        select {
×
UNCOV
5129
        case err := <-errChan:
×
UNCOV
5130
                return err
×
5131
        case <-s.quit:
×
5132
                return ErrServerShuttingDown
×
5133
        }
5134
}
5135

5136
// connectToPeer establishes a connection to a remote peer. errChan is used to
5137
// notify the caller if the connection attempt has failed. Otherwise, it will be
5138
// closed.
5139
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
5140
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
5141

×
UNCOV
5142
        conn, err := brontide.Dial(
×
UNCOV
5143
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
5144
        )
×
UNCOV
5145
        if err != nil {
×
UNCOV
5146
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
5147
                select {
×
UNCOV
5148
                case errChan <- err:
×
5149
                case <-s.quit:
×
5150
                }
UNCOV
5151
                return
×
5152
        }
5153

UNCOV
5154
        close(errChan)
×
UNCOV
5155

×
UNCOV
5156
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
5157
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
5158

×
UNCOV
5159
        s.OutboundPeerConnected(nil, conn)
×
5160
}
5161

5162
// DisconnectPeer sends the request to server to close the connection with peer
5163
// identified by public key.
5164
//
5165
// NOTE: This function is safe for concurrent access.
UNCOV
5166
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
5167
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
5168
        pubStr := string(pubBytes)
×
UNCOV
5169

×
UNCOV
5170
        s.mu.Lock()
×
UNCOV
5171
        defer s.mu.Unlock()
×
UNCOV
5172

×
UNCOV
5173
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
5174
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
5175
        // currently connected to.
×
UNCOV
5176
        peer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
5177
        if err == ErrPeerNotConnected {
×
UNCOV
5178
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
5179
        }
×
5180

UNCOV
5181
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
5182

×
UNCOV
5183
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
5184

×
UNCOV
5185
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
5186
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
5187
        // disconnect.
×
UNCOV
5188
        delete(s.persistentPeers, pubStr)
×
UNCOV
5189
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
5190

×
UNCOV
5191
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
5192
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
×
UNCOV
5193
        //
×
UNCOV
5194
        // NOTE: We call it in a goroutine to avoid blocking the main server
×
UNCOV
5195
        // goroutine because we might hold the server's mutex.
×
UNCOV
5196
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
5197

×
UNCOV
5198
        return nil
×
5199
}
5200

5201
// OpenChannel sends a request to the server to open a channel to the specified
5202
// peer identified by nodeKey with the passed channel funding parameters.
5203
//
5204
// NOTE: This function is safe for concurrent access.
5205
func (s *server) OpenChannel(
UNCOV
5206
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
5207

×
UNCOV
5208
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
5209
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
5210
        // not blocked if the caller is not reading the updates.
×
UNCOV
5211
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
5212
        req.Err = make(chan error, 1)
×
UNCOV
5213

×
UNCOV
5214
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
5215
        // we're unable to locate the peer then this request will fail.
×
UNCOV
5216
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
5217
        s.mu.RLock()
×
UNCOV
5218
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
5219
        if !ok {
×
5220
                s.mu.RUnlock()
×
5221

×
5222
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5223
                return req.Updates, req.Err
×
5224
        }
×
UNCOV
5225
        req.Peer = peer
×
UNCOV
5226
        s.mu.RUnlock()
×
UNCOV
5227

×
UNCOV
5228
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
5229
        // opening process.
×
UNCOV
5230
        select {
×
UNCOV
5231
        case <-peer.ActiveSignal():
×
5232
        case <-peer.QuitSignal():
×
5233
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5234
                return req.Updates, req.Err
×
5235
        case <-s.quit:
×
5236
                req.Err <- ErrServerShuttingDown
×
5237
                return req.Updates, req.Err
×
5238
        }
5239

5240
        // If the fee rate wasn't specified at this point we fail the funding
5241
        // because of the missing fee rate information. The caller of the
5242
        // `OpenChannel` method needs to make sure that default values for the
5243
        // fee rate are set beforehand.
UNCOV
5244
        if req.FundingFeePerKw == 0 {
×
5245
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5246
                        "the channel opening transaction")
×
5247

×
5248
                return req.Updates, req.Err
×
5249
        }
×
5250

5251
        // Spawn a goroutine to send the funding workflow request to the funding
5252
        // manager. This allows the server to continue handling queries instead
5253
        // of blocking on this request which is exported as a synchronous
5254
        // request to the outside world.
UNCOV
5255
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
5256

×
UNCOV
5257
        return req.Updates, req.Err
×
5258
}
5259

5260
// Peers returns a slice of all active peers.
5261
//
5262
// NOTE: This function is safe for concurrent access.
UNCOV
5263
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
5264
        s.mu.RLock()
×
UNCOV
5265
        defer s.mu.RUnlock()
×
UNCOV
5266

×
UNCOV
5267
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
5268
        for _, peer := range s.peersByPub {
×
UNCOV
5269
                peers = append(peers, peer)
×
UNCOV
5270
        }
×
5271

UNCOV
5272
        return peers
×
5273
}
5274

5275
// computeNextBackoff uses a truncated exponential backoff to compute the next
5276
// backoff using the value of the exiting backoff. The returned duration is
5277
// randomized in either direction by 1/20 to prevent tight loops from
5278
// stabilizing.
UNCOV
5279
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
5280
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
5281
        nextBackoff := 2 * currBackoff
×
UNCOV
5282
        if nextBackoff > maxBackoff {
×
UNCOV
5283
                nextBackoff = maxBackoff
×
UNCOV
5284
        }
×
5285

5286
        // Using 1/10 of our duration as a margin, compute a random offset to
5287
        // avoid the nodes entering connection cycles.
UNCOV
5288
        margin := nextBackoff / 10
×
UNCOV
5289

×
UNCOV
5290
        var wiggle big.Int
×
UNCOV
5291
        wiggle.SetUint64(uint64(margin))
×
UNCOV
5292
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5293
                // Randomizing is not mission critical, so we'll just return the
×
5294
                // current backoff.
×
5295
                return nextBackoff
×
5296
        }
×
5297

5298
        // Otherwise add in our wiggle, but subtract out half of the margin so
5299
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
5300
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5301
}
5302

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

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

×
UNCOV
5311
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
5312
        if err != nil {
×
5313
                return nil, err
×
5314
        }
×
5315

UNCOV
5316
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
×
UNCOV
5317
        if err != nil {
×
UNCOV
5318
                return nil, err
×
UNCOV
5319
        }
×
5320

UNCOV
5321
        if len(node.Addresses) == 0 {
×
UNCOV
5322
                return nil, errNoAdvertisedAddr
×
UNCOV
5323
        }
×
5324

UNCOV
5325
        return node.Addresses, nil
×
5326
}
5327

5328
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5329
// channel update for a target channel.
5330
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
5331
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
5332

×
UNCOV
5333
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
5334
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
5335
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
5336
                if err != nil {
×
UNCOV
5337
                        return nil, err
×
UNCOV
5338
                }
×
5339

UNCOV
5340
                return netann.ExtractChannelUpdate(
×
UNCOV
5341
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
5342
                )
×
5343
        }
5344
}
5345

5346
// applyChannelUpdate applies the channel update to the different sub-systems of
5347
// the server. The useAlias boolean denotes whether or not to send an alias in
5348
// place of the real SCID.
5349
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
5350
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
5351

×
UNCOV
5352
        var (
×
UNCOV
5353
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5354
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5355
        )
×
UNCOV
5356

×
UNCOV
5357
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5358

×
UNCOV
5359
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
5360
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
5361
        if useAlias {
×
UNCOV
5362
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
5363
                if foundAlias != defaultAlias {
×
UNCOV
5364
                        peerAlias = &foundAlias
×
UNCOV
5365
                }
×
5366
        }
5367

UNCOV
5368
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
5369
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
5370
        )
×
UNCOV
5371
        select {
×
UNCOV
5372
        case err := <-errChan:
×
UNCOV
5373
                return err
×
5374
        case <-s.quit:
×
5375
                return ErrServerShuttingDown
×
5376
        }
5377
}
5378

5379
// SendCustomMessage sends a custom message to the peer with the specified
5380
// pubkey.
5381
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5382
        data []byte) error {
×
UNCOV
5383

×
UNCOV
5384
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5385
        if err != nil {
×
5386
                return err
×
5387
        }
×
5388

5389
        // We'll wait until the peer is active.
UNCOV
5390
        select {
×
UNCOV
5391
        case <-peer.ActiveSignal():
×
5392
        case <-peer.QuitSignal():
×
5393
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5394
        case <-s.quit:
×
5395
                return ErrServerShuttingDown
×
5396
        }
5397

UNCOV
5398
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5399
        if err != nil {
×
UNCOV
5400
                return err
×
UNCOV
5401
        }
×
5402

5403
        // Send the message as low-priority. For now we assume that all
5404
        // application-defined message are low priority.
UNCOV
5405
        return peer.SendMessageLazy(true, msg)
×
5406
}
5407

5408
// newSweepPkScriptGen creates closure that generates a new public key script
5409
// which should be used to sweep any funds into the on-chain wallet.
5410
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5411
// (p2wkh) output.
5412
func newSweepPkScriptGen(
5413
        wallet lnwallet.WalletController,
UNCOV
5414
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5415

×
UNCOV
5416
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5417
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5418
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5419
                        lnwallet.DefaultAccountName,
×
UNCOV
5420
                )
×
UNCOV
5421
                if err != nil {
×
5422
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5423
                }
×
5424

UNCOV
5425
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5426
                if err != nil {
×
5427
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5428
                }
×
5429

UNCOV
5430
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5431
                        wallet, netParams, addr,
×
UNCOV
5432
                )
×
UNCOV
5433
                if err != nil {
×
5434
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5435
                }
×
5436

UNCOV
5437
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5438
                        DeliveryAddress: addr,
×
UNCOV
5439
                        InternalKey:     internalKeyDesc,
×
UNCOV
5440
                })
×
5441
        }
5442
}
5443

5444
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5445
// finished.
UNCOV
5446
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5447
        // Get a list of closed channels.
×
UNCOV
5448
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5449
        if err != nil {
×
5450
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5451
                return nil
×
5452
        }
×
5453

5454
        // Save the SCIDs in a map.
UNCOV
5455
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
UNCOV
5456
        for _, c := range channels {
×
UNCOV
5457
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5458
                if !c.IsPending {
×
UNCOV
5459
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5460
                }
×
5461
        }
5462

5463
        // Double check whether the reported closed channel has indeed finished
5464
        // closing.
5465
        //
5466
        // NOTE: There are misalignments regarding when a channel's FC is
5467
        // marked as finalized. We double check the pending channels to make
5468
        // sure the returned SCIDs are indeed terminated.
5469
        //
5470
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5471
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5472
        if err != nil {
×
5473
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5474
                return nil
×
5475
        }
×
5476

UNCOV
5477
        for _, c := range pendings {
×
UNCOV
5478
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5479
                        continue
×
5480
                }
5481

5482
                // If the channel is still reported as pending, remove it from
5483
                // the map.
5484
                delete(closedSCIDs, c.ShortChannelID)
×
5485

×
5486
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5487
                        c.ShortChannelID)
×
5488
        }
5489

UNCOV
5490
        return closedSCIDs
×
5491
}
5492

5493
// getStartingBeat returns the current beat. This is used during the startup to
5494
// initialize blockbeat consumers.
UNCOV
5495
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
UNCOV
5496
        // beat is the current blockbeat.
×
UNCOV
5497
        var beat *chainio.Beat
×
UNCOV
5498

×
UNCOV
5499
        // If the node is configured with nochainbackend mode (remote signer),
×
UNCOV
5500
        // we will skip fetching the best block.
×
UNCOV
5501
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5502
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5503
                        "mode")
×
5504

×
5505
                return &chainio.Beat{}, nil
×
5506
        }
×
5507

5508
        // We should get a notification with the current best block immediately
5509
        // by passing a nil block.
UNCOV
5510
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
UNCOV
5511
        if err != nil {
×
5512
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5513
        }
×
UNCOV
5514
        defer blockEpochs.Cancel()
×
UNCOV
5515

×
UNCOV
5516
        // We registered for the block epochs with a nil request. The notifier
×
UNCOV
5517
        // should send us the current best block immediately. So we need to
×
UNCOV
5518
        // wait for it here because we need to know the current best height.
×
UNCOV
5519
        select {
×
UNCOV
5520
        case bestBlock := <-blockEpochs.Epochs:
×
UNCOV
5521
                srvrLog.Infof("Received initial block %v at height %d",
×
UNCOV
5522
                        bestBlock.Hash, bestBlock.Height)
×
UNCOV
5523

×
UNCOV
5524
                // Update the current blockbeat.
×
UNCOV
5525
                beat = chainio.NewBeat(*bestBlock)
×
5526

5527
        case <-s.quit:
×
5528
                srvrLog.Debug("LND shutting down")
×
5529
        }
5530

UNCOV
5531
        return beat, nil
×
5532
}
5533

5534
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5535
// point has an active RBF chan closer.
5536
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
UNCOV
5537
        chanPoint wire.OutPoint) bool {
×
UNCOV
5538

×
UNCOV
5539
        pubBytes := peerPub.SerializeCompressed()
×
UNCOV
5540

×
UNCOV
5541
        s.mu.RLock()
×
UNCOV
5542
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
UNCOV
5543
        s.mu.RUnlock()
×
UNCOV
5544
        if !ok {
×
5545
                return false
×
5546
        }
×
5547

UNCOV
5548
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5549
}
5550

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

×
UNCOV
5559
        // First, we'll attempt to look up the channel based on it's
×
UNCOV
5560
        // ChannelPoint.
×
UNCOV
5561
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
UNCOV
5562
        if err != nil {
×
5563
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5564
        }
×
5565

5566
        // From the channel, we can now get the pubkey of the peer, then use
5567
        // that to eventually get the chan closer.
UNCOV
5568
        peerPub := channel.IdentityPub.SerializeCompressed()
×
UNCOV
5569

×
UNCOV
5570
        // Now that we have the peer pub, we can look up the peer itself.
×
UNCOV
5571
        s.mu.RLock()
×
UNCOV
5572
        targetPeer, ok := s.peersByPub[string(peerPub)]
×
UNCOV
5573
        s.mu.RUnlock()
×
UNCOV
5574
        if !ok {
×
5575
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5576
                        "not online", chanPoint)
×
5577
        }
×
5578

UNCOV
5579
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
UNCOV
5580
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5581
        )
×
UNCOV
5582
        if err != nil {
×
5583
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5584
                        "%w", err)
×
5585
        }
×
5586

UNCOV
5587
        return closeUpdates, nil
×
5588
}
5589

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

×
UNCOV
5598
        // If the channel is present in the switch, then the request should flow
×
UNCOV
5599
        // through the switch instead.
×
UNCOV
5600
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5601
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
×
5602
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5603
                        "invalid request", chanPoint)
×
5604
        }
×
5605

5606
        // At this point, we know that the channel isn't present in the link, so
5607
        // we'll check to see if we have an entry in the active chan closer map.
UNCOV
5608
        updates, err := s.attemptCoopRbfFeeBump(
×
UNCOV
5609
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5610
        )
×
UNCOV
5611
        if err != nil {
×
5612
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5613
                        "ChannelPoint(%v)", chanPoint)
×
5614
        }
×
5615

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

© 2025 Coveralls, Inc