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

lightningnetwork / lnd / 15869455718

25 Jun 2025 06:53AM UTC coverage: 55.806% (-12.2%) from 67.978%
15869455718

Pull #9148

github

web-flow
Merge c64e3a6c3 into 4335d9cfb
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

232 of 270 new or added lines in 5 files covered. (85.93%)

23628 existing lines in 289 files now uncovered.

108377 of 194204 relevant lines covered (55.81%)

22552.93 hits per line

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

0.0
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
202
        case peerStatusTemporary:
×
UNCOV
203
                return "temporary"
×
204

UNCOV
205
        case peerStatusProtected:
×
UNCOV
206
                return "protected"
×
207

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

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

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

228
        start sync.Once
229
        stop  sync.Once
230

231
        cfg *Config
232

233
        implCfg *ImplementationCfg
234

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

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

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

246
        chanStatusMgr *netann.ChanStatusManager
247

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

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

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

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

268
        mu sync.RWMutex
269

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

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

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

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

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

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

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

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

320
        cc *chainreg.ChainControl
321

322
        fundingMgr *funding.Manager
323

324
        graphDB *graphdb.ChannelGraph
325

326
        chanStateDB *channeldb.ChannelStateDB
327

328
        addrSource channeldb.AddrSource
329

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

334
        invoicesDB invoices.InvoiceDB
335

336
        aliasMgr *aliasmgr.Manager
337

338
        htlcSwitch *htlcswitch.Switch
339

340
        interceptableSwitch *htlcswitch.InterceptableSwitch
341

342
        invoices *invoices.InvoiceRegistry
343

344
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
345

346
        channelNotifier *channelnotifier.ChannelNotifier
347

348
        peerNotifier *peernotifier.PeerNotifier
349

350
        htlcNotifier *htlcswitch.HtlcNotifier
351

352
        witnessBeacon contractcourt.WitnessBeacon
353

354
        breachArbitrator *contractcourt.BreachArbitrator
355

356
        missionController *routing.MissionController
357
        defaultMC         *routing.MissionControl
358

359
        graphBuilder *graph.Builder
360

361
        chanRouter *routing.ChannelRouter
362

363
        controlTower routing.ControlTower
364

365
        authGossiper *discovery.AuthenticatedGossiper
366

367
        localChanMgr *localchans.Manager
368

369
        utxoNursery *contractcourt.UtxoNursery
370

371
        sweeper *sweep.UtxoSweeper
372

373
        chainArb *contractcourt.ChainArbitrator
374

375
        sphinx *hop.OnionProcessor
376

377
        towerClientMgr *wtclient.Manager
378

379
        connMgr *connmgr.ConnManager
380

381
        sigPool *lnwallet.SigPool
382

383
        writePool *pool.Write
384

385
        readPool *pool.Read
386

387
        tlsManager *TLSManager
388

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

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

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

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

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

411
        hostAnn *netann.HostAnnouncer
412

413
        // livenessMonitor monitors that lnd has access to critical resources.
414
        livenessMonitor *healthcheck.Monitor
415

416
        customMessageServer *subscribe.Server
417

418
        // txPublisher is a publisher with fee-bumping capability.
419
        txPublisher *sweep.TxPublisher
420

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

425
        // peerAccessMan implements peer access controls.
426
        peerAccessMan *accessMan
427

428
        quit chan struct{}
429

430
        wg sync.WaitGroup
431
}
432

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

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

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

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

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

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

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

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

UNCOV
488
                                        s.mu.Lock()
×
UNCOV
489

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

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

UNCOV
504
                                        s.mu.Unlock()
×
UNCOV
505

×
UNCOV
506
                                        s.connectToPersistentPeer(pubKeyStr)
×
507
                                }
508
                        }
509
                }
510
        }()
511

UNCOV
512
        return nil
×
513
}
514

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

520
        // Msg is the custom wire message.
521
        Msg *lnwire.Custom
522
}
523

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

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

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

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

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

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

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

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

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

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

×
UNCOV
598
        netParams := cfg.ActiveNetParams.Params
×
UNCOV
599

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

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

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

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

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

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

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

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

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

×
UNCOV
669
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
UNCOV
670

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

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

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

×
UNCOV
696
                listenAddrs: listenAddrs,
×
UNCOV
697

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

×
UNCOV
702
                torController: torController,
×
UNCOV
703

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

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

×
UNCOV
720
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
721

×
UNCOV
722
                customMessageServer: subscribe.NewServer(),
×
UNCOV
723

×
UNCOV
724
                tlsManager: tlsManager,
×
UNCOV
725

×
UNCOV
726
                featureMgr: featureMgr,
×
UNCOV
727
                quit:       make(chan struct{}),
×
UNCOV
728
        }
×
UNCOV
729

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

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

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

×
UNCOV
754
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
755

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

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

UNCOV
765
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
766

×
UNCOV
767
                return nil
×
768
        }
769

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

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

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

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

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

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

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

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

×
856
                discoveryTimeout := time.Duration(10 * time.Second)
×
857

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

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

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

884
                        s.natTraversal = pmp
×
885
                }
886
        }
887

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

×
903
                        listenPorts = append(listenPorts, uint16(port))
×
904
                }
×
905

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

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

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

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

943
        // If no alias is provided, default to first 10 characters of public
944
        // key.
UNCOV
945
        alias := cfg.Alias
×
UNCOV
946
        if alias == "" {
×
UNCOV
947
                alias = hex.EncodeToString(serializedPubKey[:10])
×
UNCOV
948
        }
×
UNCOV
949
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
950
        if err != nil {
×
951
                return nil, err
×
952
        }
×
UNCOV
953
        selfNode := &models.LightningNode{
×
UNCOV
954
                HaveNodeAnnouncement: true,
×
UNCOV
955
                LastUpdate:           time.Now(),
×
UNCOV
956
                Addresses:            selfAddrs,
×
UNCOV
957
                Alias:                nodeAlias.String(),
×
UNCOV
958
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
959
                Color:                color,
×
UNCOV
960
        }
×
UNCOV
961
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
962

×
UNCOV
963
        // Based on the disk representation of the node announcement generated
×
UNCOV
964
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
965
        // network so we can properly sign it.
×
UNCOV
966
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
967
        if err != nil {
×
968
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
969
        }
×
970

971
        // With the announcement generated, we'll sign it to properly
972
        // authenticate the message on the network.
UNCOV
973
        authSig, err := netann.SignAnnouncement(
×
UNCOV
974
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
UNCOV
975
        )
×
UNCOV
976
        if err != nil {
×
977
                return nil, fmt.Errorf("unable to generate signature for "+
×
978
                        "self node announcement: %v", err)
×
979
        }
×
UNCOV
980
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
981
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
982
                selfNode.AuthSigBytes,
×
UNCOV
983
        )
×
UNCOV
984
        if err != nil {
×
985
                return nil, err
×
986
        }
×
987

988
        // Finally, we'll update the representation on disk, and update our
989
        // cached in-memory version as well.
UNCOV
990
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
×
991
                return nil, fmt.Errorf("can't set self node: %w", err)
×
992
        }
×
UNCOV
993
        s.currentNodeAnn = nodeAnn
×
UNCOV
994

×
UNCOV
995
        // The router will get access to the payment ID sequencer, such that it
×
UNCOV
996
        // can generate unique payment IDs.
×
UNCOV
997
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
998
        if err != nil {
×
999
                return nil, err
×
1000
        }
×
1001

1002
        // Instantiate mission control with config from the sub server.
1003
        //
1004
        // TODO(joostjager): When we are further in the process of moving to sub
1005
        // servers, the mission control instance itself can be moved there too.
UNCOV
1006
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
1007

×
UNCOV
1008
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
1009
        var estimator routing.Estimator
×
UNCOV
1010
        if cfg.Estimator != nil {
×
1011
                estimator = cfg.Estimator
×
UNCOV
1012
        } else {
×
UNCOV
1013
                switch routingConfig.ProbabilityEstimatorType {
×
UNCOV
1014
                case routing.AprioriEstimatorName:
×
UNCOV
1015
                        aCfg := routingConfig.AprioriConfig
×
UNCOV
1016
                        aprioriConfig := routing.AprioriConfig{
×
UNCOV
1017
                                AprioriHopProbability: aCfg.HopProbability,
×
UNCOV
1018
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
UNCOV
1019
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
1020
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
1021
                        }
×
UNCOV
1022

×
UNCOV
1023
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
1024
                                aprioriConfig,
×
UNCOV
1025
                        )
×
UNCOV
1026
                        if err != nil {
×
1027
                                return nil, err
×
1028
                        }
×
1029

1030
                case routing.BimodalEstimatorName:
×
1031
                        bCfg := routingConfig.BimodalConfig
×
1032
                        bimodalConfig := routing.BimodalConfig{
×
1033
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1034
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1035
                                        bCfg.Scale,
×
1036
                                ),
×
1037
                                BimodalDecayTime: bCfg.DecayTime,
×
1038
                        }
×
1039

×
1040
                        estimator, err = routing.NewBimodalEstimator(
×
1041
                                bimodalConfig,
×
1042
                        )
×
1043
                        if err != nil {
×
1044
                                return nil, err
×
1045
                        }
×
1046

1047
                default:
×
1048
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1049
                                routingConfig.ProbabilityEstimatorType)
×
1050
                }
1051
        }
1052

UNCOV
1053
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
1054
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
UNCOV
1055
                Estimator:               estimator,
×
UNCOV
1056
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
1057
                McFlushInterval:         routingConfig.McFlushInterval,
×
UNCOV
1058
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
UNCOV
1059
        }
×
UNCOV
1060

×
UNCOV
1061
        s.missionController, err = routing.NewMissionController(
×
UNCOV
1062
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
UNCOV
1063
        )
×
UNCOV
1064
        if err != nil {
×
1065
                return nil, fmt.Errorf("can't create mission control "+
×
1066
                        "manager: %w", err)
×
1067
        }
×
UNCOV
1068
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
1069
                routing.DefaultMissionControlNamespace,
×
UNCOV
1070
        )
×
UNCOV
1071
        if err != nil {
×
1072
                return nil, fmt.Errorf("can't create mission control in the "+
×
1073
                        "default namespace: %w", err)
×
1074
        }
×
1075

UNCOV
1076
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
UNCOV
1077
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
UNCOV
1078
                int64(routingConfig.AttemptCost),
×
UNCOV
1079
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
1080
                routingConfig.MinRouteProbability)
×
UNCOV
1081

×
UNCOV
1082
        pathFindingConfig := routing.PathFindingConfig{
×
UNCOV
1083
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
UNCOV
1084
                        routingConfig.AttemptCost,
×
UNCOV
1085
                ),
×
UNCOV
1086
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
1087
                MinProbability: routingConfig.MinRouteProbability,
×
UNCOV
1088
        }
×
UNCOV
1089

×
UNCOV
1090
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
×
UNCOV
1091
        if err != nil {
×
1092
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1093
        }
×
UNCOV
1094
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
1095
                GraphSessionFactory: dbs.GraphDB,
×
UNCOV
1096
                SourceNode:          sourceNode,
×
UNCOV
1097
                MissionControl:      s.defaultMC,
×
UNCOV
1098
                GetLink:             s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1099
                PathFindingConfig:   pathFindingConfig,
×
UNCOV
1100
        }
×
UNCOV
1101

×
UNCOV
1102
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
UNCOV
1103

×
UNCOV
1104
        s.controlTower = routing.NewControlTower(paymentControl)
×
UNCOV
1105

×
UNCOV
1106
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1107
                cfg.Routing.StrictZombiePruning
×
UNCOV
1108

×
UNCOV
1109
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1110
                SelfNode:            selfNode.PubKeyBytes,
×
UNCOV
1111
                Graph:               dbs.GraphDB,
×
UNCOV
1112
                Chain:               cc.ChainIO,
×
UNCOV
1113
                ChainView:           cc.ChainView,
×
UNCOV
1114
                Notifier:            cc.ChainNotifier,
×
UNCOV
1115
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1116
                GraphPruneInterval:  time.Hour,
×
UNCOV
1117
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1118
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1119
                StrictZombiePruning: strictPruning,
×
UNCOV
1120
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1121
        })
×
UNCOV
1122
        if err != nil {
×
1123
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1124
        }
×
1125

UNCOV
1126
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1127
                SelfNode:           selfNode.PubKeyBytes,
×
UNCOV
1128
                RoutingGraph:       dbs.GraphDB,
×
UNCOV
1129
                Chain:              cc.ChainIO,
×
UNCOV
1130
                Payer:              s.htlcSwitch,
×
UNCOV
1131
                Control:            s.controlTower,
×
UNCOV
1132
                MissionControl:     s.defaultMC,
×
UNCOV
1133
                SessionSource:      paymentSessionSource,
×
UNCOV
1134
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1135
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1136
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1137
                Clock:              clock.NewDefaultClock(),
×
UNCOV
1138
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
UNCOV
1139
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1140
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1141
        })
×
UNCOV
1142
        if err != nil {
×
1143
                return nil, fmt.Errorf("can't create router: %w", err)
×
1144
        }
×
1145

UNCOV
1146
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1147
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1148
        if err != nil {
×
1149
                return nil, err
×
1150
        }
×
UNCOV
1151
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1152
        if err != nil {
×
1153
                return nil, err
×
1154
        }
×
1155

UNCOV
1156
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1157

×
UNCOV
1158
        s.authGossiper = discovery.New(discovery.Config{
×
UNCOV
1159
                Graph:                 s.graphBuilder,
×
UNCOV
1160
                ChainIO:               s.cc.ChainIO,
×
UNCOV
1161
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1162
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1163
                Broadcast:             s.BroadcastMessage,
×
UNCOV
1164
                ChanSeries:            chanSeries,
×
UNCOV
1165
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1166
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1167
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
UNCOV
1168
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
UNCOV
1169
                        error) {
×
1170

×
1171
                        return s.genNodeAnnouncement(nil)
×
1172
                },
×
1173
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1174
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1175
                RetransmitTicker:        ticker.New(time.Minute * 30),
1176
                RebroadcastInterval:     time.Hour * 24,
1177
                WaitingProofStore:       waitingProofStore,
1178
                MessageStore:            gossipMessageStore,
1179
                AnnSigner:               s.nodeSigner,
1180
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1181
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1182
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1183
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1184
                MinimumBatchSize:        10,
1185
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1186
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1187
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1188
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1189
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1190
                IsAlias:                 aliasmgr.IsAlias,
1191
                SignAliasUpdate:         s.signAliasUpdate,
1192
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1193
                GetAlias:                s.aliasMgr.GetPeerAlias,
1194
                FindChannel:             s.findChannel,
1195
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1196
                ScidCloser:              scidCloserMan,
1197
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1198
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1199
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1200
        }, nodeKeyDesc)
1201

UNCOV
1202
        accessCfg := &accessManConfig{
×
UNCOV
1203
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
UNCOV
1204
                        error) {
×
UNCOV
1205

×
UNCOV
1206
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
×
UNCOV
1207
                        return s.chanStateDB.FetchPermAndTempPeers(
×
UNCOV
1208
                                genesisHash[:],
×
UNCOV
1209
                        )
×
UNCOV
1210
                },
×
1211
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1212
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1213
        }
1214

UNCOV
1215
        peerAccessMan, err := newAccessMan(accessCfg)
×
UNCOV
1216
        if err != nil {
×
1217
                return nil, err
×
1218
        }
×
1219

UNCOV
1220
        s.peerAccessMan = peerAccessMan
×
UNCOV
1221

×
UNCOV
1222
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1223
        //nolint:ll
×
UNCOV
1224
        s.localChanMgr = &localchans.Manager{
×
UNCOV
1225
                SelfPub:              nodeKeyDesc.PubKey,
×
UNCOV
1226
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
UNCOV
1227
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
×
UNCOV
1228
                        *models.ChannelEdgePolicy) error) error {
×
UNCOV
1229

×
UNCOV
1230
                        return s.graphDB.ForEachNodeChannel(selfVertex,
×
UNCOV
1231
                                func(c *models.ChannelEdgeInfo,
×
UNCOV
1232
                                        e *models.ChannelEdgePolicy,
×
UNCOV
1233
                                        _ *models.ChannelEdgePolicy) error {
×
UNCOV
1234

×
UNCOV
1235
                                        // NOTE: The invoked callback here may
×
UNCOV
1236
                                        // receive a nil channel policy.
×
UNCOV
1237
                                        return cb(c, e)
×
UNCOV
1238
                                },
×
1239
                        )
1240
                },
1241
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1242
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1243
                FetchChannel:              s.chanStateDB.FetchChannel,
1244
                AddEdge: func(ctx context.Context,
1245
                        edge *models.ChannelEdgeInfo) error {
×
1246

×
1247
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1248
                },
×
1249
        }
1250

UNCOV
1251
        utxnStore, err := contractcourt.NewNurseryStore(
×
UNCOV
1252
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
UNCOV
1253
        )
×
UNCOV
1254
        if err != nil {
×
1255
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1256
                return nil, err
×
1257
        }
×
1258

UNCOV
1259
        sweeperStore, err := sweep.NewSweeperStore(
×
UNCOV
1260
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1261
        )
×
UNCOV
1262
        if err != nil {
×
1263
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1264
                return nil, err
×
1265
        }
×
1266

UNCOV
1267
        aggregator := sweep.NewBudgetAggregator(
×
UNCOV
1268
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1269
                s.implCfg.AuxSweeper,
×
UNCOV
1270
        )
×
UNCOV
1271

×
UNCOV
1272
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
UNCOV
1273
                Signer:     cc.Wallet.Cfg.Signer,
×
UNCOV
1274
                Wallet:     cc.Wallet,
×
UNCOV
1275
                Estimator:  cc.FeeEstimator,
×
UNCOV
1276
                Notifier:   cc.ChainNotifier,
×
UNCOV
1277
                AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1278
        })
×
UNCOV
1279

×
UNCOV
1280
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
UNCOV
1281
                FeeEstimator: cc.FeeEstimator,
×
UNCOV
1282
                GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1283
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1284
                ),
×
UNCOV
1285
                Signer:               cc.Wallet.Cfg.Signer,
×
UNCOV
1286
                Wallet:               newSweeperWallet(cc.Wallet),
×
UNCOV
1287
                Mempool:              cc.MempoolNotifier,
×
UNCOV
1288
                Notifier:             cc.ChainNotifier,
×
UNCOV
1289
                Store:                sweeperStore,
×
UNCOV
1290
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
UNCOV
1291
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
UNCOV
1292
                Aggregator:           aggregator,
×
UNCOV
1293
                Publisher:            s.txPublisher,
×
UNCOV
1294
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
UNCOV
1295
        })
×
UNCOV
1296

×
UNCOV
1297
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
UNCOV
1298
                ChainIO:             cc.ChainIO,
×
UNCOV
1299
                ConfDepth:           1,
×
UNCOV
1300
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
UNCOV
1301
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
UNCOV
1302
                Notifier:            cc.ChainNotifier,
×
UNCOV
1303
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
UNCOV
1304
                Store:               utxnStore,
×
UNCOV
1305
                SweepInput:          s.sweeper.SweepInput,
×
UNCOV
1306
                Budget:              s.cfg.Sweeper.Budget,
×
UNCOV
1307
        })
×
UNCOV
1308

×
UNCOV
1309
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
UNCOV
1310
        closeLink := func(chanPoint *wire.OutPoint,
×
UNCOV
1311
                closureType contractcourt.ChannelCloseType) {
×
UNCOV
1312
                // TODO(conner): Properly respect the update and error channels
×
UNCOV
1313
                // returned by CloseLink.
×
UNCOV
1314

×
UNCOV
1315
                // Instruct the switch to close the channel.  Provide no close out
×
UNCOV
1316
                // delivery script or target fee per kw because user input is not
×
UNCOV
1317
                // available when the remote peer closes the channel.
×
UNCOV
1318
                s.htlcSwitch.CloseLink(
×
UNCOV
1319
                        context.Background(), chanPoint, closureType, 0, 0, nil,
×
UNCOV
1320
                )
×
UNCOV
1321
        }
×
1322

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

×
UNCOV
1327
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
UNCOV
1328
                &contractcourt.BreachConfig{
×
UNCOV
1329
                        CloseLink: closeLink,
×
UNCOV
1330
                        DB:        s.chanStateDB,
×
UNCOV
1331
                        Estimator: s.cc.FeeEstimator,
×
UNCOV
1332
                        GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1333
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1334
                        ),
×
UNCOV
1335
                        Notifier:           cc.ChainNotifier,
×
UNCOV
1336
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1337
                        ContractBreaches:   contractBreaches,
×
UNCOV
1338
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1339
                        Store: contractcourt.NewRetributionStore(
×
UNCOV
1340
                                dbs.ChanStateDB,
×
UNCOV
1341
                        ),
×
UNCOV
1342
                        AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1343
                },
×
UNCOV
1344
        )
×
UNCOV
1345

×
UNCOV
1346
        //nolint:ll
×
UNCOV
1347
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
UNCOV
1348
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1349
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
UNCOV
1350
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
UNCOV
1351
                NewSweepAddr: func() ([]byte, error) {
×
1352
                        addr, err := newSweepPkScriptGen(
×
1353
                                cc.Wallet, netParams,
×
1354
                        )().Unpack()
×
1355
                        if err != nil {
×
1356
                                return nil, err
×
1357
                        }
×
1358

1359
                        return addr.DeliveryAddress, nil
×
1360
                },
1361
                PublishTx: cc.Wallet.PublishTransaction,
UNCOV
1362
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
UNCOV
1363
                        for _, msg := range msgs {
×
UNCOV
1364
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
UNCOV
1365
                                if err != nil {
×
1366
                                        return err
×
1367
                                }
×
1368
                        }
UNCOV
1369
                        return nil
×
1370
                },
1371
                IncubateOutputs: func(chanPoint wire.OutPoint,
1372
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1373
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1374
                        broadcastHeight uint32,
UNCOV
1375
                        deadlineHeight fn.Option[int32]) error {
×
UNCOV
1376

×
UNCOV
1377
                        return s.utxoNursery.IncubateOutputs(
×
UNCOV
1378
                                chanPoint, outHtlcRes, inHtlcRes,
×
UNCOV
1379
                                broadcastHeight, deadlineHeight,
×
UNCOV
1380
                        )
×
UNCOV
1381
                },
×
1382
                PreimageDB:   s.witnessBeacon,
1383
                Notifier:     cc.ChainNotifier,
1384
                Mempool:      cc.MempoolNotifier,
1385
                Signer:       cc.Wallet.Cfg.Signer,
1386
                FeeEstimator: cc.FeeEstimator,
1387
                ChainIO:      cc.ChainIO,
UNCOV
1388
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
UNCOV
1389
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1390
                        s.htlcSwitch.RemoveLink(chanID)
×
UNCOV
1391
                        return nil
×
UNCOV
1392
                },
×
1393
                IsOurAddress: cc.Wallet.IsOurAddress,
1394
                ContractBreach: func(chanPoint wire.OutPoint,
UNCOV
1395
                        breachRet *lnwallet.BreachRetribution) error {
×
UNCOV
1396

×
UNCOV
1397
                        // processACK will handle the BreachArbitrator ACKing
×
UNCOV
1398
                        // the event.
×
UNCOV
1399
                        finalErr := make(chan error, 1)
×
UNCOV
1400
                        processACK := func(brarErr error) {
×
UNCOV
1401
                                if brarErr != nil {
×
1402
                                        finalErr <- brarErr
×
1403
                                        return
×
1404
                                }
×
1405

1406
                                // If the BreachArbitrator successfully handled
1407
                                // the event, we can signal that the handoff
1408
                                // was successful.
UNCOV
1409
                                finalErr <- nil
×
1410
                        }
1411

UNCOV
1412
                        event := &contractcourt.ContractBreachEvent{
×
UNCOV
1413
                                ChanPoint:         chanPoint,
×
UNCOV
1414
                                ProcessACK:        processACK,
×
UNCOV
1415
                                BreachRetribution: breachRet,
×
UNCOV
1416
                        }
×
UNCOV
1417

×
UNCOV
1418
                        // Send the contract breach event to the
×
UNCOV
1419
                        // BreachArbitrator.
×
UNCOV
1420
                        select {
×
UNCOV
1421
                        case contractBreaches <- event:
×
1422
                        case <-s.quit:
×
1423
                                return ErrServerShuttingDown
×
1424
                        }
1425

1426
                        // We'll wait for a final error to be available from
1427
                        // the BreachArbitrator.
UNCOV
1428
                        select {
×
UNCOV
1429
                        case err := <-finalErr:
×
UNCOV
1430
                                return err
×
1431
                        case <-s.quit:
×
1432
                                return ErrServerShuttingDown
×
1433
                        }
1434
                },
UNCOV
1435
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
UNCOV
1436
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
UNCOV
1437
                },
×
1438
                Sweeper:                       s.sweeper,
1439
                Registry:                      s.invoices,
1440
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1441
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1442
                OnionProcessor:                s.sphinx,
1443
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1444
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1445
                Clock:                         clock.NewDefaultClock(),
1446
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1447
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1448
                HtlcNotifier:                  s.htlcNotifier,
1449
                Budget:                        *s.cfg.Sweeper.Budget,
1450

1451
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1452
                QueryIncomingCircuit: func(
UNCOV
1453
                        circuit models.CircuitKey) *models.CircuitKey {
×
UNCOV
1454

×
UNCOV
1455
                        // Get the circuit map.
×
UNCOV
1456
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1457

×
UNCOV
1458
                        // Lookup the outgoing circuit.
×
UNCOV
1459
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1460
                        if pc == nil {
×
UNCOV
1461
                                return nil
×
UNCOV
1462
                        }
×
1463

UNCOV
1464
                        return &pc.Incoming
×
1465
                },
1466
                AuxLeafStore: implCfg.AuxLeafStore,
1467
                AuxSigner:    implCfg.AuxSigner,
1468
                AuxResolver:  implCfg.AuxContractResolver,
1469
        }, dbs.ChanStateDB)
1470

1471
        // Select the configuration and funding parameters for Bitcoin.
UNCOV
1472
        chainCfg := cfg.Bitcoin
×
UNCOV
1473
        minRemoteDelay := funding.MinBtcRemoteDelay
×
UNCOV
1474
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
UNCOV
1475

×
UNCOV
1476
        var chanIDSeed [32]byte
×
UNCOV
1477
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1478
                return nil, err
×
1479
        }
×
1480

1481
        // Wrap the DeleteChannelEdges method so that the funding manager can
1482
        // use it without depending on several layers of indirection.
UNCOV
1483
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
UNCOV
1484
                *models.ChannelEdgePolicy, error) {
×
UNCOV
1485

×
UNCOV
1486
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
UNCOV
1487
                        scid.ToUint64(),
×
UNCOV
1488
                )
×
UNCOV
1489
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1490
                        // This is unlikely but there is a slim chance of this
×
1491
                        // being hit if lnd was killed via SIGKILL and the
×
1492
                        // funding manager was stepping through the delete
×
1493
                        // alias edge logic.
×
1494
                        return nil, nil
×
UNCOV
1495
                } else if err != nil {
×
1496
                        return nil, err
×
1497
                }
×
1498

1499
                // Grab our key to find our policy.
UNCOV
1500
                var ourKey [33]byte
×
UNCOV
1501
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1502

×
UNCOV
1503
                var ourPolicy *models.ChannelEdgePolicy
×
UNCOV
1504
                if info != nil && info.NodeKey1Bytes == ourKey {
×
UNCOV
1505
                        ourPolicy = e1
×
UNCOV
1506
                } else {
×
UNCOV
1507
                        ourPolicy = e2
×
UNCOV
1508
                }
×
1509

UNCOV
1510
                if ourPolicy == nil {
×
1511
                        // Something is wrong, so return an error.
×
1512
                        return nil, fmt.Errorf("we don't have an edge")
×
1513
                }
×
1514

UNCOV
1515
                err = s.graphDB.DeleteChannelEdges(
×
UNCOV
1516
                        false, false, scid.ToUint64(),
×
UNCOV
1517
                )
×
UNCOV
1518
                return ourPolicy, err
×
1519
        }
1520

1521
        // For the reservationTimeout and the zombieSweeperInterval different
1522
        // values are set in case we are in a dev environment so enhance test
1523
        // capacilities.
UNCOV
1524
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1525
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1526

×
UNCOV
1527
        // Get the development config for funding manager. If we are not in
×
UNCOV
1528
        // development mode, this would be nil.
×
UNCOV
1529
        var devCfg *funding.DevConfig
×
UNCOV
1530
        if lncfg.IsDevBuild() {
×
UNCOV
1531
                devCfg = &funding.DevConfig{
×
UNCOV
1532
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1533
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
×
UNCOV
1534
                                GetMaxWaitNumBlocksFundingConf(),
×
UNCOV
1535
                }
×
UNCOV
1536

×
UNCOV
1537
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1538
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1539

×
UNCOV
1540
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1541
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1542
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1543
        }
×
1544

1545
        //nolint:ll
UNCOV
1546
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1547
                Dev:                devCfg,
×
UNCOV
1548
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1549
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1550
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1551
                Wallet:             cc.Wallet,
×
UNCOV
1552
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1553
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1554
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1555
                },
×
1556
                Notifier:     cc.ChainNotifier,
1557
                ChannelDB:    s.chanStateDB,
1558
                FeeEstimator: cc.FeeEstimator,
1559
                SignMessage:  cc.MsgSigner.SignMessage,
1560
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1561
                        error) {
×
UNCOV
1562

×
UNCOV
1563
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1564
                },
×
1565
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1566
                NotifyWhenOnline:     s.NotifyWhenOnline,
1567
                TempChanIDSeed:       chanIDSeed,
1568
                FindChannel:          s.findChannel,
1569
                DefaultRoutingPolicy: cc.RoutingPolicy,
1570
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1571
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1572
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1573
                        // For large channels we increase the number
×
UNCOV
1574
                        // of confirmations we require for the
×
UNCOV
1575
                        // channel to be considered open. As it is
×
UNCOV
1576
                        // always the responder that gets to choose
×
UNCOV
1577
                        // value, the pushAmt is value being pushed
×
UNCOV
1578
                        // to us. This means we have more to lose
×
UNCOV
1579
                        // in the case this gets re-orged out, and
×
UNCOV
1580
                        // we will require more confirmations before
×
UNCOV
1581
                        // we consider it open.
×
UNCOV
1582

×
UNCOV
1583
                        // In case the user has explicitly specified
×
UNCOV
1584
                        // a default value for the number of
×
UNCOV
1585
                        // confirmations, we use it.
×
UNCOV
1586
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1587
                        if defaultConf != 0 {
×
UNCOV
1588
                                return defaultConf
×
UNCOV
1589
                        }
×
1590

1591
                        minConf := uint64(3)
×
1592
                        maxConf := uint64(6)
×
1593

×
1594
                        // If this is a wumbo channel, then we'll require the
×
1595
                        // max amount of confirmations.
×
1596
                        if chanAmt > MaxFundingAmount {
×
1597
                                return uint16(maxConf)
×
1598
                        }
×
1599

1600
                        // If not we return a value scaled linearly
1601
                        // between 3 and 6, depending on channel size.
1602
                        // TODO(halseth): Use 1 as minimum?
1603
                        maxChannelSize := uint64(
×
1604
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1605
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1606
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1607
                        if conf < minConf {
×
1608
                                conf = minConf
×
1609
                        }
×
1610
                        if conf > maxConf {
×
1611
                                conf = maxConf
×
1612
                        }
×
1613
                        return uint16(conf)
×
1614
                },
UNCOV
1615
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1616
                        // We scale the remote CSV delay (the time the
×
UNCOV
1617
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1618
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1619
                        // for small channels, to maxRemoteDelay blocks
×
UNCOV
1620
                        // for channels of size MaxFundingAmount.
×
UNCOV
1621

×
UNCOV
1622
                        // In case the user has explicitly specified
×
UNCOV
1623
                        // a default value for the remote delay, we
×
UNCOV
1624
                        // use it.
×
UNCOV
1625
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1626
                        if defaultDelay > 0 {
×
UNCOV
1627
                                return defaultDelay
×
UNCOV
1628
                        }
×
1629

1630
                        // If this is a wumbo channel, then we'll require the
1631
                        // max value.
1632
                        if chanAmt > MaxFundingAmount {
×
1633
                                return maxRemoteDelay
×
1634
                        }
×
1635

1636
                        // If not we scale according to channel size.
1637
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1638
                                chanAmt / MaxFundingAmount)
×
1639
                        if delay < minRemoteDelay {
×
1640
                                delay = minRemoteDelay
×
1641
                        }
×
1642
                        if delay > maxRemoteDelay {
×
1643
                                delay = maxRemoteDelay
×
1644
                        }
×
1645
                        return delay
×
1646
                },
1647
                WatchNewChannel: func(channel *channeldb.OpenChannel,
UNCOV
1648
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1649

×
UNCOV
1650
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1651
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1652
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1653
                        // we'll set false to prevent the server from continuing
×
UNCOV
1654
                        // to connect to this peer even if the number of
×
UNCOV
1655
                        // channels with this peer is zero.
×
UNCOV
1656
                        s.mu.Lock()
×
UNCOV
1657
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1658
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1659
                                s.persistentPeers[pubStr] = false
×
UNCOV
1660
                        }
×
UNCOV
1661
                        s.mu.Unlock()
×
UNCOV
1662

×
UNCOV
1663
                        // With that taken care of, we'll send this channel to
×
UNCOV
1664
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1665
                        return s.chainArb.WatchNewChannel(channel)
×
1666
                },
UNCOV
1667
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1668
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1669
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1670
                },
×
1671
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1672
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1673

×
UNCOV
1674
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1675
                        // at least 1% of the total channel capacity at all
×
UNCOV
1676
                        // times. If this value ends up dipping below the dust
×
UNCOV
1677
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1678
                        // reserve as required by BOLT #2.
×
UNCOV
1679
                        reserve := chanAmt / 100
×
UNCOV
1680
                        if reserve < dustLimit {
×
UNCOV
1681
                                reserve = dustLimit
×
UNCOV
1682
                        }
×
1683

UNCOV
1684
                        return reserve
×
1685
                },
UNCOV
1686
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1687
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1688
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1689
                        // required reserve.
×
UNCOV
1690
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1691
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1692
                },
×
UNCOV
1693
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1694
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1695
                                return cfg.DefaultRemoteMaxHtlcs
×
UNCOV
1696
                        }
×
1697

1698
                        // By default, we'll permit them to utilize the full
1699
                        // channel bandwidth.
1700
                        return uint16(input.MaxHTLCNumber / 2)
×
1701
                },
1702
                ZombieSweeperInterval:         zombieSweeperInterval,
1703
                ReservationTimeout:            reservationTimeout,
1704
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1705
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1706
                MaxPendingChannels:            cfg.MaxPendingChannels,
1707
                RejectPush:                    cfg.RejectPush,
1708
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1709
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1710
                OpenChannelPredicate:          chanPredicate,
1711
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1712
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1713
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1714
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1715
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1716
                DeleteAliasEdge:      deleteAliasEdge,
1717
                AliasManager:         s.aliasMgr,
1718
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1719
                AuxFundingController: implCfg.AuxFundingController,
1720
                AuxSigner:            implCfg.AuxSigner,
1721
                AuxResolver:          implCfg.AuxContractResolver,
1722
        })
UNCOV
1723
        if err != nil {
×
1724
                return nil, err
×
1725
        }
×
1726

1727
        // Next, we'll assemble the sub-system that will maintain an on-disk
1728
        // static backup of the latest channel state.
UNCOV
1729
        chanNotifier := &channelNotifier{
×
UNCOV
1730
                chanNotifier: s.channelNotifier,
×
UNCOV
1731
                addrs:        s.addrSource,
×
UNCOV
1732
        }
×
UNCOV
1733
        backupFile := chanbackup.NewMultiFile(
×
UNCOV
1734
                cfg.BackupFilePath, cfg.NoBackupArchive,
×
UNCOV
1735
        )
×
UNCOV
1736
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1737
                ctx, s.chanStateDB, s.addrSource,
×
UNCOV
1738
        )
×
UNCOV
1739
        if err != nil {
×
1740
                return nil, err
×
1741
        }
×
UNCOV
1742
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1743
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1744
        )
×
UNCOV
1745
        if err != nil {
×
1746
                return nil, err
×
1747
        }
×
1748

1749
        // Assemble a peer notifier which will provide clients with subscriptions
1750
        // to peer online and offline events.
UNCOV
1751
        s.peerNotifier = peernotifier.New()
×
UNCOV
1752

×
UNCOV
1753
        // Create a channel event store which monitors all open channels.
×
UNCOV
1754
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1755
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1756
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1757
                },
×
UNCOV
1758
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1759
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1760
                },
×
1761
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1762
                Clock:           clock.NewDefaultClock(),
1763
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1764
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1765
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1766
        })
1767

UNCOV
1768
        if cfg.WtClient.Active {
×
UNCOV
1769
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1770
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1771

×
UNCOV
1772
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1773
                // protocol operations on sat/kw.
×
UNCOV
1774
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1775
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1776
                )
×
UNCOV
1777

×
UNCOV
1778
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1779

×
UNCOV
1780
                if err := policy.Validate(); err != nil {
×
1781
                        return nil, err
×
1782
                }
×
1783

1784
                // authDial is the wrapper around the btrontide.Dial for the
1785
                // watchtower.
UNCOV
1786
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1787
                        netAddr *lnwire.NetAddress,
×
UNCOV
1788
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1789

×
UNCOV
1790
                        return brontide.Dial(
×
UNCOV
1791
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1792
                        )
×
UNCOV
1793
                }
×
1794

1795
                // buildBreachRetribution is a call-back that can be used to
1796
                // query the BreachRetribution info and channel type given a
1797
                // channel ID and commitment height.
UNCOV
1798
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1799
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1800
                        channeldb.ChannelType, error) {
×
UNCOV
1801

×
UNCOV
1802
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1803
                                nil, chanID,
×
UNCOV
1804
                        )
×
UNCOV
1805
                        if err != nil {
×
1806
                                return nil, 0, err
×
1807
                        }
×
1808

UNCOV
1809
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1810
                                channel, commitHeight, 0, nil,
×
UNCOV
1811
                                implCfg.AuxLeafStore,
×
UNCOV
1812
                                implCfg.AuxContractResolver,
×
UNCOV
1813
                        )
×
UNCOV
1814
                        if err != nil {
×
1815
                                return nil, 0, err
×
1816
                        }
×
1817

UNCOV
1818
                        return br, channel.ChanType, nil
×
1819
                }
1820

UNCOV
1821
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1822

×
UNCOV
1823
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1824
                // signalling support for anchor channels.
×
UNCOV
1825
                anchorPolicy := policy
×
UNCOV
1826
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1827

×
UNCOV
1828
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1829
                // signalling support for taproot channels.
×
UNCOV
1830
                taprootPolicy := policy
×
UNCOV
1831
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1832
                        blob.FlagTaprootChannel,
×
UNCOV
1833
                )
×
UNCOV
1834

×
UNCOV
1835
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1836
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1837
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1838
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1839
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1840
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1841
                                error) {
×
UNCOV
1842

×
UNCOV
1843
                                return s.channelNotifier.
×
UNCOV
1844
                                        SubscribeChannelEvents()
×
UNCOV
1845
                        },
×
1846
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1847
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1848
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1849
                                        cc.Wallet, netParams,
×
UNCOV
1850
                                )().Unpack()
×
UNCOV
1851
                                if err != nil {
×
1852
                                        return nil, err
×
1853
                                }
×
1854

UNCOV
1855
                                return addr.DeliveryAddress, nil
×
1856
                        },
1857
                        SecretKeyRing:      s.cc.KeyRing,
1858
                        Dial:               cfg.net.Dial,
1859
                        AuthDial:           authDial,
1860
                        DB:                 dbs.TowerClientDB,
1861
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1862
                        MinBackoff:         10 * time.Second,
1863
                        MaxBackoff:         5 * time.Minute,
1864
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1865
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1866
                if err != nil {
×
1867
                        return nil, err
×
1868
                }
×
1869
        }
1870

UNCOV
1871
        if len(cfg.ExternalHosts) != 0 {
×
1872
                advertisedIPs := make(map[string]struct{})
×
1873
                for _, addr := range s.currentNodeAnn.Addresses {
×
1874
                        advertisedIPs[addr.String()] = struct{}{}
×
1875
                }
×
1876

1877
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1878
                        Hosts:         cfg.ExternalHosts,
×
1879
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1880
                        LookupHost: func(host string) (net.Addr, error) {
×
1881
                                return lncfg.ParseAddressString(
×
1882
                                        host, strconv.Itoa(defaultPeerPort),
×
1883
                                        cfg.net.ResolveTCPAddr,
×
1884
                                )
×
1885
                        },
×
1886
                        AdvertisedIPs: advertisedIPs,
1887
                        AnnounceNewIPs: netann.IPAnnouncer(
1888
                                func(modifier ...netann.NodeAnnModifier) (
1889
                                        lnwire.NodeAnnouncement, error) {
×
1890

×
1891
                                        return s.genNodeAnnouncement(
×
1892
                                                nil, modifier...,
×
1893
                                        )
×
1894
                                }),
×
1895
                })
1896
        }
1897

1898
        // Create liveness monitor.
UNCOV
1899
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1900

×
UNCOV
1901
        listeners := make([]net.Listener, len(listenAddrs))
×
UNCOV
1902
        for i, listenAddr := range listenAddrs {
×
UNCOV
1903
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
UNCOV
1904
                // doesn't need to call the general lndResolveTCP function
×
UNCOV
1905
                // since we are resolving a local address.
×
UNCOV
1906

×
UNCOV
1907
                // RESOLVE: We are actually partially accepting inbound
×
UNCOV
1908
                // connection requests when we call NewListener.
×
UNCOV
1909
                listeners[i], err = brontide.NewListener(
×
UNCOV
1910
                        nodeKeyECDH, listenAddr.String(),
×
UNCOV
1911
                        // TODO(yy): remove this check and unify the inbound
×
UNCOV
1912
                        // connection check inside `InboundPeerConnected`.
×
UNCOV
1913
                        s.peerAccessMan.checkAcceptIncomingConn,
×
UNCOV
1914
                )
×
UNCOV
1915
                if err != nil {
×
1916
                        return nil, err
×
1917
                }
×
1918
        }
1919

1920
        // Create the connection manager which will be responsible for
1921
        // maintaining persistent outbound connections and also accepting new
1922
        // incoming connections
UNCOV
1923
        cmgr, err := connmgr.New(&connmgr.Config{
×
UNCOV
1924
                Listeners:      listeners,
×
UNCOV
1925
                OnAccept:       s.InboundPeerConnected,
×
UNCOV
1926
                RetryDuration:  time.Second * 5,
×
UNCOV
1927
                TargetOutbound: 100,
×
UNCOV
1928
                Dial: noiseDial(
×
UNCOV
1929
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
1930
                ),
×
UNCOV
1931
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
1932
        })
×
UNCOV
1933
        if err != nil {
×
1934
                return nil, err
×
1935
        }
×
UNCOV
1936
        s.connMgr = cmgr
×
UNCOV
1937

×
UNCOV
1938
        // Finally, register the subsystems in blockbeat.
×
UNCOV
1939
        s.registerBlockConsumers()
×
UNCOV
1940

×
UNCOV
1941
        return s, nil
×
1942
}
1943

1944
// UpdateRoutingConfig is a callback function to update the routing config
1945
// values in the main cfg.
UNCOV
1946
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
1947
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
1948

×
UNCOV
1949
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
1950
        case routing.AprioriConfig:
×
UNCOV
1951
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1952
                        routing.AprioriEstimatorName
×
UNCOV
1953

×
UNCOV
1954
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1955
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1956
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1957
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1958
                targetCfg.HopProbability = c.AprioriHopProbability
×
1959

UNCOV
1960
        case routing.BimodalConfig:
×
UNCOV
1961
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1962
                        routing.BimodalEstimatorName
×
UNCOV
1963

×
UNCOV
1964
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1965
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1966
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1967
                targetCfg.DecayTime = c.BimodalDecayTime
×
1968
        }
1969

UNCOV
1970
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1971
}
1972

1973
// registerBlockConsumers registers the subsystems that consume block events.
1974
// By calling `RegisterQueue`, a list of subsystems are registered in the
1975
// blockbeat for block notifications. When a new block arrives, the subsystems
1976
// in the same queue are notified sequentially, and different queues are
1977
// notified concurrently.
1978
//
1979
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1980
// a new `RegisterQueue` call.
UNCOV
1981
func (s *server) registerBlockConsumers() {
×
UNCOV
1982
        // In this queue, when a new block arrives, it will be received and
×
UNCOV
1983
        // processed in this order: chainArb -> sweeper -> txPublisher.
×
UNCOV
1984
        consumers := []chainio.Consumer{
×
UNCOV
1985
                s.chainArb,
×
UNCOV
1986
                s.sweeper,
×
UNCOV
1987
                s.txPublisher,
×
UNCOV
1988
        }
×
UNCOV
1989
        s.blockbeatDispatcher.RegisterQueue(consumers)
×
UNCOV
1990
}
×
1991

1992
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1993
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1994
// may differ from what is on disk.
1995
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
1996
        error) {
×
UNCOV
1997

×
UNCOV
1998
        data, err := u.DataToSign()
×
UNCOV
1999
        if err != nil {
×
2000
                return nil, err
×
2001
        }
×
2002

UNCOV
2003
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
2004
}
2005

2006
// createLivenessMonitor creates a set of health checks using our configured
2007
// values and uses these checks to create a liveness monitor. Available
2008
// health checks,
2009
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2010
//   - diskCheck
2011
//   - tlsHealthCheck
2012
//   - torController, only created when tor is enabled.
2013
//
2014
// If a health check has been disabled by setting attempts to 0, our monitor
2015
// will not run it.
2016
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
UNCOV
2017
        leaderElector cluster.LeaderElector) {
×
UNCOV
2018

×
UNCOV
2019
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
2020
        if cfg.Bitcoin.Node == "nochainbackend" {
×
2021
                srvrLog.Info("Disabling chain backend checks for " +
×
2022
                        "nochainbackend mode")
×
2023

×
2024
                chainBackendAttempts = 0
×
2025
        }
×
2026

UNCOV
2027
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
2028
                "chain backend",
×
UNCOV
2029
                cc.HealthCheck,
×
UNCOV
2030
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
2031
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
2032
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
2033
                chainBackendAttempts,
×
UNCOV
2034
        )
×
UNCOV
2035

×
UNCOV
2036
        diskCheck := healthcheck.NewObservation(
×
UNCOV
2037
                "disk space",
×
UNCOV
2038
                func() error {
×
2039
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2040
                                cfg.LndDir,
×
2041
                        )
×
2042
                        if err != nil {
×
2043
                                return err
×
2044
                        }
×
2045

2046
                        // If we have more free space than we require,
2047
                        // we return a nil error.
2048
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2049
                                return nil
×
2050
                        }
×
2051

2052
                        return fmt.Errorf("require: %v free space, got: %v",
×
2053
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2054
                                free)
×
2055
                },
2056
                cfg.HealthChecks.DiskCheck.Interval,
2057
                cfg.HealthChecks.DiskCheck.Timeout,
2058
                cfg.HealthChecks.DiskCheck.Backoff,
2059
                cfg.HealthChecks.DiskCheck.Attempts,
2060
        )
2061

UNCOV
2062
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
2063
                "tls",
×
UNCOV
2064
                func() error {
×
2065
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2066
                                s.cc.KeyRing,
×
2067
                        )
×
2068
                        if err != nil {
×
2069
                                return err
×
2070
                        }
×
2071
                        if expired {
×
2072
                                return fmt.Errorf("TLS certificate is "+
×
2073
                                        "expired as of %v", expTime)
×
2074
                        }
×
2075

2076
                        // If the certificate is not outdated, no error needs
2077
                        // to be returned
2078
                        return nil
×
2079
                },
2080
                cfg.HealthChecks.TLSCheck.Interval,
2081
                cfg.HealthChecks.TLSCheck.Timeout,
2082
                cfg.HealthChecks.TLSCheck.Backoff,
2083
                cfg.HealthChecks.TLSCheck.Attempts,
2084
        )
2085

UNCOV
2086
        checks := []*healthcheck.Observation{
×
UNCOV
2087
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
2088
        }
×
UNCOV
2089

×
UNCOV
2090
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
2091
        if s.torController != nil {
×
2092
                torConnectionCheck := healthcheck.NewObservation(
×
2093
                        "tor connection",
×
2094
                        func() error {
×
2095
                                return healthcheck.CheckTorServiceStatus(
×
2096
                                        s.torController,
×
2097
                                        func() error {
×
2098
                                                return s.createNewHiddenService(
×
2099
                                                        context.TODO(),
×
2100
                                                )
×
2101
                                        },
×
2102
                                )
2103
                        },
2104
                        cfg.HealthChecks.TorConnection.Interval,
2105
                        cfg.HealthChecks.TorConnection.Timeout,
2106
                        cfg.HealthChecks.TorConnection.Backoff,
2107
                        cfg.HealthChecks.TorConnection.Attempts,
2108
                )
2109
                checks = append(checks, torConnectionCheck)
×
2110
        }
2111

2112
        // If remote signing is enabled, add the healthcheck for the remote
2113
        // signing RPC interface.
UNCOV
2114
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
2115
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
2116
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
2117
                // returns exactly on time.
×
UNCOV
2118
                overhead := time.Millisecond * 10
×
UNCOV
2119

×
UNCOV
2120
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
2121
                        "remote signer connection",
×
UNCOV
2122
                        rpcwallet.HealthCheck(
×
UNCOV
2123
                                s.cfg.RemoteSigner,
×
UNCOV
2124

×
UNCOV
2125
                                // For the health check we might to be even
×
UNCOV
2126
                                // stricter than the initial/normal connect, so
×
UNCOV
2127
                                // we use the health check timeout here.
×
UNCOV
2128
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
2129
                        ),
×
UNCOV
2130
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
2131
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
2132
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
2133
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
2134
                )
×
UNCOV
2135
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
2136
        }
×
2137

2138
        // If we have a leader elector, we add a health check to ensure we are
2139
        // still the leader. During normal operation, we should always be the
2140
        // leader, but there are circumstances where this may change, such as
2141
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
2142
        if leaderElector != nil {
×
2143
                leaderCheck := healthcheck.NewObservation(
×
2144
                        "leader status",
×
2145
                        func() error {
×
2146
                                // Check if we are still the leader. Note that
×
2147
                                // we don't need to use a timeout context here
×
2148
                                // as the healthcheck observer will handle the
×
2149
                                // timeout case for us.
×
2150
                                timeoutCtx, cancel := context.WithTimeout(
×
2151
                                        context.Background(),
×
2152
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2153
                                )
×
2154
                                defer cancel()
×
2155

×
2156
                                leader, err := leaderElector.IsLeader(
×
2157
                                        timeoutCtx,
×
2158
                                )
×
2159
                                if err != nil {
×
2160
                                        return fmt.Errorf("unable to check if "+
×
2161
                                                "still leader: %v", err)
×
2162
                                }
×
2163

2164
                                if !leader {
×
2165
                                        srvrLog.Debug("Not the current leader")
×
2166
                                        return fmt.Errorf("not the current " +
×
2167
                                                "leader")
×
2168
                                }
×
2169

2170
                                return nil
×
2171
                        },
2172
                        cfg.HealthChecks.LeaderCheck.Interval,
2173
                        cfg.HealthChecks.LeaderCheck.Timeout,
2174
                        cfg.HealthChecks.LeaderCheck.Backoff,
2175
                        cfg.HealthChecks.LeaderCheck.Attempts,
2176
                )
2177

2178
                checks = append(checks, leaderCheck)
×
2179
        }
2180

2181
        // If we have not disabled all of our health checks, we create a
2182
        // liveness monitor with our configured checks.
UNCOV
2183
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2184
                &healthcheck.Config{
×
UNCOV
2185
                        Checks:   checks,
×
UNCOV
2186
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2187
                },
×
UNCOV
2188
        )
×
2189
}
2190

2191
// Started returns true if the server has been started, and false otherwise.
2192
// NOTE: This function is safe for concurrent access.
UNCOV
2193
func (s *server) Started() bool {
×
UNCOV
2194
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2195
}
×
2196

2197
// cleaner is used to aggregate "cleanup" functions during an operation that
2198
// starts several subsystems. In case one of the subsystem fails to start
2199
// and a proper resource cleanup is required, the "run" method achieves this
2200
// by running all these added "cleanup" functions.
2201
type cleaner []func() error
2202

2203
// add is used to add a cleanup function to be called when
2204
// the run function is executed.
UNCOV
2205
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2206
        return append(c, cleanup)
×
UNCOV
2207
}
×
2208

2209
// run is used to run all the previousely added cleanup functions.
2210
func (c cleaner) run() {
×
2211
        for i := len(c) - 1; i >= 0; i-- {
×
2212
                if err := c[i](); err != nil {
×
2213
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2214
                }
×
2215
        }
2216
}
2217

2218
// startLowLevelServices starts the low-level services of the server. These
2219
// services must be started successfully before running the main server. The
2220
// services are,
2221
// 1. the chain notifier.
2222
//
2223
// TODO(yy): identify and add more low-level services here.
UNCOV
2224
func (s *server) startLowLevelServices() error {
×
UNCOV
2225
        var startErr error
×
UNCOV
2226

×
UNCOV
2227
        cleanup := cleaner{}
×
UNCOV
2228

×
UNCOV
2229
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
UNCOV
2230
        if err := s.cc.ChainNotifier.Start(); err != nil {
×
2231
                startErr = err
×
2232
        }
×
2233

UNCOV
2234
        if startErr != nil {
×
2235
                cleanup.run()
×
2236
        }
×
2237

UNCOV
2238
        return startErr
×
2239
}
2240

2241
// Start starts the main daemon server, all requested listeners, and any helper
2242
// goroutines.
2243
// NOTE: This function is safe for concurrent access.
2244
//
2245
//nolint:funlen
UNCOV
2246
func (s *server) Start(ctx context.Context) error {
×
UNCOV
2247
        // Get the current blockbeat.
×
UNCOV
2248
        beat, err := s.getStartingBeat()
×
UNCOV
2249
        if err != nil {
×
2250
                return err
×
2251
        }
×
2252

UNCOV
2253
        var startErr error
×
UNCOV
2254

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

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

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

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

2283
                // Start the notification server. This is used so channel
2284
                // management goroutines can be notified when a funding
2285
                // transaction reaches a sufficient number of confirmations, or
2286
                // when the input for the funding transaction is spent in an
2287
                // attempt at an uncooperative close by the counterparty.
UNCOV
2288
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2289
                if err := s.sigPool.Start(); err != nil {
×
2290
                        startErr = err
×
2291
                        return
×
2292
                }
×
2293

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

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

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

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

UNCOV
2318
                cleanup = cleanup.add(func() error {
×
2319
                        return s.peerNotifier.Stop()
×
2320
                })
×
UNCOV
2321
                if err := s.peerNotifier.Start(); err != nil {
×
2322
                        startErr = err
×
2323
                        return
×
2324
                }
×
2325

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

UNCOV
2332
                if s.towerClientMgr != nil {
×
UNCOV
2333
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
×
UNCOV
2334
                        if err := s.towerClientMgr.Start(); err != nil {
×
2335
                                startErr = err
×
2336
                                return
×
2337
                        }
×
2338
                }
2339

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

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

UNCOV
2352
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
UNCOV
2353
                if err := s.utxoNursery.Start(); err != nil {
×
2354
                        startErr = err
×
2355
                        return
×
2356
                }
×
2357

UNCOV
2358
                cleanup = cleanup.add(s.breachArbitrator.Stop)
×
UNCOV
2359
                if err := s.breachArbitrator.Start(); err != nil {
×
2360
                        startErr = err
×
2361
                        return
×
2362
                }
×
2363

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

2370
                // htlcSwitch must be started before chainArb since the latter
2371
                // relies on htlcSwitch to deliver resolution message upon
2372
                // start.
UNCOV
2373
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2374
                if err := s.htlcSwitch.Start(); err != nil {
×
2375
                        startErr = err
×
2376
                        return
×
2377
                }
×
2378

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

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

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

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

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

UNCOV
2409
                cleanup = cleanup.add(s.chanRouter.Stop)
×
UNCOV
2410
                if err := s.chanRouter.Start(); err != nil {
×
2411
                        startErr = err
×
2412
                        return
×
2413
                }
×
2414
                // The authGossiper depends on the chanRouter and therefore
2415
                // should be started after it.
UNCOV
2416
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2417
                if err := s.authGossiper.Start(); err != nil {
×
2418
                        startErr = err
×
2419
                        return
×
2420
                }
×
2421

UNCOV
2422
                cleanup = cleanup.add(s.invoices.Stop)
×
UNCOV
2423
                if err := s.invoices.Start(); err != nil {
×
2424
                        startErr = err
×
2425
                        return
×
2426
                }
×
2427

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

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

UNCOV
2440
                cleanup = cleanup.add(s.chanEventStore.Stop)
×
UNCOV
2441
                if err := s.chanEventStore.Start(); err != nil {
×
2442
                        startErr = err
×
2443
                        return
×
2444
                }
×
2445

UNCOV
2446
                cleanup.add(func() error {
×
2447
                        s.missionController.StopStoreTickers()
×
2448
                        return nil
×
2449
                })
×
UNCOV
2450
                s.missionController.RunStoreTickers()
×
UNCOV
2451

×
UNCOV
2452
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2453
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2454
                // that have all the information we need to handle channel
×
UNCOV
2455
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2456
                chanRestorer := &chanDBRestorer{
×
UNCOV
2457
                        db:         s.chanStateDB,
×
UNCOV
2458
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2459
                        chainArb:   s.chainArb,
×
UNCOV
2460
                }
×
UNCOV
2461
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2462
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2463
                                s.chansToRestore.PackedSingleChanBackups,
×
2464
                                s.cc.KeyRing, chanRestorer, s,
×
2465
                        )
×
2466
                        if err != nil {
×
2467
                                startErr = fmt.Errorf("unable to unpack single "+
×
2468
                                        "backups: %v", err)
×
2469
                                return
×
2470
                        }
×
2471
                }
UNCOV
2472
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2473
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2474
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2475
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2476
                        )
×
UNCOV
2477
                        if err != nil {
×
2478
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2479
                                        "backup: %v", err)
×
2480
                                return
×
2481
                        }
×
2482
                }
2483

2484
                // chanSubSwapper must be started after the `channelNotifier`
2485
                // because it depends on channel events as a synchronization
2486
                // point.
UNCOV
2487
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2488
                if err := s.chanSubSwapper.Start(); err != nil {
×
2489
                        startErr = err
×
2490
                        return
×
2491
                }
×
2492

UNCOV
2493
                if s.torController != nil {
×
2494
                        cleanup = cleanup.add(s.torController.Stop)
×
2495
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2496
                                startErr = err
×
2497
                                return
×
2498
                        }
×
2499
                }
2500

UNCOV
2501
                if s.natTraversal != nil {
×
2502
                        s.wg.Add(1)
×
2503
                        go s.watchExternalIP()
×
2504
                }
×
2505

2506
                // Start connmgr last to prevent connections before init.
UNCOV
2507
                cleanup = cleanup.add(func() error {
×
2508
                        s.connMgr.Stop()
×
2509
                        return nil
×
2510
                })
×
2511

2512
                // RESOLVE: s.connMgr.Start() is called here, but
2513
                // brontide.NewListener() is called in newServer. This means
2514
                // that we are actually listening and partially accepting
2515
                // inbound connections even before the connMgr starts.
2516
                //
2517
                // TODO(yy): move the log into the connMgr's `Start` method.
UNCOV
2518
                srvrLog.Info("connMgr starting...")
×
UNCOV
2519
                s.connMgr.Start()
×
UNCOV
2520
                srvrLog.Debug("connMgr started")
×
UNCOV
2521

×
UNCOV
2522
                // If peers are specified as a config option, we'll add those
×
UNCOV
2523
                // peers first.
×
UNCOV
2524
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
UNCOV
2525
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
UNCOV
2526
                                peerAddrCfg,
×
UNCOV
2527
                        )
×
UNCOV
2528
                        if err != nil {
×
2529
                                startErr = fmt.Errorf("unable to parse peer "+
×
2530
                                        "pubkey from config: %v", err)
×
2531
                                return
×
2532
                        }
×
UNCOV
2533
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
UNCOV
2534
                        if err != nil {
×
2535
                                startErr = fmt.Errorf("unable to parse peer "+
×
2536
                                        "address provided as a config option: "+
×
2537
                                        "%v", err)
×
2538
                                return
×
2539
                        }
×
2540

UNCOV
2541
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2542
                                IdentityKey: parsedPubkey,
×
UNCOV
2543
                                Address:     addr,
×
UNCOV
2544
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2545
                        }
×
UNCOV
2546

×
UNCOV
2547
                        err = s.ConnectToPeer(
×
UNCOV
2548
                                peerAddr, true,
×
UNCOV
2549
                                s.cfg.ConnectionTimeout,
×
UNCOV
2550
                        )
×
UNCOV
2551
                        if err != nil {
×
2552
                                startErr = fmt.Errorf("unable to connect to "+
×
2553
                                        "peer address provided as a config "+
×
2554
                                        "option: %v", err)
×
2555
                                return
×
2556
                        }
×
2557
                }
2558

2559
                // Subscribe to NodeAnnouncements that advertise new addresses
2560
                // our persistent peers.
UNCOV
2561
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2562
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2563
                                "addr: %v", err)
×
2564

×
2565
                        startErr = err
×
2566
                        return
×
2567
                }
×
2568

2569
                // With all the relevant sub-systems started, we'll now attempt
2570
                // to establish persistent connections to our direct channel
2571
                // collaborators within the network. Before doing so however,
2572
                // we'll prune our set of link nodes found within the database
2573
                // to ensure we don't reconnect to any nodes we no longer have
2574
                // open channels with.
UNCOV
2575
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2576
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2577

×
2578
                        startErr = err
×
2579
                        return
×
2580
                }
×
2581

UNCOV
2582
                if err := s.establishPersistentConnections(); err != nil {
×
2583
                        srvrLog.Errorf("Failed to establish persistent "+
×
2584
                                "connections: %v", err)
×
2585
                }
×
2586

2587
                // setSeedList is a helper function that turns multiple DNS seed
2588
                // server tuples from the command line or config file into the
2589
                // data structure we need and does a basic formal sanity check
2590
                // in the process.
UNCOV
2591
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2592
                        if len(tuples) == 0 {
×
2593
                                return
×
2594
                        }
×
2595

2596
                        result := make([][2]string, len(tuples))
×
2597
                        for idx, tuple := range tuples {
×
2598
                                tuple = strings.TrimSpace(tuple)
×
2599
                                if len(tuple) == 0 {
×
2600
                                        return
×
2601
                                }
×
2602

2603
                                servers := strings.Split(tuple, ",")
×
2604
                                if len(servers) > 2 || len(servers) == 0 {
×
2605
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2606
                                                "seed tuple: %v", servers)
×
2607
                                        return
×
2608
                                }
×
2609

2610
                                copy(result[idx][:], servers)
×
2611
                        }
2612

2613
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2614
                }
2615

2616
                // Let users overwrite the DNS seed nodes. We only allow them
2617
                // for bitcoin mainnet/testnet/signet.
UNCOV
2618
                if s.cfg.Bitcoin.MainNet {
×
2619
                        setSeedList(
×
2620
                                s.cfg.Bitcoin.DNSSeeds,
×
2621
                                chainreg.BitcoinMainnetGenesis,
×
2622
                        )
×
2623
                }
×
UNCOV
2624
                if s.cfg.Bitcoin.TestNet3 {
×
2625
                        setSeedList(
×
2626
                                s.cfg.Bitcoin.DNSSeeds,
×
2627
                                chainreg.BitcoinTestnetGenesis,
×
2628
                        )
×
2629
                }
×
UNCOV
2630
                if s.cfg.Bitcoin.TestNet4 {
×
2631
                        setSeedList(
×
2632
                                s.cfg.Bitcoin.DNSSeeds,
×
2633
                                chainreg.BitcoinTestnet4Genesis,
×
2634
                        )
×
2635
                }
×
UNCOV
2636
                if s.cfg.Bitcoin.SigNet {
×
2637
                        setSeedList(
×
2638
                                s.cfg.Bitcoin.DNSSeeds,
×
2639
                                chainreg.BitcoinSignetGenesis,
×
2640
                        )
×
2641
                }
×
2642

2643
                // If network bootstrapping hasn't been disabled, then we'll
2644
                // configure the set of active bootstrappers, and launch a
2645
                // dedicated goroutine to maintain a set of persistent
2646
                // connections.
UNCOV
2647
                if !s.cfg.NoNetBootstrap {
×
UNCOV
2648
                        bootstrappers, err := initNetworkBootstrappers(s)
×
UNCOV
2649
                        if err != nil {
×
2650
                                startErr = err
×
2651
                                return
×
2652
                        }
×
2653

UNCOV
2654
                        s.wg.Add(1)
×
UNCOV
2655
                        go s.peerBootstrapper(
×
UNCOV
2656
                                ctx, defaultMinPeers, bootstrappers,
×
UNCOV
2657
                        )
×
UNCOV
2658
                } else {
×
UNCOV
2659
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2660
                }
×
2661

2662
                // Start the blockbeat after all other subsystems have been
2663
                // started so they are ready to receive new blocks.
UNCOV
2664
                cleanup = cleanup.add(func() error {
×
2665
                        s.blockbeatDispatcher.Stop()
×
2666
                        return nil
×
2667
                })
×
UNCOV
2668
                if err := s.blockbeatDispatcher.Start(); err != nil {
×
2669
                        startErr = err
×
2670
                        return
×
2671
                }
×
2672

2673
                // Set the active flag now that we've completed the full
2674
                // startup.
UNCOV
2675
                atomic.StoreInt32(&s.active, 1)
×
2676
        })
2677

UNCOV
2678
        if startErr != nil {
×
2679
                cleanup.run()
×
2680
        }
×
UNCOV
2681
        return startErr
×
2682
}
2683

2684
// Stop gracefully shutsdown the main daemon server. This function will signal
2685
// any active goroutines, or helper objects to exit, then blocks until they've
2686
// all successfully exited. Additionally, any/all listeners are closed.
2687
// NOTE: This function is safe for concurrent access.
UNCOV
2688
func (s *server) Stop() error {
×
UNCOV
2689
        s.stop.Do(func() {
×
UNCOV
2690
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2691

×
UNCOV
2692
                ctx := context.Background()
×
UNCOV
2693

×
UNCOV
2694
                close(s.quit)
×
UNCOV
2695

×
UNCOV
2696
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2697
                s.connMgr.Stop()
×
UNCOV
2698

×
UNCOV
2699
                // Stop dispatching blocks to other systems immediately.
×
UNCOV
2700
                s.blockbeatDispatcher.Stop()
×
UNCOV
2701

×
UNCOV
2702
                // Shutdown the wallet, funding manager, and the rpc server.
×
UNCOV
2703
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2704
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2705
                }
×
UNCOV
2706
                if err := s.htlcSwitch.Stop(); err != nil {
×
2707
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2708
                }
×
UNCOV
2709
                if err := s.sphinx.Stop(); err != nil {
×
2710
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2711
                }
×
UNCOV
2712
                if err := s.invoices.Stop(); err != nil {
×
2713
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2714
                }
×
UNCOV
2715
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2716
                        srvrLog.Warnf("failed to stop interceptable "+
×
2717
                                "switch: %v", err)
×
2718
                }
×
UNCOV
2719
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2720
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2721
                                "modifier: %v", err)
×
2722
                }
×
UNCOV
2723
                if err := s.chanRouter.Stop(); err != nil {
×
2724
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2725
                }
×
UNCOV
2726
                if err := s.graphBuilder.Stop(); err != nil {
×
2727
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2728
                }
×
UNCOV
2729
                if err := s.graphDB.Stop(); err != nil {
×
2730
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2731
                }
×
UNCOV
2732
                if err := s.chainArb.Stop(); err != nil {
×
2733
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2734
                }
×
UNCOV
2735
                if err := s.fundingMgr.Stop(); err != nil {
×
2736
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2737
                }
×
UNCOV
2738
                if err := s.breachArbitrator.Stop(); err != nil {
×
2739
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2740
                                err)
×
2741
                }
×
UNCOV
2742
                if err := s.utxoNursery.Stop(); err != nil {
×
2743
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2744
                }
×
UNCOV
2745
                if err := s.authGossiper.Stop(); err != nil {
×
2746
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2747
                }
×
UNCOV
2748
                if err := s.sweeper.Stop(); err != nil {
×
2749
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2750
                }
×
UNCOV
2751
                if err := s.txPublisher.Stop(); err != nil {
×
2752
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2753
                }
×
UNCOV
2754
                if err := s.channelNotifier.Stop(); err != nil {
×
2755
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2756
                }
×
UNCOV
2757
                if err := s.peerNotifier.Stop(); err != nil {
×
2758
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2759
                }
×
UNCOV
2760
                if err := s.htlcNotifier.Stop(); err != nil {
×
2761
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2762
                }
×
2763

2764
                // Update channel.backup file. Make sure to do it before
2765
                // stopping chanSubSwapper.
UNCOV
2766
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2767
                        ctx, s.chanStateDB, s.addrSource,
×
UNCOV
2768
                )
×
UNCOV
2769
                if err != nil {
×
2770
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2771
                                err)
×
UNCOV
2772
                } else {
×
UNCOV
2773
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
UNCOV
2774
                        if err != nil {
×
UNCOV
2775
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2776
                                        "backup failed: %v", err)
×
UNCOV
2777
                        }
×
2778
                }
2779

UNCOV
2780
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2781
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2782
                }
×
UNCOV
2783
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2784
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2785
                }
×
UNCOV
2786
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2787
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2788
                                err)
×
2789
                }
×
UNCOV
2790
                if err := s.chanEventStore.Stop(); err != nil {
×
2791
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2792
                                err)
×
2793
                }
×
UNCOV
2794
                s.missionController.StopStoreTickers()
×
UNCOV
2795

×
UNCOV
2796
                // Disconnect from each active peers to ensure that
×
UNCOV
2797
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2798
                for _, peer := range s.Peers() {
×
UNCOV
2799
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2800
                        if err != nil {
×
2801
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2802
                                        "received error: %v", peer.IdentityKey(),
×
2803
                                        err,
×
2804
                                )
×
2805
                        }
×
2806
                }
2807

2808
                // Now that all connections have been torn down, stop the tower
2809
                // client which will reliably flush all queued states to the
2810
                // tower. If this is halted for any reason, the force quit timer
2811
                // will kick in and abort to allow this method to return.
UNCOV
2812
                if s.towerClientMgr != nil {
×
UNCOV
2813
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2814
                                srvrLog.Warnf("Unable to shut down tower "+
×
2815
                                        "client manager: %v", err)
×
2816
                        }
×
2817
                }
2818

UNCOV
2819
                if s.hostAnn != nil {
×
2820
                        if err := s.hostAnn.Stop(); err != nil {
×
2821
                                srvrLog.Warnf("unable to shut down host "+
×
2822
                                        "annoucner: %v", err)
×
2823
                        }
×
2824
                }
2825

UNCOV
2826
                if s.livenessMonitor != nil {
×
UNCOV
2827
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2828
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2829
                                        "monitor: %v", err)
×
2830
                        }
×
2831
                }
2832

2833
                // Wait for all lingering goroutines to quit.
UNCOV
2834
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2835
                s.wg.Wait()
×
UNCOV
2836

×
UNCOV
2837
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2838
                s.sigPool.Stop()
×
UNCOV
2839
                s.writePool.Stop()
×
UNCOV
2840
                s.readPool.Stop()
×
2841
        })
2842

UNCOV
2843
        return nil
×
2844
}
2845

2846
// Stopped returns true if the server has been instructed to shutdown.
2847
// NOTE: This function is safe for concurrent access.
UNCOV
2848
func (s *server) Stopped() bool {
×
UNCOV
2849
        return atomic.LoadInt32(&s.stopping) != 0
×
UNCOV
2850
}
×
2851

2852
// configurePortForwarding attempts to set up port forwarding for the different
2853
// ports that the server will be listening on.
2854
//
2855
// NOTE: This should only be used when using some kind of NAT traversal to
2856
// automatically set up forwarding rules.
2857
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2858
        ip, err := s.natTraversal.ExternalIP()
×
2859
        if err != nil {
×
2860
                return nil, err
×
2861
        }
×
2862
        s.lastDetectedIP = ip
×
2863

×
2864
        externalIPs := make([]string, 0, len(ports))
×
2865
        for _, port := range ports {
×
2866
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2867
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2868
                        continue
×
2869
                }
2870

2871
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2872
                externalIPs = append(externalIPs, hostIP)
×
2873
        }
2874

2875
        return externalIPs, nil
×
2876
}
2877

2878
// removePortForwarding attempts to clear the forwarding rules for the different
2879
// ports the server is currently listening on.
2880
//
2881
// NOTE: This should only be used when using some kind of NAT traversal to
2882
// automatically set up forwarding rules.
2883
func (s *server) removePortForwarding() {
×
2884
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2885
        for _, port := range forwardedPorts {
×
2886
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2887
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2888
                                "port %d: %v", port, err)
×
2889
                }
×
2890
        }
2891
}
2892

2893
// watchExternalIP continuously checks for an updated external IP address every
2894
// 15 minutes. Once a new IP address has been detected, it will automatically
2895
// handle port forwarding rules and send updated node announcements to the
2896
// currently connected peers.
2897
//
2898
// NOTE: This MUST be run as a goroutine.
2899
func (s *server) watchExternalIP() {
×
2900
        defer s.wg.Done()
×
2901

×
2902
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2903
        // up by the server.
×
2904
        defer s.removePortForwarding()
×
2905

×
2906
        // Keep track of the external IPs set by the user to avoid replacing
×
2907
        // them when detecting a new IP.
×
2908
        ipsSetByUser := make(map[string]struct{})
×
2909
        for _, ip := range s.cfg.ExternalIPs {
×
2910
                ipsSetByUser[ip.String()] = struct{}{}
×
2911
        }
×
2912

2913
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2914

×
2915
        ticker := time.NewTicker(15 * time.Minute)
×
2916
        defer ticker.Stop()
×
2917
out:
×
2918
        for {
×
2919
                select {
×
2920
                case <-ticker.C:
×
2921
                        // We'll start off by making sure a new IP address has
×
2922
                        // been detected.
×
2923
                        ip, err := s.natTraversal.ExternalIP()
×
2924
                        if err != nil {
×
2925
                                srvrLog.Debugf("Unable to retrieve the "+
×
2926
                                        "external IP address: %v", err)
×
2927
                                continue
×
2928
                        }
2929

2930
                        // Periodically renew the NAT port forwarding.
2931
                        for _, port := range forwardedPorts {
×
2932
                                err := s.natTraversal.AddPortMapping(port)
×
2933
                                if err != nil {
×
2934
                                        srvrLog.Warnf("Unable to automatically "+
×
2935
                                                "re-create port forwarding using %s: %v",
×
2936
                                                s.natTraversal.Name(), err)
×
2937
                                } else {
×
2938
                                        srvrLog.Debugf("Automatically re-created "+
×
2939
                                                "forwarding for port %d using %s to "+
×
2940
                                                "advertise external IP",
×
2941
                                                port, s.natTraversal.Name())
×
2942
                                }
×
2943
                        }
2944

2945
                        if ip.Equal(s.lastDetectedIP) {
×
2946
                                continue
×
2947
                        }
2948

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

×
2951
                        // Next, we'll craft the new addresses that will be
×
2952
                        // included in the new node announcement and advertised
×
2953
                        // to the network. Each address will consist of the new
×
2954
                        // IP detected and one of the currently advertised
×
2955
                        // ports.
×
2956
                        var newAddrs []net.Addr
×
2957
                        for _, port := range forwardedPorts {
×
2958
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2959
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2960
                                if err != nil {
×
2961
                                        srvrLog.Debugf("Unable to resolve "+
×
2962
                                                "host %v: %v", addr, err)
×
2963
                                        continue
×
2964
                                }
2965

2966
                                newAddrs = append(newAddrs, addr)
×
2967
                        }
2968

2969
                        // Skip the update if we weren't able to resolve any of
2970
                        // the new addresses.
2971
                        if len(newAddrs) == 0 {
×
2972
                                srvrLog.Debug("Skipping node announcement " +
×
2973
                                        "update due to not being able to " +
×
2974
                                        "resolve any new addresses")
×
2975
                                continue
×
2976
                        }
2977

2978
                        // Now, we'll need to update the addresses in our node's
2979
                        // announcement in order to propagate the update
2980
                        // throughout the network. We'll only include addresses
2981
                        // that have a different IP from the previous one, as
2982
                        // the previous IP is no longer valid.
2983
                        currentNodeAnn := s.getNodeAnnouncement()
×
2984

×
2985
                        for _, addr := range currentNodeAnn.Addresses {
×
2986
                                host, _, err := net.SplitHostPort(addr.String())
×
2987
                                if err != nil {
×
2988
                                        srvrLog.Debugf("Unable to determine "+
×
2989
                                                "host from address %v: %v",
×
2990
                                                addr, err)
×
2991
                                        continue
×
2992
                                }
2993

2994
                                // We'll also make sure to include external IPs
2995
                                // set manually by the user.
2996
                                _, setByUser := ipsSetByUser[addr.String()]
×
2997
                                if setByUser || host != s.lastDetectedIP.String() {
×
2998
                                        newAddrs = append(newAddrs, addr)
×
2999
                                }
×
3000
                        }
3001

3002
                        // Then, we'll generate a new timestamped node
3003
                        // announcement with the updated addresses and broadcast
3004
                        // it to our peers.
3005
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3006
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3007
                        )
×
3008
                        if err != nil {
×
3009
                                srvrLog.Debugf("Unable to generate new node "+
×
3010
                                        "announcement: %v", err)
×
3011
                                continue
×
3012
                        }
3013

3014
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3015
                        if err != nil {
×
3016
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3017
                                        "announcement to peers: %v", err)
×
3018
                                continue
×
3019
                        }
3020

3021
                        // Finally, update the last IP seen to the current one.
3022
                        s.lastDetectedIP = ip
×
3023
                case <-s.quit:
×
3024
                        break out
×
3025
                }
3026
        }
3027
}
3028

3029
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3030
// based on the server, and currently active bootstrap mechanisms as defined
3031
// within the current configuration.
UNCOV
3032
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
UNCOV
3033
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
UNCOV
3034

×
UNCOV
3035
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
UNCOV
3036

×
UNCOV
3037
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
UNCOV
3038
        // this can be used by default if we've already partially seeded the
×
UNCOV
3039
        // network.
×
UNCOV
3040
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
UNCOV
3041
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
UNCOV
3042
        if err != nil {
×
3043
                return nil, err
×
3044
        }
×
UNCOV
3045
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
UNCOV
3046

×
UNCOV
3047
        // If this isn't simnet mode, then one of our additional bootstrapping
×
UNCOV
3048
        // sources will be the set of running DNS seeds.
×
UNCOV
3049
        if !s.cfg.Bitcoin.SimNet {
×
UNCOV
3050
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
UNCOV
3051

×
UNCOV
3052
                // If we have a set of DNS seeds for this chain, then we'll add
×
UNCOV
3053
                // it as an additional bootstrapping source.
×
UNCOV
3054
                if ok {
×
3055
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3056
                                "seeds: %v", dnsSeeds)
×
3057

×
3058
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3059
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3060
                        )
×
3061
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3062
                }
×
3063
        }
3064

UNCOV
3065
        return bootStrappers, nil
×
3066
}
3067

3068
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3069
// needs to ignore, which is made of three parts,
3070
//   - the node itself needs to be skipped as it doesn't make sense to connect
3071
//     to itself.
3072
//   - the peers that already have connections with, as in s.peersByPub.
3073
//   - the peers that we are attempting to connect, as in s.persistentPeers.
UNCOV
3074
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
UNCOV
3075
        s.mu.RLock()
×
UNCOV
3076
        defer s.mu.RUnlock()
×
UNCOV
3077

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

×
UNCOV
3080
        // We should ignore ourselves from bootstrapping.
×
UNCOV
3081
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
UNCOV
3082
        ignore[selfKey] = struct{}{}
×
UNCOV
3083

×
UNCOV
3084
        // Ignore all connected peers.
×
UNCOV
3085
        for _, peer := range s.peersByPub {
×
3086
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3087
                ignore[nID] = struct{}{}
×
3088
        }
×
3089

3090
        // Ignore all persistent peers as they have a dedicated reconnecting
3091
        // process.
UNCOV
3092
        for pubKeyStr := range s.persistentPeers {
×
3093
                var nID autopilot.NodeID
×
3094
                copy(nID[:], []byte(pubKeyStr))
×
3095
                ignore[nID] = struct{}{}
×
3096
        }
×
3097

UNCOV
3098
        return ignore
×
3099
}
3100

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

×
UNCOV
3109
        defer s.wg.Done()
×
UNCOV
3110

×
UNCOV
3111
        // Before we continue, init the ignore peers map.
×
UNCOV
3112
        ignoreList := s.createBootstrapIgnorePeers()
×
UNCOV
3113

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

×
UNCOV
3118
        // Once done, we'll attempt to maintain our target minimum number of
×
UNCOV
3119
        // peers.
×
UNCOV
3120
        //
×
UNCOV
3121
        // We'll use a 15 second backoff, and double the time every time an
×
UNCOV
3122
        // epoch fails up to a ceiling.
×
UNCOV
3123
        backOff := time.Second * 15
×
UNCOV
3124

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

×
UNCOV
3130
        // We'll use the number of attempts and errors to determine if we need
×
UNCOV
3131
        // to increase the time between discovery epochs.
×
UNCOV
3132
        var epochErrors uint32 // To be used atomically.
×
UNCOV
3133
        var epochAttempts uint32
×
UNCOV
3134

×
UNCOV
3135
        for {
×
UNCOV
3136
                select {
×
3137
                // The ticker has just woken us up, so we'll need to check if
3138
                // we need to attempt to connect our to any more peers.
3139
                case <-sampleTicker.C:
×
3140
                        // Obtain the current number of peers, so we can gauge
×
3141
                        // if we need to sample more peers or not.
×
3142
                        s.mu.RLock()
×
3143
                        numActivePeers := uint32(len(s.peersByPub))
×
3144
                        s.mu.RUnlock()
×
3145

×
3146
                        // If we have enough peers, then we can loop back
×
3147
                        // around to the next round as we're done here.
×
3148
                        if numActivePeers >= numTargetPeers {
×
3149
                                continue
×
3150
                        }
3151

3152
                        // If all of our attempts failed during this last back
3153
                        // off period, then will increase our backoff to 5
3154
                        // minute ceiling to avoid an excessive number of
3155
                        // queries
3156
                        //
3157
                        // TODO(roasbeef): add reverse policy too?
3158

3159
                        if epochAttempts > 0 &&
×
3160
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3161

×
3162
                                sampleTicker.Stop()
×
3163

×
3164
                                backOff *= 2
×
3165
                                if backOff > bootstrapBackOffCeiling {
×
3166
                                        backOff = bootstrapBackOffCeiling
×
3167
                                }
×
3168

3169
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3170
                                        "%v", backOff)
×
3171
                                sampleTicker = time.NewTicker(backOff)
×
3172
                                continue
×
3173
                        }
3174

3175
                        atomic.StoreUint32(&epochErrors, 0)
×
3176
                        epochAttempts = 0
×
3177

×
3178
                        // Since we know need more peers, we'll compute the
×
3179
                        // exact number we need to reach our threshold.
×
3180
                        numNeeded := numTargetPeers - numActivePeers
×
3181

×
3182
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3183
                                "peers", numNeeded)
×
3184

×
3185
                        // With the number of peers we need calculated, we'll
×
3186
                        // query the network bootstrappers to sample a set of
×
3187
                        // random addrs for us.
×
3188
                        //
×
3189
                        // Before we continue, get a copy of the ignore peers
×
3190
                        // map.
×
3191
                        ignoreList = s.createBootstrapIgnorePeers()
×
3192

×
3193
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3194
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3195
                        )
×
3196
                        if err != nil {
×
3197
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3198
                                        "peers: %v", err)
×
3199
                                continue
×
3200
                        }
3201

3202
                        // Finally, we'll launch a new goroutine for each
3203
                        // prospective peer candidates.
3204
                        for _, addr := range peerAddrs {
×
3205
                                epochAttempts++
×
3206

×
3207
                                go func(a *lnwire.NetAddress) {
×
3208
                                        // TODO(roasbeef): can do AS, subnet,
×
3209
                                        // country diversity, etc
×
3210
                                        errChan := make(chan error, 1)
×
3211
                                        s.connectToPeer(
×
3212
                                                a, errChan,
×
3213
                                                s.cfg.ConnectionTimeout,
×
3214
                                        )
×
3215
                                        select {
×
3216
                                        case err := <-errChan:
×
3217
                                                if err == nil {
×
3218
                                                        return
×
3219
                                                }
×
3220

3221
                                                srvrLog.Errorf("Unable to "+
×
3222
                                                        "connect to %v: %v",
×
3223
                                                        a, err)
×
3224
                                                atomic.AddUint32(&epochErrors, 1)
×
3225
                                        case <-s.quit:
×
3226
                                        }
3227
                                }(addr)
3228
                        }
UNCOV
3229
                case <-s.quit:
×
UNCOV
3230
                        return
×
3231
                }
3232
        }
3233
}
3234

3235
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3236
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3237
// query back off each time we encounter a failure.
3238
const bootstrapBackOffCeiling = time.Minute * 5
3239

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

×
UNCOV
3247
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
UNCOV
3248
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
UNCOV
3249

×
UNCOV
3250
        // We'll start off by waiting 2 seconds between failed attempts, then
×
UNCOV
3251
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
UNCOV
3252
        var delaySignal <-chan time.Time
×
UNCOV
3253
        delayTime := time.Second * 2
×
UNCOV
3254

×
UNCOV
3255
        // As want to be more aggressive, we'll use a lower back off celling
×
UNCOV
3256
        // then the main peer bootstrap logic.
×
UNCOV
3257
        backOffCeiling := bootstrapBackOffCeiling / 5
×
UNCOV
3258

×
UNCOV
3259
        for attempts := 0; ; attempts++ {
×
UNCOV
3260
                // Check if the server has been requested to shut down in order
×
UNCOV
3261
                // to prevent blocking.
×
UNCOV
3262
                if s.Stopped() {
×
3263
                        return
×
3264
                }
×
3265

3266
                // We can exit our aggressive initial peer bootstrapping stage
3267
                // if we've reached out target number of peers.
UNCOV
3268
                s.mu.RLock()
×
UNCOV
3269
                numActivePeers := uint32(len(s.peersByPub))
×
UNCOV
3270
                s.mu.RUnlock()
×
UNCOV
3271

×
UNCOV
3272
                if numActivePeers >= numTargetPeers {
×
UNCOV
3273
                        return
×
UNCOV
3274
                }
×
3275

UNCOV
3276
                if attempts > 0 {
×
3277
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3278
                                "bootstrap peers (attempt #%v)", delayTime,
×
3279
                                attempts)
×
3280

×
3281
                        // We've completed at least one iterating and haven't
×
3282
                        // finished, so we'll start to insert a delay period
×
3283
                        // between each attempt.
×
3284
                        delaySignal = time.After(delayTime)
×
3285
                        select {
×
3286
                        case <-delaySignal:
×
3287
                        case <-s.quit:
×
3288
                                return
×
3289
                        }
3290

3291
                        // After our delay, we'll double the time we wait up to
3292
                        // the max back off period.
3293
                        delayTime *= 2
×
3294
                        if delayTime > backOffCeiling {
×
3295
                                delayTime = backOffCeiling
×
3296
                        }
×
3297
                }
3298

3299
                // Otherwise, we'll request for the remaining number of peers
3300
                // in order to reach our target.
UNCOV
3301
                peersNeeded := numTargetPeers - numActivePeers
×
UNCOV
3302
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
UNCOV
3303
                        ctx, ignore, peersNeeded, bootstrappers...,
×
UNCOV
3304
                )
×
UNCOV
3305
                if err != nil {
×
3306
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3307
                                "peers: %v", err)
×
3308
                        continue
×
3309
                }
3310

3311
                // Then, we'll attempt to establish a connection to the
3312
                // different peer addresses retrieved by our bootstrappers.
UNCOV
3313
                var wg sync.WaitGroup
×
UNCOV
3314
                for _, bootstrapAddr := range bootstrapAddrs {
×
UNCOV
3315
                        wg.Add(1)
×
UNCOV
3316
                        go func(addr *lnwire.NetAddress) {
×
UNCOV
3317
                                defer wg.Done()
×
UNCOV
3318

×
UNCOV
3319
                                errChan := make(chan error, 1)
×
UNCOV
3320
                                go s.connectToPeer(
×
UNCOV
3321
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
UNCOV
3322
                                )
×
UNCOV
3323

×
UNCOV
3324
                                // We'll only allow this connection attempt to
×
UNCOV
3325
                                // take up to 3 seconds. This allows us to move
×
UNCOV
3326
                                // quickly by discarding peers that are slowing
×
UNCOV
3327
                                // us down.
×
UNCOV
3328
                                select {
×
UNCOV
3329
                                case err := <-errChan:
×
UNCOV
3330
                                        if err == nil {
×
UNCOV
3331
                                                return
×
UNCOV
3332
                                        }
×
3333
                                        srvrLog.Errorf("Unable to connect to "+
×
3334
                                                "%v: %v", addr, err)
×
3335
                                // TODO: tune timeout? 3 seconds might be *too*
3336
                                // aggressive but works well.
3337
                                case <-time.After(3 * time.Second):
×
3338
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3339
                                                "to not establishing a "+
×
3340
                                                "connection within 3 seconds",
×
3341
                                                addr)
×
3342
                                case <-s.quit:
×
3343
                                }
3344
                        }(bootstrapAddr)
3345
                }
3346

UNCOV
3347
                wg.Wait()
×
3348
        }
3349
}
3350

3351
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3352
// order to listen for inbound connections over Tor.
3353
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3354
        // Determine the different ports the server is listening on. The onion
×
3355
        // service's virtual port will map to these ports and one will be picked
×
3356
        // at random when the onion service is being accessed.
×
3357
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3358
        for _, listenAddr := range s.listenAddrs {
×
3359
                port := listenAddr.(*net.TCPAddr).Port
×
3360
                listenPorts = append(listenPorts, port)
×
3361
        }
×
3362

3363
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3364
        if err != nil {
×
3365
                return err
×
3366
        }
×
3367

3368
        // Once the port mapping has been set, we can go ahead and automatically
3369
        // create our onion service. The service's private key will be saved to
3370
        // disk in order to regain access to this service when restarting `lnd`.
3371
        onionCfg := tor.AddOnionConfig{
×
3372
                VirtualPort: defaultPeerPort,
×
3373
                TargetPorts: listenPorts,
×
3374
                Store: tor.NewOnionFile(
×
3375
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3376
                        encrypter,
×
3377
                ),
×
3378
        }
×
3379

×
3380
        switch {
×
3381
        case s.cfg.Tor.V2:
×
3382
                onionCfg.Type = tor.V2
×
3383
        case s.cfg.Tor.V3:
×
3384
                onionCfg.Type = tor.V3
×
3385
        }
3386

3387
        addr, err := s.torController.AddOnion(onionCfg)
×
3388
        if err != nil {
×
3389
                return err
×
3390
        }
×
3391

3392
        // Now that the onion service has been created, we'll add the onion
3393
        // address it can be reached at to our list of advertised addresses.
3394
        newNodeAnn, err := s.genNodeAnnouncement(
×
3395
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3396
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3397
                },
×
3398
        )
3399
        if err != nil {
×
3400
                return fmt.Errorf("unable to generate new node "+
×
3401
                        "announcement: %v", err)
×
3402
        }
×
3403

3404
        // Finally, we'll update the on-disk version of our announcement so it
3405
        // will eventually propagate to nodes in the network.
3406
        selfNode := &models.LightningNode{
×
3407
                HaveNodeAnnouncement: true,
×
3408
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3409
                Addresses:            newNodeAnn.Addresses,
×
3410
                Alias:                newNodeAnn.Alias.String(),
×
3411
                Features: lnwire.NewFeatureVector(
×
3412
                        newNodeAnn.Features, lnwire.Features,
×
3413
                ),
×
3414
                Color:        newNodeAnn.RGBColor,
×
3415
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3416
        }
×
3417
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3418
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3419
                return fmt.Errorf("can't set self node: %w", err)
×
3420
        }
×
3421

3422
        return nil
×
3423
}
3424

3425
// findChannel finds a channel given a public key and ChannelID. It is an
3426
// optimization that is quicker than seeking for a channel given only the
3427
// ChannelID.
3428
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
UNCOV
3429
        *channeldb.OpenChannel, error) {
×
UNCOV
3430

×
UNCOV
3431
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3432
        if err != nil {
×
3433
                return nil, err
×
3434
        }
×
3435

UNCOV
3436
        for _, channel := range nodeChans {
×
UNCOV
3437
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3438
                        return channel, nil
×
UNCOV
3439
                }
×
3440
        }
3441

UNCOV
3442
        return nil, fmt.Errorf("unable to find channel")
×
3443
}
3444

3445
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3446
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3447
        s.mu.Lock()
×
UNCOV
3448
        defer s.mu.Unlock()
×
UNCOV
3449

×
UNCOV
3450
        return *s.currentNodeAnn
×
UNCOV
3451
}
×
3452

3453
// genNodeAnnouncement generates and returns the current fully signed node
3454
// announcement. The time stamp of the announcement will be updated in order
3455
// to ensure it propagates through the network.
3456
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3457
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3458

×
UNCOV
3459
        s.mu.Lock()
×
UNCOV
3460
        defer s.mu.Unlock()
×
UNCOV
3461

×
UNCOV
3462
        // Create a shallow copy of the current node announcement to work on.
×
UNCOV
3463
        // This ensures the original announcement remains unchanged
×
UNCOV
3464
        // until the new announcement is fully signed and valid.
×
UNCOV
3465
        newNodeAnn := *s.currentNodeAnn
×
UNCOV
3466

×
UNCOV
3467
        // First, try to update our feature manager with the updated set of
×
UNCOV
3468
        // features.
×
UNCOV
3469
        if features != nil {
×
UNCOV
3470
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3471
                        feature.SetNodeAnn: features,
×
UNCOV
3472
                }
×
UNCOV
3473
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3474
                if err != nil {
×
UNCOV
3475
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3476
                }
×
3477

3478
                // If we could successfully update our feature manager, add
3479
                // an update modifier to include these new features to our
3480
                // set.
UNCOV
3481
                modifiers = append(
×
UNCOV
3482
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3483
                )
×
3484
        }
3485

3486
        // Always update the timestamp when refreshing to ensure the update
3487
        // propagates.
UNCOV
3488
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3489

×
UNCOV
3490
        // Apply the requested changes to the node announcement.
×
UNCOV
3491
        for _, modifier := range modifiers {
×
UNCOV
3492
                modifier(&newNodeAnn)
×
UNCOV
3493
        }
×
3494

3495
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3496
        err := netann.SignNodeAnnouncement(
×
UNCOV
3497
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
UNCOV
3498
        )
×
UNCOV
3499
        if err != nil {
×
3500
                return lnwire.NodeAnnouncement{}, err
×
3501
        }
×
3502

3503
        // If signing succeeds, update the current announcement.
UNCOV
3504
        *s.currentNodeAnn = newNodeAnn
×
UNCOV
3505

×
UNCOV
3506
        return *s.currentNodeAnn, nil
×
3507
}
3508

3509
// updateAndBroadcastSelfNode generates a new node announcement
3510
// applying the giving modifiers and updating the time stamp
3511
// to ensure it propagates through the network. Then it broadcasts
3512
// it to the network.
3513
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3514
        features *lnwire.RawFeatureVector,
UNCOV
3515
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3516

×
UNCOV
3517
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3518
        if err != nil {
×
UNCOV
3519
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3520
                        "announcement: %v", err)
×
UNCOV
3521
        }
×
3522

3523
        // Update the on-disk version of our announcement.
3524
        // Load and modify self node istead of creating anew instance so we
3525
        // don't risk overwriting any existing values.
UNCOV
3526
        selfNode, err := s.graphDB.SourceNode(ctx)
×
UNCOV
3527
        if err != nil {
×
3528
                return fmt.Errorf("unable to get current source node: %w", err)
×
3529
        }
×
3530

UNCOV
3531
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3532
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3533
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3534
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3535
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3536
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3537
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3538

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

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

3545
        // Finally, propagate it to the nodes in the network.
UNCOV
3546
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3547
        if err != nil {
×
3548
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3549
                        "announcement to peers: %v", err)
×
3550
                return err
×
3551
        }
×
3552

UNCOV
3553
        return nil
×
3554
}
3555

3556
type nodeAddresses struct {
3557
        pubKey    *btcec.PublicKey
3558
        addresses []net.Addr
3559
}
3560

3561
// establishPersistentConnections attempts to establish persistent connections
3562
// to all our direct channel collaborators. In order to promote liveness of our
3563
// active channels, we instruct the connection manager to attempt to establish
3564
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3565
func (s *server) establishPersistentConnections() error {
×
UNCOV
3566
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3567
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3568
        // since other PubKey forms can't be compared.
×
UNCOV
3569
        nodeAddrsMap := map[string]*nodeAddresses{}
×
UNCOV
3570

×
UNCOV
3571
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3572
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3573
        // the reconnection port to the default peer port.
×
UNCOV
3574
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3575
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3576
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3577
        }
×
3578

UNCOV
3579
        for _, node := range linkNodes {
×
UNCOV
3580
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3581
                nodeAddrs := &nodeAddresses{
×
UNCOV
3582
                        pubKey:    node.IdentityPub,
×
UNCOV
3583
                        addresses: node.Addresses,
×
UNCOV
3584
                }
×
UNCOV
3585
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3586
        }
×
3587

3588
        // After checking our previous connections for addresses to connect to,
3589
        // iterate through the nodes in our channel graph to find addresses
3590
        // that have been added via NodeAnnouncement messages.
3591
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3592
        // each of the nodes.
UNCOV
3593
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
×
UNCOV
3594
                havePolicy bool, channelPeer *models.LightningNode) error {
×
UNCOV
3595

×
UNCOV
3596
                // If the remote party has announced the channel to us, but we
×
UNCOV
3597
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3598
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3599
                if !havePolicy {
×
3600
                        srvrLog.Warnf("No channel policy found for "+
×
3601
                                "ChannelPoint(%v): ", chanPoint)
×
3602
                }
×
3603

UNCOV
3604
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3605

×
UNCOV
3606
                // Add all unique addresses from channel
×
UNCOV
3607
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3608
                // connect to for this peer.
×
UNCOV
3609
                addrSet := make(map[string]net.Addr)
×
UNCOV
3610
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3611
                        switch addr.(type) {
×
UNCOV
3612
                        case *net.TCPAddr:
×
UNCOV
3613
                                addrSet[addr.String()] = addr
×
3614

3615
                        // We'll only attempt to connect to Tor addresses if Tor
3616
                        // outbound support is enabled.
3617
                        case *tor.OnionAddr:
×
3618
                                if s.cfg.Tor.Active {
×
3619
                                        addrSet[addr.String()] = addr
×
3620
                                }
×
3621
                        }
3622
                }
3623

3624
                // If this peer is also recorded as a link node, we'll add any
3625
                // additional addresses that have not already been selected.
UNCOV
3626
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3627
                if ok {
×
UNCOV
3628
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3629
                                switch lnAddress.(type) {
×
UNCOV
3630
                                case *net.TCPAddr:
×
UNCOV
3631
                                        addrSet[lnAddress.String()] = lnAddress
×
3632

3633
                                // We'll only attempt to connect to Tor
3634
                                // addresses if Tor outbound support is enabled.
3635
                                case *tor.OnionAddr:
×
3636
                                        if s.cfg.Tor.Active {
×
3637
                                                addrSet[lnAddress.String()] = lnAddress
×
3638
                                        }
×
3639
                                }
3640
                        }
3641
                }
3642

3643
                // Construct a slice of the deduped addresses.
UNCOV
3644
                var addrs []net.Addr
×
UNCOV
3645
                for _, addr := range addrSet {
×
UNCOV
3646
                        addrs = append(addrs, addr)
×
UNCOV
3647
                }
×
3648

UNCOV
3649
                n := &nodeAddresses{
×
UNCOV
3650
                        addresses: addrs,
×
UNCOV
3651
                }
×
UNCOV
3652
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3653
                if err != nil {
×
3654
                        return err
×
3655
                }
×
3656

UNCOV
3657
                nodeAddrsMap[pubStr] = n
×
UNCOV
3658
                return nil
×
3659
        })
UNCOV
3660
        if err != nil {
×
3661
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3662
                        "%v", err)
×
3663

×
3664
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3665
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3666

×
3667
                        return err
×
3668
                }
×
3669
        }
3670

UNCOV
3671
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3672
                len(nodeAddrsMap))
×
UNCOV
3673

×
UNCOV
3674
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3675
        // have been recorded and sent to the connection manager.
×
UNCOV
3676
        s.mu.Lock()
×
UNCOV
3677
        defer s.mu.Unlock()
×
UNCOV
3678

×
UNCOV
3679
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3680
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3681
        var numOutboundConns int
×
UNCOV
3682
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3683
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3684
                // persistent connection with. We set the value to false to
×
UNCOV
3685
                // indicate that we should not continue to reconnect if the
×
UNCOV
3686
                // number of channels returns to zero, since this peer has not
×
UNCOV
3687
                // been requested as perm by the user.
×
UNCOV
3688
                s.persistentPeers[pubStr] = false
×
UNCOV
3689
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
UNCOV
3690
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
UNCOV
3691
                }
×
3692

UNCOV
3693
                for _, address := range nodeAddr.addresses {
×
UNCOV
3694
                        // Create a wrapper address which couples the IP and
×
UNCOV
3695
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3696
                        // can be established.
×
UNCOV
3697
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3698
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3699
                                Address:     address,
×
UNCOV
3700
                        }
×
UNCOV
3701

×
UNCOV
3702
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3703
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3704
                }
×
3705

3706
                // We'll connect to the first 10 peers immediately, then
3707
                // randomly stagger any remaining connections if the
3708
                // stagger initial reconnect flag is set. This ensures
3709
                // that mobile nodes or nodes with a small number of
3710
                // channels obtain connectivity quickly, but larger
3711
                // nodes are able to disperse the costs of connecting to
3712
                // all peers at once.
UNCOV
3713
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3714
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3715

×
UNCOV
3716
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3717
                } else {
×
3718
                        go s.delayInitialReconnect(pubStr)
×
3719
                }
×
3720

UNCOV
3721
                numOutboundConns++
×
3722
        }
3723

UNCOV
3724
        return nil
×
3725
}
3726

3727
// delayInitialReconnect will attempt a reconnection to the given peer after
3728
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3729
//
3730
// NOTE: This method MUST be run as a goroutine.
3731
func (s *server) delayInitialReconnect(pubStr string) {
×
3732
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3733
        select {
×
3734
        case <-time.After(delay):
×
3735
                s.connectToPersistentPeer(pubStr)
×
3736
        case <-s.quit:
×
3737
        }
3738
}
3739

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

×
UNCOV
3746
        s.mu.Lock()
×
UNCOV
3747
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3748
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3749
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3750
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3751
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3752
                s.mu.Unlock()
×
UNCOV
3753

×
UNCOV
3754
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3755
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3756

×
UNCOV
3757
                return
×
UNCOV
3758
        }
×
UNCOV
3759
        s.mu.Unlock()
×
3760
}
3761

3762
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3763
// is instead used to remove persistent peer state for a peer that has been
3764
// disconnected for good cause by the server. Currently, a gossip ban from
3765
// sending garbage and the server running out of restricted-access
3766
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3767
// future, this function may expand when more ban criteria is added.
3768
//
3769
// NOTE: The server's write lock MUST be held when this is called.
3770
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3771
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3772
                delete(s.persistentPeers, remotePub)
×
3773
                delete(s.persistentPeersBackoff, remotePub)
×
3774
                delete(s.persistentPeerAddrs, remotePub)
×
3775
                s.cancelConnReqs(remotePub, nil)
×
3776
        }
×
3777
}
3778

3779
// BroadcastMessage sends a request to the server to broadcast a set of
3780
// messages to all peers other than the one specified by the `skips` parameter.
3781
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3782
// the target peers.
3783
//
3784
// NOTE: This function is safe for concurrent access.
3785
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3786
        msgs ...lnwire.Message) error {
×
UNCOV
3787

×
UNCOV
3788
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3789
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3790
        // exact set of peers present at the time of invocation.
×
UNCOV
3791
        s.mu.RLock()
×
UNCOV
3792
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3793
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3794
                if skips != nil {
×
UNCOV
3795
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3796
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3797
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
UNCOV
3798
                                continue
×
3799
                        }
3800
                }
3801

UNCOV
3802
                peers = append(peers, sPeer)
×
3803
        }
UNCOV
3804
        s.mu.RUnlock()
×
UNCOV
3805

×
UNCOV
3806
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3807
        // all messages to each of peers.
×
UNCOV
3808
        var wg sync.WaitGroup
×
UNCOV
3809
        for _, sPeer := range peers {
×
UNCOV
3810
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3811
                        sPeer.PubKey())
×
UNCOV
3812

×
UNCOV
3813
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3814
                wg.Add(1)
×
UNCOV
3815
                s.wg.Add(1)
×
UNCOV
3816
                go func(p lnpeer.Peer) {
×
UNCOV
3817
                        defer s.wg.Done()
×
UNCOV
3818
                        defer wg.Done()
×
UNCOV
3819

×
UNCOV
3820
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3821
                }(sPeer)
×
3822
        }
3823

3824
        // Wait for all messages to have been dispatched before returning to
3825
        // caller.
UNCOV
3826
        wg.Wait()
×
UNCOV
3827

×
UNCOV
3828
        return nil
×
3829
}
3830

3831
// NotifyWhenOnline can be called by other subsystems to get notified when a
3832
// particular peer comes online. The peer itself is sent across the peerChan.
3833
//
3834
// NOTE: This function is safe for concurrent access.
3835
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3836
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3837

×
UNCOV
3838
        s.mu.Lock()
×
UNCOV
3839

×
UNCOV
3840
        // Compute the target peer's identifier.
×
UNCOV
3841
        pubStr := string(peerKey[:])
×
UNCOV
3842

×
UNCOV
3843
        // Check if peer is connected.
×
UNCOV
3844
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3845
        if ok {
×
UNCOV
3846
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3847
                // waiting for the peer to become active.
×
UNCOV
3848
                s.mu.Unlock()
×
UNCOV
3849

×
UNCOV
3850
                // Wait until the peer signals that it is actually active
×
UNCOV
3851
                // rather than only in the server's maps.
×
UNCOV
3852
                select {
×
UNCOV
3853
                case <-peer.ActiveSignal():
×
UNCOV
3854
                case <-peer.QuitSignal():
×
UNCOV
3855
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3856
                        // and return.
×
UNCOV
3857
                        s.mu.Lock()
×
UNCOV
3858
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3859
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3860
                        )
×
UNCOV
3861
                        s.mu.Unlock()
×
UNCOV
3862
                        return
×
3863
                }
3864

3865
                // Connected, can return early.
UNCOV
3866
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3867

×
UNCOV
3868
                select {
×
UNCOV
3869
                case peerChan <- peer:
×
3870
                case <-s.quit:
×
3871
                }
3872

UNCOV
3873
                return
×
3874
        }
3875

3876
        // Not connected, store this listener such that it can be notified when
3877
        // the peer comes online.
UNCOV
3878
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3879
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3880
        )
×
UNCOV
3881
        s.mu.Unlock()
×
3882
}
3883

3884
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3885
// the given public key has been disconnected. The notification is signaled by
3886
// closing the channel returned.
UNCOV
3887
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3888
        s.mu.Lock()
×
UNCOV
3889
        defer s.mu.Unlock()
×
UNCOV
3890

×
UNCOV
3891
        c := make(chan struct{})
×
UNCOV
3892

×
UNCOV
3893
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3894
        // notification.
×
UNCOV
3895
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3896
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3897
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3898
                close(c)
×
3899
                return c
×
3900
        }
×
3901

3902
        // Otherwise, the peer is online, so we'll keep track of the channel to
3903
        // trigger the notification once the server detects the peer
3904
        // disconnects.
UNCOV
3905
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
3906
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
3907
        )
×
UNCOV
3908

×
UNCOV
3909
        return c
×
3910
}
3911

3912
// FindPeer will return the peer that corresponds to the passed in public key.
3913
// This function is used by the funding manager, allowing it to update the
3914
// daemon's local representation of the remote peer.
3915
//
3916
// NOTE: This function is safe for concurrent access.
UNCOV
3917
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
3918
        s.mu.RLock()
×
UNCOV
3919
        defer s.mu.RUnlock()
×
UNCOV
3920

×
UNCOV
3921
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3922

×
UNCOV
3923
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3924
}
×
3925

3926
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3927
// which should be a string representation of the peer's serialized, compressed
3928
// public key.
3929
//
3930
// NOTE: This function is safe for concurrent access.
UNCOV
3931
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3932
        s.mu.RLock()
×
UNCOV
3933
        defer s.mu.RUnlock()
×
UNCOV
3934

×
UNCOV
3935
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3936
}
×
3937

3938
// findPeerByPubStr is an internal method that retrieves the specified peer from
3939
// the server's internal state using.
UNCOV
3940
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3941
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3942
        if !ok {
×
UNCOV
3943
                return nil, ErrPeerNotConnected
×
UNCOV
3944
        }
×
3945

UNCOV
3946
        return peer, nil
×
3947
}
3948

3949
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3950
// exponential backoff. If no previous backoff was known, the default is
3951
// returned.
3952
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
3953
        startTime time.Time) time.Duration {
×
UNCOV
3954

×
UNCOV
3955
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
3956
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
3957
        if !ok {
×
UNCOV
3958
                // If an existing backoff was unknown, use the default.
×
UNCOV
3959
                return s.cfg.MinBackoff
×
UNCOV
3960
        }
×
3961

3962
        // If the peer failed to start properly, we'll just use the previous
3963
        // backoff to compute the subsequent randomized exponential backoff
3964
        // duration. This will roughly double on average.
UNCOV
3965
        if startTime.IsZero() {
×
3966
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3967
        }
×
3968

3969
        // The peer succeeded in starting. If the connection didn't last long
3970
        // enough to be considered stable, we'll continue to back off retries
3971
        // with this peer.
UNCOV
3972
        connDuration := time.Since(startTime)
×
UNCOV
3973
        if connDuration < defaultStableConnDuration {
×
UNCOV
3974
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3975
        }
×
3976

3977
        // The peer succeed in starting and this was stable peer, so we'll
3978
        // reduce the timeout duration by the length of the connection after
3979
        // applying randomized exponential backoff. We'll only apply this in the
3980
        // case that:
3981
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3982
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3983
        if relaxedBackoff > s.cfg.MinBackoff {
×
3984
                return relaxedBackoff
×
3985
        }
×
3986

3987
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3988
        // the stable connection lasted much longer than our previous backoff.
3989
        // To reward such good behavior, we'll reconnect after the default
3990
        // timeout.
3991
        return s.cfg.MinBackoff
×
3992
}
3993

3994
// shouldDropLocalConnection determines if our local connection to a remote peer
3995
// should be dropped in the case of concurrent connection establishment. In
3996
// order to deterministically decide which connection should be dropped, we'll
3997
// utilize the ordering of the local and remote public key. If we didn't use
3998
// such a tie breaker, then we risk _both_ connections erroneously being
3999
// dropped.
4000
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4001
        localPubBytes := local.SerializeCompressed()
×
4002
        remotePubPbytes := remote.SerializeCompressed()
×
4003

×
4004
        // The connection that comes from the node with a "smaller" pubkey
×
4005
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4006
        // should drop our established connection.
×
4007
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4008
}
×
4009

4010
// InboundPeerConnected initializes a new peer in response to a new inbound
4011
// connection.
4012
//
4013
// NOTE: This function is safe for concurrent access.
UNCOV
4014
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
4015
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
4016
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
4017
        if s.Stopped() {
×
4018
                return
×
4019
        }
×
4020

UNCOV
4021
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4022
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4023
        pubStr := string(pubSer)
×
UNCOV
4024

×
UNCOV
4025
        var pubBytes [33]byte
×
UNCOV
4026
        copy(pubBytes[:], pubSer)
×
UNCOV
4027

×
UNCOV
4028
        s.mu.Lock()
×
UNCOV
4029
        defer s.mu.Unlock()
×
UNCOV
4030

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

×
UNCOV
4038
                conn.Close()
×
UNCOV
4039
                return
×
UNCOV
4040
        }
×
4041

4042
        // If we already have a valid connection that is scheduled to take
4043
        // precedence once the prior peer has finished disconnecting, we'll
4044
        // ignore this connection.
UNCOV
4045
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4046
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4047
                        "scheduled", conn.RemoteAddr(), p)
×
4048
                conn.Close()
×
4049
                return
×
4050
        }
×
4051

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

×
UNCOV
4054
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
4055
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
4056
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
4057
        // default case as we expect these to be the only error values returned
×
UNCOV
4058
        // from findPeerByPubStr.
×
UNCOV
4059
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4060
        switch err {
×
UNCOV
4061
        case ErrPeerNotConnected:
×
UNCOV
4062
                // We were unable to locate an existing connection with the
×
UNCOV
4063
                // target peer, proceed to connect.
×
UNCOV
4064
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4065
                s.peerConnected(conn, nil, true)
×
4066

UNCOV
4067
        case nil:
×
UNCOV
4068
                // We already have a connection with the incoming peer. If the
×
UNCOV
4069
                // connection we've already established should be kept and is
×
UNCOV
4070
                // not of the same type of the new connection (inbound), then
×
UNCOV
4071
                // we'll close out the new connection s.t there's only a single
×
UNCOV
4072
                // connection between us.
×
UNCOV
4073
                localPub := s.identityECDH.PubKey()
×
UNCOV
4074
                if !connectedPeer.Inbound() &&
×
UNCOV
4075
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4076

×
4077
                        srvrLog.Warnf("Received inbound connection from "+
×
4078
                                "peer %v, but already have outbound "+
×
4079
                                "connection, dropping conn", connectedPeer)
×
4080
                        conn.Close()
×
4081
                        return
×
4082
                }
×
4083

4084
                // Otherwise, if we should drop the connection, then we'll
4085
                // disconnect our already connected peer.
UNCOV
4086
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
UNCOV
4087
                        connectedPeer)
×
UNCOV
4088

×
UNCOV
4089
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4090

×
UNCOV
4091
                // Remove the current peer from the server's internal state and
×
UNCOV
4092
                // signal that the peer termination watcher does not need to
×
UNCOV
4093
                // execute for this peer.
×
UNCOV
4094
                s.removePeer(connectedPeer)
×
UNCOV
4095
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
4096
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
4097
                        s.peerConnected(conn, nil, true)
×
UNCOV
4098
                }
×
4099
        }
4100
}
4101

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

UNCOV
4112
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4113
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4114
        pubStr := string(pubSer)
×
UNCOV
4115

×
UNCOV
4116
        var pubBytes [33]byte
×
UNCOV
4117
        copy(pubBytes[:], pubSer)
×
UNCOV
4118

×
UNCOV
4119
        s.mu.Lock()
×
UNCOV
4120
        defer s.mu.Unlock()
×
UNCOV
4121

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

×
UNCOV
4129
                if connReq != nil {
×
UNCOV
4130
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4131
                }
×
UNCOV
4132
                conn.Close()
×
UNCOV
4133
                return
×
4134
        }
UNCOV
4135
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4136
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4137
                s.connMgr.Remove(connReq.ID())
×
4138
                conn.Close()
×
4139
                return
×
4140
        }
×
4141

4142
        // If we already have a valid connection that is scheduled to take
4143
        // precedence once the prior peer has finished disconnecting, we'll
4144
        // ignore this connection.
UNCOV
4145
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4146
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4147

×
4148
                if connReq != nil {
×
4149
                        s.connMgr.Remove(connReq.ID())
×
4150
                }
×
4151

4152
                conn.Close()
×
4153
                return
×
4154
        }
4155

UNCOV
4156
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
UNCOV
4157
                conn.RemoteAddr())
×
UNCOV
4158

×
UNCOV
4159
        if connReq != nil {
×
UNCOV
4160
                // A successful connection was returned by the connmgr.
×
UNCOV
4161
                // Immediately cancel all pending requests, excluding the
×
UNCOV
4162
                // outbound connection we just established.
×
UNCOV
4163
                ignore := connReq.ID()
×
UNCOV
4164
                s.cancelConnReqs(pubStr, &ignore)
×
UNCOV
4165
        } else {
×
UNCOV
4166
                // This was a successful connection made by some other
×
UNCOV
4167
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
4168
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4169
        }
×
4170

4171
        // If we already have a connection with this peer, decide whether or not
4172
        // we need to drop the stale connection. We forgo adding a default case
4173
        // as we expect these to be the only error values returned from
4174
        // findPeerByPubStr.
UNCOV
4175
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4176
        switch err {
×
UNCOV
4177
        case ErrPeerNotConnected:
×
UNCOV
4178
                // We were unable to locate an existing connection with the
×
UNCOV
4179
                // target peer, proceed to connect.
×
UNCOV
4180
                s.peerConnected(conn, connReq, false)
×
4181

UNCOV
4182
        case nil:
×
UNCOV
4183
                // We already have a connection with the incoming peer. If the
×
UNCOV
4184
                // connection we've already established should be kept and is
×
UNCOV
4185
                // not of the same type of the new connection (outbound), then
×
UNCOV
4186
                // we'll close out the new connection s.t there's only a single
×
UNCOV
4187
                // connection between us.
×
UNCOV
4188
                localPub := s.identityECDH.PubKey()
×
UNCOV
4189
                if connectedPeer.Inbound() &&
×
UNCOV
4190
                        shouldDropLocalConnection(localPub, nodePub) {
×
4191

×
4192
                        srvrLog.Warnf("Established outbound connection to "+
×
4193
                                "peer %v, but already have inbound "+
×
4194
                                "connection, dropping conn", connectedPeer)
×
4195
                        if connReq != nil {
×
4196
                                s.connMgr.Remove(connReq.ID())
×
4197
                        }
×
4198
                        conn.Close()
×
4199
                        return
×
4200
                }
4201

4202
                // Otherwise, _their_ connection should be dropped. So we'll
4203
                // disconnect the peer and send the now obsolete peer to the
4204
                // server for garbage collection.
UNCOV
4205
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
UNCOV
4206
                        connectedPeer)
×
UNCOV
4207

×
UNCOV
4208
                // Remove the current peer from the server's internal state and
×
UNCOV
4209
                // signal that the peer termination watcher does not need to
×
UNCOV
4210
                // execute for this peer.
×
UNCOV
4211
                s.removePeer(connectedPeer)
×
UNCOV
4212
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
UNCOV
4213
                s.scheduledPeerConnection[pubStr] = func() {
×
UNCOV
4214
                        s.peerConnected(conn, connReq, false)
×
UNCOV
4215
                }
×
4216
        }
4217
}
4218

4219
// UnassignedConnID is the default connection ID that a request can have before
4220
// it actually is submitted to the connmgr.
4221
// TODO(conner): move into connmgr package, or better, add connmgr method for
4222
// generating atomic IDs
4223
const UnassignedConnID uint64 = 0
4224

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

4239
        // Next, check to see if we have any outstanding persistent connection
4240
        // requests to this peer. If so, then we'll remove all of these
4241
        // connection requests, and also delete the entry from the map.
UNCOV
4242
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4243
        if !ok {
×
UNCOV
4244
                return
×
UNCOV
4245
        }
×
4246

UNCOV
4247
        for _, connReq := range connReqs {
×
UNCOV
4248
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4249

×
UNCOV
4250
                // Atomically capture the current request identifier.
×
UNCOV
4251
                connID := connReq.ID()
×
UNCOV
4252

×
UNCOV
4253
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4254
                // yet been schedule.
×
UNCOV
4255
                if connID == UnassignedConnID {
×
4256
                        continue
×
4257
                }
4258

4259
                // Skip a particular connection ID if instructed.
UNCOV
4260
                if skip != nil && connID == *skip {
×
UNCOV
4261
                        continue
×
4262
                }
4263

UNCOV
4264
                s.connMgr.Remove(connID)
×
4265
        }
4266

UNCOV
4267
        delete(s.persistentConnReqs, pubStr)
×
4268
}
4269

4270
// handleCustomMessage dispatches an incoming custom peers message to
4271
// subscribers.
UNCOV
4272
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4273
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4274
                peer, msg.Type)
×
UNCOV
4275

×
UNCOV
4276
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4277
                Peer: peer,
×
UNCOV
4278
                Msg:  msg,
×
UNCOV
4279
        })
×
UNCOV
4280
}
×
4281

4282
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4283
// messages.
UNCOV
4284
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4285
        return s.customMessageServer.Subscribe()
×
UNCOV
4286
}
×
4287

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

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

4299
        // Notify subscribers about this open channel event.
UNCOV
4300
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4301
}
4302

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

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

4316
        // Notify subscribers about this event.
UNCOV
4317
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4318
}
4319

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

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

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

4341
        // Notify subscribers about this event.
UNCOV
4342
        s.channelNotifier.NotifyFundingTimeout(op)
×
4343
}
4344

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

×
UNCOV
4352
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4353
        addr := conn.RemoteAddr()
×
UNCOV
4354
        pubKey := brontideConn.RemotePub()
×
UNCOV
4355

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

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

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

×
4374
                conn.Close()
×
4375

×
4376
                return
×
4377
        }
×
4378

UNCOV
4379
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4380
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4381

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

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

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

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

UNCOV
4417
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4418
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4419

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

×
UNCOV
4463
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4464
                },
×
4465

4466
                PongBuf: s.pongBuf,
4467

4468
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4469

4470
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4471

4472
                FundingManager: s.fundingMgr,
4473

4474
                Hodl:                    s.cfg.Hodl,
4475
                UnsafeReplay:            s.cfg.UnsafeReplay,
4476
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4477
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4478
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4479
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4480
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4481
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4482
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4483
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4484
                HandleCustomMessage:    s.handleCustomMessage,
4485
                GetAliases:             s.aliasMgr.GetAliases,
4486
                RequestAlias:           s.aliasMgr.RequestAlias,
4487
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4488
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4489
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4490
                MaxFeeExposure:         thresholdMSats,
4491
                Quit:                   s.quit,
4492
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4493
                AuxSigner:              s.implCfg.AuxSigner,
4494
                MsgRouter:              s.implCfg.MsgRouter,
4495
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4496
                AuxResolver:            s.implCfg.AuxContractResolver,
4497
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
UNCOV
4498
                ShouldFwdExpEndorsement: func() bool {
×
UNCOV
4499
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
UNCOV
4500
                                return false
×
UNCOV
4501
                        }
×
4502

UNCOV
4503
                        return clock.NewDefaultClock().Now().Before(
×
UNCOV
4504
                                EndorsementExperimentEnd,
×
UNCOV
4505
                        )
×
4506
                },
4507
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4508
        }
4509

UNCOV
4510
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4511
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4512

×
UNCOV
4513
        p := peer.NewBrontide(pCfg)
×
UNCOV
4514

×
UNCOV
4515
        // Update the access manager with the access permission for this peer.
×
UNCOV
4516
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
UNCOV
4517

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

×
UNCOV
4521
        s.addPeer(p)
×
UNCOV
4522

×
UNCOV
4523
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4524
        // delete the previous error buffer from the server's map of error
×
UNCOV
4525
        // buffers.
×
UNCOV
4526
        delete(s.peerErrors, pkStr)
×
UNCOV
4527

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

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

UNCOV
4542
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4543

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

×
4550
                return
×
4551
        }
×
4552

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

4558
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4559
        // be human-readable.
UNCOV
4560
        pubStr := string(pubBytes)
×
UNCOV
4561

×
UNCOV
4562
        s.peersByPub[pubStr] = p
×
UNCOV
4563

×
UNCOV
4564
        if p.Inbound() {
×
UNCOV
4565
                s.inboundPeers[pubStr] = p
×
UNCOV
4566
        } else {
×
UNCOV
4567
                s.outboundPeers[pubStr] = p
×
UNCOV
4568
        }
×
4569

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

×
UNCOV
4575
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
4576
}
4577

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

×
UNCOV
4590
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4591

×
UNCOV
4592
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4593
        if s.Stopped() {
×
4594
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4595
                        pubBytes)
×
4596
                return
×
4597
        }
×
4598

4599
        // Create a channel that will be used to signal a successful start of
4600
        // the link. This prevents the peer termination watcher from beginning
4601
        // its duty too early.
UNCOV
4602
        ready := make(chan struct{})
×
UNCOV
4603

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

×
UNCOV
4613
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4614
        // will unblock the peerTerminationWatcher.
×
UNCOV
4615
        if err := p.Start(); err != nil {
×
UNCOV
4616
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4617

×
UNCOV
4618
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4619
                return
×
UNCOV
4620
        }
×
4621

4622
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4623
        // was successful, and to begin watching the peer's wait group.
UNCOV
4624
        close(ready)
×
UNCOV
4625

×
UNCOV
4626
        s.mu.Lock()
×
UNCOV
4627
        defer s.mu.Unlock()
×
UNCOV
4628

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

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

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

×
UNCOV
4659
        ctx := context.TODO()
×
UNCOV
4660

×
UNCOV
4661
        p.WaitForDisconnect(ready)
×
UNCOV
4662

×
UNCOV
4663
        srvrLog.Debugf("Peer %v has been disconnected", p)
×
UNCOV
4664

×
UNCOV
4665
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4666
        // the other sub-systems will already be shutting down.
×
UNCOV
4667
        if s.Stopped() {
×
UNCOV
4668
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
×
UNCOV
4669
                return
×
UNCOV
4670
        }
×
4671

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

×
UNCOV
4678
        pubKey := p.IdentityKey()
×
UNCOV
4679

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

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

UNCOV
4694
        for _, link := range links {
×
UNCOV
4695
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4696
        }
×
4697

UNCOV
4698
        s.mu.Lock()
×
UNCOV
4699
        defer s.mu.Unlock()
×
UNCOV
4700

×
UNCOV
4701
        // If there were any notification requests for when this peer
×
UNCOV
4702
        // disconnected, we can trigger them now.
×
UNCOV
4703
        srvrLog.Debugf("Notifying that peer %v is offline", p)
×
UNCOV
4704
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4705
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4706
                close(offlineChan)
×
UNCOV
4707
        }
×
UNCOV
4708
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4709

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

×
UNCOV
4715
                pubKey := p.PubKey()
×
UNCOV
4716
                pubStr := string(pubKey[:])
×
UNCOV
4717

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

4731
        // First, cleanup any remaining state the server has regarding the peer
4732
        // in question.
UNCOV
4733
        s.removePeer(p)
×
UNCOV
4734

×
UNCOV
4735
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4736
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4737
                return
×
UNCOV
4738
        }
×
4739

4740
        // Get the last address that we used to connect to the peer.
UNCOV
4741
        addrs := []net.Addr{
×
UNCOV
4742
                p.NetAddress().Address,
×
UNCOV
4743
        }
×
UNCOV
4744

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

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

4761
                // Fall back to the existing peer address if
4762
                // we're not accepting connections over Tor.
UNCOV
4763
                if s.torController == nil {
×
UNCOV
4764
                        break
×
4765
                }
4766

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

4777
        // We came across an error retrieving an advertised
4778
        // address, log it, and fall back to the existing peer
4779
        // address.
UNCOV
4780
        default:
×
UNCOV
4781
                srvrLog.Errorf("Unable to retrieve advertised "+
×
UNCOV
4782
                        "address for node %x: %v", p.PubKey(),
×
UNCOV
4783
                        err)
×
4784
        }
4785

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

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

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

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

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

4821
        // We choose not to wait group this go routine since the Connect
4822
        // call can stall for arbitrarily long if we shutdown while an
4823
        // outbound connection attempt is being made.
UNCOV
4824
        go func() {
×
UNCOV
4825
                srvrLog.Debugf("Scheduling connection re-establishment to "+
×
UNCOV
4826
                        "persistent peer %x in %s",
×
UNCOV
4827
                        p.IdentityKey().SerializeCompressed(), backoff)
×
UNCOV
4828

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

UNCOV
4837
                srvrLog.Debugf("Attempting to re-establish persistent "+
×
UNCOV
4838
                        "connection to peer %x",
×
UNCOV
4839
                        p.IdentityKey().SerializeCompressed())
×
UNCOV
4840

×
UNCOV
4841
                s.connectToPersistentPeer(pubStr)
×
4842
        }()
4843
}
4844

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

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

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

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

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

UNCOV
4895
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4896

×
UNCOV
4897
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4898
        if !ok {
×
UNCOV
4899
                cancelChan = make(chan struct{})
×
UNCOV
4900
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4901
        }
×
4902

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

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

×
UNCOV
4920
                        s.mu.Lock()
×
UNCOV
4921
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4922
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4923
                        )
×
UNCOV
4924
                        s.mu.Unlock()
×
UNCOV
4925

×
UNCOV
4926
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4927
                                "channel peer %v", addr)
×
UNCOV
4928

×
UNCOV
4929
                        go s.connMgr.Connect(connReq)
×
UNCOV
4930

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

4942
// removePeer removes the passed peer from the server's state of all active
4943
// peers.
UNCOV
4944
func (s *server) removePeer(p *peer.Brontide) {
×
UNCOV
4945
        if p == nil {
×
4946
                return
×
4947
        }
×
4948

UNCOV
4949
        srvrLog.Debugf("removing peer %v", p)
×
UNCOV
4950

×
UNCOV
4951
        // As the peer is now finished, ensure that the TCP connection is
×
UNCOV
4952
        // closed and all of its related goroutines have exited.
×
UNCOV
4953
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
×
UNCOV
4954

×
UNCOV
4955
        // If this peer had an active persistent connection request, remove it.
×
UNCOV
4956
        if p.ConnReq() != nil {
×
UNCOV
4957
                s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4958
        }
×
4959

4960
        // Ignore deleting peers if we're shutting down.
UNCOV
4961
        if s.Stopped() {
×
4962
                return
×
4963
        }
×
4964

UNCOV
4965
        pKey := p.PubKey()
×
UNCOV
4966
        pubSer := pKey[:]
×
UNCOV
4967
        pubStr := string(pubSer)
×
UNCOV
4968

×
UNCOV
4969
        delete(s.peersByPub, pubStr)
×
UNCOV
4970

×
UNCOV
4971
        if p.Inbound() {
×
UNCOV
4972
                delete(s.inboundPeers, pubStr)
×
UNCOV
4973
        } else {
×
UNCOV
4974
                delete(s.outboundPeers, pubStr)
×
UNCOV
4975
        }
×
4976

4977
        // Remove the peer's access permission from the access manager.
UNCOV
4978
        peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
UNCOV
4979
        s.peerAccessMan.removePeerAccess(peerPubStr)
×
UNCOV
4980

×
UNCOV
4981
        // Copy the peer's error buffer across to the server if it has any items
×
UNCOV
4982
        // in it so that we can restore peer errors across connections.
×
UNCOV
4983
        if p.ErrorBuffer().Total() > 0 {
×
UNCOV
4984
                s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
4985
        }
×
4986

4987
        // Inform the peer notifier of a peer offline event so that it can be
4988
        // reported to clients listening for peer events.
UNCOV
4989
        var pubKey [33]byte
×
UNCOV
4990
        copy(pubKey[:], pubSer)
×
UNCOV
4991

×
UNCOV
4992
        s.peerNotifier.NotifyPeerOffline(pubKey)
×
4993
}
4994

4995
// ConnectToPeer requests that the server connect to a Lightning Network peer
4996
// at the specified address. This function will *block* until either a
4997
// connection is established, or the initial handshake process fails.
4998
//
4999
// NOTE: This function is safe for concurrent access.
5000
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
5001
        perm bool, timeout time.Duration) error {
×
UNCOV
5002

×
UNCOV
5003
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
5004

×
UNCOV
5005
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
5006
        // better granularity.  In certain conditions, this method requires
×
UNCOV
5007
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
5008
        // lock to be released, and subsequently reacquired.
×
UNCOV
5009
        s.mu.Lock()
×
UNCOV
5010

×
UNCOV
5011
        // Ensure we're not already connected to this peer.
×
UNCOV
5012
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
5013

×
UNCOV
5014
        // When there's no error it means we already have a connection with this
×
UNCOV
5015
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
UNCOV
5016
        // set, we will ignore the existing connection and continue.
×
UNCOV
5017
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
UNCOV
5018
                s.mu.Unlock()
×
UNCOV
5019
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
5020
        }
×
5021

5022
        // Peer was not found, continue to pursue connection with peer.
5023

5024
        // If there's already a pending connection request for this pubkey,
5025
        // then we ignore this request to ensure we don't create a redundant
5026
        // connection.
UNCOV
5027
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
5028
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
5029
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
5030
        }
×
5031

5032
        // If there's not already a pending or active connection to this node,
5033
        // then instruct the connection manager to attempt to establish a
5034
        // persistent connection to the peer.
UNCOV
5035
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
5036
        if perm {
×
UNCOV
5037
                connReq := &connmgr.ConnReq{
×
UNCOV
5038
                        Addr:      addr,
×
UNCOV
5039
                        Permanent: true,
×
UNCOV
5040
                }
×
UNCOV
5041

×
UNCOV
5042
                // Since the user requested a permanent connection, we'll set
×
UNCOV
5043
                // the entry to true which will tell the server to continue
×
UNCOV
5044
                // reconnecting even if the number of channels with this peer is
×
UNCOV
5045
                // zero.
×
UNCOV
5046
                s.persistentPeers[targetPub] = true
×
UNCOV
5047
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
5048
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
5049
                }
×
UNCOV
5050
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
5051
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
5052
                )
×
UNCOV
5053
                s.mu.Unlock()
×
UNCOV
5054

×
UNCOV
5055
                go s.connMgr.Connect(connReq)
×
UNCOV
5056

×
UNCOV
5057
                return nil
×
5058
        }
UNCOV
5059
        s.mu.Unlock()
×
UNCOV
5060

×
UNCOV
5061
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
5062
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
5063
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
5064
        // caller.
×
UNCOV
5065
        errChan := make(chan error, 1)
×
UNCOV
5066
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
5067

×
UNCOV
5068
        select {
×
UNCOV
5069
        case err := <-errChan:
×
UNCOV
5070
                return err
×
5071
        case <-s.quit:
×
5072
                return ErrServerShuttingDown
×
5073
        }
5074
}
5075

5076
// connectToPeer establishes a connection to a remote peer. errChan is used to
5077
// notify the caller if the connection attempt has failed. Otherwise, it will be
5078
// closed.
5079
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
5080
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
5081

×
UNCOV
5082
        conn, err := brontide.Dial(
×
UNCOV
5083
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
5084
        )
×
UNCOV
5085
        if err != nil {
×
UNCOV
5086
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
5087
                select {
×
UNCOV
5088
                case errChan <- err:
×
5089
                case <-s.quit:
×
5090
                }
UNCOV
5091
                return
×
5092
        }
5093

UNCOV
5094
        close(errChan)
×
UNCOV
5095

×
UNCOV
5096
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
5097
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
5098

×
UNCOV
5099
        s.OutboundPeerConnected(nil, conn)
×
5100
}
5101

5102
// DisconnectPeer sends the request to server to close the connection with peer
5103
// identified by public key.
5104
//
5105
// NOTE: This function is safe for concurrent access.
UNCOV
5106
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
5107
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
5108
        pubStr := string(pubBytes)
×
UNCOV
5109

×
UNCOV
5110
        s.mu.Lock()
×
UNCOV
5111
        defer s.mu.Unlock()
×
UNCOV
5112

×
UNCOV
5113
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
5114
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
5115
        // currently connected to.
×
UNCOV
5116
        peer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
5117
        if err == ErrPeerNotConnected {
×
UNCOV
5118
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
5119
        }
×
5120

UNCOV
5121
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
5122

×
UNCOV
5123
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
5124

×
UNCOV
5125
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
5126
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
5127
        // disconnect.
×
UNCOV
5128
        delete(s.persistentPeers, pubStr)
×
UNCOV
5129
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
5130

×
UNCOV
5131
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
5132
        // removePeer, which bypassed the peerTerminationWatcher.
×
UNCOV
5133
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
5134

×
UNCOV
5135
        return nil
×
5136
}
5137

5138
// OpenChannel sends a request to the server to open a channel to the specified
5139
// peer identified by nodeKey with the passed channel funding parameters.
5140
//
5141
// NOTE: This function is safe for concurrent access.
5142
func (s *server) OpenChannel(
UNCOV
5143
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
5144

×
UNCOV
5145
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
5146
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
5147
        // not blocked if the caller is not reading the updates.
×
UNCOV
5148
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
5149
        req.Err = make(chan error, 1)
×
UNCOV
5150

×
UNCOV
5151
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
5152
        // we're unable to locate the peer then this request will fail.
×
UNCOV
5153
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
5154
        s.mu.RLock()
×
UNCOV
5155
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
5156
        if !ok {
×
5157
                s.mu.RUnlock()
×
5158

×
5159
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5160
                return req.Updates, req.Err
×
5161
        }
×
UNCOV
5162
        req.Peer = peer
×
UNCOV
5163
        s.mu.RUnlock()
×
UNCOV
5164

×
UNCOV
5165
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
5166
        // opening process.
×
UNCOV
5167
        select {
×
UNCOV
5168
        case <-peer.ActiveSignal():
×
5169
        case <-peer.QuitSignal():
×
5170
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5171
                return req.Updates, req.Err
×
5172
        case <-s.quit:
×
5173
                req.Err <- ErrServerShuttingDown
×
5174
                return req.Updates, req.Err
×
5175
        }
5176

5177
        // If the fee rate wasn't specified at this point we fail the funding
5178
        // because of the missing fee rate information. The caller of the
5179
        // `OpenChannel` method needs to make sure that default values for the
5180
        // fee rate are set beforehand.
UNCOV
5181
        if req.FundingFeePerKw == 0 {
×
5182
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5183
                        "the channel opening transaction")
×
5184

×
5185
                return req.Updates, req.Err
×
5186
        }
×
5187

5188
        // Spawn a goroutine to send the funding workflow request to the funding
5189
        // manager. This allows the server to continue handling queries instead
5190
        // of blocking on this request which is exported as a synchronous
5191
        // request to the outside world.
UNCOV
5192
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
5193

×
UNCOV
5194
        return req.Updates, req.Err
×
5195
}
5196

5197
// Peers returns a slice of all active peers.
5198
//
5199
// NOTE: This function is safe for concurrent access.
UNCOV
5200
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
5201
        s.mu.RLock()
×
UNCOV
5202
        defer s.mu.RUnlock()
×
UNCOV
5203

×
UNCOV
5204
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
5205
        for _, peer := range s.peersByPub {
×
UNCOV
5206
                peers = append(peers, peer)
×
UNCOV
5207
        }
×
5208

UNCOV
5209
        return peers
×
5210
}
5211

5212
// computeNextBackoff uses a truncated exponential backoff to compute the next
5213
// backoff using the value of the exiting backoff. The returned duration is
5214
// randomized in either direction by 1/20 to prevent tight loops from
5215
// stabilizing.
UNCOV
5216
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
5217
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
5218
        nextBackoff := 2 * currBackoff
×
UNCOV
5219
        if nextBackoff > maxBackoff {
×
UNCOV
5220
                nextBackoff = maxBackoff
×
UNCOV
5221
        }
×
5222

5223
        // Using 1/10 of our duration as a margin, compute a random offset to
5224
        // avoid the nodes entering connection cycles.
UNCOV
5225
        margin := nextBackoff / 10
×
UNCOV
5226

×
UNCOV
5227
        var wiggle big.Int
×
UNCOV
5228
        wiggle.SetUint64(uint64(margin))
×
UNCOV
5229
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5230
                // Randomizing is not mission critical, so we'll just return the
×
5231
                // current backoff.
×
5232
                return nextBackoff
×
5233
        }
×
5234

5235
        // Otherwise add in our wiggle, but subtract out half of the margin so
5236
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
5237
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5238
}
5239

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

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

×
UNCOV
5248
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
5249
        if err != nil {
×
5250
                return nil, err
×
5251
        }
×
5252

UNCOV
5253
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
×
UNCOV
5254
        if err != nil {
×
UNCOV
5255
                return nil, err
×
UNCOV
5256
        }
×
5257

UNCOV
5258
        if len(node.Addresses) == 0 {
×
UNCOV
5259
                return nil, errNoAdvertisedAddr
×
UNCOV
5260
        }
×
5261

UNCOV
5262
        return node.Addresses, nil
×
5263
}
5264

5265
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5266
// channel update for a target channel.
5267
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
5268
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
5269

×
UNCOV
5270
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
5271
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
5272
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
5273
                if err != nil {
×
UNCOV
5274
                        return nil, err
×
UNCOV
5275
                }
×
5276

UNCOV
5277
                return netann.ExtractChannelUpdate(
×
UNCOV
5278
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
5279
                )
×
5280
        }
5281
}
5282

5283
// applyChannelUpdate applies the channel update to the different sub-systems of
5284
// the server. The useAlias boolean denotes whether or not to send an alias in
5285
// place of the real SCID.
5286
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
5287
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
5288

×
UNCOV
5289
        var (
×
UNCOV
5290
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5291
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5292
        )
×
UNCOV
5293

×
UNCOV
5294
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5295

×
UNCOV
5296
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
5297
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
5298
        if useAlias {
×
UNCOV
5299
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
5300
                if foundAlias != defaultAlias {
×
UNCOV
5301
                        peerAlias = &foundAlias
×
UNCOV
5302
                }
×
5303
        }
5304

UNCOV
5305
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
5306
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
5307
        )
×
UNCOV
5308
        select {
×
UNCOV
5309
        case err := <-errChan:
×
UNCOV
5310
                return err
×
5311
        case <-s.quit:
×
5312
                return ErrServerShuttingDown
×
5313
        }
5314
}
5315

5316
// SendCustomMessage sends a custom message to the peer with the specified
5317
// pubkey.
5318
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5319
        data []byte) error {
×
UNCOV
5320

×
UNCOV
5321
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5322
        if err != nil {
×
5323
                return err
×
5324
        }
×
5325

5326
        // We'll wait until the peer is active.
UNCOV
5327
        select {
×
UNCOV
5328
        case <-peer.ActiveSignal():
×
5329
        case <-peer.QuitSignal():
×
5330
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5331
        case <-s.quit:
×
5332
                return ErrServerShuttingDown
×
5333
        }
5334

UNCOV
5335
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5336
        if err != nil {
×
UNCOV
5337
                return err
×
UNCOV
5338
        }
×
5339

5340
        // Send the message as low-priority. For now we assume that all
5341
        // application-defined message are low priority.
UNCOV
5342
        return peer.SendMessageLazy(true, msg)
×
5343
}
5344

5345
// newSweepPkScriptGen creates closure that generates a new public key script
5346
// which should be used to sweep any funds into the on-chain wallet.
5347
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5348
// (p2wkh) output.
5349
func newSweepPkScriptGen(
5350
        wallet lnwallet.WalletController,
UNCOV
5351
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5352

×
UNCOV
5353
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5354
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5355
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5356
                        lnwallet.DefaultAccountName,
×
UNCOV
5357
                )
×
UNCOV
5358
                if err != nil {
×
5359
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5360
                }
×
5361

UNCOV
5362
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5363
                if err != nil {
×
5364
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5365
                }
×
5366

UNCOV
5367
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5368
                        wallet, netParams, addr,
×
UNCOV
5369
                )
×
UNCOV
5370
                if err != nil {
×
5371
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5372
                }
×
5373

UNCOV
5374
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5375
                        DeliveryAddress: addr,
×
UNCOV
5376
                        InternalKey:     internalKeyDesc,
×
UNCOV
5377
                })
×
5378
        }
5379
}
5380

5381
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5382
// finished.
UNCOV
5383
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5384
        // Get a list of closed channels.
×
UNCOV
5385
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5386
        if err != nil {
×
5387
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5388
                return nil
×
5389
        }
×
5390

5391
        // Save the SCIDs in a map.
UNCOV
5392
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
UNCOV
5393
        for _, c := range channels {
×
UNCOV
5394
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5395
                if !c.IsPending {
×
UNCOV
5396
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5397
                }
×
5398
        }
5399

5400
        // Double check whether the reported closed channel has indeed finished
5401
        // closing.
5402
        //
5403
        // NOTE: There are misalignments regarding when a channel's FC is
5404
        // marked as finalized. We double check the pending channels to make
5405
        // sure the returned SCIDs are indeed terminated.
5406
        //
5407
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5408
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5409
        if err != nil {
×
5410
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5411
                return nil
×
5412
        }
×
5413

UNCOV
5414
        for _, c := range pendings {
×
UNCOV
5415
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5416
                        continue
×
5417
                }
5418

5419
                // If the channel is still reported as pending, remove it from
5420
                // the map.
5421
                delete(closedSCIDs, c.ShortChannelID)
×
5422

×
5423
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5424
                        c.ShortChannelID)
×
5425
        }
5426

UNCOV
5427
        return closedSCIDs
×
5428
}
5429

5430
// getStartingBeat returns the current beat. This is used during the startup to
5431
// initialize blockbeat consumers.
UNCOV
5432
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
UNCOV
5433
        // beat is the current blockbeat.
×
UNCOV
5434
        var beat *chainio.Beat
×
UNCOV
5435

×
UNCOV
5436
        // If the node is configured with nochainbackend mode (remote signer),
×
UNCOV
5437
        // we will skip fetching the best block.
×
UNCOV
5438
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5439
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5440
                        "mode")
×
5441

×
5442
                return &chainio.Beat{}, nil
×
5443
        }
×
5444

5445
        // We should get a notification with the current best block immediately
5446
        // by passing a nil block.
UNCOV
5447
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
UNCOV
5448
        if err != nil {
×
5449
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5450
        }
×
UNCOV
5451
        defer blockEpochs.Cancel()
×
UNCOV
5452

×
UNCOV
5453
        // We registered for the block epochs with a nil request. The notifier
×
UNCOV
5454
        // should send us the current best block immediately. So we need to
×
UNCOV
5455
        // wait for it here because we need to know the current best height.
×
UNCOV
5456
        select {
×
UNCOV
5457
        case bestBlock := <-blockEpochs.Epochs:
×
UNCOV
5458
                srvrLog.Infof("Received initial block %v at height %d",
×
UNCOV
5459
                        bestBlock.Hash, bestBlock.Height)
×
UNCOV
5460

×
UNCOV
5461
                // Update the current blockbeat.
×
UNCOV
5462
                beat = chainio.NewBeat(*bestBlock)
×
5463

5464
        case <-s.quit:
×
5465
                srvrLog.Debug("LND shutting down")
×
5466
        }
5467

UNCOV
5468
        return beat, nil
×
5469
}
5470

5471
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5472
// point has an active RBF chan closer.
5473
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
UNCOV
5474
        chanPoint wire.OutPoint) bool {
×
UNCOV
5475

×
UNCOV
5476
        pubBytes := peerPub.SerializeCompressed()
×
UNCOV
5477

×
UNCOV
5478
        s.mu.RLock()
×
UNCOV
5479
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
UNCOV
5480
        s.mu.RUnlock()
×
UNCOV
5481
        if !ok {
×
5482
                return false
×
5483
        }
×
5484

UNCOV
5485
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5486
}
5487

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

×
UNCOV
5496
        // First, we'll attempt to look up the channel based on it's
×
UNCOV
5497
        // ChannelPoint.
×
UNCOV
5498
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
UNCOV
5499
        if err != nil {
×
5500
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5501
        }
×
5502

5503
        // From the channel, we can now get the pubkey of the peer, then use
5504
        // that to eventually get the chan closer.
UNCOV
5505
        peerPub := channel.IdentityPub.SerializeCompressed()
×
UNCOV
5506

×
UNCOV
5507
        // Now that we have the peer pub, we can look up the peer itself.
×
UNCOV
5508
        s.mu.RLock()
×
UNCOV
5509
        targetPeer, ok := s.peersByPub[string(peerPub)]
×
UNCOV
5510
        s.mu.RUnlock()
×
UNCOV
5511
        if !ok {
×
5512
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5513
                        "not online", chanPoint)
×
5514
        }
×
5515

UNCOV
5516
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
UNCOV
5517
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5518
        )
×
UNCOV
5519
        if err != nil {
×
5520
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5521
                        "%w", err)
×
5522
        }
×
5523

UNCOV
5524
        return closeUpdates, nil
×
5525
}
5526

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

×
UNCOV
5535
        // If the channel is present in the switch, then the request should flow
×
UNCOV
5536
        // through the switch instead.
×
UNCOV
5537
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5538
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
×
5539
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5540
                        "invalid request", chanPoint)
×
5541
        }
×
5542

5543
        // At this point, we know that the channel isn't present in the link, so
5544
        // we'll check to see if we have an entry in the active chan closer map.
UNCOV
5545
        updates, err := s.attemptCoopRbfFeeBump(
×
UNCOV
5546
                ctx, chanPoint, feeRate, deliveryScript,
×
UNCOV
5547
        )
×
UNCOV
5548
        if err != nil {
×
5549
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5550
                        "ChannelPoint(%v)", chanPoint)
×
5551
        }
×
5552

UNCOV
5553
        return updates, nil
×
5554
}
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