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

lightningnetwork / lnd / 16683051882

01 Aug 2025 07:03PM UTC coverage: 54.949% (-12.1%) from 67.047%
16683051882

Pull #9455

github

web-flow
Merge 3f1f50be8 into 37523b6cb
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

144 of 226 new or added lines in 7 files covered. (63.72%)

23852 existing lines in 290 files now uncovered.

108751 of 197912 relevant lines covered (54.95%)

22080.83 hits per line

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

0.98
/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.
527
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
15✔
528
        var (
15✔
529
                host string
15✔
530
                port int
15✔
531
        )
15✔
532

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

550
        // Handle the Onion address type.
551
        if tor.IsOnionHost(host) {
17✔
552
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
2✔
553
        }
2✔
554

555
        // For loopback or IP addresses: Use ResolveTCPAddr to properly
556
        // resolve these through Tor or other proxies, preventing IP leakage.
557
        if lncfg.IsLoopback(host) || isIP(host) {
20✔
558
                hostPort := net.JoinHostPort(host, strconv.Itoa(port))
7✔
559
                return netCfg.ResolveTCPAddr("tcp", hostPort)
7✔
560
        }
7✔
561

562
        // Attempt to parse as a DNS address.
563
        addr, err := lnwire.NewDNSAddr(host, uint16(port))
6✔
564
        if err != nil {
10✔
565
                return nil, err
4✔
566
        }
4✔
567

568
        // Check if that DNS address resolve to any TCP addresses.
569
        if _, err = netCfg.ResolveTCPAddr("tcp", addr.String()); err != nil {
2✔
NEW
570
                return nil, err
×
NEW
571
        }
×
572

573
        return addr, nil
2✔
574
}
575

576
// isIP checks if the provided host is an IP address (IPv4 or IPv6).
577
func isIP(host string) bool {
13✔
578
        // Try parsing the host as an IP address.
13✔
579
        ip := net.ParseIP(host)
13✔
580
        return ip != nil
13✔
581
}
13✔
582

583
// parseDNSAddr parses a raw DNS addressand assert it of type DNSAddr.
NEW
584
func parseDNSAddr(rawAddress string, netCfg tor.Net) (*lnwire.DNSAddr, error) {
×
NEW
585
        addr, err := parseAddr(rawAddress, netCfg)
×
NEW
586
        if err != nil {
×
NEW
587
                return nil, err
×
NEW
588
        }
×
589

590
        // Check if the parsed address is a DNS address.
NEW
591
        dnsAddr, ok := addr.(*lnwire.DNSAddr)
×
NEW
592
        if !ok {
×
NEW
593
                return nil, fmt.Errorf("expected DNS hostname address, got "+
×
NEW
594
                        "%T", addr)
×
NEW
595
        }
×
596

NEW
597
        return dnsAddr, nil
×
598
}
599

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

×
UNCOV
605
        return func(a net.Addr) (net.Conn, error) {
×
UNCOV
606
                lnAddr := a.(*lnwire.NetAddress)
×
UNCOV
607
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
UNCOV
608
        }
×
609
}
610

611
// newServer creates a new instance of the server which is to listen using the
612
// passed listener address.
613
//
614
//nolint:funlen
615
func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
616
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
617
        nodeKeyDesc *keychain.KeyDescriptor,
618
        chansToRestore walletunlocker.ChannelsToRecover,
619
        chanPredicate chanacceptor.ChannelAcceptor,
620
        torController *tor.Controller, tlsManager *TLSManager,
621
        leaderElector cluster.LeaderElector,
UNCOV
622
        implCfg *ImplementationCfg) (*server, error) {
×
UNCOV
623

×
UNCOV
624
        var (
×
UNCOV
625
                err         error
×
UNCOV
626
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
UNCOV
627

×
UNCOV
628
                // We just derived the full descriptor, so we know the public
×
UNCOV
629
                // key is set on it.
×
UNCOV
630
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
×
UNCOV
631
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
×
UNCOV
632
                )
×
UNCOV
633
        )
×
UNCOV
634

×
UNCOV
635
        var serializedPubKey [33]byte
×
UNCOV
636
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
637

×
UNCOV
638
        netParams := cfg.ActiveNetParams.Params
×
UNCOV
639

×
UNCOV
640
        // Initialize the sphinx router.
×
UNCOV
641
        replayLog := htlcswitch.NewDecayedLog(
×
UNCOV
642
                dbs.DecayedLogDB, cc.ChainNotifier,
×
UNCOV
643
        )
×
UNCOV
644
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
×
UNCOV
645

×
UNCOV
646
        writeBufferPool := pool.NewWriteBuffer(
×
UNCOV
647
                pool.DefaultWriteBufferGCInterval,
×
UNCOV
648
                pool.DefaultWriteBufferExpiryInterval,
×
UNCOV
649
        )
×
UNCOV
650

×
UNCOV
651
        writePool := pool.NewWrite(
×
UNCOV
652
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
UNCOV
653
        )
×
UNCOV
654

×
UNCOV
655
        readBufferPool := pool.NewReadBuffer(
×
UNCOV
656
                pool.DefaultReadBufferGCInterval,
×
UNCOV
657
                pool.DefaultReadBufferExpiryInterval,
×
UNCOV
658
        )
×
UNCOV
659

×
UNCOV
660
        readPool := pool.NewRead(
×
UNCOV
661
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
UNCOV
662
        )
×
UNCOV
663

×
UNCOV
664
        // If the taproot overlay flag is set, but we don't have an aux funding
×
UNCOV
665
        // controller, then we'll exit as this is incompatible.
×
UNCOV
666
        if cfg.ProtocolOptions.TaprootOverlayChans &&
×
UNCOV
667
                implCfg.AuxFundingController.IsNone() {
×
668

×
669
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
670
                        "aux controllers")
×
671
        }
×
672

673
        //nolint:ll
UNCOV
674
        featureMgr, err := feature.NewManager(feature.Config{
×
UNCOV
675
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
×
UNCOV
676
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
×
UNCOV
677
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
×
UNCOV
678
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
679
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
×
UNCOV
680
                NoKeysend:                 !cfg.AcceptKeySend,
×
UNCOV
681
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
×
UNCOV
682
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
×
UNCOV
683
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
×
UNCOV
684
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
×
UNCOV
685
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
×
UNCOV
686
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
×
UNCOV
687
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
×
UNCOV
688
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
×
UNCOV
689
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
×
UNCOV
690
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
×
UNCOV
691
        })
×
UNCOV
692
        if err != nil {
×
693
                return nil, err
×
694
        }
×
695

UNCOV
696
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
×
UNCOV
697
        registryConfig := invoices.RegistryConfig{
×
UNCOV
698
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
699
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
×
UNCOV
700
                Clock:                       clock.NewDefaultClock(),
×
UNCOV
701
                AcceptKeySend:               cfg.AcceptKeySend,
×
UNCOV
702
                AcceptAMP:                   cfg.AcceptAMP,
×
UNCOV
703
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
×
UNCOV
704
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
×
UNCOV
705
                KeysendHoldTime:             cfg.KeysendHoldTime,
×
UNCOV
706
                HtlcInterceptor:             invoiceHtlcModifier,
×
UNCOV
707
        }
×
UNCOV
708

×
UNCOV
709
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
UNCOV
710

×
UNCOV
711
        s := &server{
×
UNCOV
712
                cfg:            cfg,
×
UNCOV
713
                implCfg:        implCfg,
×
UNCOV
714
                graphDB:        dbs.GraphDB,
×
UNCOV
715
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
716
                addrSource:     addrSource,
×
UNCOV
717
                miscDB:         dbs.ChanStateDB,
×
UNCOV
718
                invoicesDB:     dbs.InvoiceDB,
×
UNCOV
719
                cc:             cc,
×
UNCOV
720
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
×
UNCOV
721
                writePool:      writePool,
×
UNCOV
722
                readPool:       readPool,
×
UNCOV
723
                chansToRestore: chansToRestore,
×
UNCOV
724

×
UNCOV
725
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
×
UNCOV
726
                        cc.ChainNotifier,
×
UNCOV
727
                ),
×
UNCOV
728
                channelNotifier: channelnotifier.New(
×
UNCOV
729
                        dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
730
                ),
×
UNCOV
731

×
UNCOV
732
                identityECDH:   nodeKeyECDH,
×
UNCOV
733
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
UNCOV
734
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
UNCOV
735

×
UNCOV
736
                listenAddrs: listenAddrs,
×
UNCOV
737

×
UNCOV
738
                // TODO(roasbeef): derive proper onion key based on rotation
×
UNCOV
739
                // schedule
×
UNCOV
740
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
UNCOV
741

×
UNCOV
742
                torController: torController,
×
UNCOV
743

×
UNCOV
744
                persistentPeers:         make(map[string]bool),
×
UNCOV
745
                persistentPeersBackoff:  make(map[string]time.Duration),
×
UNCOV
746
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
×
UNCOV
747
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
×
UNCOV
748
                persistentRetryCancels:  make(map[string]chan struct{}),
×
UNCOV
749
                peerErrors:              make(map[string]*queue.CircularBuffer),
×
UNCOV
750
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
×
UNCOV
751
                scheduledPeerConnection: make(map[string]func()),
×
UNCOV
752
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
×
UNCOV
753

×
UNCOV
754
                peersByPub:                make(map[string]*peer.Brontide),
×
UNCOV
755
                inboundPeers:              make(map[string]*peer.Brontide),
×
UNCOV
756
                outboundPeers:             make(map[string]*peer.Brontide),
×
UNCOV
757
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
UNCOV
758
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
UNCOV
759

×
UNCOV
760
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
761

×
UNCOV
762
                customMessageServer: subscribe.NewServer(),
×
UNCOV
763

×
UNCOV
764
                tlsManager: tlsManager,
×
UNCOV
765

×
UNCOV
766
                featureMgr: featureMgr,
×
UNCOV
767
                quit:       make(chan struct{}),
×
UNCOV
768
        }
×
UNCOV
769

×
UNCOV
770
        // Start the low-level services once they are initialized.
×
UNCOV
771
        //
×
UNCOV
772
        // TODO(yy): break the server startup into four steps,
×
UNCOV
773
        // 1. init the low-level services.
×
UNCOV
774
        // 2. start the low-level services.
×
UNCOV
775
        // 3. init the high-level services.
×
UNCOV
776
        // 4. start the high-level services.
×
UNCOV
777
        if err := s.startLowLevelServices(); err != nil {
×
778
                return nil, err
×
779
        }
×
780

UNCOV
781
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
782
        if err != nil {
×
783
                return nil, err
×
784
        }
×
785

UNCOV
786
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
UNCOV
787
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
UNCOV
788
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
UNCOV
789
        )
×
UNCOV
790
        s.invoices = invoices.NewRegistry(
×
UNCOV
791
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
UNCOV
792
        )
×
UNCOV
793

×
UNCOV
794
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
795

×
UNCOV
796
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
797
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
798

×
UNCOV
799
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
UNCOV
800
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
UNCOV
801
                if err != nil {
×
802
                        return err
×
803
                }
×
804

UNCOV
805
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
806

×
UNCOV
807
                return nil
×
808
        }
809

UNCOV
810
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
811
        if err != nil {
×
812
                return nil, err
×
813
        }
×
814

UNCOV
815
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
UNCOV
816
                DB:                   dbs.ChanStateDB,
×
UNCOV
817
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
×
UNCOV
818
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
UNCOV
819
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
UNCOV
820
                LocalChannelClose: func(pubKey []byte,
×
UNCOV
821
                        request *htlcswitch.ChanClose) {
×
UNCOV
822

×
UNCOV
823
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
UNCOV
824
                        if err != nil {
×
825
                                srvrLog.Errorf("unable to close channel, peer"+
×
826
                                        " with %v id can't be found: %v",
×
827
                                        pubKey, err,
×
828
                                )
×
829
                                return
×
830
                        }
×
831

UNCOV
832
                        peer.HandleLocalCloseChanReqs(request)
×
833
                },
834
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
835
                SwitchPackager:         channeldb.NewSwitchPackager(),
836
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
837
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
838
                Notifier:               s.cc.ChainNotifier,
839
                HtlcNotifier:           s.htlcNotifier,
840
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
841
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
842
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
843
                AllowCircularRoute:     cfg.AllowCircularRoute,
844
                RejectHTLC:             cfg.RejectHTLC,
845
                Clock:                  clock.NewDefaultClock(),
846
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
847
                MaxFeeExposure:         thresholdMSats,
848
                SignAliasUpdate:        s.signAliasUpdate,
849
                IsAlias:                aliasmgr.IsAlias,
850
        }, uint32(currentHeight))
UNCOV
851
        if err != nil {
×
852
                return nil, err
×
853
        }
×
UNCOV
854
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
×
UNCOV
855
                &htlcswitch.InterceptableSwitchConfig{
×
UNCOV
856
                        Switch:             s.htlcSwitch,
×
UNCOV
857
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
858
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
×
UNCOV
859
                        RequireInterceptor: s.cfg.RequireInterceptor,
×
UNCOV
860
                        Notifier:           s.cc.ChainNotifier,
×
UNCOV
861
                },
×
UNCOV
862
        )
×
UNCOV
863
        if err != nil {
×
864
                return nil, err
×
865
        }
×
866

UNCOV
867
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
868
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
869
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
870
        )
×
UNCOV
871

×
UNCOV
872
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
UNCOV
873
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
UNCOV
874
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
UNCOV
875
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
UNCOV
876
                OurPubKey:                nodeKeyDesc.PubKey,
×
UNCOV
877
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
UNCOV
878
                MessageSigner:            s.nodeSigner,
×
UNCOV
879
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
×
UNCOV
880
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
UNCOV
881
                DB:                       s.chanStateDB,
×
UNCOV
882
                Graph:                    dbs.GraphDB,
×
UNCOV
883
        }
×
UNCOV
884

×
UNCOV
885
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
886
        if err != nil {
×
887
                return nil, err
×
888
        }
×
UNCOV
889
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
890

×
UNCOV
891
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
UNCOV
892
        // port forwarding for users behind a NAT.
×
UNCOV
893
        if cfg.NAT {
×
894
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
895

×
896
                discoveryTimeout := time.Duration(10 * time.Second)
×
897

×
898
                ctx, cancel := context.WithTimeout(
×
899
                        context.Background(), discoveryTimeout,
×
900
                )
×
901
                defer cancel()
×
902
                upnp, err := nat.DiscoverUPnP(ctx)
×
903
                if err == nil {
×
904
                        s.natTraversal = upnp
×
905
                } else {
×
906
                        // If we were not able to discover a UPnP enabled device
×
907
                        // on the local network, we'll fall back to attempting
×
908
                        // to discover a NAT-PMP enabled device.
×
909
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
910
                                "device on the local network: %v", err)
×
911

×
912
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
913
                                "enabled device")
×
914

×
915
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
916
                        if err != nil {
×
917
                                err := fmt.Errorf("unable to discover a "+
×
918
                                        "NAT-PMP enabled device on the local "+
×
919
                                        "network: %v", err)
×
920
                                srvrLog.Error(err)
×
921
                                return nil, err
×
922
                        }
×
923

924
                        s.natTraversal = pmp
×
925
                }
926
        }
927

928
        // If we were requested to automatically configure port forwarding,
929
        // we'll use the ports that the server will be listening on.
UNCOV
930
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
×
UNCOV
931
        for idx, ip := range cfg.ExternalIPs {
×
UNCOV
932
                externalIPStrings[idx] = ip.String()
×
UNCOV
933
        }
×
UNCOV
934
        if s.natTraversal != nil {
×
935
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
936
                for _, listenAddr := range listenAddrs {
×
937
                        // At this point, the listen addresses should have
×
938
                        // already been normalized, so it's safe to ignore the
×
939
                        // errors.
×
940
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
941
                        port, _ := strconv.Atoi(portStr)
×
942

×
943
                        listenPorts = append(listenPorts, uint16(port))
×
944
                }
×
945

946
                ips, err := s.configurePortForwarding(listenPorts...)
×
947
                if err != nil {
×
948
                        srvrLog.Errorf("Unable to automatically set up port "+
×
949
                                "forwarding using %s: %v",
×
950
                                s.natTraversal.Name(), err)
×
951
                } else {
×
952
                        srvrLog.Infof("Automatically set up port forwarding "+
×
953
                                "using %s to advertise external IP",
×
954
                                s.natTraversal.Name())
×
955
                        externalIPStrings = append(externalIPStrings, ips...)
×
956
                }
×
957
        }
958

959
        // If external IP addresses have been specified, add those to the list
960
        // of this server's addresses.
UNCOV
961
        externalIPs, err := lncfg.NormalizeAddresses(
×
UNCOV
962
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
963
                cfg.net.ResolveTCPAddr,
×
UNCOV
964
        )
×
UNCOV
965
        if err != nil {
×
966
                return nil, err
×
967
        }
×
968

969
        // Determine the length of network addresses taking into the
970
        // consideration the external DNS address if exists.
NEW
971
        addrsLen := len(externalIPs)
×
NEW
972
        if cfg.ExternalDNSAddress != nil {
×
NEW
973
                addrsLen++
×
NEW
974
        }
×
975

NEW
976
        selfAddrs := make([]net.Addr, 0, addrsLen)
×
UNCOV
977
        selfAddrs = append(selfAddrs, externalIPs...)
×
UNCOV
978

×
NEW
979
        if cfg.ExternalDNSAddress != nil {
×
NEW
980
                selfAddrs = append(selfAddrs, cfg.ExternalDNSAddress)
×
NEW
981
        }
×
982

983
        // We'll now reconstruct a node announcement based on our current
984
        // configuration so we can send it out as a sort of heart beat within
985
        // the network.
986
        //
987
        // We'll start by parsing the node color from configuration.
UNCOV
988
        color, err := lncfg.ParseHexColor(cfg.Color)
×
UNCOV
989
        if err != nil {
×
990
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
991
                return nil, err
×
992
        }
×
993

994
        // If no alias is provided, default to first 10 characters of public
995
        // key.
UNCOV
996
        alias := cfg.Alias
×
UNCOV
997
        if alias == "" {
×
UNCOV
998
                alias = hex.EncodeToString(serializedPubKey[:10])
×
UNCOV
999
        }
×
UNCOV
1000
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
1001
        if err != nil {
×
1002
                return nil, err
×
1003
        }
×
1004

1005
        // TODO(elle): All previously persisted node announcement fields (ie,
1006
        //  not just LastUpdate) should be consulted here to ensure that we
1007
        //  aren't overwriting any fields that may have been set during the
1008
        //  last run of lnd.
UNCOV
1009
        nodeLastUpdate := time.Now()
×
UNCOV
1010
        srcNode, err := dbs.GraphDB.SourceNode(ctx)
×
UNCOV
1011
        switch {
×
1012
        // If we have a source node persisted in the DB already, then we just
1013
        // need to make sure that the new LastUpdate time is at least one
1014
        // second after the last update time.
UNCOV
1015
        case err == nil:
×
UNCOV
1016
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
×
UNCOV
1017
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
×
UNCOV
1018
                }
×
1019

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

1024
        // If the above cases are not matched, then we have an unhandled non
1025
        // nil error.
1026
        default:
×
1027
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
1028
        }
1029

UNCOV
1030
        selfNode := &models.LightningNode{
×
UNCOV
1031
                HaveNodeAnnouncement: true,
×
UNCOV
1032
                LastUpdate:           nodeLastUpdate,
×
UNCOV
1033
                Addresses:            selfAddrs,
×
UNCOV
1034
                Alias:                nodeAlias.String(),
×
UNCOV
1035
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
1036
                Color:                color,
×
UNCOV
1037
        }
×
UNCOV
1038
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1039

×
UNCOV
1040
        // Based on the disk representation of the node announcement generated
×
UNCOV
1041
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
1042
        // network so we can properly sign it.
×
UNCOV
1043
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
1044
        if err != nil {
×
1045
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
1046
        }
×
1047

1048
        // With the announcement generated, we'll sign it to properly
1049
        // authenticate the message on the network.
UNCOV
1050
        authSig, err := netann.SignAnnouncement(
×
UNCOV
1051
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
UNCOV
1052
        )
×
UNCOV
1053
        if err != nil {
×
1054
                return nil, fmt.Errorf("unable to generate signature for "+
×
1055
                        "self node announcement: %v", err)
×
1056
        }
×
UNCOV
1057
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
1058
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
1059
                selfNode.AuthSigBytes,
×
UNCOV
1060
        )
×
UNCOV
1061
        if err != nil {
×
1062
                return nil, err
×
1063
        }
×
1064

1065
        // Finally, we'll update the representation on disk, and update our
1066
        // cached in-memory version as well.
UNCOV
1067
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
×
1068
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1069
        }
×
UNCOV
1070
        s.currentNodeAnn = nodeAnn
×
UNCOV
1071

×
UNCOV
1072
        // The router will get access to the payment ID sequencer, such that it
×
UNCOV
1073
        // can generate unique payment IDs.
×
UNCOV
1074
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
1075
        if err != nil {
×
1076
                return nil, err
×
1077
        }
×
1078

1079
        // Instantiate mission control with config from the sub server.
1080
        //
1081
        // TODO(joostjager): When we are further in the process of moving to sub
1082
        // servers, the mission control instance itself can be moved there too.
UNCOV
1083
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
1084

×
UNCOV
1085
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
1086
        var estimator routing.Estimator
×
UNCOV
1087
        if cfg.Estimator != nil {
×
1088
                estimator = cfg.Estimator
×
UNCOV
1089
        } else {
×
UNCOV
1090
                switch routingConfig.ProbabilityEstimatorType {
×
UNCOV
1091
                case routing.AprioriEstimatorName:
×
UNCOV
1092
                        aCfg := routingConfig.AprioriConfig
×
UNCOV
1093
                        aprioriConfig := routing.AprioriConfig{
×
UNCOV
1094
                                AprioriHopProbability: aCfg.HopProbability,
×
UNCOV
1095
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
UNCOV
1096
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
1097
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
1098
                        }
×
UNCOV
1099

×
UNCOV
1100
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
1101
                                aprioriConfig,
×
UNCOV
1102
                        )
×
UNCOV
1103
                        if err != nil {
×
1104
                                return nil, err
×
1105
                        }
×
1106

1107
                case routing.BimodalEstimatorName:
×
1108
                        bCfg := routingConfig.BimodalConfig
×
1109
                        bimodalConfig := routing.BimodalConfig{
×
1110
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1111
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1112
                                        bCfg.Scale,
×
1113
                                ),
×
1114
                                BimodalDecayTime: bCfg.DecayTime,
×
1115
                        }
×
1116

×
1117
                        estimator, err = routing.NewBimodalEstimator(
×
1118
                                bimodalConfig,
×
1119
                        )
×
1120
                        if err != nil {
×
1121
                                return nil, err
×
1122
                        }
×
1123

1124
                default:
×
1125
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1126
                                routingConfig.ProbabilityEstimatorType)
×
1127
                }
1128
        }
1129

UNCOV
1130
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
1131
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
UNCOV
1132
                Estimator:               estimator,
×
UNCOV
1133
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
1134
                McFlushInterval:         routingConfig.McFlushInterval,
×
UNCOV
1135
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
UNCOV
1136
        }
×
UNCOV
1137

×
UNCOV
1138
        s.missionController, err = routing.NewMissionController(
×
UNCOV
1139
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
UNCOV
1140
        )
×
UNCOV
1141
        if err != nil {
×
1142
                return nil, fmt.Errorf("can't create mission control "+
×
1143
                        "manager: %w", err)
×
1144
        }
×
UNCOV
1145
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
1146
                routing.DefaultMissionControlNamespace,
×
UNCOV
1147
        )
×
UNCOV
1148
        if err != nil {
×
1149
                return nil, fmt.Errorf("can't create mission control in the "+
×
1150
                        "default namespace: %w", err)
×
1151
        }
×
1152

UNCOV
1153
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
UNCOV
1154
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
UNCOV
1155
                int64(routingConfig.AttemptCost),
×
UNCOV
1156
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
1157
                routingConfig.MinRouteProbability)
×
UNCOV
1158

×
UNCOV
1159
        pathFindingConfig := routing.PathFindingConfig{
×
UNCOV
1160
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
UNCOV
1161
                        routingConfig.AttemptCost,
×
UNCOV
1162
                ),
×
UNCOV
1163
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
1164
                MinProbability: routingConfig.MinRouteProbability,
×
UNCOV
1165
        }
×
UNCOV
1166

×
UNCOV
1167
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
×
UNCOV
1168
        if err != nil {
×
1169
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1170
        }
×
UNCOV
1171
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
1172
                GraphSessionFactory: dbs.GraphDB,
×
UNCOV
1173
                SourceNode:          sourceNode,
×
UNCOV
1174
                MissionControl:      s.defaultMC,
×
UNCOV
1175
                GetLink:             s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1176
                PathFindingConfig:   pathFindingConfig,
×
UNCOV
1177
        }
×
UNCOV
1178

×
UNCOV
1179
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
UNCOV
1180

×
UNCOV
1181
        s.controlTower = routing.NewControlTower(paymentControl)
×
UNCOV
1182

×
UNCOV
1183
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1184
                cfg.Routing.StrictZombiePruning
×
UNCOV
1185

×
UNCOV
1186
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1187
                SelfNode:            selfNode.PubKeyBytes,
×
UNCOV
1188
                Graph:               dbs.GraphDB,
×
UNCOV
1189
                Chain:               cc.ChainIO,
×
UNCOV
1190
                ChainView:           cc.ChainView,
×
UNCOV
1191
                Notifier:            cc.ChainNotifier,
×
UNCOV
1192
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1193
                GraphPruneInterval:  time.Hour,
×
UNCOV
1194
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1195
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1196
                StrictZombiePruning: strictPruning,
×
UNCOV
1197
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1198
        })
×
UNCOV
1199
        if err != nil {
×
1200
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1201
        }
×
1202

UNCOV
1203
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1204
                SelfNode:           selfNode.PubKeyBytes,
×
UNCOV
1205
                RoutingGraph:       dbs.GraphDB,
×
UNCOV
1206
                Chain:              cc.ChainIO,
×
UNCOV
1207
                Payer:              s.htlcSwitch,
×
UNCOV
1208
                Control:            s.controlTower,
×
UNCOV
1209
                MissionControl:     s.defaultMC,
×
UNCOV
1210
                SessionSource:      paymentSessionSource,
×
UNCOV
1211
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1212
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1213
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1214
                Clock:              clock.NewDefaultClock(),
×
UNCOV
1215
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
UNCOV
1216
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1217
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1218
        })
×
UNCOV
1219
        if err != nil {
×
1220
                return nil, fmt.Errorf("can't create router: %w", err)
×
1221
        }
×
1222

UNCOV
1223
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1224
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1225
        if err != nil {
×
1226
                return nil, err
×
1227
        }
×
UNCOV
1228
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1229
        if err != nil {
×
1230
                return nil, err
×
1231
        }
×
1232

UNCOV
1233
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1234

×
UNCOV
1235
        s.authGossiper = discovery.New(discovery.Config{
×
UNCOV
1236
                Graph:                 s.graphBuilder,
×
UNCOV
1237
                ChainIO:               s.cc.ChainIO,
×
UNCOV
1238
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1239
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1240
                Broadcast:             s.BroadcastMessage,
×
UNCOV
1241
                ChanSeries:            chanSeries,
×
UNCOV
1242
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1243
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1244
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
UNCOV
1245
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
UNCOV
1246
                        error) {
×
1247

×
1248
                        return s.genNodeAnnouncement(nil)
×
1249
                },
×
1250
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1251
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1252
                RetransmitTicker:        ticker.New(time.Minute * 30),
1253
                RebroadcastInterval:     time.Hour * 24,
1254
                WaitingProofStore:       waitingProofStore,
1255
                MessageStore:            gossipMessageStore,
1256
                AnnSigner:               s.nodeSigner,
1257
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1258
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1259
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1260
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1261
                MinimumBatchSize:        10,
1262
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1263
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1264
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1265
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1266
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1267
                IsAlias:                 aliasmgr.IsAlias,
1268
                SignAliasUpdate:         s.signAliasUpdate,
1269
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1270
                GetAlias:                s.aliasMgr.GetPeerAlias,
1271
                FindChannel:             s.findChannel,
1272
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1273
                ScidCloser:              scidCloserMan,
1274
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1275
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1276
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1277
        }, nodeKeyDesc)
1278

UNCOV
1279
        accessCfg := &accessManConfig{
×
UNCOV
1280
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
UNCOV
1281
                        error) {
×
UNCOV
1282

×
UNCOV
1283
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
×
UNCOV
1284
                        return s.chanStateDB.FetchPermAndTempPeers(
×
UNCOV
1285
                                genesisHash[:],
×
UNCOV
1286
                        )
×
UNCOV
1287
                },
×
1288
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1289
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1290
        }
1291

UNCOV
1292
        peerAccessMan, err := newAccessMan(accessCfg)
×
UNCOV
1293
        if err != nil {
×
1294
                return nil, err
×
1295
        }
×
1296

UNCOV
1297
        s.peerAccessMan = peerAccessMan
×
UNCOV
1298

×
UNCOV
1299
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1300
        //nolint:ll
×
UNCOV
1301
        s.localChanMgr = &localchans.Manager{
×
UNCOV
1302
                SelfPub:              nodeKeyDesc.PubKey,
×
UNCOV
1303
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
UNCOV
1304
                ForAllOutgoingChannels: func(ctx context.Context,
×
UNCOV
1305
                        cb func(*models.ChannelEdgeInfo,
×
UNCOV
1306
                                *models.ChannelEdgePolicy) error,
×
UNCOV
1307
                        reset func()) error {
×
UNCOV
1308

×
UNCOV
1309
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
×
UNCOV
1310
                                func(c *models.ChannelEdgeInfo,
×
UNCOV
1311
                                        e *models.ChannelEdgePolicy,
×
UNCOV
1312
                                        _ *models.ChannelEdgePolicy) error {
×
UNCOV
1313

×
UNCOV
1314
                                        // NOTE: The invoked callback here may
×
UNCOV
1315
                                        // receive a nil channel policy.
×
UNCOV
1316
                                        return cb(c, e)
×
UNCOV
1317
                                }, reset,
×
1318
                        )
1319
                },
1320
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1321
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1322
                FetchChannel:              s.chanStateDB.FetchChannel,
1323
                AddEdge: func(ctx context.Context,
1324
                        edge *models.ChannelEdgeInfo) error {
×
1325

×
1326
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1327
                },
×
1328
        }
1329

UNCOV
1330
        utxnStore, err := contractcourt.NewNurseryStore(
×
UNCOV
1331
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
UNCOV
1332
        )
×
UNCOV
1333
        if err != nil {
×
1334
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1335
                return nil, err
×
1336
        }
×
1337

UNCOV
1338
        sweeperStore, err := sweep.NewSweeperStore(
×
UNCOV
1339
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1340
        )
×
UNCOV
1341
        if err != nil {
×
1342
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1343
                return nil, err
×
1344
        }
×
1345

UNCOV
1346
        aggregator := sweep.NewBudgetAggregator(
×
UNCOV
1347
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1348
                s.implCfg.AuxSweeper,
×
UNCOV
1349
        )
×
UNCOV
1350

×
UNCOV
1351
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
UNCOV
1352
                Signer:     cc.Wallet.Cfg.Signer,
×
UNCOV
1353
                Wallet:     cc.Wallet,
×
UNCOV
1354
                Estimator:  cc.FeeEstimator,
×
UNCOV
1355
                Notifier:   cc.ChainNotifier,
×
UNCOV
1356
                AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1357
        })
×
UNCOV
1358

×
UNCOV
1359
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
UNCOV
1360
                FeeEstimator: cc.FeeEstimator,
×
UNCOV
1361
                GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1362
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1363
                ),
×
UNCOV
1364
                Signer:               cc.Wallet.Cfg.Signer,
×
UNCOV
1365
                Wallet:               newSweeperWallet(cc.Wallet),
×
UNCOV
1366
                Mempool:              cc.MempoolNotifier,
×
UNCOV
1367
                Notifier:             cc.ChainNotifier,
×
UNCOV
1368
                Store:                sweeperStore,
×
UNCOV
1369
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
UNCOV
1370
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
UNCOV
1371
                Aggregator:           aggregator,
×
UNCOV
1372
                Publisher:            s.txPublisher,
×
UNCOV
1373
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
UNCOV
1374
        })
×
UNCOV
1375

×
UNCOV
1376
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
UNCOV
1377
                ChainIO:             cc.ChainIO,
×
UNCOV
1378
                ConfDepth:           1,
×
UNCOV
1379
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
UNCOV
1380
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
UNCOV
1381
                Notifier:            cc.ChainNotifier,
×
UNCOV
1382
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
UNCOV
1383
                Store:               utxnStore,
×
UNCOV
1384
                SweepInput:          s.sweeper.SweepInput,
×
UNCOV
1385
                Budget:              s.cfg.Sweeper.Budget,
×
UNCOV
1386
        })
×
UNCOV
1387

×
UNCOV
1388
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
UNCOV
1389
        closeLink := func(chanPoint *wire.OutPoint,
×
UNCOV
1390
                closureType contractcourt.ChannelCloseType) {
×
UNCOV
1391
                // TODO(conner): Properly respect the update and error channels
×
UNCOV
1392
                // returned by CloseLink.
×
UNCOV
1393

×
UNCOV
1394
                // Instruct the switch to close the channel.  Provide no close out
×
UNCOV
1395
                // delivery script or target fee per kw because user input is not
×
UNCOV
1396
                // available when the remote peer closes the channel.
×
UNCOV
1397
                s.htlcSwitch.CloseLink(
×
UNCOV
1398
                        context.Background(), chanPoint, closureType, 0, 0, nil,
×
UNCOV
1399
                )
×
UNCOV
1400
        }
×
1401

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

×
UNCOV
1406
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
UNCOV
1407
                &contractcourt.BreachConfig{
×
UNCOV
1408
                        CloseLink: closeLink,
×
UNCOV
1409
                        DB:        s.chanStateDB,
×
UNCOV
1410
                        Estimator: s.cc.FeeEstimator,
×
UNCOV
1411
                        GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1412
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1413
                        ),
×
UNCOV
1414
                        Notifier:           cc.ChainNotifier,
×
UNCOV
1415
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1416
                        ContractBreaches:   contractBreaches,
×
UNCOV
1417
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1418
                        Store: contractcourt.NewRetributionStore(
×
UNCOV
1419
                                dbs.ChanStateDB,
×
UNCOV
1420
                        ),
×
UNCOV
1421
                        AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1422
                },
×
UNCOV
1423
        )
×
UNCOV
1424

×
UNCOV
1425
        //nolint:ll
×
UNCOV
1426
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
UNCOV
1427
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1428
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
UNCOV
1429
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
UNCOV
1430
                NewSweepAddr: func() ([]byte, error) {
×
1431
                        addr, err := newSweepPkScriptGen(
×
1432
                                cc.Wallet, netParams,
×
1433
                        )().Unpack()
×
1434
                        if err != nil {
×
1435
                                return nil, err
×
1436
                        }
×
1437

1438
                        return addr.DeliveryAddress, nil
×
1439
                },
1440
                PublishTx: cc.Wallet.PublishTransaction,
UNCOV
1441
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
UNCOV
1442
                        for _, msg := range msgs {
×
UNCOV
1443
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
UNCOV
1444
                                if err != nil {
×
1445
                                        return err
×
1446
                                }
×
1447
                        }
UNCOV
1448
                        return nil
×
1449
                },
1450
                IncubateOutputs: func(chanPoint wire.OutPoint,
1451
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1452
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1453
                        broadcastHeight uint32,
UNCOV
1454
                        deadlineHeight fn.Option[int32]) error {
×
UNCOV
1455

×
UNCOV
1456
                        return s.utxoNursery.IncubateOutputs(
×
UNCOV
1457
                                chanPoint, outHtlcRes, inHtlcRes,
×
UNCOV
1458
                                broadcastHeight, deadlineHeight,
×
UNCOV
1459
                        )
×
UNCOV
1460
                },
×
1461
                PreimageDB:   s.witnessBeacon,
1462
                Notifier:     cc.ChainNotifier,
1463
                Mempool:      cc.MempoolNotifier,
1464
                Signer:       cc.Wallet.Cfg.Signer,
1465
                FeeEstimator: cc.FeeEstimator,
1466
                ChainIO:      cc.ChainIO,
UNCOV
1467
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
UNCOV
1468
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1469
                        s.htlcSwitch.RemoveLink(chanID)
×
UNCOV
1470
                        return nil
×
UNCOV
1471
                },
×
1472
                IsOurAddress: cc.Wallet.IsOurAddress,
1473
                ContractBreach: func(chanPoint wire.OutPoint,
UNCOV
1474
                        breachRet *lnwallet.BreachRetribution) error {
×
UNCOV
1475

×
UNCOV
1476
                        // processACK will handle the BreachArbitrator ACKing
×
UNCOV
1477
                        // the event.
×
UNCOV
1478
                        finalErr := make(chan error, 1)
×
UNCOV
1479
                        processACK := func(brarErr error) {
×
UNCOV
1480
                                if brarErr != nil {
×
1481
                                        finalErr <- brarErr
×
1482
                                        return
×
1483
                                }
×
1484

1485
                                // If the BreachArbitrator successfully handled
1486
                                // the event, we can signal that the handoff
1487
                                // was successful.
UNCOV
1488
                                finalErr <- nil
×
1489
                        }
1490

UNCOV
1491
                        event := &contractcourt.ContractBreachEvent{
×
UNCOV
1492
                                ChanPoint:         chanPoint,
×
UNCOV
1493
                                ProcessACK:        processACK,
×
UNCOV
1494
                                BreachRetribution: breachRet,
×
UNCOV
1495
                        }
×
UNCOV
1496

×
UNCOV
1497
                        // Send the contract breach event to the
×
UNCOV
1498
                        // BreachArbitrator.
×
UNCOV
1499
                        select {
×
UNCOV
1500
                        case contractBreaches <- event:
×
1501
                        case <-s.quit:
×
1502
                                return ErrServerShuttingDown
×
1503
                        }
1504

1505
                        // We'll wait for a final error to be available from
1506
                        // the BreachArbitrator.
UNCOV
1507
                        select {
×
UNCOV
1508
                        case err := <-finalErr:
×
UNCOV
1509
                                return err
×
1510
                        case <-s.quit:
×
1511
                                return ErrServerShuttingDown
×
1512
                        }
1513
                },
UNCOV
1514
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
UNCOV
1515
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
UNCOV
1516
                },
×
1517
                Sweeper:                       s.sweeper,
1518
                Registry:                      s.invoices,
1519
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1520
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1521
                OnionProcessor:                s.sphinx,
1522
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1523
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1524
                Clock:                         clock.NewDefaultClock(),
1525
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1526
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1527
                HtlcNotifier:                  s.htlcNotifier,
1528
                Budget:                        *s.cfg.Sweeper.Budget,
1529

1530
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1531
                QueryIncomingCircuit: func(
UNCOV
1532
                        circuit models.CircuitKey) *models.CircuitKey {
×
UNCOV
1533

×
UNCOV
1534
                        // Get the circuit map.
×
UNCOV
1535
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1536

×
UNCOV
1537
                        // Lookup the outgoing circuit.
×
UNCOV
1538
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1539
                        if pc == nil {
×
UNCOV
1540
                                return nil
×
UNCOV
1541
                        }
×
1542

UNCOV
1543
                        return &pc.Incoming
×
1544
                },
1545
                AuxLeafStore: implCfg.AuxLeafStore,
1546
                AuxSigner:    implCfg.AuxSigner,
1547
                AuxResolver:  implCfg.AuxContractResolver,
1548
        }, dbs.ChanStateDB)
1549

1550
        // Select the configuration and funding parameters for Bitcoin.
UNCOV
1551
        chainCfg := cfg.Bitcoin
×
UNCOV
1552
        minRemoteDelay := funding.MinBtcRemoteDelay
×
UNCOV
1553
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
UNCOV
1554

×
UNCOV
1555
        var chanIDSeed [32]byte
×
UNCOV
1556
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1557
                return nil, err
×
1558
        }
×
1559

1560
        // Wrap the DeleteChannelEdges method so that the funding manager can
1561
        // use it without depending on several layers of indirection.
UNCOV
1562
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
UNCOV
1563
                *models.ChannelEdgePolicy, error) {
×
UNCOV
1564

×
UNCOV
1565
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
UNCOV
1566
                        scid.ToUint64(),
×
UNCOV
1567
                )
×
UNCOV
1568
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1569
                        // This is unlikely but there is a slim chance of this
×
1570
                        // being hit if lnd was killed via SIGKILL and the
×
1571
                        // funding manager was stepping through the delete
×
1572
                        // alias edge logic.
×
1573
                        return nil, nil
×
UNCOV
1574
                } else if err != nil {
×
1575
                        return nil, err
×
1576
                }
×
1577

1578
                // Grab our key to find our policy.
UNCOV
1579
                var ourKey [33]byte
×
UNCOV
1580
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1581

×
UNCOV
1582
                var ourPolicy *models.ChannelEdgePolicy
×
UNCOV
1583
                if info != nil && info.NodeKey1Bytes == ourKey {
×
UNCOV
1584
                        ourPolicy = e1
×
UNCOV
1585
                } else {
×
UNCOV
1586
                        ourPolicy = e2
×
UNCOV
1587
                }
×
1588

UNCOV
1589
                if ourPolicy == nil {
×
1590
                        // Something is wrong, so return an error.
×
1591
                        return nil, fmt.Errorf("we don't have an edge")
×
1592
                }
×
1593

UNCOV
1594
                err = s.graphDB.DeleteChannelEdges(
×
UNCOV
1595
                        false, false, scid.ToUint64(),
×
UNCOV
1596
                )
×
UNCOV
1597
                return ourPolicy, err
×
1598
        }
1599

1600
        // For the reservationTimeout and the zombieSweeperInterval different
1601
        // values are set in case we are in a dev environment so enhance test
1602
        // capacilities.
UNCOV
1603
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1604
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1605

×
UNCOV
1606
        // Get the development config for funding manager. If we are not in
×
UNCOV
1607
        // development mode, this would be nil.
×
UNCOV
1608
        var devCfg *funding.DevConfig
×
UNCOV
1609
        if lncfg.IsDevBuild() {
×
UNCOV
1610
                devCfg = &funding.DevConfig{
×
UNCOV
1611
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1612
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
×
UNCOV
1613
                                GetMaxWaitNumBlocksFundingConf(),
×
UNCOV
1614
                }
×
UNCOV
1615

×
UNCOV
1616
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1617
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1618

×
UNCOV
1619
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1620
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1621
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1622
        }
×
1623

1624
        //nolint:ll
UNCOV
1625
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1626
                Dev:                devCfg,
×
UNCOV
1627
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1628
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1629
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1630
                Wallet:             cc.Wallet,
×
UNCOV
1631
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1632
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1633
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1634
                },
×
1635
                Notifier:     cc.ChainNotifier,
1636
                ChannelDB:    s.chanStateDB,
1637
                FeeEstimator: cc.FeeEstimator,
1638
                SignMessage:  cc.MsgSigner.SignMessage,
1639
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1640
                        error) {
×
UNCOV
1641

×
UNCOV
1642
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1643
                },
×
1644
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1645
                NotifyWhenOnline:     s.NotifyWhenOnline,
1646
                TempChanIDSeed:       chanIDSeed,
1647
                FindChannel:          s.findChannel,
1648
                DefaultRoutingPolicy: cc.RoutingPolicy,
1649
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1650
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1651
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1652
                        // For large channels we increase the number
×
UNCOV
1653
                        // of confirmations we require for the
×
UNCOV
1654
                        // channel to be considered open. As it is
×
UNCOV
1655
                        // always the responder that gets to choose
×
UNCOV
1656
                        // value, the pushAmt is value being pushed
×
UNCOV
1657
                        // to us. This means we have more to lose
×
UNCOV
1658
                        // in the case this gets re-orged out, and
×
UNCOV
1659
                        // we will require more confirmations before
×
UNCOV
1660
                        // we consider it open.
×
UNCOV
1661

×
UNCOV
1662
                        // In case the user has explicitly specified
×
UNCOV
1663
                        // a default value for the number of
×
UNCOV
1664
                        // confirmations, we use it.
×
UNCOV
1665
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1666
                        if defaultConf != 0 {
×
UNCOV
1667
                                return defaultConf
×
UNCOV
1668
                        }
×
1669

1670
                        minConf := uint64(3)
×
1671
                        maxConf := uint64(6)
×
1672

×
1673
                        // If this is a wumbo channel, then we'll require the
×
1674
                        // max amount of confirmations.
×
1675
                        if chanAmt > MaxFundingAmount {
×
1676
                                return uint16(maxConf)
×
1677
                        }
×
1678

1679
                        // If not we return a value scaled linearly
1680
                        // between 3 and 6, depending on channel size.
1681
                        // TODO(halseth): Use 1 as minimum?
1682
                        maxChannelSize := uint64(
×
1683
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1684
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1685
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1686
                        if conf < minConf {
×
1687
                                conf = minConf
×
1688
                        }
×
1689
                        if conf > maxConf {
×
1690
                                conf = maxConf
×
1691
                        }
×
1692
                        return uint16(conf)
×
1693
                },
UNCOV
1694
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1695
                        // We scale the remote CSV delay (the time the
×
UNCOV
1696
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1697
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1698
                        // for small channels, to maxRemoteDelay blocks
×
UNCOV
1699
                        // for channels of size MaxFundingAmount.
×
UNCOV
1700

×
UNCOV
1701
                        // In case the user has explicitly specified
×
UNCOV
1702
                        // a default value for the remote delay, we
×
UNCOV
1703
                        // use it.
×
UNCOV
1704
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1705
                        if defaultDelay > 0 {
×
UNCOV
1706
                                return defaultDelay
×
UNCOV
1707
                        }
×
1708

1709
                        // If this is a wumbo channel, then we'll require the
1710
                        // max value.
1711
                        if chanAmt > MaxFundingAmount {
×
1712
                                return maxRemoteDelay
×
1713
                        }
×
1714

1715
                        // If not we scale according to channel size.
1716
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1717
                                chanAmt / MaxFundingAmount)
×
1718
                        if delay < minRemoteDelay {
×
1719
                                delay = minRemoteDelay
×
1720
                        }
×
1721
                        if delay > maxRemoteDelay {
×
1722
                                delay = maxRemoteDelay
×
1723
                        }
×
1724
                        return delay
×
1725
                },
1726
                WatchNewChannel: func(channel *channeldb.OpenChannel,
UNCOV
1727
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1728

×
UNCOV
1729
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1730
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1731
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1732
                        // we'll set false to prevent the server from continuing
×
UNCOV
1733
                        // to connect to this peer even if the number of
×
UNCOV
1734
                        // channels with this peer is zero.
×
UNCOV
1735
                        s.mu.Lock()
×
UNCOV
1736
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1737
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1738
                                s.persistentPeers[pubStr] = false
×
UNCOV
1739
                        }
×
UNCOV
1740
                        s.mu.Unlock()
×
UNCOV
1741

×
UNCOV
1742
                        // With that taken care of, we'll send this channel to
×
UNCOV
1743
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1744
                        return s.chainArb.WatchNewChannel(channel)
×
1745
                },
UNCOV
1746
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1747
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1748
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1749
                },
×
1750
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1751
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1752

×
UNCOV
1753
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1754
                        // at least 1% of the total channel capacity at all
×
UNCOV
1755
                        // times. If this value ends up dipping below the dust
×
UNCOV
1756
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1757
                        // reserve as required by BOLT #2.
×
UNCOV
1758
                        reserve := chanAmt / 100
×
UNCOV
1759
                        if reserve < dustLimit {
×
UNCOV
1760
                                reserve = dustLimit
×
UNCOV
1761
                        }
×
1762

UNCOV
1763
                        return reserve
×
1764
                },
UNCOV
1765
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1766
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1767
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1768
                        // required reserve.
×
UNCOV
1769
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1770
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1771
                },
×
UNCOV
1772
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1773
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1774
                                return cfg.DefaultRemoteMaxHtlcs
×
UNCOV
1775
                        }
×
1776

1777
                        // By default, we'll permit them to utilize the full
1778
                        // channel bandwidth.
1779
                        return uint16(input.MaxHTLCNumber / 2)
×
1780
                },
1781
                ZombieSweeperInterval:         zombieSweeperInterval,
1782
                ReservationTimeout:            reservationTimeout,
1783
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1784
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1785
                MaxPendingChannels:            cfg.MaxPendingChannels,
1786
                RejectPush:                    cfg.RejectPush,
1787
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1788
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1789
                OpenChannelPredicate:          chanPredicate,
1790
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1791
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1792
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1793
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1794
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1795
                DeleteAliasEdge:      deleteAliasEdge,
1796
                AliasManager:         s.aliasMgr,
1797
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1798
                AuxFundingController: implCfg.AuxFundingController,
1799
                AuxSigner:            implCfg.AuxSigner,
1800
                AuxResolver:          implCfg.AuxContractResolver,
1801
        })
UNCOV
1802
        if err != nil {
×
1803
                return nil, err
×
1804
        }
×
1805

1806
        // Next, we'll assemble the sub-system that will maintain an on-disk
1807
        // static backup of the latest channel state.
UNCOV
1808
        chanNotifier := &channelNotifier{
×
UNCOV
1809
                chanNotifier: s.channelNotifier,
×
UNCOV
1810
                addrs:        s.addrSource,
×
UNCOV
1811
        }
×
UNCOV
1812
        backupFile := chanbackup.NewMultiFile(
×
UNCOV
1813
                cfg.BackupFilePath, cfg.NoBackupArchive,
×
UNCOV
1814
        )
×
UNCOV
1815
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1816
                ctx, s.chanStateDB, s.addrSource,
×
UNCOV
1817
        )
×
UNCOV
1818
        if err != nil {
×
1819
                return nil, err
×
1820
        }
×
UNCOV
1821
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1822
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1823
        )
×
UNCOV
1824
        if err != nil {
×
1825
                return nil, err
×
1826
        }
×
1827

1828
        // Assemble a peer notifier which will provide clients with subscriptions
1829
        // to peer online and offline events.
UNCOV
1830
        s.peerNotifier = peernotifier.New()
×
UNCOV
1831

×
UNCOV
1832
        // Create a channel event store which monitors all open channels.
×
UNCOV
1833
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1834
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1835
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1836
                },
×
UNCOV
1837
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1838
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1839
                },
×
1840
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1841
                Clock:           clock.NewDefaultClock(),
1842
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1843
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1844
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1845
        })
1846

UNCOV
1847
        if cfg.WtClient.Active {
×
UNCOV
1848
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1849
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1850

×
UNCOV
1851
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1852
                // protocol operations on sat/kw.
×
UNCOV
1853
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1854
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1855
                )
×
UNCOV
1856

×
UNCOV
1857
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1858

×
UNCOV
1859
                if err := policy.Validate(); err != nil {
×
1860
                        return nil, err
×
1861
                }
×
1862

1863
                // authDial is the wrapper around the btrontide.Dial for the
1864
                // watchtower.
UNCOV
1865
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1866
                        netAddr *lnwire.NetAddress,
×
UNCOV
1867
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1868

×
UNCOV
1869
                        return brontide.Dial(
×
UNCOV
1870
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1871
                        )
×
UNCOV
1872
                }
×
1873

1874
                // buildBreachRetribution is a call-back that can be used to
1875
                // query the BreachRetribution info and channel type given a
1876
                // channel ID and commitment height.
UNCOV
1877
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1878
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1879
                        channeldb.ChannelType, error) {
×
UNCOV
1880

×
UNCOV
1881
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1882
                                nil, chanID,
×
UNCOV
1883
                        )
×
UNCOV
1884
                        if err != nil {
×
1885
                                return nil, 0, err
×
1886
                        }
×
1887

UNCOV
1888
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1889
                                channel, commitHeight, 0, nil,
×
UNCOV
1890
                                implCfg.AuxLeafStore,
×
UNCOV
1891
                                implCfg.AuxContractResolver,
×
UNCOV
1892
                        )
×
UNCOV
1893
                        if err != nil {
×
1894
                                return nil, 0, err
×
1895
                        }
×
1896

UNCOV
1897
                        return br, channel.ChanType, nil
×
1898
                }
1899

UNCOV
1900
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1901

×
UNCOV
1902
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1903
                // signalling support for anchor channels.
×
UNCOV
1904
                anchorPolicy := policy
×
UNCOV
1905
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1906

×
UNCOV
1907
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1908
                // signalling support for taproot channels.
×
UNCOV
1909
                taprootPolicy := policy
×
UNCOV
1910
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1911
                        blob.FlagTaprootChannel,
×
UNCOV
1912
                )
×
UNCOV
1913

×
UNCOV
1914
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1915
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1916
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1917
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1918
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1919
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1920
                                error) {
×
UNCOV
1921

×
UNCOV
1922
                                return s.channelNotifier.
×
UNCOV
1923
                                        SubscribeChannelEvents()
×
UNCOV
1924
                        },
×
1925
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1926
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1927
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1928
                                        cc.Wallet, netParams,
×
UNCOV
1929
                                )().Unpack()
×
UNCOV
1930
                                if err != nil {
×
1931
                                        return nil, err
×
1932
                                }
×
1933

UNCOV
1934
                                return addr.DeliveryAddress, nil
×
1935
                        },
1936
                        SecretKeyRing:      s.cc.KeyRing,
1937
                        Dial:               cfg.net.Dial,
1938
                        AuthDial:           authDial,
1939
                        DB:                 dbs.TowerClientDB,
1940
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1941
                        MinBackoff:         10 * time.Second,
1942
                        MaxBackoff:         5 * time.Minute,
1943
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1944
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1945
                if err != nil {
×
1946
                        return nil, err
×
1947
                }
×
1948
        }
1949

UNCOV
1950
        if len(cfg.ExternalHosts) != 0 {
×
1951
                advertisedIPs := make(map[string]struct{})
×
1952
                for _, addr := range s.currentNodeAnn.Addresses {
×
1953
                        advertisedIPs[addr.String()] = struct{}{}
×
1954
                }
×
1955

1956
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1957
                        Hosts:         cfg.ExternalHosts,
×
1958
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1959
                        LookupHost: func(host string) (net.Addr, error) {
×
1960
                                return lncfg.ParseAddressString(
×
1961
                                        host, strconv.Itoa(defaultPeerPort),
×
1962
                                        cfg.net.ResolveTCPAddr,
×
1963
                                )
×
1964
                        },
×
1965
                        AdvertisedIPs: advertisedIPs,
1966
                        AnnounceNewIPs: netann.IPAnnouncer(
1967
                                func(modifier ...netann.NodeAnnModifier) (
1968
                                        lnwire.NodeAnnouncement, error) {
×
1969

×
1970
                                        return s.genNodeAnnouncement(
×
1971
                                                nil, modifier...,
×
1972
                                        )
×
1973
                                }),
×
1974
                })
1975
        }
1976

1977
        // Create liveness monitor.
UNCOV
1978
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1979

×
UNCOV
1980
        listeners := make([]net.Listener, len(listenAddrs))
×
UNCOV
1981
        for i, listenAddr := range listenAddrs {
×
UNCOV
1982
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
UNCOV
1983
                // doesn't need to call the general lndResolveTCP function
×
UNCOV
1984
                // since we are resolving a local address.
×
UNCOV
1985

×
UNCOV
1986
                // RESOLVE: We are actually partially accepting inbound
×
UNCOV
1987
                // connection requests when we call NewListener.
×
UNCOV
1988
                listeners[i], err = brontide.NewListener(
×
UNCOV
1989
                        nodeKeyECDH, listenAddr.String(),
×
UNCOV
1990
                        // TODO(yy): remove this check and unify the inbound
×
UNCOV
1991
                        // connection check inside `InboundPeerConnected`.
×
UNCOV
1992
                        s.peerAccessMan.checkAcceptIncomingConn,
×
UNCOV
1993
                )
×
UNCOV
1994
                if err != nil {
×
1995
                        return nil, err
×
1996
                }
×
1997
        }
1998

1999
        // Create the connection manager which will be responsible for
2000
        // maintaining persistent outbound connections and also accepting new
2001
        // incoming connections
UNCOV
2002
        cmgr, err := connmgr.New(&connmgr.Config{
×
UNCOV
2003
                Listeners:      listeners,
×
UNCOV
2004
                OnAccept:       s.InboundPeerConnected,
×
UNCOV
2005
                RetryDuration:  time.Second * 5,
×
UNCOV
2006
                TargetOutbound: 100,
×
UNCOV
2007
                Dial: noiseDial(
×
UNCOV
2008
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
2009
                ),
×
UNCOV
2010
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
2011
        })
×
UNCOV
2012
        if err != nil {
×
2013
                return nil, err
×
2014
        }
×
UNCOV
2015
        s.connMgr = cmgr
×
UNCOV
2016

×
UNCOV
2017
        // Finally, register the subsystems in blockbeat.
×
UNCOV
2018
        s.registerBlockConsumers()
×
UNCOV
2019

×
UNCOV
2020
        return s, nil
×
2021
}
2022

2023
// UpdateRoutingConfig is a callback function to update the routing config
2024
// values in the main cfg.
UNCOV
2025
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
2026
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
2027

×
UNCOV
2028
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
2029
        case routing.AprioriConfig:
×
UNCOV
2030
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
2031
                        routing.AprioriEstimatorName
×
UNCOV
2032

×
UNCOV
2033
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
2034
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
2035
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
2036
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
2037
                targetCfg.HopProbability = c.AprioriHopProbability
×
2038

UNCOV
2039
        case routing.BimodalConfig:
×
UNCOV
2040
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
2041
                        routing.BimodalEstimatorName
×
UNCOV
2042

×
UNCOV
2043
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
2044
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
2045
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
2046
                targetCfg.DecayTime = c.BimodalDecayTime
×
2047
        }
2048

UNCOV
2049
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
2050
}
2051

2052
// registerBlockConsumers registers the subsystems that consume block events.
2053
// By calling `RegisterQueue`, a list of subsystems are registered in the
2054
// blockbeat for block notifications. When a new block arrives, the subsystems
2055
// in the same queue are notified sequentially, and different queues are
2056
// notified concurrently.
2057
//
2058
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
2059
// a new `RegisterQueue` call.
UNCOV
2060
func (s *server) registerBlockConsumers() {
×
UNCOV
2061
        // In this queue, when a new block arrives, it will be received and
×
UNCOV
2062
        // processed in this order: chainArb -> sweeper -> txPublisher.
×
UNCOV
2063
        consumers := []chainio.Consumer{
×
UNCOV
2064
                s.chainArb,
×
UNCOV
2065
                s.sweeper,
×
UNCOV
2066
                s.txPublisher,
×
UNCOV
2067
        }
×
UNCOV
2068
        s.blockbeatDispatcher.RegisterQueue(consumers)
×
UNCOV
2069
}
×
2070

2071
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2072
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2073
// may differ from what is on disk.
2074
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
2075
        error) {
×
UNCOV
2076

×
UNCOV
2077
        data, err := u.DataToSign()
×
UNCOV
2078
        if err != nil {
×
2079
                return nil, err
×
2080
        }
×
2081

UNCOV
2082
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
2083
}
2084

2085
// createLivenessMonitor creates a set of health checks using our configured
2086
// values and uses these checks to create a liveness monitor. Available
2087
// health checks,
2088
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2089
//   - diskCheck
2090
//   - tlsHealthCheck
2091
//   - torController, only created when tor is enabled.
2092
//
2093
// If a health check has been disabled by setting attempts to 0, our monitor
2094
// will not run it.
2095
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
UNCOV
2096
        leaderElector cluster.LeaderElector) {
×
UNCOV
2097

×
UNCOV
2098
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
2099
        if cfg.Bitcoin.Node == "nochainbackend" {
×
2100
                srvrLog.Info("Disabling chain backend checks for " +
×
2101
                        "nochainbackend mode")
×
2102

×
2103
                chainBackendAttempts = 0
×
2104
        }
×
2105

UNCOV
2106
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
2107
                "chain backend",
×
UNCOV
2108
                cc.HealthCheck,
×
UNCOV
2109
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
2110
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
2111
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
2112
                chainBackendAttempts,
×
UNCOV
2113
        )
×
UNCOV
2114

×
UNCOV
2115
        diskCheck := healthcheck.NewObservation(
×
UNCOV
2116
                "disk space",
×
UNCOV
2117
                func() error {
×
2118
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2119
                                cfg.LndDir,
×
2120
                        )
×
2121
                        if err != nil {
×
2122
                                return err
×
2123
                        }
×
2124

2125
                        // If we have more free space than we require,
2126
                        // we return a nil error.
2127
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2128
                                return nil
×
2129
                        }
×
2130

2131
                        return fmt.Errorf("require: %v free space, got: %v",
×
2132
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2133
                                free)
×
2134
                },
2135
                cfg.HealthChecks.DiskCheck.Interval,
2136
                cfg.HealthChecks.DiskCheck.Timeout,
2137
                cfg.HealthChecks.DiskCheck.Backoff,
2138
                cfg.HealthChecks.DiskCheck.Attempts,
2139
        )
2140

UNCOV
2141
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
2142
                "tls",
×
UNCOV
2143
                func() error {
×
2144
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2145
                                s.cc.KeyRing,
×
2146
                        )
×
2147
                        if err != nil {
×
2148
                                return err
×
2149
                        }
×
2150
                        if expired {
×
2151
                                return fmt.Errorf("TLS certificate is "+
×
2152
                                        "expired as of %v", expTime)
×
2153
                        }
×
2154

2155
                        // If the certificate is not outdated, no error needs
2156
                        // to be returned
2157
                        return nil
×
2158
                },
2159
                cfg.HealthChecks.TLSCheck.Interval,
2160
                cfg.HealthChecks.TLSCheck.Timeout,
2161
                cfg.HealthChecks.TLSCheck.Backoff,
2162
                cfg.HealthChecks.TLSCheck.Attempts,
2163
        )
2164

UNCOV
2165
        checks := []*healthcheck.Observation{
×
UNCOV
2166
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
2167
        }
×
UNCOV
2168

×
UNCOV
2169
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
2170
        if s.torController != nil {
×
2171
                torConnectionCheck := healthcheck.NewObservation(
×
2172
                        "tor connection",
×
2173
                        func() error {
×
2174
                                return healthcheck.CheckTorServiceStatus(
×
2175
                                        s.torController,
×
2176
                                        func() error {
×
2177
                                                return s.createNewHiddenService(
×
2178
                                                        context.TODO(),
×
2179
                                                )
×
2180
                                        },
×
2181
                                )
2182
                        },
2183
                        cfg.HealthChecks.TorConnection.Interval,
2184
                        cfg.HealthChecks.TorConnection.Timeout,
2185
                        cfg.HealthChecks.TorConnection.Backoff,
2186
                        cfg.HealthChecks.TorConnection.Attempts,
2187
                )
2188
                checks = append(checks, torConnectionCheck)
×
2189
        }
2190

2191
        // If remote signing is enabled, add the healthcheck for the remote
2192
        // signing RPC interface.
UNCOV
2193
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
2194
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
2195
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
2196
                // returns exactly on time.
×
UNCOV
2197
                overhead := time.Millisecond * 10
×
UNCOV
2198

×
UNCOV
2199
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
2200
                        "remote signer connection",
×
UNCOV
2201
                        rpcwallet.HealthCheck(
×
UNCOV
2202
                                s.cfg.RemoteSigner,
×
UNCOV
2203

×
UNCOV
2204
                                // For the health check we might to be even
×
UNCOV
2205
                                // stricter than the initial/normal connect, so
×
UNCOV
2206
                                // we use the health check timeout here.
×
UNCOV
2207
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
2208
                        ),
×
UNCOV
2209
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
2210
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
2211
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
2212
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
2213
                )
×
UNCOV
2214
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
2215
        }
×
2216

2217
        // If we have a leader elector, we add a health check to ensure we are
2218
        // still the leader. During normal operation, we should always be the
2219
        // leader, but there are circumstances where this may change, such as
2220
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
2221
        if leaderElector != nil {
×
2222
                leaderCheck := healthcheck.NewObservation(
×
2223
                        "leader status",
×
2224
                        func() error {
×
2225
                                // Check if we are still the leader. Note that
×
2226
                                // we don't need to use a timeout context here
×
2227
                                // as the healthcheck observer will handle the
×
2228
                                // timeout case for us.
×
2229
                                timeoutCtx, cancel := context.WithTimeout(
×
2230
                                        context.Background(),
×
2231
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2232
                                )
×
2233
                                defer cancel()
×
2234

×
2235
                                leader, err := leaderElector.IsLeader(
×
2236
                                        timeoutCtx,
×
2237
                                )
×
2238
                                if err != nil {
×
2239
                                        return fmt.Errorf("unable to check if "+
×
2240
                                                "still leader: %v", err)
×
2241
                                }
×
2242

2243
                                if !leader {
×
2244
                                        srvrLog.Debug("Not the current leader")
×
2245
                                        return fmt.Errorf("not the current " +
×
2246
                                                "leader")
×
2247
                                }
×
2248

2249
                                return nil
×
2250
                        },
2251
                        cfg.HealthChecks.LeaderCheck.Interval,
2252
                        cfg.HealthChecks.LeaderCheck.Timeout,
2253
                        cfg.HealthChecks.LeaderCheck.Backoff,
2254
                        cfg.HealthChecks.LeaderCheck.Attempts,
2255
                )
2256

2257
                checks = append(checks, leaderCheck)
×
2258
        }
2259

2260
        // If we have not disabled all of our health checks, we create a
2261
        // liveness monitor with our configured checks.
UNCOV
2262
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2263
                &healthcheck.Config{
×
UNCOV
2264
                        Checks:   checks,
×
UNCOV
2265
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2266
                },
×
UNCOV
2267
        )
×
2268
}
2269

2270
// Started returns true if the server has been started, and false otherwise.
2271
// NOTE: This function is safe for concurrent access.
UNCOV
2272
func (s *server) Started() bool {
×
UNCOV
2273
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2274
}
×
2275

2276
// cleaner is used to aggregate "cleanup" functions during an operation that
2277
// starts several subsystems. In case one of the subsystem fails to start
2278
// and a proper resource cleanup is required, the "run" method achieves this
2279
// by running all these added "cleanup" functions.
2280
type cleaner []func() error
2281

2282
// add is used to add a cleanup function to be called when
2283
// the run function is executed.
UNCOV
2284
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2285
        return append(c, cleanup)
×
UNCOV
2286
}
×
2287

2288
// run is used to run all the previousely added cleanup functions.
2289
func (c cleaner) run() {
×
2290
        for i := len(c) - 1; i >= 0; i-- {
×
2291
                if err := c[i](); err != nil {
×
2292
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2293
                }
×
2294
        }
2295
}
2296

2297
// startLowLevelServices starts the low-level services of the server. These
2298
// services must be started successfully before running the main server. The
2299
// services are,
2300
// 1. the chain notifier.
2301
//
2302
// TODO(yy): identify and add more low-level services here.
UNCOV
2303
func (s *server) startLowLevelServices() error {
×
UNCOV
2304
        var startErr error
×
UNCOV
2305

×
UNCOV
2306
        cleanup := cleaner{}
×
UNCOV
2307

×
UNCOV
2308
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
UNCOV
2309
        if err := s.cc.ChainNotifier.Start(); err != nil {
×
2310
                startErr = err
×
2311
        }
×
2312

UNCOV
2313
        if startErr != nil {
×
2314
                cleanup.run()
×
2315
        }
×
2316

UNCOV
2317
        return startErr
×
2318
}
2319

2320
// Start starts the main daemon server, all requested listeners, and any helper
2321
// goroutines.
2322
// NOTE: This function is safe for concurrent access.
2323
//
2324
//nolint:funlen
UNCOV
2325
func (s *server) Start(ctx context.Context) error {
×
UNCOV
2326
        // Get the current blockbeat.
×
UNCOV
2327
        beat, err := s.getStartingBeat()
×
UNCOV
2328
        if err != nil {
×
2329
                return err
×
2330
        }
×
2331

UNCOV
2332
        var startErr error
×
UNCOV
2333

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

×
UNCOV
2339
        s.start.Do(func() {
×
UNCOV
2340
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
UNCOV
2341
                if err := s.customMessageServer.Start(); err != nil {
×
2342
                        startErr = err
×
2343
                        return
×
2344
                }
×
2345

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

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

2362
                // Start the notification server. This is used so channel
2363
                // management goroutines can be notified when a funding
2364
                // transaction reaches a sufficient number of confirmations, or
2365
                // when the input for the funding transaction is spent in an
2366
                // attempt at an uncooperative close by the counterparty.
UNCOV
2367
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2368
                if err := s.sigPool.Start(); err != nil {
×
2369
                        startErr = err
×
2370
                        return
×
2371
                }
×
2372

UNCOV
2373
                cleanup = cleanup.add(s.writePool.Stop)
×
UNCOV
2374
                if err := s.writePool.Start(); err != nil {
×
2375
                        startErr = err
×
2376
                        return
×
2377
                }
×
2378

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

UNCOV
2385
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
UNCOV
2386
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2387
                        startErr = err
×
2388
                        return
×
2389
                }
×
2390

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

UNCOV
2397
                cleanup = cleanup.add(func() error {
×
2398
                        return s.peerNotifier.Stop()
×
2399
                })
×
UNCOV
2400
                if err := s.peerNotifier.Start(); err != nil {
×
2401
                        startErr = err
×
2402
                        return
×
2403
                }
×
2404

UNCOV
2405
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
UNCOV
2406
                if err := s.htlcNotifier.Start(); err != nil {
×
2407
                        startErr = err
×
2408
                        return
×
2409
                }
×
2410

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

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

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

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

UNCOV
2437
                cleanup = cleanup.add(s.breachArbitrator.Stop)
×
UNCOV
2438
                if err := s.breachArbitrator.Start(); err != nil {
×
2439
                        startErr = err
×
2440
                        return
×
2441
                }
×
2442

UNCOV
2443
                cleanup = cleanup.add(s.fundingMgr.Stop)
×
UNCOV
2444
                if err := s.fundingMgr.Start(); err != nil {
×
2445
                        startErr = err
×
2446
                        return
×
2447
                }
×
2448

2449
                // htlcSwitch must be started before chainArb since the latter
2450
                // relies on htlcSwitch to deliver resolution message upon
2451
                // start.
UNCOV
2452
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2453
                if err := s.htlcSwitch.Start(); err != nil {
×
2454
                        startErr = err
×
2455
                        return
×
2456
                }
×
2457

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

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

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

UNCOV
2476
                cleanup = cleanup.add(s.graphDB.Stop)
×
UNCOV
2477
                if err := s.graphDB.Start(); err != nil {
×
2478
                        startErr = err
×
2479
                        return
×
2480
                }
×
2481

UNCOV
2482
                cleanup = cleanup.add(s.graphBuilder.Stop)
×
UNCOV
2483
                if err := s.graphBuilder.Start(); err != nil {
×
2484
                        startErr = err
×
2485
                        return
×
2486
                }
×
2487

UNCOV
2488
                cleanup = cleanup.add(s.chanRouter.Stop)
×
UNCOV
2489
                if err := s.chanRouter.Start(); err != nil {
×
2490
                        startErr = err
×
2491
                        return
×
2492
                }
×
2493
                // The authGossiper depends on the chanRouter and therefore
2494
                // should be started after it.
UNCOV
2495
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2496
                if err := s.authGossiper.Start(); err != nil {
×
2497
                        startErr = err
×
2498
                        return
×
2499
                }
×
2500

UNCOV
2501
                cleanup = cleanup.add(s.invoices.Stop)
×
UNCOV
2502
                if err := s.invoices.Start(); err != nil {
×
2503
                        startErr = err
×
2504
                        return
×
2505
                }
×
2506

UNCOV
2507
                cleanup = cleanup.add(s.sphinx.Stop)
×
UNCOV
2508
                if err := s.sphinx.Start(); err != nil {
×
2509
                        startErr = err
×
2510
                        return
×
2511
                }
×
2512

UNCOV
2513
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
×
UNCOV
2514
                if err := s.chanStatusMgr.Start(); err != nil {
×
2515
                        startErr = err
×
2516
                        return
×
2517
                }
×
2518

UNCOV
2519
                cleanup = cleanup.add(s.chanEventStore.Stop)
×
UNCOV
2520
                if err := s.chanEventStore.Start(); err != nil {
×
2521
                        startErr = err
×
2522
                        return
×
2523
                }
×
2524

UNCOV
2525
                cleanup.add(func() error {
×
2526
                        s.missionController.StopStoreTickers()
×
2527
                        return nil
×
2528
                })
×
UNCOV
2529
                s.missionController.RunStoreTickers()
×
UNCOV
2530

×
UNCOV
2531
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2532
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2533
                // that have all the information we need to handle channel
×
UNCOV
2534
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2535
                chanRestorer := &chanDBRestorer{
×
UNCOV
2536
                        db:         s.chanStateDB,
×
UNCOV
2537
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2538
                        chainArb:   s.chainArb,
×
UNCOV
2539
                }
×
UNCOV
2540
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2541
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2542
                                s.chansToRestore.PackedSingleChanBackups,
×
2543
                                s.cc.KeyRing, chanRestorer, s,
×
2544
                        )
×
2545
                        if err != nil {
×
2546
                                startErr = fmt.Errorf("unable to unpack single "+
×
2547
                                        "backups: %v", err)
×
2548
                                return
×
2549
                        }
×
2550
                }
UNCOV
2551
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2552
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2553
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2554
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2555
                        )
×
UNCOV
2556
                        if err != nil {
×
2557
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2558
                                        "backup: %v", err)
×
2559
                                return
×
2560
                        }
×
2561
                }
2562

2563
                // chanSubSwapper must be started after the `channelNotifier`
2564
                // because it depends on channel events as a synchronization
2565
                // point.
UNCOV
2566
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2567
                if err := s.chanSubSwapper.Start(); err != nil {
×
2568
                        startErr = err
×
2569
                        return
×
2570
                }
×
2571

UNCOV
2572
                if s.torController != nil {
×
2573
                        cleanup = cleanup.add(s.torController.Stop)
×
2574
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2575
                                startErr = err
×
2576
                                return
×
2577
                        }
×
2578
                }
2579

UNCOV
2580
                if s.natTraversal != nil {
×
2581
                        s.wg.Add(1)
×
2582
                        go s.watchExternalIP()
×
2583
                }
×
2584

2585
                // Start connmgr last to prevent connections before init.
UNCOV
2586
                cleanup = cleanup.add(func() error {
×
2587
                        s.connMgr.Stop()
×
2588
                        return nil
×
2589
                })
×
2590

2591
                // RESOLVE: s.connMgr.Start() is called here, but
2592
                // brontide.NewListener() is called in newServer. This means
2593
                // that we are actually listening and partially accepting
2594
                // inbound connections even before the connMgr starts.
2595
                //
2596
                // TODO(yy): move the log into the connMgr's `Start` method.
UNCOV
2597
                srvrLog.Info("connMgr starting...")
×
UNCOV
2598
                s.connMgr.Start()
×
UNCOV
2599
                srvrLog.Debug("connMgr started")
×
UNCOV
2600

×
UNCOV
2601
                // If peers are specified as a config option, we'll add those
×
UNCOV
2602
                // peers first.
×
UNCOV
2603
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
UNCOV
2604
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
UNCOV
2605
                                peerAddrCfg,
×
UNCOV
2606
                        )
×
UNCOV
2607
                        if err != nil {
×
2608
                                startErr = fmt.Errorf("unable to parse peer "+
×
2609
                                        "pubkey from config: %v", err)
×
2610
                                return
×
2611
                        }
×
UNCOV
2612
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
UNCOV
2613
                        if err != nil {
×
2614
                                startErr = fmt.Errorf("unable to parse peer "+
×
2615
                                        "address provided as a config option: "+
×
2616
                                        "%v", err)
×
2617
                                return
×
2618
                        }
×
2619

UNCOV
2620
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2621
                                IdentityKey: parsedPubkey,
×
UNCOV
2622
                                Address:     addr,
×
UNCOV
2623
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2624
                        }
×
UNCOV
2625

×
UNCOV
2626
                        err = s.ConnectToPeer(
×
UNCOV
2627
                                peerAddr, true,
×
UNCOV
2628
                                s.cfg.ConnectionTimeout,
×
UNCOV
2629
                        )
×
UNCOV
2630
                        if err != nil {
×
2631
                                startErr = fmt.Errorf("unable to connect to "+
×
2632
                                        "peer address provided as a config "+
×
2633
                                        "option: %v", err)
×
2634
                                return
×
2635
                        }
×
2636
                }
2637

2638
                // Subscribe to NodeAnnouncements that advertise new addresses
2639
                // our persistent peers.
UNCOV
2640
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2641
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2642
                                "addr: %v", err)
×
2643

×
2644
                        startErr = err
×
2645
                        return
×
2646
                }
×
2647

2648
                // With all the relevant sub-systems started, we'll now attempt
2649
                // to establish persistent connections to our direct channel
2650
                // collaborators within the network. Before doing so however,
2651
                // we'll prune our set of link nodes found within the database
2652
                // to ensure we don't reconnect to any nodes we no longer have
2653
                // open channels with.
UNCOV
2654
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2655
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2656

×
2657
                        startErr = err
×
2658
                        return
×
2659
                }
×
2660

UNCOV
2661
                if err := s.establishPersistentConnections(ctx); err != nil {
×
2662
                        srvrLog.Errorf("Failed to establish persistent "+
×
2663
                                "connections: %v", err)
×
2664
                }
×
2665

2666
                // setSeedList is a helper function that turns multiple DNS seed
2667
                // server tuples from the command line or config file into the
2668
                // data structure we need and does a basic formal sanity check
2669
                // in the process.
UNCOV
2670
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2671
                        if len(tuples) == 0 {
×
2672
                                return
×
2673
                        }
×
2674

2675
                        result := make([][2]string, len(tuples))
×
2676
                        for idx, tuple := range tuples {
×
2677
                                tuple = strings.TrimSpace(tuple)
×
2678
                                if len(tuple) == 0 {
×
2679
                                        return
×
2680
                                }
×
2681

2682
                                servers := strings.Split(tuple, ",")
×
2683
                                if len(servers) > 2 || len(servers) == 0 {
×
2684
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2685
                                                "seed tuple: %v", servers)
×
2686
                                        return
×
2687
                                }
×
2688

2689
                                copy(result[idx][:], servers)
×
2690
                        }
2691

2692
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2693
                }
2694

2695
                // Let users overwrite the DNS seed nodes. We only allow them
2696
                // for bitcoin mainnet/testnet/signet.
UNCOV
2697
                if s.cfg.Bitcoin.MainNet {
×
2698
                        setSeedList(
×
2699
                                s.cfg.Bitcoin.DNSSeeds,
×
2700
                                chainreg.BitcoinMainnetGenesis,
×
2701
                        )
×
2702
                }
×
UNCOV
2703
                if s.cfg.Bitcoin.TestNet3 {
×
2704
                        setSeedList(
×
2705
                                s.cfg.Bitcoin.DNSSeeds,
×
2706
                                chainreg.BitcoinTestnetGenesis,
×
2707
                        )
×
2708
                }
×
UNCOV
2709
                if s.cfg.Bitcoin.TestNet4 {
×
2710
                        setSeedList(
×
2711
                                s.cfg.Bitcoin.DNSSeeds,
×
2712
                                chainreg.BitcoinTestnet4Genesis,
×
2713
                        )
×
2714
                }
×
UNCOV
2715
                if s.cfg.Bitcoin.SigNet {
×
2716
                        setSeedList(
×
2717
                                s.cfg.Bitcoin.DNSSeeds,
×
2718
                                chainreg.BitcoinSignetGenesis,
×
2719
                        )
×
2720
                }
×
2721

2722
                // If network bootstrapping hasn't been disabled, then we'll
2723
                // configure the set of active bootstrappers, and launch a
2724
                // dedicated goroutine to maintain a set of persistent
2725
                // connections.
UNCOV
2726
                if !s.cfg.NoNetBootstrap {
×
UNCOV
2727
                        bootstrappers, err := initNetworkBootstrappers(s)
×
UNCOV
2728
                        if err != nil {
×
2729
                                startErr = err
×
2730
                                return
×
2731
                        }
×
2732

UNCOV
2733
                        s.wg.Add(1)
×
UNCOV
2734
                        go s.peerBootstrapper(
×
UNCOV
2735
                                ctx, defaultMinPeers, bootstrappers,
×
UNCOV
2736
                        )
×
UNCOV
2737
                } else {
×
UNCOV
2738
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2739
                }
×
2740

2741
                // Start the blockbeat after all other subsystems have been
2742
                // started so they are ready to receive new blocks.
UNCOV
2743
                cleanup = cleanup.add(func() error {
×
2744
                        s.blockbeatDispatcher.Stop()
×
2745
                        return nil
×
2746
                })
×
UNCOV
2747
                if err := s.blockbeatDispatcher.Start(); err != nil {
×
2748
                        startErr = err
×
2749
                        return
×
2750
                }
×
2751

2752
                // Set the active flag now that we've completed the full
2753
                // startup.
UNCOV
2754
                atomic.StoreInt32(&s.active, 1)
×
2755
        })
2756

UNCOV
2757
        if startErr != nil {
×
2758
                cleanup.run()
×
2759
        }
×
UNCOV
2760
        return startErr
×
2761
}
2762

2763
// Stop gracefully shutsdown the main daemon server. This function will signal
2764
// any active goroutines, or helper objects to exit, then blocks until they've
2765
// all successfully exited. Additionally, any/all listeners are closed.
2766
// NOTE: This function is safe for concurrent access.
UNCOV
2767
func (s *server) Stop() error {
×
UNCOV
2768
        s.stop.Do(func() {
×
UNCOV
2769
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2770

×
UNCOV
2771
                ctx := context.Background()
×
UNCOV
2772

×
UNCOV
2773
                close(s.quit)
×
UNCOV
2774

×
UNCOV
2775
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2776
                s.connMgr.Stop()
×
UNCOV
2777

×
UNCOV
2778
                // Stop dispatching blocks to other systems immediately.
×
UNCOV
2779
                s.blockbeatDispatcher.Stop()
×
UNCOV
2780

×
UNCOV
2781
                // Shutdown the wallet, funding manager, and the rpc server.
×
UNCOV
2782
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2783
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2784
                }
×
UNCOV
2785
                if err := s.htlcSwitch.Stop(); err != nil {
×
2786
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2787
                }
×
UNCOV
2788
                if err := s.sphinx.Stop(); err != nil {
×
2789
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2790
                }
×
UNCOV
2791
                if err := s.invoices.Stop(); err != nil {
×
2792
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2793
                }
×
UNCOV
2794
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2795
                        srvrLog.Warnf("failed to stop interceptable "+
×
2796
                                "switch: %v", err)
×
2797
                }
×
UNCOV
2798
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2799
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2800
                                "modifier: %v", err)
×
2801
                }
×
UNCOV
2802
                if err := s.chanRouter.Stop(); err != nil {
×
2803
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2804
                }
×
UNCOV
2805
                if err := s.graphBuilder.Stop(); err != nil {
×
2806
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2807
                }
×
UNCOV
2808
                if err := s.graphDB.Stop(); err != nil {
×
2809
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2810
                }
×
UNCOV
2811
                if err := s.chainArb.Stop(); err != nil {
×
2812
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2813
                }
×
UNCOV
2814
                if err := s.fundingMgr.Stop(); err != nil {
×
2815
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2816
                }
×
UNCOV
2817
                if err := s.breachArbitrator.Stop(); err != nil {
×
2818
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2819
                                err)
×
2820
                }
×
UNCOV
2821
                if err := s.utxoNursery.Stop(); err != nil {
×
2822
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2823
                }
×
UNCOV
2824
                if err := s.authGossiper.Stop(); err != nil {
×
2825
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2826
                }
×
UNCOV
2827
                if err := s.sweeper.Stop(); err != nil {
×
2828
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2829
                }
×
UNCOV
2830
                if err := s.txPublisher.Stop(); err != nil {
×
2831
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2832
                }
×
UNCOV
2833
                if err := s.channelNotifier.Stop(); err != nil {
×
2834
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2835
                }
×
UNCOV
2836
                if err := s.peerNotifier.Stop(); err != nil {
×
2837
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2838
                }
×
UNCOV
2839
                if err := s.htlcNotifier.Stop(); err != nil {
×
2840
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2841
                }
×
2842

2843
                // Update channel.backup file. Make sure to do it before
2844
                // stopping chanSubSwapper.
UNCOV
2845
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2846
                        ctx, s.chanStateDB, s.addrSource,
×
UNCOV
2847
                )
×
UNCOV
2848
                if err != nil {
×
2849
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2850
                                err)
×
UNCOV
2851
                } else {
×
UNCOV
2852
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
UNCOV
2853
                        if err != nil {
×
UNCOV
2854
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2855
                                        "backup failed: %v", err)
×
UNCOV
2856
                        }
×
2857
                }
2858

UNCOV
2859
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2860
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2861
                }
×
UNCOV
2862
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2863
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2864
                }
×
UNCOV
2865
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2866
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2867
                                err)
×
2868
                }
×
UNCOV
2869
                if err := s.chanEventStore.Stop(); err != nil {
×
2870
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2871
                                err)
×
2872
                }
×
UNCOV
2873
                s.missionController.StopStoreTickers()
×
UNCOV
2874

×
UNCOV
2875
                // Disconnect from each active peers to ensure that
×
UNCOV
2876
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2877
                for _, peer := range s.Peers() {
×
UNCOV
2878
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2879
                        if err != nil {
×
2880
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2881
                                        "received error: %v", peer.IdentityKey(),
×
2882
                                        err,
×
2883
                                )
×
2884
                        }
×
2885
                }
2886

2887
                // Now that all connections have been torn down, stop the tower
2888
                // client which will reliably flush all queued states to the
2889
                // tower. If this is halted for any reason, the force quit timer
2890
                // will kick in and abort to allow this method to return.
UNCOV
2891
                if s.towerClientMgr != nil {
×
UNCOV
2892
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2893
                                srvrLog.Warnf("Unable to shut down tower "+
×
2894
                                        "client manager: %v", err)
×
2895
                        }
×
2896
                }
2897

UNCOV
2898
                if s.hostAnn != nil {
×
2899
                        if err := s.hostAnn.Stop(); err != nil {
×
2900
                                srvrLog.Warnf("unable to shut down host "+
×
2901
                                        "annoucner: %v", err)
×
2902
                        }
×
2903
                }
2904

UNCOV
2905
                if s.livenessMonitor != nil {
×
UNCOV
2906
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2907
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2908
                                        "monitor: %v", err)
×
2909
                        }
×
2910
                }
2911

2912
                // Wait for all lingering goroutines to quit.
UNCOV
2913
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2914
                s.wg.Wait()
×
UNCOV
2915

×
UNCOV
2916
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2917
                s.sigPool.Stop()
×
UNCOV
2918
                s.writePool.Stop()
×
UNCOV
2919
                s.readPool.Stop()
×
2920
        })
2921

UNCOV
2922
        return nil
×
2923
}
2924

2925
// Stopped returns true if the server has been instructed to shutdown.
2926
// NOTE: This function is safe for concurrent access.
UNCOV
2927
func (s *server) Stopped() bool {
×
UNCOV
2928
        return atomic.LoadInt32(&s.stopping) != 0
×
UNCOV
2929
}
×
2930

2931
// configurePortForwarding attempts to set up port forwarding for the different
2932
// ports that the server will be listening on.
2933
//
2934
// NOTE: This should only be used when using some kind of NAT traversal to
2935
// automatically set up forwarding rules.
2936
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2937
        ip, err := s.natTraversal.ExternalIP()
×
2938
        if err != nil {
×
2939
                return nil, err
×
2940
        }
×
2941
        s.lastDetectedIP = ip
×
2942

×
2943
        externalIPs := make([]string, 0, len(ports))
×
2944
        for _, port := range ports {
×
2945
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2946
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2947
                        continue
×
2948
                }
2949

2950
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2951
                externalIPs = append(externalIPs, hostIP)
×
2952
        }
2953

2954
        return externalIPs, nil
×
2955
}
2956

2957
// removePortForwarding attempts to clear the forwarding rules for the different
2958
// ports the server is currently listening on.
2959
//
2960
// NOTE: This should only be used when using some kind of NAT traversal to
2961
// automatically set up forwarding rules.
2962
func (s *server) removePortForwarding() {
×
2963
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2964
        for _, port := range forwardedPorts {
×
2965
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2966
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2967
                                "port %d: %v", port, err)
×
2968
                }
×
2969
        }
2970
}
2971

2972
// watchExternalIP continuously checks for an updated external IP address every
2973
// 15 minutes. Once a new IP address has been detected, it will automatically
2974
// handle port forwarding rules and send updated node announcements to the
2975
// currently connected peers.
2976
//
2977
// NOTE: This MUST be run as a goroutine.
2978
func (s *server) watchExternalIP() {
×
2979
        defer s.wg.Done()
×
2980

×
2981
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2982
        // up by the server.
×
2983
        defer s.removePortForwarding()
×
2984

×
2985
        // Keep track of the external IPs set by the user to avoid replacing
×
2986
        // them when detecting a new IP.
×
2987
        ipsSetByUser := make(map[string]struct{})
×
2988
        for _, ip := range s.cfg.ExternalIPs {
×
2989
                ipsSetByUser[ip.String()] = struct{}{}
×
2990
        }
×
2991

2992
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2993

×
2994
        ticker := time.NewTicker(15 * time.Minute)
×
2995
        defer ticker.Stop()
×
2996
out:
×
2997
        for {
×
2998
                select {
×
2999
                case <-ticker.C:
×
3000
                        // We'll start off by making sure a new IP address has
×
3001
                        // been detected.
×
3002
                        ip, err := s.natTraversal.ExternalIP()
×
3003
                        if err != nil {
×
3004
                                srvrLog.Debugf("Unable to retrieve the "+
×
3005
                                        "external IP address: %v", err)
×
3006
                                continue
×
3007
                        }
3008

3009
                        // Periodically renew the NAT port forwarding.
3010
                        for _, port := range forwardedPorts {
×
3011
                                err := s.natTraversal.AddPortMapping(port)
×
3012
                                if err != nil {
×
3013
                                        srvrLog.Warnf("Unable to automatically "+
×
3014
                                                "re-create port forwarding using %s: %v",
×
3015
                                                s.natTraversal.Name(), err)
×
3016
                                } else {
×
3017
                                        srvrLog.Debugf("Automatically re-created "+
×
3018
                                                "forwarding for port %d using %s to "+
×
3019
                                                "advertise external IP",
×
3020
                                                port, s.natTraversal.Name())
×
3021
                                }
×
3022
                        }
3023

3024
                        if ip.Equal(s.lastDetectedIP) {
×
3025
                                continue
×
3026
                        }
3027

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

×
3030
                        // Next, we'll craft the new addresses that will be
×
3031
                        // included in the new node announcement and advertised
×
3032
                        // to the network. Each address will consist of the new
×
3033
                        // IP detected and one of the currently advertised
×
3034
                        // ports.
×
3035
                        var newAddrs []net.Addr
×
3036
                        for _, port := range forwardedPorts {
×
3037
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
3038
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
3039
                                if err != nil {
×
3040
                                        srvrLog.Debugf("Unable to resolve "+
×
3041
                                                "host %v: %v", addr, err)
×
3042
                                        continue
×
3043
                                }
3044

3045
                                newAddrs = append(newAddrs, addr)
×
3046
                        }
3047

3048
                        // Skip the update if we weren't able to resolve any of
3049
                        // the new addresses.
3050
                        if len(newAddrs) == 0 {
×
3051
                                srvrLog.Debug("Skipping node announcement " +
×
3052
                                        "update due to not being able to " +
×
3053
                                        "resolve any new addresses")
×
3054
                                continue
×
3055
                        }
3056

3057
                        // Now, we'll need to update the addresses in our node's
3058
                        // announcement in order to propagate the update
3059
                        // throughout the network. We'll only include addresses
3060
                        // that have a different IP from the previous one, as
3061
                        // the previous IP is no longer valid.
3062
                        currentNodeAnn := s.getNodeAnnouncement()
×
3063

×
3064
                        for _, addr := range currentNodeAnn.Addresses {
×
3065
                                host, _, err := net.SplitHostPort(addr.String())
×
3066
                                if err != nil {
×
3067
                                        srvrLog.Debugf("Unable to determine "+
×
3068
                                                "host from address %v: %v",
×
3069
                                                addr, err)
×
3070
                                        continue
×
3071
                                }
3072

3073
                                // We'll also make sure to include external IPs
3074
                                // set manually by the user.
3075
                                _, setByUser := ipsSetByUser[addr.String()]
×
3076
                                if setByUser || host != s.lastDetectedIP.String() {
×
3077
                                        newAddrs = append(newAddrs, addr)
×
3078
                                }
×
3079
                        }
3080

3081
                        // Then, we'll generate a new timestamped node
3082
                        // announcement with the updated addresses and broadcast
3083
                        // it to our peers.
3084
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3085
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3086
                        )
×
3087
                        if err != nil {
×
3088
                                srvrLog.Debugf("Unable to generate new node "+
×
3089
                                        "announcement: %v", err)
×
3090
                                continue
×
3091
                        }
3092

3093
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3094
                        if err != nil {
×
3095
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3096
                                        "announcement to peers: %v", err)
×
3097
                                continue
×
3098
                        }
3099

3100
                        // Finally, update the last IP seen to the current one.
3101
                        s.lastDetectedIP = ip
×
3102
                case <-s.quit:
×
3103
                        break out
×
3104
                }
3105
        }
3106
}
3107

3108
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3109
// based on the server, and currently active bootstrap mechanisms as defined
3110
// within the current configuration.
UNCOV
3111
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
UNCOV
3112
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
UNCOV
3113

×
UNCOV
3114
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
UNCOV
3115

×
UNCOV
3116
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
UNCOV
3117
        // this can be used by default if we've already partially seeded the
×
UNCOV
3118
        // network.
×
UNCOV
3119
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
UNCOV
3120
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
×
UNCOV
3121
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
×
UNCOV
3122
        )
×
UNCOV
3123
        if err != nil {
×
3124
                return nil, err
×
3125
        }
×
UNCOV
3126
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
UNCOV
3127

×
UNCOV
3128
        // If this isn't using simnet or regtest mode, then one of our
×
UNCOV
3129
        // additional bootstrapping sources will be the set of running DNS
×
UNCOV
3130
        // seeds.
×
UNCOV
3131
        if !s.cfg.Bitcoin.IsLocalNetwork() {
×
3132
                //nolint:ll
×
3133
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3134

×
3135
                // If we have a set of DNS seeds for this chain, then we'll add
×
3136
                // it as an additional bootstrapping source.
×
3137
                if ok {
×
3138
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3139
                                "seeds: %v", dnsSeeds)
×
3140

×
3141
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3142
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3143
                        )
×
3144
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3145
                }
×
3146
        }
3147

UNCOV
3148
        return bootStrappers, nil
×
3149
}
3150

3151
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3152
// needs to ignore, which is made of three parts,
3153
//   - the node itself needs to be skipped as it doesn't make sense to connect
3154
//     to itself.
3155
//   - the peers that already have connections with, as in s.peersByPub.
3156
//   - the peers that we are attempting to connect, as in s.persistentPeers.
UNCOV
3157
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
UNCOV
3158
        s.mu.RLock()
×
UNCOV
3159
        defer s.mu.RUnlock()
×
UNCOV
3160

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

×
UNCOV
3163
        // We should ignore ourselves from bootstrapping.
×
UNCOV
3164
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
UNCOV
3165
        ignore[selfKey] = struct{}{}
×
UNCOV
3166

×
UNCOV
3167
        // Ignore all connected peers.
×
UNCOV
3168
        for _, peer := range s.peersByPub {
×
3169
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3170
                ignore[nID] = struct{}{}
×
3171
        }
×
3172

3173
        // Ignore all persistent peers as they have a dedicated reconnecting
3174
        // process.
UNCOV
3175
        for pubKeyStr := range s.persistentPeers {
×
3176
                var nID autopilot.NodeID
×
3177
                copy(nID[:], []byte(pubKeyStr))
×
3178
                ignore[nID] = struct{}{}
×
3179
        }
×
3180

UNCOV
3181
        return ignore
×
3182
}
3183

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

×
UNCOV
3192
        defer s.wg.Done()
×
UNCOV
3193

×
UNCOV
3194
        // Before we continue, init the ignore peers map.
×
UNCOV
3195
        ignoreList := s.createBootstrapIgnorePeers()
×
UNCOV
3196

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

×
UNCOV
3201
        // Once done, we'll attempt to maintain our target minimum number of
×
UNCOV
3202
        // peers.
×
UNCOV
3203
        //
×
UNCOV
3204
        // We'll use a 15 second backoff, and double the time every time an
×
UNCOV
3205
        // epoch fails up to a ceiling.
×
UNCOV
3206
        backOff := time.Second * 15
×
UNCOV
3207

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

×
UNCOV
3213
        // We'll use the number of attempts and errors to determine if we need
×
UNCOV
3214
        // to increase the time between discovery epochs.
×
UNCOV
3215
        var epochErrors uint32 // To be used atomically.
×
UNCOV
3216
        var epochAttempts uint32
×
UNCOV
3217

×
UNCOV
3218
        for {
×
UNCOV
3219
                select {
×
3220
                // The ticker has just woken us up, so we'll need to check if
3221
                // we need to attempt to connect our to any more peers.
3222
                case <-sampleTicker.C:
×
3223
                        // Obtain the current number of peers, so we can gauge
×
3224
                        // if we need to sample more peers or not.
×
3225
                        s.mu.RLock()
×
3226
                        numActivePeers := uint32(len(s.peersByPub))
×
3227
                        s.mu.RUnlock()
×
3228

×
3229
                        // If we have enough peers, then we can loop back
×
3230
                        // around to the next round as we're done here.
×
3231
                        if numActivePeers >= numTargetPeers {
×
3232
                                continue
×
3233
                        }
3234

3235
                        // If all of our attempts failed during this last back
3236
                        // off period, then will increase our backoff to 5
3237
                        // minute ceiling to avoid an excessive number of
3238
                        // queries
3239
                        //
3240
                        // TODO(roasbeef): add reverse policy too?
3241

3242
                        if epochAttempts > 0 &&
×
3243
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3244

×
3245
                                sampleTicker.Stop()
×
3246

×
3247
                                backOff *= 2
×
3248
                                if backOff > bootstrapBackOffCeiling {
×
3249
                                        backOff = bootstrapBackOffCeiling
×
3250
                                }
×
3251

3252
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3253
                                        "%v", backOff)
×
3254
                                sampleTicker = time.NewTicker(backOff)
×
3255
                                continue
×
3256
                        }
3257

3258
                        atomic.StoreUint32(&epochErrors, 0)
×
3259
                        epochAttempts = 0
×
3260

×
3261
                        // Since we know need more peers, we'll compute the
×
3262
                        // exact number we need to reach our threshold.
×
3263
                        numNeeded := numTargetPeers - numActivePeers
×
3264

×
3265
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3266
                                "peers", numNeeded)
×
3267

×
3268
                        // With the number of peers we need calculated, we'll
×
3269
                        // query the network bootstrappers to sample a set of
×
3270
                        // random addrs for us.
×
3271
                        //
×
3272
                        // Before we continue, get a copy of the ignore peers
×
3273
                        // map.
×
3274
                        ignoreList = s.createBootstrapIgnorePeers()
×
3275

×
3276
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3277
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3278
                        )
×
3279
                        if err != nil {
×
3280
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3281
                                        "peers: %v", err)
×
3282
                                continue
×
3283
                        }
3284

3285
                        // Finally, we'll launch a new goroutine for each
3286
                        // prospective peer candidates.
3287
                        for _, addr := range peerAddrs {
×
3288
                                epochAttempts++
×
3289

×
3290
                                go func(a *lnwire.NetAddress) {
×
3291
                                        // TODO(roasbeef): can do AS, subnet,
×
3292
                                        // country diversity, etc
×
3293
                                        errChan := make(chan error, 1)
×
3294
                                        s.connectToPeer(
×
3295
                                                a, errChan,
×
3296
                                                s.cfg.ConnectionTimeout,
×
3297
                                        )
×
3298
                                        select {
×
3299
                                        case err := <-errChan:
×
3300
                                                if err == nil {
×
3301
                                                        return
×
3302
                                                }
×
3303

3304
                                                srvrLog.Errorf("Unable to "+
×
3305
                                                        "connect to %v: %v",
×
3306
                                                        a, err)
×
3307
                                                atomic.AddUint32(&epochErrors, 1)
×
3308
                                        case <-s.quit:
×
3309
                                        }
3310
                                }(addr)
3311
                        }
UNCOV
3312
                case <-s.quit:
×
UNCOV
3313
                        return
×
3314
                }
3315
        }
3316
}
3317

3318
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3319
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3320
// query back off each time we encounter a failure.
3321
const bootstrapBackOffCeiling = time.Minute * 5
3322

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

×
UNCOV
3330
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
UNCOV
3331
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
UNCOV
3332

×
UNCOV
3333
        // We'll start off by waiting 2 seconds between failed attempts, then
×
UNCOV
3334
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
UNCOV
3335
        var delaySignal <-chan time.Time
×
UNCOV
3336
        delayTime := time.Second * 2
×
UNCOV
3337

×
UNCOV
3338
        // As want to be more aggressive, we'll use a lower back off celling
×
UNCOV
3339
        // then the main peer bootstrap logic.
×
UNCOV
3340
        backOffCeiling := bootstrapBackOffCeiling / 5
×
UNCOV
3341

×
UNCOV
3342
        for attempts := 0; ; attempts++ {
×
UNCOV
3343
                // Check if the server has been requested to shut down in order
×
UNCOV
3344
                // to prevent blocking.
×
UNCOV
3345
                if s.Stopped() {
×
3346
                        return
×
3347
                }
×
3348

3349
                // We can exit our aggressive initial peer bootstrapping stage
3350
                // if we've reached out target number of peers.
UNCOV
3351
                s.mu.RLock()
×
UNCOV
3352
                numActivePeers := uint32(len(s.peersByPub))
×
UNCOV
3353
                s.mu.RUnlock()
×
UNCOV
3354

×
UNCOV
3355
                if numActivePeers >= numTargetPeers {
×
UNCOV
3356
                        return
×
UNCOV
3357
                }
×
3358

UNCOV
3359
                if attempts > 0 {
×
3360
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3361
                                "bootstrap peers (attempt #%v)", delayTime,
×
3362
                                attempts)
×
3363

×
3364
                        // We've completed at least one iterating and haven't
×
3365
                        // finished, so we'll start to insert a delay period
×
3366
                        // between each attempt.
×
3367
                        delaySignal = time.After(delayTime)
×
3368
                        select {
×
3369
                        case <-delaySignal:
×
3370
                        case <-s.quit:
×
3371
                                return
×
3372
                        }
3373

3374
                        // After our delay, we'll double the time we wait up to
3375
                        // the max back off period.
3376
                        delayTime *= 2
×
3377
                        if delayTime > backOffCeiling {
×
3378
                                delayTime = backOffCeiling
×
3379
                        }
×
3380
                }
3381

3382
                // Otherwise, we'll request for the remaining number of peers
3383
                // in order to reach our target.
UNCOV
3384
                peersNeeded := numTargetPeers - numActivePeers
×
UNCOV
3385
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
UNCOV
3386
                        ctx, ignore, peersNeeded, bootstrappers...,
×
UNCOV
3387
                )
×
UNCOV
3388
                if err != nil {
×
3389
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3390
                                "peers: %v", err)
×
3391
                        continue
×
3392
                }
3393

3394
                // Then, we'll attempt to establish a connection to the
3395
                // different peer addresses retrieved by our bootstrappers.
UNCOV
3396
                var wg sync.WaitGroup
×
UNCOV
3397
                for _, bootstrapAddr := range bootstrapAddrs {
×
UNCOV
3398
                        wg.Add(1)
×
UNCOV
3399
                        go func(addr *lnwire.NetAddress) {
×
UNCOV
3400
                                defer wg.Done()
×
UNCOV
3401

×
UNCOV
3402
                                errChan := make(chan error, 1)
×
UNCOV
3403
                                go s.connectToPeer(
×
UNCOV
3404
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
UNCOV
3405
                                )
×
UNCOV
3406

×
UNCOV
3407
                                // We'll only allow this connection attempt to
×
UNCOV
3408
                                // take up to 3 seconds. This allows us to move
×
UNCOV
3409
                                // quickly by discarding peers that are slowing
×
UNCOV
3410
                                // us down.
×
UNCOV
3411
                                select {
×
UNCOV
3412
                                case err := <-errChan:
×
UNCOV
3413
                                        if err == nil {
×
UNCOV
3414
                                                return
×
UNCOV
3415
                                        }
×
3416
                                        srvrLog.Errorf("Unable to connect to "+
×
3417
                                                "%v: %v", addr, err)
×
3418
                                // TODO: tune timeout? 3 seconds might be *too*
3419
                                // aggressive but works well.
3420
                                case <-time.After(3 * time.Second):
×
3421
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3422
                                                "to not establishing a "+
×
3423
                                                "connection within 3 seconds",
×
3424
                                                addr)
×
3425
                                case <-s.quit:
×
3426
                                }
3427
                        }(bootstrapAddr)
3428
                }
3429

UNCOV
3430
                wg.Wait()
×
3431
        }
3432
}
3433

3434
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3435
// order to listen for inbound connections over Tor.
3436
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3437
        // Determine the different ports the server is listening on. The onion
×
3438
        // service's virtual port will map to these ports and one will be picked
×
3439
        // at random when the onion service is being accessed.
×
3440
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3441
        for _, listenAddr := range s.listenAddrs {
×
3442
                port := listenAddr.(*net.TCPAddr).Port
×
3443
                listenPorts = append(listenPorts, port)
×
3444
        }
×
3445

3446
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3447
        if err != nil {
×
3448
                return err
×
3449
        }
×
3450

3451
        // Once the port mapping has been set, we can go ahead and automatically
3452
        // create our onion service. The service's private key will be saved to
3453
        // disk in order to regain access to this service when restarting `lnd`.
3454
        onionCfg := tor.AddOnionConfig{
×
3455
                VirtualPort: defaultPeerPort,
×
3456
                TargetPorts: listenPorts,
×
3457
                Store: tor.NewOnionFile(
×
3458
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3459
                        encrypter,
×
3460
                ),
×
3461
        }
×
3462

×
3463
        switch {
×
3464
        case s.cfg.Tor.V2:
×
3465
                onionCfg.Type = tor.V2
×
3466
        case s.cfg.Tor.V3:
×
3467
                onionCfg.Type = tor.V3
×
3468
        }
3469

3470
        addr, err := s.torController.AddOnion(onionCfg)
×
3471
        if err != nil {
×
3472
                return err
×
3473
        }
×
3474

3475
        // Now that the onion service has been created, we'll add the onion
3476
        // address it can be reached at to our list of advertised addresses.
3477
        newNodeAnn, err := s.genNodeAnnouncement(
×
3478
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3479
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3480
                },
×
3481
        )
3482
        if err != nil {
×
3483
                return fmt.Errorf("unable to generate new node "+
×
3484
                        "announcement: %v", err)
×
3485
        }
×
3486

3487
        // Finally, we'll update the on-disk version of our announcement so it
3488
        // will eventually propagate to nodes in the network.
3489
        selfNode := &models.LightningNode{
×
3490
                HaveNodeAnnouncement: true,
×
3491
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3492
                Addresses:            newNodeAnn.Addresses,
×
3493
                Alias:                newNodeAnn.Alias.String(),
×
3494
                Features: lnwire.NewFeatureVector(
×
3495
                        newNodeAnn.Features, lnwire.Features,
×
3496
                ),
×
3497
                Color:        newNodeAnn.RGBColor,
×
3498
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3499
        }
×
3500
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3501
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3502
                return fmt.Errorf("can't set self node: %w", err)
×
3503
        }
×
3504

3505
        return nil
×
3506
}
3507

3508
// findChannel finds a channel given a public key and ChannelID. It is an
3509
// optimization that is quicker than seeking for a channel given only the
3510
// ChannelID.
3511
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
UNCOV
3512
        *channeldb.OpenChannel, error) {
×
UNCOV
3513

×
UNCOV
3514
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3515
        if err != nil {
×
3516
                return nil, err
×
3517
        }
×
3518

UNCOV
3519
        for _, channel := range nodeChans {
×
UNCOV
3520
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3521
                        return channel, nil
×
UNCOV
3522
                }
×
3523
        }
3524

UNCOV
3525
        return nil, fmt.Errorf("unable to find channel")
×
3526
}
3527

3528
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3529
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3530
        s.mu.Lock()
×
UNCOV
3531
        defer s.mu.Unlock()
×
UNCOV
3532

×
UNCOV
3533
        return *s.currentNodeAnn
×
UNCOV
3534
}
×
3535

3536
// genNodeAnnouncement generates and returns the current fully signed node
3537
// announcement. The time stamp of the announcement will be updated in order
3538
// to ensure it propagates through the network.
3539
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3540
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3541

×
UNCOV
3542
        s.mu.Lock()
×
UNCOV
3543
        defer s.mu.Unlock()
×
UNCOV
3544

×
UNCOV
3545
        // Create a shallow copy of the current node announcement to work on.
×
UNCOV
3546
        // This ensures the original announcement remains unchanged
×
UNCOV
3547
        // until the new announcement is fully signed and valid.
×
UNCOV
3548
        newNodeAnn := *s.currentNodeAnn
×
UNCOV
3549

×
UNCOV
3550
        // First, try to update our feature manager with the updated set of
×
UNCOV
3551
        // features.
×
UNCOV
3552
        if features != nil {
×
UNCOV
3553
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3554
                        feature.SetNodeAnn: features,
×
UNCOV
3555
                }
×
UNCOV
3556
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3557
                if err != nil {
×
UNCOV
3558
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3559
                }
×
3560

3561
                // If we could successfully update our feature manager, add
3562
                // an update modifier to include these new features to our
3563
                // set.
UNCOV
3564
                modifiers = append(
×
UNCOV
3565
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3566
                )
×
3567
        }
3568

3569
        // Always update the timestamp when refreshing to ensure the update
3570
        // propagates.
UNCOV
3571
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3572

×
UNCOV
3573
        // Apply the requested changes to the node announcement.
×
UNCOV
3574
        for _, modifier := range modifiers {
×
UNCOV
3575
                modifier(&newNodeAnn)
×
UNCOV
3576
        }
×
3577

3578
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3579
        err := netann.SignNodeAnnouncement(
×
UNCOV
3580
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
UNCOV
3581
        )
×
UNCOV
3582
        if err != nil {
×
3583
                return lnwire.NodeAnnouncement{}, err
×
3584
        }
×
3585

3586
        // If signing succeeds, update the current announcement.
UNCOV
3587
        *s.currentNodeAnn = newNodeAnn
×
UNCOV
3588

×
UNCOV
3589
        return *s.currentNodeAnn, nil
×
3590
}
3591

3592
// updateAndBroadcastSelfNode generates a new node announcement
3593
// applying the giving modifiers and updating the time stamp
3594
// to ensure it propagates through the network. Then it broadcasts
3595
// it to the network.
3596
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3597
        features *lnwire.RawFeatureVector,
UNCOV
3598
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3599

×
UNCOV
3600
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3601
        if err != nil {
×
UNCOV
3602
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3603
                        "announcement: %v", err)
×
UNCOV
3604
        }
×
3605

3606
        // Update the on-disk version of our announcement.
3607
        // Load and modify self node istead of creating anew instance so we
3608
        // don't risk overwriting any existing values.
UNCOV
3609
        selfNode, err := s.graphDB.SourceNode(ctx)
×
UNCOV
3610
        if err != nil {
×
3611
                return fmt.Errorf("unable to get current source node: %w", err)
×
3612
        }
×
3613

UNCOV
3614
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3615
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3616
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3617
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3618
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3619
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3620
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3621

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

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

3628
        // Finally, propagate it to the nodes in the network.
UNCOV
3629
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3630
        if err != nil {
×
3631
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3632
                        "announcement to peers: %v", err)
×
3633
                return err
×
3634
        }
×
3635

UNCOV
3636
        return nil
×
3637
}
3638

3639
type nodeAddresses struct {
3640
        pubKey    *btcec.PublicKey
3641
        addresses []net.Addr
3642
}
3643

3644
// establishPersistentConnections attempts to establish persistent connections
3645
// to all our direct channel collaborators. In order to promote liveness of our
3646
// active channels, we instruct the connection manager to attempt to establish
3647
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3648
func (s *server) establishPersistentConnections(ctx context.Context) error {
×
UNCOV
3649
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3650
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3651
        // since other PubKey forms can't be compared.
×
UNCOV
3652
        nodeAddrsMap := make(map[string]*nodeAddresses)
×
UNCOV
3653

×
UNCOV
3654
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3655
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3656
        // the reconnection port to the default peer port.
×
UNCOV
3657
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3658
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
×
3659
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3660
        }
×
3661

UNCOV
3662
        for _, node := range linkNodes {
×
UNCOV
3663
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3664
                nodeAddrs := &nodeAddresses{
×
UNCOV
3665
                        pubKey:    node.IdentityPub,
×
UNCOV
3666
                        addresses: node.Addresses,
×
UNCOV
3667
                }
×
UNCOV
3668
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3669
        }
×
3670

3671
        // After checking our previous connections for addresses to connect to,
3672
        // iterate through the nodes in our channel graph to find addresses
3673
        // that have been added via NodeAnnouncement messages.
3674
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3675
        // each of the nodes.
UNCOV
3676
        graphAddrs := make(map[string]*nodeAddresses)
×
UNCOV
3677
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
×
UNCOV
3678
                havePolicy bool, channelPeer *models.LightningNode) error {
×
UNCOV
3679

×
UNCOV
3680
                // If the remote party has announced the channel to us, but we
×
UNCOV
3681
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3682
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3683
                if !havePolicy {
×
3684
                        srvrLog.Warnf("No channel policy found for "+
×
3685
                                "ChannelPoint(%v): ", chanPoint)
×
3686
                }
×
3687

UNCOV
3688
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3689

×
UNCOV
3690
                // Add all unique addresses from channel
×
UNCOV
3691
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3692
                // connect to for this peer.
×
UNCOV
3693
                addrSet := make(map[string]net.Addr)
×
UNCOV
3694
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3695
                        switch addr.(type) {
×
UNCOV
3696
                        case *net.TCPAddr:
×
UNCOV
3697
                                addrSet[addr.String()] = addr
×
3698

3699
                        // We'll only attempt to connect to Tor addresses if Tor
3700
                        // outbound support is enabled.
3701
                        case *tor.OnionAddr:
×
3702
                                if s.cfg.Tor.Active {
×
3703
                                        addrSet[addr.String()] = addr
×
3704
                                }
×
3705
                        }
3706
                }
3707

3708
                // If this peer is also recorded as a link node, we'll add any
3709
                // additional addresses that have not already been selected.
UNCOV
3710
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3711
                if ok {
×
UNCOV
3712
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3713
                                switch lnAddress.(type) {
×
UNCOV
3714
                                case *net.TCPAddr:
×
UNCOV
3715
                                        addrSet[lnAddress.String()] = lnAddress
×
3716

3717
                                // We'll only attempt to connect to Tor
3718
                                // addresses if Tor outbound support is enabled.
3719
                                case *tor.OnionAddr:
×
3720
                                        if s.cfg.Tor.Active {
×
3721
                                                //nolint:ll
×
3722
                                                addrSet[lnAddress.String()] = lnAddress
×
3723
                                        }
×
3724
                                }
3725
                        }
3726
                }
3727

3728
                // Construct a slice of the deduped addresses.
UNCOV
3729
                var addrs []net.Addr
×
UNCOV
3730
                for _, addr := range addrSet {
×
UNCOV
3731
                        addrs = append(addrs, addr)
×
UNCOV
3732
                }
×
3733

UNCOV
3734
                n := &nodeAddresses{
×
UNCOV
3735
                        addresses: addrs,
×
UNCOV
3736
                }
×
UNCOV
3737
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3738
                if err != nil {
×
3739
                        return err
×
3740
                }
×
3741

UNCOV
3742
                graphAddrs[pubStr] = n
×
UNCOV
3743
                return nil
×
3744
        }
UNCOV
3745
        err = s.graphDB.ForEachSourceNodeChannel(
×
UNCOV
3746
                ctx, forEachSrcNodeChan, func() {
×
UNCOV
3747
                        clear(graphAddrs)
×
UNCOV
3748
                },
×
3749
        )
UNCOV
3750
        if err != nil {
×
3751
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3752
                        "%v", err)
×
3753

×
3754
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3755
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3756

×
3757
                        return err
×
3758
                }
×
3759
        }
3760

3761
        // Combine the addresses from the link nodes and the channel graph.
UNCOV
3762
        for pubStr, nodeAddr := range graphAddrs {
×
UNCOV
3763
                nodeAddrsMap[pubStr] = nodeAddr
×
UNCOV
3764
        }
×
3765

UNCOV
3766
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3767
                len(nodeAddrsMap))
×
UNCOV
3768

×
UNCOV
3769
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3770
        // have been recorded and sent to the connection manager.
×
UNCOV
3771
        s.mu.Lock()
×
UNCOV
3772
        defer s.mu.Unlock()
×
UNCOV
3773

×
UNCOV
3774
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3775
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3776
        var numOutboundConns int
×
UNCOV
3777
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3778
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3779
                // persistent connection with. We set the value to false to
×
UNCOV
3780
                // indicate that we should not continue to reconnect if the
×
UNCOV
3781
                // number of channels returns to zero, since this peer has not
×
UNCOV
3782
                // been requested as perm by the user.
×
UNCOV
3783
                s.persistentPeers[pubStr] = false
×
UNCOV
3784
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
UNCOV
3785
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
UNCOV
3786
                }
×
3787

UNCOV
3788
                for _, address := range nodeAddr.addresses {
×
UNCOV
3789
                        // Create a wrapper address which couples the IP and
×
UNCOV
3790
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3791
                        // can be established.
×
UNCOV
3792
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3793
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3794
                                Address:     address,
×
UNCOV
3795
                        }
×
UNCOV
3796

×
UNCOV
3797
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3798
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3799
                }
×
3800

3801
                // We'll connect to the first 10 peers immediately, then
3802
                // randomly stagger any remaining connections if the
3803
                // stagger initial reconnect flag is set. This ensures
3804
                // that mobile nodes or nodes with a small number of
3805
                // channels obtain connectivity quickly, but larger
3806
                // nodes are able to disperse the costs of connecting to
3807
                // all peers at once.
UNCOV
3808
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3809
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3810

×
UNCOV
3811
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3812
                } else {
×
3813
                        go s.delayInitialReconnect(pubStr)
×
3814
                }
×
3815

UNCOV
3816
                numOutboundConns++
×
3817
        }
3818

UNCOV
3819
        return nil
×
3820
}
3821

3822
// delayInitialReconnect will attempt a reconnection to the given peer after
3823
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3824
//
3825
// NOTE: This method MUST be run as a goroutine.
3826
func (s *server) delayInitialReconnect(pubStr string) {
×
3827
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3828
        select {
×
3829
        case <-time.After(delay):
×
3830
                s.connectToPersistentPeer(pubStr)
×
3831
        case <-s.quit:
×
3832
        }
3833
}
3834

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

×
UNCOV
3841
        s.mu.Lock()
×
UNCOV
3842
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3843
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3844
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3845
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3846
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3847
                s.mu.Unlock()
×
UNCOV
3848

×
UNCOV
3849
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3850
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3851

×
UNCOV
3852
                return
×
UNCOV
3853
        }
×
UNCOV
3854
        s.mu.Unlock()
×
3855
}
3856

3857
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3858
// is instead used to remove persistent peer state for a peer that has been
3859
// disconnected for good cause by the server. Currently, a gossip ban from
3860
// sending garbage and the server running out of restricted-access
3861
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3862
// future, this function may expand when more ban criteria is added.
3863
//
3864
// NOTE: The server's write lock MUST be held when this is called.
3865
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3866
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3867
                delete(s.persistentPeers, remotePub)
×
3868
                delete(s.persistentPeersBackoff, remotePub)
×
3869
                delete(s.persistentPeerAddrs, remotePub)
×
3870
                s.cancelConnReqs(remotePub, nil)
×
3871
        }
×
3872
}
3873

3874
// BroadcastMessage sends a request to the server to broadcast a set of
3875
// messages to all peers other than the one specified by the `skips` parameter.
3876
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3877
// the target peers.
3878
//
3879
// NOTE: This function is safe for concurrent access.
3880
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3881
        msgs ...lnwire.Message) error {
×
UNCOV
3882

×
UNCOV
3883
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3884
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3885
        // exact set of peers present at the time of invocation.
×
UNCOV
3886
        s.mu.RLock()
×
UNCOV
3887
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3888
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3889
                if skips != nil {
×
UNCOV
3890
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3891
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3892
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
UNCOV
3893
                                continue
×
3894
                        }
3895
                }
3896

UNCOV
3897
                peers = append(peers, sPeer)
×
3898
        }
UNCOV
3899
        s.mu.RUnlock()
×
UNCOV
3900

×
UNCOV
3901
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3902
        // all messages to each of peers.
×
UNCOV
3903
        var wg sync.WaitGroup
×
UNCOV
3904
        for _, sPeer := range peers {
×
UNCOV
3905
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3906
                        sPeer.PubKey())
×
UNCOV
3907

×
UNCOV
3908
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3909
                wg.Add(1)
×
UNCOV
3910
                s.wg.Add(1)
×
UNCOV
3911
                go func(p lnpeer.Peer) {
×
UNCOV
3912
                        defer s.wg.Done()
×
UNCOV
3913
                        defer wg.Done()
×
UNCOV
3914

×
UNCOV
3915
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3916
                }(sPeer)
×
3917
        }
3918

3919
        // Wait for all messages to have been dispatched before returning to
3920
        // caller.
UNCOV
3921
        wg.Wait()
×
UNCOV
3922

×
UNCOV
3923
        return nil
×
3924
}
3925

3926
// NotifyWhenOnline can be called by other subsystems to get notified when a
3927
// particular peer comes online. The peer itself is sent across the peerChan.
3928
//
3929
// NOTE: This function is safe for concurrent access.
3930
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3931
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3932

×
UNCOV
3933
        s.mu.Lock()
×
UNCOV
3934

×
UNCOV
3935
        // Compute the target peer's identifier.
×
UNCOV
3936
        pubStr := string(peerKey[:])
×
UNCOV
3937

×
UNCOV
3938
        // Check if peer is connected.
×
UNCOV
3939
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3940
        if ok {
×
UNCOV
3941
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3942
                // waiting for the peer to become active.
×
UNCOV
3943
                s.mu.Unlock()
×
UNCOV
3944

×
UNCOV
3945
                // Wait until the peer signals that it is actually active
×
UNCOV
3946
                // rather than only in the server's maps.
×
UNCOV
3947
                select {
×
UNCOV
3948
                case <-peer.ActiveSignal():
×
UNCOV
3949
                case <-peer.QuitSignal():
×
UNCOV
3950
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3951
                        // and return.
×
UNCOV
3952
                        s.mu.Lock()
×
UNCOV
3953
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3954
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3955
                        )
×
UNCOV
3956
                        s.mu.Unlock()
×
UNCOV
3957
                        return
×
3958
                }
3959

3960
                // Connected, can return early.
UNCOV
3961
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3962

×
UNCOV
3963
                select {
×
UNCOV
3964
                case peerChan <- peer:
×
3965
                case <-s.quit:
×
3966
                }
3967

UNCOV
3968
                return
×
3969
        }
3970

3971
        // Not connected, store this listener such that it can be notified when
3972
        // the peer comes online.
UNCOV
3973
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3974
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3975
        )
×
UNCOV
3976
        s.mu.Unlock()
×
3977
}
3978

3979
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3980
// the given public key has been disconnected. The notification is signaled by
3981
// closing the channel returned.
UNCOV
3982
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3983
        s.mu.Lock()
×
UNCOV
3984
        defer s.mu.Unlock()
×
UNCOV
3985

×
UNCOV
3986
        c := make(chan struct{})
×
UNCOV
3987

×
UNCOV
3988
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3989
        // notification.
×
UNCOV
3990
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3991
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3992
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3993
                close(c)
×
3994
                return c
×
3995
        }
×
3996

3997
        // Otherwise, the peer is online, so we'll keep track of the channel to
3998
        // trigger the notification once the server detects the peer
3999
        // disconnects.
UNCOV
4000
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
4001
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
4002
        )
×
UNCOV
4003

×
UNCOV
4004
        return c
×
4005
}
4006

4007
// FindPeer will return the peer that corresponds to the passed in public key.
4008
// This function is used by the funding manager, allowing it to update the
4009
// daemon's local representation of the remote peer.
4010
//
4011
// NOTE: This function is safe for concurrent access.
UNCOV
4012
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
4013
        s.mu.RLock()
×
UNCOV
4014
        defer s.mu.RUnlock()
×
UNCOV
4015

×
UNCOV
4016
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
4017

×
UNCOV
4018
        return s.findPeerByPubStr(pubStr)
×
UNCOV
4019
}
×
4020

4021
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
4022
// which should be a string representation of the peer's serialized, compressed
4023
// public key.
4024
//
4025
// NOTE: This function is safe for concurrent access.
UNCOV
4026
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
4027
        s.mu.RLock()
×
UNCOV
4028
        defer s.mu.RUnlock()
×
UNCOV
4029

×
UNCOV
4030
        return s.findPeerByPubStr(pubStr)
×
UNCOV
4031
}
×
4032

4033
// findPeerByPubStr is an internal method that retrieves the specified peer from
4034
// the server's internal state using.
UNCOV
4035
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
4036
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
4037
        if !ok {
×
UNCOV
4038
                return nil, ErrPeerNotConnected
×
UNCOV
4039
        }
×
4040

UNCOV
4041
        return peer, nil
×
4042
}
4043

4044
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
4045
// exponential backoff. If no previous backoff was known, the default is
4046
// returned.
4047
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
4048
        startTime time.Time) time.Duration {
×
UNCOV
4049

×
UNCOV
4050
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
4051
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
4052
        if !ok {
×
UNCOV
4053
                // If an existing backoff was unknown, use the default.
×
UNCOV
4054
                return s.cfg.MinBackoff
×
UNCOV
4055
        }
×
4056

4057
        // If the peer failed to start properly, we'll just use the previous
4058
        // backoff to compute the subsequent randomized exponential backoff
4059
        // duration. This will roughly double on average.
UNCOV
4060
        if startTime.IsZero() {
×
4061
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4062
        }
×
4063

4064
        // The peer succeeded in starting. If the connection didn't last long
4065
        // enough to be considered stable, we'll continue to back off retries
4066
        // with this peer.
UNCOV
4067
        connDuration := time.Since(startTime)
×
UNCOV
4068
        if connDuration < defaultStableConnDuration {
×
UNCOV
4069
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
4070
        }
×
4071

4072
        // The peer succeed in starting and this was stable peer, so we'll
4073
        // reduce the timeout duration by the length of the connection after
4074
        // applying randomized exponential backoff. We'll only apply this in the
4075
        // case that:
4076
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4077
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4078
        if relaxedBackoff > s.cfg.MinBackoff {
×
4079
                return relaxedBackoff
×
4080
        }
×
4081

4082
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4083
        // the stable connection lasted much longer than our previous backoff.
4084
        // To reward such good behavior, we'll reconnect after the default
4085
        // timeout.
4086
        return s.cfg.MinBackoff
×
4087
}
4088

4089
// shouldDropLocalConnection determines if our local connection to a remote peer
4090
// should be dropped in the case of concurrent connection establishment. In
4091
// order to deterministically decide which connection should be dropped, we'll
4092
// utilize the ordering of the local and remote public key. If we didn't use
4093
// such a tie breaker, then we risk _both_ connections erroneously being
4094
// dropped.
4095
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4096
        localPubBytes := local.SerializeCompressed()
×
4097
        remotePubPbytes := remote.SerializeCompressed()
×
4098

×
4099
        // The connection that comes from the node with a "smaller" pubkey
×
4100
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4101
        // should drop our established connection.
×
4102
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4103
}
×
4104

4105
// InboundPeerConnected initializes a new peer in response to a new inbound
4106
// connection.
4107
//
4108
// NOTE: This function is safe for concurrent access.
UNCOV
4109
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
4110
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
4111
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
4112
        if s.Stopped() {
×
4113
                return
×
4114
        }
×
4115

UNCOV
4116
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4117
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4118
        pubStr := string(pubSer)
×
UNCOV
4119

×
UNCOV
4120
        var pubBytes [33]byte
×
UNCOV
4121
        copy(pubBytes[:], pubSer)
×
UNCOV
4122

×
UNCOV
4123
        s.mu.Lock()
×
UNCOV
4124
        defer s.mu.Unlock()
×
UNCOV
4125

×
UNCOV
4126
        // If we already have an outbound connection to this peer, then ignore
×
UNCOV
4127
        // this new connection.
×
UNCOV
4128
        if p, ok := s.outboundPeers[pubStr]; ok {
×
UNCOV
4129
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
UNCOV
4130
                        "ignoring inbound connection from local=%v, remote=%v",
×
UNCOV
4131
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4132

×
UNCOV
4133
                conn.Close()
×
UNCOV
4134
                return
×
UNCOV
4135
        }
×
4136

4137
        // If we already have a valid connection that is scheduled to take
4138
        // precedence once the prior peer has finished disconnecting, we'll
4139
        // ignore this connection.
UNCOV
4140
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4141
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4142
                        "scheduled", conn.RemoteAddr(), p)
×
4143
                conn.Close()
×
4144
                return
×
4145
        }
×
4146

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

×
UNCOV
4149
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
4150
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
4151
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
4152
        // default case as we expect these to be the only error values returned
×
UNCOV
4153
        // from findPeerByPubStr.
×
UNCOV
4154
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4155
        switch err {
×
UNCOV
4156
        case ErrPeerNotConnected:
×
UNCOV
4157
                // We were unable to locate an existing connection with the
×
UNCOV
4158
                // target peer, proceed to connect.
×
UNCOV
4159
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4160
                s.peerConnected(conn, nil, true)
×
4161

UNCOV
4162
        case nil:
×
UNCOV
4163
                ctx := btclog.WithCtx(
×
UNCOV
4164
                        context.TODO(),
×
UNCOV
4165
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
4166
                )
×
UNCOV
4167

×
UNCOV
4168
                // We already have a connection with the incoming peer. If the
×
UNCOV
4169
                // connection we've already established should be kept and is
×
UNCOV
4170
                // not of the same type of the new connection (inbound), then
×
UNCOV
4171
                // we'll close out the new connection s.t there's only a single
×
UNCOV
4172
                // connection between us.
×
UNCOV
4173
                localPub := s.identityECDH.PubKey()
×
UNCOV
4174
                if !connectedPeer.Inbound() &&
×
UNCOV
4175
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4176

×
4177
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4178
                                "peer, but already have outbound "+
×
4179
                                "connection, dropping conn",
×
4180
                                fmt.Errorf("already have outbound conn"))
×
4181
                        conn.Close()
×
4182
                        return
×
4183
                }
×
4184

4185
                // Otherwise, if we should drop the connection, then we'll
4186
                // disconnect our already connected peer.
UNCOV
4187
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
4188

×
UNCOV
4189
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4190

×
UNCOV
4191
                // Remove the current peer from the server's internal state and
×
UNCOV
4192
                // signal that the peer termination watcher does not need to
×
UNCOV
4193
                // execute for this peer.
×
UNCOV
4194
                s.removePeerUnsafe(ctx, connectedPeer)
×
UNCOV
4195
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
4196
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
4197
                        s.peerConnected(conn, nil, true)
×
UNCOV
4198
                }
×
4199
        }
4200
}
4201

4202
// OutboundPeerConnected initializes a new peer in response to a new outbound
4203
// connection.
4204
// NOTE: This function is safe for concurrent access.
UNCOV
4205
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
UNCOV
4206
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
4207
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
4208
        if s.Stopped() {
×
4209
                return
×
4210
        }
×
4211

UNCOV
4212
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4213
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4214
        pubStr := string(pubSer)
×
UNCOV
4215

×
UNCOV
4216
        var pubBytes [33]byte
×
UNCOV
4217
        copy(pubBytes[:], pubSer)
×
UNCOV
4218

×
UNCOV
4219
        s.mu.Lock()
×
UNCOV
4220
        defer s.mu.Unlock()
×
UNCOV
4221

×
UNCOV
4222
        // If we already have an inbound connection to this peer, then ignore
×
UNCOV
4223
        // this new connection.
×
UNCOV
4224
        if p, ok := s.inboundPeers[pubStr]; ok {
×
UNCOV
4225
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
UNCOV
4226
                        "ignoring outbound connection from local=%v, remote=%v",
×
UNCOV
4227
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4228

×
UNCOV
4229
                if connReq != nil {
×
UNCOV
4230
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4231
                }
×
UNCOV
4232
                conn.Close()
×
UNCOV
4233
                return
×
4234
        }
UNCOV
4235
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4236
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4237
                s.connMgr.Remove(connReq.ID())
×
4238
                conn.Close()
×
4239
                return
×
4240
        }
×
4241

4242
        // If we already have a valid connection that is scheduled to take
4243
        // precedence once the prior peer has finished disconnecting, we'll
4244
        // ignore this connection.
UNCOV
4245
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4246
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4247

×
4248
                if connReq != nil {
×
4249
                        s.connMgr.Remove(connReq.ID())
×
4250
                }
×
4251

4252
                conn.Close()
×
4253
                return
×
4254
        }
4255

UNCOV
4256
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
UNCOV
4257
                conn.RemoteAddr())
×
UNCOV
4258

×
UNCOV
4259
        if connReq != nil {
×
UNCOV
4260
                // A successful connection was returned by the connmgr.
×
UNCOV
4261
                // Immediately cancel all pending requests, excluding the
×
UNCOV
4262
                // outbound connection we just established.
×
UNCOV
4263
                ignore := connReq.ID()
×
UNCOV
4264
                s.cancelConnReqs(pubStr, &ignore)
×
UNCOV
4265
        } else {
×
UNCOV
4266
                // This was a successful connection made by some other
×
UNCOV
4267
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
4268
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4269
        }
×
4270

4271
        // If we already have a connection with this peer, decide whether or not
4272
        // we need to drop the stale connection. We forgo adding a default case
4273
        // as we expect these to be the only error values returned from
4274
        // findPeerByPubStr.
UNCOV
4275
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4276
        switch err {
×
UNCOV
4277
        case ErrPeerNotConnected:
×
UNCOV
4278
                // We were unable to locate an existing connection with the
×
UNCOV
4279
                // target peer, proceed to connect.
×
UNCOV
4280
                s.peerConnected(conn, connReq, false)
×
4281

UNCOV
4282
        case nil:
×
UNCOV
4283
                ctx := btclog.WithCtx(
×
UNCOV
4284
                        context.TODO(),
×
UNCOV
4285
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
UNCOV
4286
                )
×
UNCOV
4287

×
UNCOV
4288
                // We already have a connection with the incoming peer. If the
×
UNCOV
4289
                // connection we've already established should be kept and is
×
UNCOV
4290
                // not of the same type of the new connection (outbound), then
×
UNCOV
4291
                // we'll close out the new connection s.t there's only a single
×
UNCOV
4292
                // connection between us.
×
UNCOV
4293
                localPub := s.identityECDH.PubKey()
×
UNCOV
4294
                if connectedPeer.Inbound() &&
×
UNCOV
4295
                        shouldDropLocalConnection(localPub, nodePub) {
×
4296

×
4297
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4298
                                "to peer, but already have inbound "+
×
4299
                                "connection, dropping conn",
×
4300
                                fmt.Errorf("already have inbound conn"))
×
4301
                        if connReq != nil {
×
4302
                                s.connMgr.Remove(connReq.ID())
×
4303
                        }
×
4304
                        conn.Close()
×
4305
                        return
×
4306
                }
4307

4308
                // Otherwise, _their_ connection should be dropped. So we'll
4309
                // disconnect the peer and send the now obsolete peer to the
4310
                // server for garbage collection.
UNCOV
4311
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
UNCOV
4312

×
UNCOV
4313
                // Remove the current peer from the server's internal state and
×
UNCOV
4314
                // signal that the peer termination watcher does not need to
×
UNCOV
4315
                // execute for this peer.
×
UNCOV
4316
                s.removePeerUnsafe(ctx, connectedPeer)
×
UNCOV
4317
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
4318
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
4319
                        s.peerConnected(conn, connReq, false)
×
UNCOV
4320
                }
×
4321
        }
4322
}
4323

4324
// UnassignedConnID is the default connection ID that a request can have before
4325
// it actually is submitted to the connmgr.
4326
// TODO(conner): move into connmgr package, or better, add connmgr method for
4327
// generating atomic IDs
4328
const UnassignedConnID uint64 = 0
4329

4330
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4331
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4332
// Afterwards, each connection request removed from the connmgr. The caller can
4333
// optionally specify a connection ID to ignore, which prevents us from
4334
// canceling a successful request. All persistent connreqs for the provided
4335
// pubkey are discarded after the operationjw.
UNCOV
4336
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
4337
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
4338
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
4339
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
4340
                close(cancelChan)
×
UNCOV
4341
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
4342
        }
×
4343

4344
        // Next, check to see if we have any outstanding persistent connection
4345
        // requests to this peer. If so, then we'll remove all of these
4346
        // connection requests, and also delete the entry from the map.
UNCOV
4347
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4348
        if !ok {
×
UNCOV
4349
                return
×
UNCOV
4350
        }
×
4351

UNCOV
4352
        for _, connReq := range connReqs {
×
UNCOV
4353
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4354

×
UNCOV
4355
                // Atomically capture the current request identifier.
×
UNCOV
4356
                connID := connReq.ID()
×
UNCOV
4357

×
UNCOV
4358
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4359
                // yet been schedule.
×
UNCOV
4360
                if connID == UnassignedConnID {
×
4361
                        continue
×
4362
                }
4363

4364
                // Skip a particular connection ID if instructed.
UNCOV
4365
                if skip != nil && connID == *skip {
×
UNCOV
4366
                        continue
×
4367
                }
4368

UNCOV
4369
                s.connMgr.Remove(connID)
×
4370
        }
4371

UNCOV
4372
        delete(s.persistentConnReqs, pubStr)
×
4373
}
4374

4375
// handleCustomMessage dispatches an incoming custom peers message to
4376
// subscribers.
UNCOV
4377
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4378
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4379
                peer, msg.Type)
×
UNCOV
4380

×
UNCOV
4381
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4382
                Peer: peer,
×
UNCOV
4383
                Msg:  msg,
×
UNCOV
4384
        })
×
UNCOV
4385
}
×
4386

4387
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4388
// messages.
UNCOV
4389
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4390
        return s.customMessageServer.Subscribe()
×
UNCOV
4391
}
×
4392

4393
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4394
// the channelNotifier's NotifyOpenChannelEvent.
4395
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
UNCOV
4396
        remotePub *btcec.PublicKey) {
×
UNCOV
4397

×
UNCOV
4398
        // Call newOpenChan to update the access manager's maps for this peer.
×
UNCOV
4399
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
×
UNCOV
4400
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
UNCOV
4401
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
×
UNCOV
4402
        }
×
4403

4404
        // Notify subscribers about this open channel event.
UNCOV
4405
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4406
}
4407

4408
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4409
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4410
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
UNCOV
4411
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
×
UNCOV
4412

×
UNCOV
4413
        // Call newPendingOpenChan to update the access manager's maps for this
×
UNCOV
4414
        // peer.
×
UNCOV
4415
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
×
4416
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4417
                        "channel[%v] pending open",
×
4418
                        remotePub.SerializeCompressed(), op)
×
4419
        }
×
4420

4421
        // Notify subscribers about this event.
UNCOV
4422
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4423
}
4424

4425
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4426
// calls the channelNotifier's NotifyFundingTimeout.
4427
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
UNCOV
4428
        remotePub *btcec.PublicKey) {
×
UNCOV
4429

×
UNCOV
4430
        // Call newPendingCloseChan to potentially demote the peer.
×
UNCOV
4431
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
UNCOV
4432
        if err != nil {
×
4433
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4434
                        "channel[%v] pending close",
×
4435
                        remotePub.SerializeCompressed(), op)
×
4436
        }
×
4437

UNCOV
4438
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
×
4439
                // If we encounter an error while attempting to disconnect the
×
4440
                // peer, log the error.
×
4441
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4442
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4443
                }
×
4444
        }
4445

4446
        // Notify subscribers about this event.
UNCOV
4447
        s.channelNotifier.NotifyFundingTimeout(op)
×
4448
}
4449

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

×
UNCOV
4457
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4458
        addr := conn.RemoteAddr()
×
UNCOV
4459
        pubKey := brontideConn.RemotePub()
×
UNCOV
4460

×
UNCOV
4461
        // Only restrict access for inbound connections, which means if the
×
UNCOV
4462
        // remote node's public key is banned or the restricted slots are used
×
UNCOV
4463
        // up, we will drop the connection.
×
UNCOV
4464
        //
×
UNCOV
4465
        // TODO(yy): Consider perform this check in
×
UNCOV
4466
        // `peerAccessMan.addPeerAccess`.
×
UNCOV
4467
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
×
UNCOV
4468
        if inbound && err != nil {
×
4469
                pubSer := pubKey.SerializeCompressed()
×
4470

×
4471
                // Clean up the persistent peer maps if we're dropping this
×
4472
                // connection.
×
4473
                s.bannedPersistentPeerConnection(string(pubSer))
×
4474

×
4475
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4476
                        "of restricted-access connection slots: %v.", pubSer,
×
4477
                        err)
×
4478

×
4479
                conn.Close()
×
4480

×
4481
                return
×
4482
        }
×
4483

UNCOV
4484
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4485
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4486

×
UNCOV
4487
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4488
                IdentityKey: pubKey,
×
UNCOV
4489
                Address:     addr,
×
UNCOV
4490
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4491
        }
×
UNCOV
4492

×
UNCOV
4493
        // With the brontide connection established, we'll now craft the feature
×
UNCOV
4494
        // vectors to advertise to the remote node.
×
UNCOV
4495
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
UNCOV
4496
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
UNCOV
4497

×
UNCOV
4498
        // Lookup past error caches for the peer in the server. If no buffer is
×
UNCOV
4499
        // found, create a fresh buffer.
×
UNCOV
4500
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4501
        errBuffer, ok := s.peerErrors[pkStr]
×
UNCOV
4502
        if !ok {
×
UNCOV
4503
                var err error
×
UNCOV
4504
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
UNCOV
4505
                if err != nil {
×
4506
                        srvrLog.Errorf("unable to create peer %v", err)
×
4507
                        return
×
4508
                }
×
4509
        }
4510

4511
        // If we directly set the peer.Config TowerClient member to the
4512
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4513
        // the peer.Config's TowerClient member will not evaluate to nil even
4514
        // though the underlying value is nil. To avoid this gotcha which can
4515
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4516
        // TowerClient if needed.
UNCOV
4517
        var towerClient wtclient.ClientManager
×
UNCOV
4518
        if s.towerClientMgr != nil {
×
UNCOV
4519
                towerClient = s.towerClientMgr
×
UNCOV
4520
        }
×
4521

UNCOV
4522
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4523
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4524

×
UNCOV
4525
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4526
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4527
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4528
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4529
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4530
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4531
        pCfg := peer.Config{
×
UNCOV
4532
                Conn:                    brontideConn,
×
UNCOV
4533
                ConnReq:                 connReq,
×
UNCOV
4534
                Addr:                    peerAddr,
×
UNCOV
4535
                Inbound:                 inbound,
×
UNCOV
4536
                Features:                initFeatures,
×
UNCOV
4537
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4538
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4539
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4540
                ErrorBuffer:             errBuffer,
×
UNCOV
4541
                WritePool:               s.writePool,
×
UNCOV
4542
                ReadPool:                s.readPool,
×
UNCOV
4543
                Switch:                  s.htlcSwitch,
×
UNCOV
4544
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4545
                ChannelDB:               s.chanStateDB,
×
UNCOV
4546
                ChannelGraph:            s.graphDB,
×
UNCOV
4547
                ChainArb:                s.chainArb,
×
UNCOV
4548
                AuthGossiper:            s.authGossiper,
×
UNCOV
4549
                ChanStatusMgr:           s.chanStatusMgr,
×
UNCOV
4550
                ChainIO:                 s.cc.ChainIO,
×
UNCOV
4551
                FeeEstimator:            s.cc.FeeEstimator,
×
UNCOV
4552
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
UNCOV
4553
                SigPool:                 s.sigPool,
×
UNCOV
4554
                Wallet:                  s.cc.Wallet,
×
UNCOV
4555
                ChainNotifier:           s.cc.ChainNotifier,
×
UNCOV
4556
                BestBlockView:           s.cc.BestBlockTracker,
×
UNCOV
4557
                RoutingPolicy:           s.cc.RoutingPolicy,
×
UNCOV
4558
                Sphinx:                  s.sphinx,
×
UNCOV
4559
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4560
                Invoices:                s.invoices,
×
UNCOV
4561
                ChannelNotifier:         s.channelNotifier,
×
UNCOV
4562
                HtlcNotifier:            s.htlcNotifier,
×
UNCOV
4563
                TowerClient:             towerClient,
×
UNCOV
4564
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4565
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4566
                        lnwire.NodeAnnouncement, error) {
×
UNCOV
4567

×
UNCOV
4568
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4569
                },
×
4570

4571
                PongBuf: s.pongBuf,
4572

4573
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4574

4575
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4576

4577
                FundingManager: s.fundingMgr,
4578

4579
                Hodl:                    s.cfg.Hodl,
4580
                UnsafeReplay:            s.cfg.UnsafeReplay,
4581
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4582
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4583
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4584
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4585
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4586
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4587
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4588
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4589
                HandleCustomMessage:    s.handleCustomMessage,
4590
                GetAliases:             s.aliasMgr.GetAliases,
4591
                RequestAlias:           s.aliasMgr.RequestAlias,
4592
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4593
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4594
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4595
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4596
                MaxFeeExposure:         thresholdMSats,
4597
                Quit:                   s.quit,
4598
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4599
                AuxSigner:              s.implCfg.AuxSigner,
4600
                MsgRouter:              s.implCfg.MsgRouter,
4601
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4602
                AuxResolver:            s.implCfg.AuxContractResolver,
4603
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
UNCOV
4604
                ShouldFwdExpEndorsement: func() bool {
×
UNCOV
4605
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
UNCOV
4606
                                return false
×
UNCOV
4607
                        }
×
4608

UNCOV
4609
                        return clock.NewDefaultClock().Now().Before(
×
UNCOV
4610
                                EndorsementExperimentEnd,
×
UNCOV
4611
                        )
×
4612
                },
4613
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4614
        }
4615

UNCOV
4616
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4617
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4618

×
UNCOV
4619
        p := peer.NewBrontide(pCfg)
×
UNCOV
4620

×
UNCOV
4621
        // Update the access manager with the access permission for this peer.
×
UNCOV
4622
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
UNCOV
4623

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

×
UNCOV
4627
        s.addPeer(p)
×
UNCOV
4628

×
UNCOV
4629
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4630
        // delete the previous error buffer from the server's map of error
×
UNCOV
4631
        // buffers.
×
UNCOV
4632
        delete(s.peerErrors, pkStr)
×
UNCOV
4633

×
UNCOV
4634
        // Dispatch a goroutine to asynchronously start the peer. This process
×
UNCOV
4635
        // includes sending and receiving Init messages, which would be a DOS
×
UNCOV
4636
        // vector if we held the server's mutex throughout the procedure.
×
UNCOV
4637
        s.wg.Add(1)
×
UNCOV
4638
        go s.peerInitializer(p)
×
4639
}
4640

4641
// addPeer adds the passed peer to the server's global state of all active
4642
// peers.
UNCOV
4643
func (s *server) addPeer(p *peer.Brontide) {
×
UNCOV
4644
        if p == nil {
×
4645
                return
×
4646
        }
×
4647

UNCOV
4648
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4649

×
UNCOV
4650
        // Ignore new peers if we're shutting down.
×
UNCOV
4651
        if s.Stopped() {
×
4652
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4653
                        pubBytes)
×
4654
                p.Disconnect(ErrServerShuttingDown)
×
4655

×
4656
                return
×
4657
        }
×
4658

4659
        // Track the new peer in our indexes so we can quickly look it up either
4660
        // according to its public key, or its peer ID.
4661
        // TODO(roasbeef): pipe all requests through to the
4662
        // queryHandler/peerManager
4663

4664
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4665
        // be human-readable.
UNCOV
4666
        pubStr := string(pubBytes)
×
UNCOV
4667

×
UNCOV
4668
        s.peersByPub[pubStr] = p
×
UNCOV
4669

×
UNCOV
4670
        if p.Inbound() {
×
UNCOV
4671
                s.inboundPeers[pubStr] = p
×
UNCOV
4672
        } else {
×
UNCOV
4673
                s.outboundPeers[pubStr] = p
×
UNCOV
4674
        }
×
4675

4676
        // Inform the peer notifier of a peer online event so that it can be reported
4677
        // to clients listening for peer events.
UNCOV
4678
        var pubKey [33]byte
×
UNCOV
4679
        copy(pubKey[:], pubBytes)
×
4680
}
4681

4682
// peerInitializer asynchronously starts a newly connected peer after it has
4683
// been added to the server's peer map. This method sets up a
4684
// peerTerminationWatcher for the given peer, and ensures that it executes even
4685
// if the peer failed to start. In the event of a successful connection, this
4686
// method reads the negotiated, local feature-bits and spawns the appropriate
4687
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4688
// be signaled of the new peer once the method returns.
4689
//
4690
// NOTE: This MUST be launched as a goroutine.
UNCOV
4691
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4692
        defer s.wg.Done()
×
UNCOV
4693

×
UNCOV
4694
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4695

×
UNCOV
4696
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4697
        if s.Stopped() {
×
4698
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4699
                        pubBytes)
×
4700
                return
×
4701
        }
×
4702

4703
        // Create a channel that will be used to signal a successful start of
4704
        // the link. This prevents the peer termination watcher from beginning
4705
        // its duty too early.
UNCOV
4706
        ready := make(chan struct{})
×
UNCOV
4707

×
UNCOV
4708
        // Before starting the peer, launch a goroutine to watch for the
×
UNCOV
4709
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4710
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4711
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4712
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4713
        // that the server has already handled the removal of this peer.
×
UNCOV
4714
        s.wg.Add(1)
×
UNCOV
4715
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4716

×
UNCOV
4717
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4718
        // will unblock the peerTerminationWatcher.
×
UNCOV
4719
        if err := p.Start(); err != nil {
×
UNCOV
4720
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4721

×
UNCOV
4722
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4723
                return
×
UNCOV
4724
        }
×
4725

4726
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4727
        // was successful, and to begin watching the peer's wait group.
UNCOV
4728
        close(ready)
×
UNCOV
4729

×
UNCOV
4730
        s.mu.Lock()
×
UNCOV
4731
        defer s.mu.Unlock()
×
UNCOV
4732

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

×
UNCOV
4736
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4737
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4738
        pubStr := string(pubBytes)
×
UNCOV
4739
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4740
                select {
×
UNCOV
4741
                case peerChan <- p:
×
4742
                case <-s.quit:
×
4743
                        return
×
4744
                }
4745
        }
UNCOV
4746
        delete(s.peerConnectedListeners, pubStr)
×
UNCOV
4747

×
UNCOV
4748
        // Since the peer has been fully initialized, now it's time to notify
×
UNCOV
4749
        // the RPC about the peer online event.
×
UNCOV
4750
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
×
4751
}
4752

4753
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4754
// and then cleans up all resources allocated to the peer, notifies relevant
4755
// sub-systems of its demise, and finally handles re-connecting to the peer if
4756
// it's persistent. If the server intentionally disconnects a peer, it should
4757
// have a corresponding entry in the ignorePeerTermination map which will cause
4758
// the cleanup routine to exit early. The passed `ready` chan is used to
4759
// synchronize when WaitForDisconnect should begin watching on the peer's
4760
// waitgroup. The ready chan should only be signaled if the peer starts
4761
// successfully, otherwise the peer should be disconnected instead.
4762
//
4763
// NOTE: This MUST be launched as a goroutine.
UNCOV
4764
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4765
        defer s.wg.Done()
×
UNCOV
4766

×
UNCOV
4767
        ctx := btclog.WithCtx(
×
UNCOV
4768
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
UNCOV
4769
        )
×
UNCOV
4770

×
UNCOV
4771
        p.WaitForDisconnect(ready)
×
UNCOV
4772

×
UNCOV
4773
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
UNCOV
4774

×
UNCOV
4775
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4776
        // the other sub-systems will already be shutting down.
×
UNCOV
4777
        if s.Stopped() {
×
UNCOV
4778
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
×
UNCOV
4779
                return
×
UNCOV
4780
        }
×
4781

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

×
UNCOV
4788
        pubKey := p.IdentityKey()
×
UNCOV
4789

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

×
UNCOV
4794
        // Tell the switch to remove all links associated with this peer.
×
UNCOV
4795
        // Passing nil as the target link indicates that all links associated
×
UNCOV
4796
        // with this interface should be closed.
×
UNCOV
4797
        //
×
UNCOV
4798
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
UNCOV
4799
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
UNCOV
4800
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4801
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4802
        }
×
4803

UNCOV
4804
        for _, link := range links {
×
UNCOV
4805
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4806
        }
×
4807

UNCOV
4808
        s.mu.Lock()
×
UNCOV
4809
        defer s.mu.Unlock()
×
UNCOV
4810

×
UNCOV
4811
        // If there were any notification requests for when this peer
×
UNCOV
4812
        // disconnected, we can trigger them now.
×
UNCOV
4813
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
UNCOV
4814
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4815
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4816
                close(offlineChan)
×
UNCOV
4817
        }
×
UNCOV
4818
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4819

×
UNCOV
4820
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4821
        // peer termination watcher and skip cleanup.
×
UNCOV
4822
        if _, ok := s.ignorePeerTermination[p]; ok {
×
UNCOV
4823
                delete(s.ignorePeerTermination, p)
×
UNCOV
4824

×
UNCOV
4825
                pubKey := p.PubKey()
×
UNCOV
4826
                pubStr := string(pubKey[:])
×
UNCOV
4827

×
UNCOV
4828
                // If a connection callback is present, we'll go ahead and
×
UNCOV
4829
                // execute it now that previous peer has fully disconnected. If
×
UNCOV
4830
                // the callback is not present, this likely implies the peer was
×
UNCOV
4831
                // purposefully disconnected via RPC, and that no reconnect
×
UNCOV
4832
                // should be attempted.
×
UNCOV
4833
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
UNCOV
4834
                if ok {
×
UNCOV
4835
                        delete(s.scheduledPeerConnection, pubStr)
×
UNCOV
4836
                        connCallback()
×
UNCOV
4837
                }
×
UNCOV
4838
                return
×
4839
        }
4840

4841
        // First, cleanup any remaining state the server has regarding the peer
4842
        // in question.
UNCOV
4843
        s.removePeerUnsafe(ctx, p)
×
UNCOV
4844

×
UNCOV
4845
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4846
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4847
                return
×
UNCOV
4848
        }
×
4849

4850
        // Get the last address that we used to connect to the peer.
UNCOV
4851
        addrs := []net.Addr{
×
UNCOV
4852
                p.NetAddress().Address,
×
UNCOV
4853
        }
×
UNCOV
4854

×
UNCOV
4855
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4856
        // reconnection purposes.
×
UNCOV
4857
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
×
UNCOV
4858
        switch {
×
4859
        // We found advertised addresses, so use them.
UNCOV
4860
        case err == nil:
×
UNCOV
4861
                addrs = advertisedAddrs
×
4862

4863
        // The peer doesn't have an advertised address.
UNCOV
4864
        case err == errNoAdvertisedAddr:
×
UNCOV
4865
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4866
                // peer address.
×
UNCOV
4867
                if !p.Inbound() {
×
UNCOV
4868
                        break
×
4869
                }
4870

4871
                // Fall back to the existing peer address if
4872
                // we're not accepting connections over Tor.
UNCOV
4873
                if s.torController == nil {
×
UNCOV
4874
                        break
×
4875
                }
4876

4877
                // If we are, the peer's address won't be known
4878
                // to us (we'll see a private address, which is
4879
                // the address used by our onion service to dial
4880
                // to lnd), so we don't have enough information
4881
                // to attempt a reconnect.
4882
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4883
                        "to inbound peer without advertised address")
×
4884
                return
×
4885

4886
        // We came across an error retrieving an advertised
4887
        // address, log it, and fall back to the existing peer
4888
        // address.
UNCOV
4889
        default:
×
UNCOV
4890
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
UNCOV
4891
                        "address for peer", err)
×
4892
        }
4893

4894
        // Make an easy lookup map so that we can check if an address
4895
        // is already in the address list that we have stored for this peer.
UNCOV
4896
        existingAddrs := make(map[string]bool)
×
UNCOV
4897
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4898
                existingAddrs[addr.String()] = true
×
UNCOV
4899
        }
×
4900

4901
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4902
        for _, addr := range addrs {
×
UNCOV
4903
                if existingAddrs[addr.String()] {
×
4904
                        continue
×
4905
                }
4906

UNCOV
4907
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4908
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4909
                        &lnwire.NetAddress{
×
UNCOV
4910
                                IdentityKey: p.IdentityKey(),
×
UNCOV
4911
                                Address:     addr,
×
UNCOV
4912
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4913
                        },
×
UNCOV
4914
                )
×
4915
        }
4916

4917
        // Record the computed backoff in the backoff map.
UNCOV
4918
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4919
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4920

×
UNCOV
4921
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4922
        // exist.
×
UNCOV
4923
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4924
        if !ok {
×
UNCOV
4925
                cancelChan = make(chan struct{})
×
UNCOV
4926
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4927
        }
×
4928

4929
        // We choose not to wait group this go routine since the Connect
4930
        // call can stall for arbitrarily long if we shutdown while an
4931
        // outbound connection attempt is being made.
UNCOV
4932
        go func() {
×
UNCOV
4933
                srvrLog.DebugS(ctx, "Scheduling connection "+
×
UNCOV
4934
                        "re-establishment to persistent peer",
×
UNCOV
4935
                        "reconnecting_in", backoff)
×
UNCOV
4936

×
UNCOV
4937
                select {
×
UNCOV
4938
                case <-time.After(backoff):
×
UNCOV
4939
                case <-cancelChan:
×
UNCOV
4940
                        return
×
UNCOV
4941
                case <-s.quit:
×
UNCOV
4942
                        return
×
4943
                }
4944

UNCOV
4945
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
UNCOV
4946
                        "connection")
×
UNCOV
4947

×
UNCOV
4948
                s.connectToPersistentPeer(pubStr)
×
4949
        }()
4950
}
4951

4952
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4953
// to connect to the peer. It creates connection requests if there are
4954
// currently none for a given address and it removes old connection requests
4955
// if the associated address is no longer in the latest address list for the
4956
// peer.
UNCOV
4957
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
UNCOV
4958
        s.mu.Lock()
×
UNCOV
4959
        defer s.mu.Unlock()
×
UNCOV
4960

×
UNCOV
4961
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4962
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4963
        // connection requests for the associated address and then any leftover
×
UNCOV
4964
        // entries will indicate which addresses we should create new
×
UNCOV
4965
        // connection requests for.
×
UNCOV
4966
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4967
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4968
                addrMap[addr.String()] = addr
×
UNCOV
4969
        }
×
4970

4971
        // Go through each of the existing connection requests and
4972
        // check if they correspond to the latest set of addresses. If
4973
        // there is a connection requests that does not use one of the latest
4974
        // advertised addresses then remove that connection request.
UNCOV
4975
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4976
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4977
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4978

×
UNCOV
4979
                switch _, ok := addrMap[lnAddr]; ok {
×
4980
                // If the existing connection request is using one of the
4981
                // latest advertised addresses for the peer then we add it to
4982
                // updatedConnReqs and remove the associated address from
4983
                // addrMap so that we don't recreate this connReq later on.
4984
                case true:
×
4985
                        updatedConnReqs = append(
×
4986
                                updatedConnReqs, connReq,
×
4987
                        )
×
4988
                        delete(addrMap, lnAddr)
×
4989

4990
                // If the existing connection request is using an address that
4991
                // is not one of the latest advertised addresses for the peer
4992
                // then we remove the connecting request from the connection
4993
                // manager.
UNCOV
4994
                case false:
×
UNCOV
4995
                        srvrLog.Info(
×
UNCOV
4996
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4997
                        )
×
UNCOV
4998
                        s.connMgr.Remove(connReq.ID())
×
4999
                }
5000
        }
5001

UNCOV
5002
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
5003

×
UNCOV
5004
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
5005
        if !ok {
×
UNCOV
5006
                cancelChan = make(chan struct{})
×
UNCOV
5007
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
5008
        }
×
5009

5010
        // Any addresses left in addrMap are new ones that we have not made
5011
        // connection requests for. So create new connection requests for those.
5012
        // If there is more than one address in the address map, stagger the
5013
        // creation of the connection requests for those.
UNCOV
5014
        go func() {
×
UNCOV
5015
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
UNCOV
5016
                defer ticker.Stop()
×
UNCOV
5017

×
UNCOV
5018
                for _, addr := range addrMap {
×
UNCOV
5019
                        // Send the persistent connection request to the
×
UNCOV
5020
                        // connection manager, saving the request itself so we
×
UNCOV
5021
                        // can cancel/restart the process as needed.
×
UNCOV
5022
                        connReq := &connmgr.ConnReq{
×
UNCOV
5023
                                Addr:      addr,
×
UNCOV
5024
                                Permanent: true,
×
UNCOV
5025
                        }
×
UNCOV
5026

×
UNCOV
5027
                        s.mu.Lock()
×
UNCOV
5028
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
5029
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
5030
                        )
×
UNCOV
5031
                        s.mu.Unlock()
×
UNCOV
5032

×
UNCOV
5033
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
5034
                                "channel peer %v", addr)
×
UNCOV
5035

×
UNCOV
5036
                        go s.connMgr.Connect(connReq)
×
UNCOV
5037

×
UNCOV
5038
                        select {
×
UNCOV
5039
                        case <-s.quit:
×
UNCOV
5040
                                return
×
UNCOV
5041
                        case <-cancelChan:
×
UNCOV
5042
                                return
×
UNCOV
5043
                        case <-ticker.C:
×
5044
                        }
5045
                }
5046
        }()
5047
}
5048

5049
// removePeerUnsafe removes the passed peer from the server's state of all
5050
// active peers.
5051
//
5052
// NOTE: Server mutex must be held when calling this function.
UNCOV
5053
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
×
UNCOV
5054
        if p == nil {
×
5055
                return
×
5056
        }
×
5057

UNCOV
5058
        srvrLog.DebugS(ctx, "Removing peer")
×
UNCOV
5059

×
UNCOV
5060
        // Exit early if we have already been instructed to shutdown, the peers
×
UNCOV
5061
        // will be disconnected in the server shutdown process.
×
UNCOV
5062
        if s.Stopped() {
×
5063
                return
×
5064
        }
×
5065

5066
        // Capture the peer's public key and string representation.
UNCOV
5067
        pKey := p.PubKey()
×
UNCOV
5068
        pubSer := pKey[:]
×
UNCOV
5069
        pubStr := string(pubSer)
×
UNCOV
5070

×
UNCOV
5071
        delete(s.peersByPub, pubStr)
×
UNCOV
5072

×
UNCOV
5073
        if p.Inbound() {
×
UNCOV
5074
                delete(s.inboundPeers, pubStr)
×
UNCOV
5075
        } else {
×
UNCOV
5076
                delete(s.outboundPeers, pubStr)
×
UNCOV
5077
        }
×
5078

5079
        // When removing the peer we make sure to disconnect it asynchronously
5080
        // to avoid blocking the main server goroutine because it is holding the
5081
        // server's mutex. Disconnecting the peer might block and wait until the
5082
        // peer has fully started up. This can happen if an inbound and outbound
5083
        // race condition occurs.
UNCOV
5084
        s.wg.Add(1)
×
UNCOV
5085
        go func() {
×
UNCOV
5086
                defer s.wg.Done()
×
UNCOV
5087

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

×
UNCOV
5090
                // If this peer had an active persistent connection request,
×
UNCOV
5091
                // remove it.
×
UNCOV
5092
                if p.ConnReq() != nil {
×
UNCOV
5093
                        s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
5094
                }
×
5095

5096
                // Remove the peer's access permission from the access manager.
UNCOV
5097
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
UNCOV
5098
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
UNCOV
5099

×
UNCOV
5100
                // Copy the peer's error buffer across to the server if it has
×
UNCOV
5101
                // any items in it so that we can restore peer errors across
×
UNCOV
5102
                // connections. We need to look up the error after the peer has
×
UNCOV
5103
                // been disconnected because we write the error in the
×
UNCOV
5104
                // `Disconnect` method.
×
UNCOV
5105
                s.mu.Lock()
×
UNCOV
5106
                if p.ErrorBuffer().Total() > 0 {
×
UNCOV
5107
                        s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
5108
                }
×
UNCOV
5109
                s.mu.Unlock()
×
UNCOV
5110

×
UNCOV
5111
                // Inform the peer notifier of a peer offline event so that it
×
UNCOV
5112
                // can be reported to clients listening for peer events.
×
UNCOV
5113
                var pubKey [33]byte
×
UNCOV
5114
                copy(pubKey[:], pubSer)
×
UNCOV
5115

×
UNCOV
5116
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
5117
        }()
5118
}
5119

5120
// ConnectToPeer requests that the server connect to a Lightning Network peer
5121
// at the specified address. This function will *block* until either a
5122
// connection is established, or the initial handshake process fails.
5123
//
5124
// NOTE: This function is safe for concurrent access.
5125
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
5126
        perm bool, timeout time.Duration) error {
×
UNCOV
5127

×
UNCOV
5128
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
5129

×
UNCOV
5130
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
5131
        // better granularity.  In certain conditions, this method requires
×
UNCOV
5132
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
5133
        // lock to be released, and subsequently reacquired.
×
UNCOV
5134
        s.mu.Lock()
×
UNCOV
5135

×
UNCOV
5136
        // Ensure we're not already connected to this peer.
×
UNCOV
5137
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
5138

×
UNCOV
5139
        // When there's no error it means we already have a connection with this
×
UNCOV
5140
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
UNCOV
5141
        // set, we will ignore the existing connection and continue.
×
UNCOV
5142
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
UNCOV
5143
                s.mu.Unlock()
×
UNCOV
5144
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
5145
        }
×
5146

5147
        // Peer was not found, continue to pursue connection with peer.
5148

5149
        // If there's already a pending connection request for this pubkey,
5150
        // then we ignore this request to ensure we don't create a redundant
5151
        // connection.
UNCOV
5152
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
5153
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
5154
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
5155
        }
×
5156

5157
        // If there's not already a pending or active connection to this node,
5158
        // then instruct the connection manager to attempt to establish a
5159
        // persistent connection to the peer.
UNCOV
5160
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
5161
        if perm {
×
UNCOV
5162
                connReq := &connmgr.ConnReq{
×
UNCOV
5163
                        Addr:      addr,
×
UNCOV
5164
                        Permanent: true,
×
UNCOV
5165
                }
×
UNCOV
5166

×
UNCOV
5167
                // Since the user requested a permanent connection, we'll set
×
UNCOV
5168
                // the entry to true which will tell the server to continue
×
UNCOV
5169
                // reconnecting even if the number of channels with this peer is
×
UNCOV
5170
                // zero.
×
UNCOV
5171
                s.persistentPeers[targetPub] = true
×
UNCOV
5172
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
5173
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
5174
                }
×
UNCOV
5175
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
5176
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
5177
                )
×
UNCOV
5178
                s.mu.Unlock()
×
UNCOV
5179

×
UNCOV
5180
                go s.connMgr.Connect(connReq)
×
UNCOV
5181

×
UNCOV
5182
                return nil
×
5183
        }
UNCOV
5184
        s.mu.Unlock()
×
UNCOV
5185

×
UNCOV
5186
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
5187
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
5188
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
5189
        // caller.
×
UNCOV
5190
        errChan := make(chan error, 1)
×
UNCOV
5191
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
5192

×
UNCOV
5193
        select {
×
UNCOV
5194
        case err := <-errChan:
×
UNCOV
5195
                return err
×
5196
        case <-s.quit:
×
5197
                return ErrServerShuttingDown
×
5198
        }
5199
}
5200

5201
// connectToPeer establishes a connection to a remote peer. errChan is used to
5202
// notify the caller if the connection attempt has failed. Otherwise, it will be
5203
// closed.
5204
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
5205
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
5206

×
UNCOV
5207
        conn, err := brontide.Dial(
×
UNCOV
5208
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
5209
        )
×
UNCOV
5210
        if err != nil {
×
UNCOV
5211
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
5212
                select {
×
UNCOV
5213
                case errChan <- err:
×
5214
                case <-s.quit:
×
5215
                }
UNCOV
5216
                return
×
5217
        }
5218

UNCOV
5219
        close(errChan)
×
UNCOV
5220

×
UNCOV
5221
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
5222
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
5223

×
UNCOV
5224
        s.OutboundPeerConnected(nil, conn)
×
5225
}
5226

5227
// DisconnectPeer sends the request to server to close the connection with peer
5228
// identified by public key.
5229
//
5230
// NOTE: This function is safe for concurrent access.
UNCOV
5231
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
5232
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
5233
        pubStr := string(pubBytes)
×
UNCOV
5234

×
UNCOV
5235
        s.mu.Lock()
×
UNCOV
5236
        defer s.mu.Unlock()
×
UNCOV
5237

×
UNCOV
5238
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
5239
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
5240
        // currently connected to.
×
UNCOV
5241
        peer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
5242
        if err == ErrPeerNotConnected {
×
UNCOV
5243
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
5244
        }
×
5245

UNCOV
5246
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
5247

×
UNCOV
5248
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
5249

×
UNCOV
5250
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
5251
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
5252
        // disconnect.
×
UNCOV
5253
        delete(s.persistentPeers, pubStr)
×
UNCOV
5254
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
5255

×
UNCOV
5256
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
5257
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
×
UNCOV
5258
        //
×
UNCOV
5259
        // NOTE: We call it in a goroutine to avoid blocking the main server
×
UNCOV
5260
        // goroutine because we might hold the server's mutex.
×
UNCOV
5261
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
5262

×
UNCOV
5263
        return nil
×
5264
}
5265

5266
// OpenChannel sends a request to the server to open a channel to the specified
5267
// peer identified by nodeKey with the passed channel funding parameters.
5268
//
5269
// NOTE: This function is safe for concurrent access.
5270
func (s *server) OpenChannel(
UNCOV
5271
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
5272

×
UNCOV
5273
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
5274
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
5275
        // not blocked if the caller is not reading the updates.
×
UNCOV
5276
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
5277
        req.Err = make(chan error, 1)
×
UNCOV
5278

×
UNCOV
5279
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
5280
        // we're unable to locate the peer then this request will fail.
×
UNCOV
5281
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
5282
        s.mu.RLock()
×
UNCOV
5283
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
5284
        if !ok {
×
5285
                s.mu.RUnlock()
×
5286

×
5287
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5288
                return req.Updates, req.Err
×
5289
        }
×
UNCOV
5290
        req.Peer = peer
×
UNCOV
5291
        s.mu.RUnlock()
×
UNCOV
5292

×
UNCOV
5293
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
5294
        // opening process.
×
UNCOV
5295
        select {
×
UNCOV
5296
        case <-peer.ActiveSignal():
×
5297
        case <-peer.QuitSignal():
×
5298
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5299
                return req.Updates, req.Err
×
5300
        case <-s.quit:
×
5301
                req.Err <- ErrServerShuttingDown
×
5302
                return req.Updates, req.Err
×
5303
        }
5304

5305
        // If the fee rate wasn't specified at this point we fail the funding
5306
        // because of the missing fee rate information. The caller of the
5307
        // `OpenChannel` method needs to make sure that default values for the
5308
        // fee rate are set beforehand.
UNCOV
5309
        if req.FundingFeePerKw == 0 {
×
5310
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5311
                        "the channel opening transaction")
×
5312

×
5313
                return req.Updates, req.Err
×
5314
        }
×
5315

5316
        // Spawn a goroutine to send the funding workflow request to the funding
5317
        // manager. This allows the server to continue handling queries instead
5318
        // of blocking on this request which is exported as a synchronous
5319
        // request to the outside world.
UNCOV
5320
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
5321

×
UNCOV
5322
        return req.Updates, req.Err
×
5323
}
5324

5325
// Peers returns a slice of all active peers.
5326
//
5327
// NOTE: This function is safe for concurrent access.
UNCOV
5328
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
5329
        s.mu.RLock()
×
UNCOV
5330
        defer s.mu.RUnlock()
×
UNCOV
5331

×
UNCOV
5332
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
5333
        for _, peer := range s.peersByPub {
×
UNCOV
5334
                peers = append(peers, peer)
×
UNCOV
5335
        }
×
5336

UNCOV
5337
        return peers
×
5338
}
5339

5340
// computeNextBackoff uses a truncated exponential backoff to compute the next
5341
// backoff using the value of the exiting backoff. The returned duration is
5342
// randomized in either direction by 1/20 to prevent tight loops from
5343
// stabilizing.
UNCOV
5344
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
5345
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
5346
        nextBackoff := 2 * currBackoff
×
UNCOV
5347
        if nextBackoff > maxBackoff {
×
UNCOV
5348
                nextBackoff = maxBackoff
×
UNCOV
5349
        }
×
5350

5351
        // Using 1/10 of our duration as a margin, compute a random offset to
5352
        // avoid the nodes entering connection cycles.
UNCOV
5353
        margin := nextBackoff / 10
×
UNCOV
5354

×
UNCOV
5355
        var wiggle big.Int
×
UNCOV
5356
        wiggle.SetUint64(uint64(margin))
×
UNCOV
5357
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5358
                // Randomizing is not mission critical, so we'll just return the
×
5359
                // current backoff.
×
5360
                return nextBackoff
×
5361
        }
×
5362

5363
        // Otherwise add in our wiggle, but subtract out half of the margin so
5364
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
5365
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5366
}
5367

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

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

×
UNCOV
5376
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
5377
        if err != nil {
×
5378
                return nil, err
×
5379
        }
×
5380

UNCOV
5381
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
×
UNCOV
5382
        if err != nil {
×
UNCOV
5383
                return nil, err
×
UNCOV
5384
        }
×
5385

UNCOV
5386
        if len(node.Addresses) == 0 {
×
UNCOV
5387
                return nil, errNoAdvertisedAddr
×
UNCOV
5388
        }
×
5389

UNCOV
5390
        return node.Addresses, nil
×
5391
}
5392

5393
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5394
// channel update for a target channel.
5395
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
5396
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
5397

×
UNCOV
5398
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
5399
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
5400
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
5401
                if err != nil {
×
UNCOV
5402
                        return nil, err
×
UNCOV
5403
                }
×
5404

UNCOV
5405
                return netann.ExtractChannelUpdate(
×
UNCOV
5406
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
5407
                )
×
5408
        }
5409
}
5410

5411
// applyChannelUpdate applies the channel update to the different sub-systems of
5412
// the server. The useAlias boolean denotes whether or not to send an alias in
5413
// place of the real SCID.
5414
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
5415
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
5416

×
UNCOV
5417
        var (
×
UNCOV
5418
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5419
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5420
        )
×
UNCOV
5421

×
UNCOV
5422
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5423

×
UNCOV
5424
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
5425
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
5426
        if useAlias {
×
UNCOV
5427
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
5428
                if foundAlias != defaultAlias {
×
UNCOV
5429
                        peerAlias = &foundAlias
×
UNCOV
5430
                }
×
5431
        }
5432

UNCOV
5433
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
5434
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
5435
        )
×
UNCOV
5436
        select {
×
UNCOV
5437
        case err := <-errChan:
×
UNCOV
5438
                return err
×
5439
        case <-s.quit:
×
5440
                return ErrServerShuttingDown
×
5441
        }
5442
}
5443

5444
// SendCustomMessage sends a custom message to the peer with the specified
5445
// pubkey.
5446
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5447
        data []byte) error {
×
UNCOV
5448

×
UNCOV
5449
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5450
        if err != nil {
×
UNCOV
5451
                return err
×
UNCOV
5452
        }
×
5453

5454
        // We'll wait until the peer is active.
UNCOV
5455
        select {
×
UNCOV
5456
        case <-peer.ActiveSignal():
×
5457
        case <-peer.QuitSignal():
×
5458
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5459
        case <-s.quit:
×
5460
                return ErrServerShuttingDown
×
5461
        }
5462

UNCOV
5463
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5464
        if err != nil {
×
UNCOV
5465
                return err
×
UNCOV
5466
        }
×
5467

5468
        // Send the message as low-priority. For now we assume that all
5469
        // application-defined message are low priority.
UNCOV
5470
        return peer.SendMessageLazy(true, msg)
×
5471
}
5472

5473
// newSweepPkScriptGen creates closure that generates a new public key script
5474
// which should be used to sweep any funds into the on-chain wallet.
5475
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5476
// (p2wkh) output.
5477
func newSweepPkScriptGen(
5478
        wallet lnwallet.WalletController,
UNCOV
5479
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5480

×
UNCOV
5481
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5482
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5483
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5484
                        lnwallet.DefaultAccountName,
×
UNCOV
5485
                )
×
UNCOV
5486
                if err != nil {
×
5487
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5488
                }
×
5489

UNCOV
5490
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5491
                if err != nil {
×
5492
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5493
                }
×
5494

UNCOV
5495
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5496
                        wallet, netParams, addr,
×
UNCOV
5497
                )
×
UNCOV
5498
                if err != nil {
×
5499
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5500
                }
×
5501

UNCOV
5502
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5503
                        DeliveryAddress: addr,
×
UNCOV
5504
                        InternalKey:     internalKeyDesc,
×
UNCOV
5505
                })
×
5506
        }
5507
}
5508

5509
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5510
// finished.
UNCOV
5511
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5512
        // Get a list of closed channels.
×
UNCOV
5513
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5514
        if err != nil {
×
5515
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5516
                return nil
×
5517
        }
×
5518

5519
        // Save the SCIDs in a map.
UNCOV
5520
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
UNCOV
5521
        for _, c := range channels {
×
UNCOV
5522
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5523
                if !c.IsPending {
×
UNCOV
5524
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5525
                }
×
5526
        }
5527

5528
        // Double check whether the reported closed channel has indeed finished
5529
        // closing.
5530
        //
5531
        // NOTE: There are misalignments regarding when a channel's FC is
5532
        // marked as finalized. We double check the pending channels to make
5533
        // sure the returned SCIDs are indeed terminated.
5534
        //
5535
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5536
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5537
        if err != nil {
×
5538
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5539
                return nil
×
5540
        }
×
5541

UNCOV
5542
        for _, c := range pendings {
×
UNCOV
5543
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5544
                        continue
×
5545
                }
5546

5547
                // If the channel is still reported as pending, remove it from
5548
                // the map.
5549
                delete(closedSCIDs, c.ShortChannelID)
×
5550

×
5551
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5552
                        c.ShortChannelID)
×
5553
        }
5554

UNCOV
5555
        return closedSCIDs
×
5556
}
5557

5558
// getStartingBeat returns the current beat. This is used during the startup to
5559
// initialize blockbeat consumers.
UNCOV
5560
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
UNCOV
5561
        // beat is the current blockbeat.
×
UNCOV
5562
        var beat *chainio.Beat
×
UNCOV
5563

×
UNCOV
5564
        // If the node is configured with nochainbackend mode (remote signer),
×
UNCOV
5565
        // we will skip fetching the best block.
×
UNCOV
5566
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5567
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5568
                        "mode")
×
5569

×
5570
                return &chainio.Beat{}, nil
×
5571
        }
×
5572

5573
        // We should get a notification with the current best block immediately
5574
        // by passing a nil block.
UNCOV
5575
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
UNCOV
5576
        if err != nil {
×
5577
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5578
        }
×
UNCOV
5579
        defer blockEpochs.Cancel()
×
UNCOV
5580

×
UNCOV
5581
        // We registered for the block epochs with a nil request. The notifier
×
UNCOV
5582
        // should send us the current best block immediately. So we need to
×
UNCOV
5583
        // wait for it here because we need to know the current best height.
×
UNCOV
5584
        select {
×
UNCOV
5585
        case bestBlock := <-blockEpochs.Epochs:
×
UNCOV
5586
                srvrLog.Infof("Received initial block %v at height %d",
×
UNCOV
5587
                        bestBlock.Hash, bestBlock.Height)
×
UNCOV
5588

×
UNCOV
5589
                // Update the current blockbeat.
×
UNCOV
5590
                beat = chainio.NewBeat(*bestBlock)
×
5591

5592
        case <-s.quit:
×
5593
                srvrLog.Debug("LND shutting down")
×
5594
        }
5595

UNCOV
5596
        return beat, nil
×
5597
}
5598

5599
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5600
// point has an active RBF chan closer.
5601
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
UNCOV
5602
        chanPoint wire.OutPoint) bool {
×
UNCOV
5603

×
UNCOV
5604
        pubBytes := peerPub.SerializeCompressed()
×
UNCOV
5605

×
UNCOV
5606
        s.mu.RLock()
×
UNCOV
5607
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
UNCOV
5608
        s.mu.RUnlock()
×
UNCOV
5609
        if !ok {
×
5610
                return false
×
5611
        }
×
5612

UNCOV
5613
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5614
}
5615

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

×
UNCOV
5624
        // First, we'll attempt to look up the channel based on it's
×
UNCOV
5625
        // ChannelPoint.
×
UNCOV
5626
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
UNCOV
5627
        if err != nil {
×
5628
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5629
        }
×
5630

5631
        // From the channel, we can now get the pubkey of the peer, then use
5632
        // that to eventually get the chan closer.
UNCOV
5633
        peerPub := channel.IdentityPub.SerializeCompressed()
×
UNCOV
5634

×
UNCOV
5635
        // Now that we have the peer pub, we can look up the peer itself.
×
UNCOV
5636
        s.mu.RLock()
×
UNCOV
5637
        targetPeer, ok := s.peersByPub[string(peerPub)]
×
UNCOV
5638
        s.mu.RUnlock()
×
UNCOV
5639
        if !ok {
×
5640
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5641
                        "not online", chanPoint)
×
5642
        }
×
5643

UNCOV
5644
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
UNCOV
5645
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5646
        )
×
UNCOV
5647
        if err != nil {
×
5648
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5649
                        "%w", err)
×
5650
        }
×
5651

UNCOV
5652
        return closeUpdates, nil
×
5653
}
5654

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

×
UNCOV
5663
        // If the channel is present in the switch, then the request should flow
×
UNCOV
5664
        // through the switch instead.
×
UNCOV
5665
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5666
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
×
5667
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5668
                        "invalid request", chanPoint)
×
5669
        }
×
5670

5671
        // At this point, we know that the channel isn't present in the link, so
5672
        // we'll check to see if we have an entry in the active chan closer map.
UNCOV
5673
        updates, err := s.attemptCoopRbfFeeBump(
×
UNCOV
5674
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5675
        )
×
UNCOV
5676
        if err != nil {
×
5677
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5678
                        "ChannelPoint(%v)", chanPoint)
×
5679
        }
×
5680

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

© 2025 Coveralls, Inc