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

lightningnetwork / lnd / 16634042345

30 Jul 2025 09:21PM UTC coverage: 67.156% (-0.03%) from 67.181%
16634042345

Pull #8825

github

web-flow
Merge 330140745 into 438906798
Pull Request #8825: lnd: use persisted node announcement settings across restarts

90 of 128 new or added lines in 1 file covered. (70.31%)

119 existing lines in 22 files now uncovered.

135533 of 201817 relevant lines covered (67.16%)

21675.41 hits per line

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

69.52
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

204
        case peerStatusTemporary:
3✔
205
                return "temporary"
3✔
206

207
        case peerStatusProtected:
3✔
208
                return "protected"
3✔
209

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

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

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

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

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

248
        chanStatusMgr *netann.ChanStatusManager
249

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

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

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

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

270
        mu sync.RWMutex
271

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

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

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

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

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

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

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

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

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

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

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

413
        hostAnn *netann.HostAnnouncer
414

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

418
        customMessageServer *subscribe.Server
419

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

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

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

430
        quit chan struct{}
431

432
        wg sync.WaitGroup
433
}
434

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

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

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

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

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

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

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

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

490
                                        s.mu.Lock()
3✔
491

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

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

506
                                        s.mu.Unlock()
3✔
507

3✔
508
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
509
                                }
510
                        }
511
                }
512
        }()
513

514
        return nil
3✔
515
}
516

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

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

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

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

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

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

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

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

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

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

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

3✔
597
        netParams := cfg.ActiveNetParams.Params
3✔
598

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

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

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

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

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

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

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

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

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

3✔
668
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
669

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

3✔
684
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
685
                        cc.ChainNotifier,
3✔
686
                ),
3✔
687
                channelNotifier: channelnotifier.New(
3✔
688
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
689
                ),
3✔
690

3✔
691
                identityECDH:   nodeKeyECDH,
3✔
692
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
693
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
694

3✔
695
                listenAddrs: listenAddrs,
3✔
696

3✔
697
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
698
                // schedule
3✔
699
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
700

3✔
701
                torController: torController,
3✔
702

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

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

3✔
719
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
720

3✔
721
                customMessageServer: subscribe.NewServer(),
3✔
722

3✔
723
                tlsManager: tlsManager,
3✔
724

3✔
725
                featureMgr: featureMgr,
3✔
726
                quit:       make(chan struct{}),
3✔
727
        }
3✔
728

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

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

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

3✔
753
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
754

3✔
755
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
756
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
757

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

764
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
765

3✔
766
                return nil
3✔
767
        }
768

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

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

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

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

826
        s.witnessBeacon = newPreimageBeacon(
3✔
827
                dbs.ChanStateDB.NewWitnessCache(),
3✔
828
                s.interceptableSwitch.ForwardPacket,
3✔
829
        )
3✔
830

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

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

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

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

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

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

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

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

887
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
888
        // Set the self node which represents our node in the graph.
3✔
889
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
890
        if err != nil {
3✔
891
                return nil, err
×
892
        }
×
893

894
        // The router will get access to the payment ID sequencer, such that it
895
        // can generate unique payment IDs.
896
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
897
        if err != nil {
3✔
898
                return nil, err
×
899
        }
×
900

901
        // Instantiate mission control with config from the sub server.
902
        //
903
        // TODO(joostjager): When we are further in the process of moving to sub
904
        // servers, the mission control instance itself can be moved there too.
905
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
906

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

3✔
922
                        estimator, err = routing.NewAprioriEstimator(
3✔
923
                                aprioriConfig,
3✔
924
                        )
3✔
925
                        if err != nil {
3✔
926
                                return nil, err
×
927
                        }
×
928

929
                case routing.BimodalEstimatorName:
×
930
                        bCfg := routingConfig.BimodalConfig
×
931
                        bimodalConfig := routing.BimodalConfig{
×
932
                                BimodalNodeWeight: bCfg.NodeWeight,
×
933
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
934
                                        bCfg.Scale,
×
935
                                ),
×
936
                                BimodalDecayTime: bCfg.DecayTime,
×
937
                        }
×
938

×
939
                        estimator, err = routing.NewBimodalEstimator(
×
940
                                bimodalConfig,
×
941
                        )
×
942
                        if err != nil {
×
943
                                return nil, err
×
944
                        }
×
945

946
                default:
×
947
                        return nil, fmt.Errorf("unknown estimator type %v",
×
948
                                routingConfig.ProbabilityEstimatorType)
×
949
                }
950
        }
951

952
        mcCfg := &routing.MissionControlConfig{
3✔
953
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
954
                Estimator:               estimator,
3✔
955
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
956
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
957
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
958
        }
3✔
959

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

975
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
976
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
977
                int64(routingConfig.AttemptCost),
3✔
978
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
979
                routingConfig.MinRouteProbability)
3✔
980

3✔
981
        pathFindingConfig := routing.PathFindingConfig{
3✔
982
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
983
                        routingConfig.AttemptCost,
3✔
984
                ),
3✔
985
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
986
                MinProbability: routingConfig.MinRouteProbability,
3✔
987
        }
3✔
988

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

3✔
1001
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1002

3✔
1003
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1004

3✔
1005
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1006
                cfg.Routing.StrictZombiePruning
3✔
1007

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

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

1045
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1046
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1047
        if err != nil {
3✔
1048
                return nil, err
×
1049
        }
×
1050
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1051
        if err != nil {
3✔
1052
                return nil, err
×
1053
        }
×
1054

1055
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1056

3✔
1057
        s.authGossiper = discovery.New(discovery.Config{
3✔
1058
                Graph:                 s.graphBuilder,
3✔
1059
                ChainIO:               s.cc.ChainIO,
3✔
1060
                Notifier:              s.cc.ChainNotifier,
3✔
1061
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1062
                Broadcast:             s.BroadcastMessage,
3✔
1063
                ChanSeries:            chanSeries,
3✔
1064
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1065
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1066
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1067
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1068
                        error) {
3✔
1069

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

1101
        accessCfg := &accessManConfig{
3✔
1102
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1103
                        error) {
6✔
1104

3✔
1105
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1106
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1107
                                genesisHash[:],
3✔
1108
                        )
3✔
1109
                },
3✔
1110
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1111
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1112
        }
1113

1114
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1115
        if err != nil {
3✔
1116
                return nil, err
×
1117
        }
×
1118

1119
        s.peerAccessMan = peerAccessMan
3✔
1120

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

3✔
1131
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1132
                                func(c *models.ChannelEdgeInfo,
3✔
1133
                                        e *models.ChannelEdgePolicy,
3✔
1134
                                        _ *models.ChannelEdgePolicy) error {
6✔
1135

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

×
1148
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1149
                },
×
1150
        }
1151

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

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

1168
        aggregator := sweep.NewBudgetAggregator(
3✔
1169
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1170
                s.implCfg.AuxSweeper,
3✔
1171
        )
3✔
1172

3✔
1173
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1174
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1175
                Wallet:     cc.Wallet,
3✔
1176
                Estimator:  cc.FeeEstimator,
3✔
1177
                Notifier:   cc.ChainNotifier,
3✔
1178
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1179
        })
3✔
1180

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

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

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

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

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

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

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

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

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

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

1307
                                // If the BreachArbitrator successfully handled
1308
                                // the event, we can signal that the handoff
1309
                                // was successful.
1310
                                finalErr <- nil
3✔
1311
                        }
1312

1313
                        event := &contractcourt.ContractBreachEvent{
3✔
1314
                                ChanPoint:         chanPoint,
3✔
1315
                                ProcessACK:        processACK,
3✔
1316
                                BreachRetribution: breachRet,
3✔
1317
                        }
3✔
1318

3✔
1319
                        // Send the contract breach event to the
3✔
1320
                        // BreachArbitrator.
3✔
1321
                        select {
3✔
1322
                        case contractBreaches <- event:
3✔
1323
                        case <-s.quit:
×
1324
                                return ErrServerShuttingDown
×
1325
                        }
1326

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

1352
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1353
                QueryIncomingCircuit: func(
1354
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1355

3✔
1356
                        // Get the circuit map.
3✔
1357
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1358

3✔
1359
                        // Lookup the outgoing circuit.
3✔
1360
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1361
                        if pc == nil {
5✔
1362
                                return nil
2✔
1363
                        }
2✔
1364

1365
                        return &pc.Incoming
3✔
1366
                },
1367
                AuxLeafStore: implCfg.AuxLeafStore,
1368
                AuxSigner:    implCfg.AuxSigner,
1369
                AuxResolver:  implCfg.AuxContractResolver,
1370
        }, dbs.ChanStateDB)
1371

1372
        // Select the configuration and funding parameters for Bitcoin.
1373
        chainCfg := cfg.Bitcoin
3✔
1374
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1375
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1376

3✔
1377
        var chanIDSeed [32]byte
3✔
1378
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1379
                return nil, err
×
1380
        }
×
1381

1382
        // Wrap the DeleteChannelEdges method so that the funding manager can
1383
        // use it without depending on several layers of indirection.
1384
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1385
                *models.ChannelEdgePolicy, error) {
6✔
1386

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

1400
                // Grab our key to find our policy.
1401
                var ourKey [33]byte
3✔
1402
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1403

3✔
1404
                var ourPolicy *models.ChannelEdgePolicy
3✔
1405
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1406
                        ourPolicy = e1
3✔
1407
                } else {
6✔
1408
                        ourPolicy = e2
3✔
1409
                }
3✔
1410

1411
                if ourPolicy == nil {
3✔
1412
                        // Something is wrong, so return an error.
×
1413
                        return nil, fmt.Errorf("we don't have an edge")
×
1414
                }
×
1415

1416
                err = s.graphDB.DeleteChannelEdges(
3✔
1417
                        false, false, scid.ToUint64(),
3✔
1418
                )
3✔
1419
                return ourPolicy, err
3✔
1420
        }
1421

1422
        // For the reservationTimeout and the zombieSweeperInterval different
1423
        // values are set in case we are in a dev environment so enhance test
1424
        // capacilities.
1425
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1426
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1427

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

3✔
1438
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1439
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1440

3✔
1441
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1442
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1443
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1444
        }
3✔
1445

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

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

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

1492
                        minConf := uint64(3)
×
1493
                        maxConf := uint64(6)
×
1494

×
1495
                        // If this is a wumbo channel, then we'll require the
×
1496
                        // max amount of confirmations.
×
1497
                        if chanAmt > MaxFundingAmount {
×
1498
                                return uint16(maxConf)
×
1499
                        }
×
1500

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

3✔
1523
                        // In case the user has explicitly specified
3✔
1524
                        // a default value for the remote delay, we
3✔
1525
                        // use it.
3✔
1526
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1527
                        if defaultDelay > 0 {
6✔
1528
                                return defaultDelay
3✔
1529
                        }
3✔
1530

1531
                        // If this is a wumbo channel, then we'll require the
1532
                        // max value.
1533
                        if chanAmt > MaxFundingAmount {
×
1534
                                return maxRemoteDelay
×
1535
                        }
×
1536

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

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

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

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

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

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

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

1650
        // Assemble a peer notifier which will provide clients with subscriptions
1651
        // to peer online and offline events.
1652
        s.peerNotifier = peernotifier.New()
3✔
1653

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

1669
        if cfg.WtClient.Active {
6✔
1670
                policy := wtpolicy.DefaultPolicy()
3✔
1671
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1672

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

3✔
1679
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1680

3✔
1681
                if err := policy.Validate(); err != nil {
3✔
1682
                        return nil, err
×
1683
                }
×
1684

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

3✔
1691
                        return brontide.Dial(
3✔
1692
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1693
                        )
3✔
1694
                }
3✔
1695

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

3✔
1703
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1704
                                nil, chanID,
3✔
1705
                        )
3✔
1706
                        if err != nil {
3✔
1707
                                return nil, 0, err
×
1708
                        }
×
1709

1710
                        br, err := lnwallet.NewBreachRetribution(
3✔
1711
                                channel, commitHeight, 0, nil,
3✔
1712
                                implCfg.AuxLeafStore,
3✔
1713
                                implCfg.AuxContractResolver,
3✔
1714
                        )
3✔
1715
                        if err != nil {
3✔
1716
                                return nil, 0, err
×
1717
                        }
×
1718

1719
                        return br, channel.ChanType, nil
3✔
1720
                }
1721

1722
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1723

3✔
1724
                // Copy the policy for legacy channels and set the blob flag
3✔
1725
                // signalling support for anchor channels.
3✔
1726
                anchorPolicy := policy
3✔
1727
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1728

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

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

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

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

1772
        if len(cfg.ExternalHosts) != 0 {
3✔
1773
                advertisedIPs := make(map[string]struct{})
×
1774
                for _, addr := range s.currentNodeAnn.Addresses {
×
1775
                        advertisedIPs[addr.String()] = struct{}{}
×
1776
                }
×
1777

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

×
1792
                                        return s.genNodeAnnouncement(
×
1793
                                                nil, modifier...,
×
1794
                                        )
×
1795
                                }),
×
1796
                })
1797
        }
1798

1799
        // Create liveness monitor.
1800
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1801

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

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

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

3✔
1839
        // Finally, register the subsystems in blockbeat.
3✔
1840
        s.registerBlockConsumers()
3✔
1841

3✔
1842
        return s, nil
3✔
1843
}
1844

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

3✔
1850
        switch c := cfg.Estimator.Config().(type) {
3✔
1851
        case routing.AprioriConfig:
3✔
1852
                routerCfg.ProbabilityEstimatorType =
3✔
1853
                        routing.AprioriEstimatorName
3✔
1854

3✔
1855
                targetCfg := routerCfg.AprioriConfig
3✔
1856
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1857
                targetCfg.Weight = c.AprioriWeight
3✔
1858
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1859
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1860

1861
        case routing.BimodalConfig:
3✔
1862
                routerCfg.ProbabilityEstimatorType =
3✔
1863
                        routing.BimodalEstimatorName
3✔
1864

3✔
1865
                targetCfg := routerCfg.BimodalConfig
3✔
1866
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1867
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1868
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1869
        }
1870

1871
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1872
}
1873

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

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

3✔
1899
        data, err := u.DataToSign()
3✔
1900
        if err != nil {
3✔
1901
                return nil, err
×
1902
        }
×
1903

1904
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1905
}
1906

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

3✔
1920
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1921
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1922
                srvrLog.Info("Disabling chain backend checks for " +
×
1923
                        "nochainbackend mode")
×
1924

×
1925
                chainBackendAttempts = 0
×
1926
        }
×
1927

1928
        chainHealthCheck := healthcheck.NewObservation(
3✔
1929
                "chain backend",
3✔
1930
                cc.HealthCheck,
3✔
1931
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1932
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1933
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1934
                chainBackendAttempts,
3✔
1935
        )
3✔
1936

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

1947
                        // If we have more free space than we require,
1948
                        // we return a nil error.
1949
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1950
                                return nil
×
1951
                        }
×
1952

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

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

1977
                        // If the certificate is not outdated, no error needs
1978
                        // to be returned
1979
                        return nil
×
1980
                },
1981
                cfg.HealthChecks.TLSCheck.Interval,
1982
                cfg.HealthChecks.TLSCheck.Timeout,
1983
                cfg.HealthChecks.TLSCheck.Backoff,
1984
                cfg.HealthChecks.TLSCheck.Attempts,
1985
        )
1986

1987
        checks := []*healthcheck.Observation{
3✔
1988
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1989
        }
3✔
1990

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

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

3✔
2021
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2022
                        "remote signer connection",
3✔
2023
                        rpcwallet.HealthCheck(
3✔
2024
                                s.cfg.RemoteSigner,
3✔
2025

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

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

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

2065
                                if !leader {
×
2066
                                        srvrLog.Debug("Not the current leader")
×
2067
                                        return fmt.Errorf("not the current " +
×
2068
                                                "leader")
×
2069
                                }
×
2070

2071
                                return nil
×
2072
                        },
2073
                        cfg.HealthChecks.LeaderCheck.Interval,
2074
                        cfg.HealthChecks.LeaderCheck.Timeout,
2075
                        cfg.HealthChecks.LeaderCheck.Backoff,
2076
                        cfg.HealthChecks.LeaderCheck.Attempts,
2077
                )
2078

2079
                checks = append(checks, leaderCheck)
×
2080
        }
2081

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

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

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

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

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

2119
// startLowLevelServices starts the low-level services of the server. These
2120
// services must be started successfully before running the main server. The
2121
// services are,
2122
// 1. the chain notifier.
2123
//
2124
// TODO(yy): identify and add more low-level services here.
2125
func (s *server) startLowLevelServices() error {
3✔
2126
        var startErr error
3✔
2127

3✔
2128
        cleanup := cleaner{}
3✔
2129

3✔
2130
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2131
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2132
                startErr = err
×
2133
        }
×
2134

2135
        if startErr != nil {
3✔
2136
                cleanup.run()
×
2137
        }
×
2138

2139
        return startErr
3✔
2140
}
2141

2142
// Start starts the main daemon server, all requested listeners, and any helper
2143
// goroutines.
2144
// NOTE: This function is safe for concurrent access.
2145
//
2146
//nolint:funlen
2147
func (s *server) Start(ctx context.Context) error {
3✔
2148
        // Get the current blockbeat.
3✔
2149
        beat, err := s.getStartingBeat()
3✔
2150
        if err != nil {
3✔
2151
                return err
×
2152
        }
×
2153

2154
        var startErr error
3✔
2155

3✔
2156
        // If one sub system fails to start, the following code ensures that the
3✔
2157
        // previous started ones are stopped. It also ensures a proper wallet
3✔
2158
        // shutdown which is important for releasing its resources (boltdb, etc...)
3✔
2159
        cleanup := cleaner{}
3✔
2160

3✔
2161
        s.start.Do(func() {
6✔
2162
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2163
                if err := s.customMessageServer.Start(); err != nil {
3✔
2164
                        startErr = err
×
2165
                        return
×
2166
                }
×
2167

2168
                if s.hostAnn != nil {
3✔
2169
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2170
                        if err := s.hostAnn.Start(); err != nil {
×
2171
                                startErr = err
×
2172
                                return
×
2173
                        }
×
2174
                }
2175

2176
                if s.livenessMonitor != nil {
6✔
2177
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2178
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2179
                                startErr = err
×
2180
                                return
×
2181
                        }
×
2182
                }
2183

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

2195
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2196
                if err := s.writePool.Start(); err != nil {
3✔
2197
                        startErr = err
×
2198
                        return
×
2199
                }
×
2200

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

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

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

2219
                cleanup = cleanup.add(func() error {
3✔
2220
                        return s.peerNotifier.Stop()
×
2221
                })
×
2222
                if err := s.peerNotifier.Start(); err != nil {
3✔
2223
                        startErr = err
×
2224
                        return
×
2225
                }
×
2226

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

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

2241
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2242
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2243
                        startErr = err
×
2244
                        return
×
2245
                }
×
2246

2247
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2248
                if err := s.sweeper.Start(beat); err != nil {
3✔
2249
                        startErr = err
×
2250
                        return
×
2251
                }
×
2252

2253
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
2254
                if err := s.utxoNursery.Start(); err != nil {
3✔
2255
                        startErr = err
×
2256
                        return
×
2257
                }
×
2258

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

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

2271
                // htlcSwitch must be started before chainArb since the latter
2272
                // relies on htlcSwitch to deliver resolution message upon
2273
                // start.
2274
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2275
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2276
                        startErr = err
×
2277
                        return
×
2278
                }
×
2279

2280
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
3✔
2281
                if err := s.interceptableSwitch.Start(); err != nil {
3✔
2282
                        startErr = err
×
2283
                        return
×
2284
                }
×
2285

2286
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
3✔
2287
                if err := s.invoiceHtlcModifier.Start(); err != nil {
3✔
2288
                        startErr = err
×
2289
                        return
×
2290
                }
×
2291

2292
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2293
                if err := s.chainArb.Start(beat); err != nil {
3✔
2294
                        startErr = err
×
2295
                        return
×
2296
                }
×
2297

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

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

2310
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2311
                if err := s.chanRouter.Start(); err != nil {
3✔
2312
                        startErr = err
×
2313
                        return
×
2314
                }
×
2315
                // The authGossiper depends on the chanRouter and therefore
2316
                // should be started after it.
2317
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2318
                if err := s.authGossiper.Start(); err != nil {
3✔
2319
                        startErr = err
×
2320
                        return
×
2321
                }
×
2322

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

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

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

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

2347
                cleanup.add(func() error {
3✔
2348
                        s.missionController.StopStoreTickers()
×
2349
                        return nil
×
2350
                })
×
2351
                s.missionController.RunStoreTickers()
3✔
2352

3✔
2353
                // Before we start the connMgr, we'll check to see if we have
3✔
2354
                // any backups to recover. We do this now as we want to ensure
3✔
2355
                // that have all the information we need to handle channel
3✔
2356
                // recovery _before_ we even accept connections from any peers.
3✔
2357
                chanRestorer := &chanDBRestorer{
3✔
2358
                        db:         s.chanStateDB,
3✔
2359
                        secretKeys: s.cc.KeyRing,
3✔
2360
                        chainArb:   s.chainArb,
3✔
2361
                }
3✔
2362
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2363
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2364
                                s.chansToRestore.PackedSingleChanBackups,
×
2365
                                s.cc.KeyRing, chanRestorer, s,
×
2366
                        )
×
2367
                        if err != nil {
×
2368
                                startErr = fmt.Errorf("unable to unpack single "+
×
2369
                                        "backups: %v", err)
×
2370
                                return
×
2371
                        }
×
2372
                }
2373
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2374
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2375
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2376
                                s.cc.KeyRing, chanRestorer, s,
3✔
2377
                        )
3✔
2378
                        if err != nil {
3✔
2379
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2380
                                        "backup: %v", err)
×
2381
                                return
×
2382
                        }
×
2383
                }
2384

2385
                // chanSubSwapper must be started after the `channelNotifier`
2386
                // because it depends on channel events as a synchronization
2387
                // point.
2388
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2389
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2390
                        startErr = err
×
2391
                        return
×
2392
                }
×
2393

2394
                if s.torController != nil {
3✔
2395
                        cleanup = cleanup.add(s.torController.Stop)
×
2396
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2397
                                startErr = err
×
2398
                                return
×
2399
                        }
×
2400
                }
2401

2402
                if s.natTraversal != nil {
3✔
2403
                        s.wg.Add(1)
×
2404
                        go s.watchExternalIP()
×
2405
                }
×
2406

2407
                // Start connmgr last to prevent connections before init.
2408
                cleanup = cleanup.add(func() error {
3✔
2409
                        s.connMgr.Stop()
×
2410
                        return nil
×
2411
                })
×
2412

2413
                // RESOLVE: s.connMgr.Start() is called here, but
2414
                // brontide.NewListener() is called in newServer. This means
2415
                // that we are actually listening and partially accepting
2416
                // inbound connections even before the connMgr starts.
2417
                //
2418
                // TODO(yy): move the log into the connMgr's `Start` method.
2419
                srvrLog.Info("connMgr starting...")
3✔
2420
                s.connMgr.Start()
3✔
2421
                srvrLog.Debug("connMgr started")
3✔
2422

3✔
2423
                // If peers are specified as a config option, we'll add those
3✔
2424
                // peers first.
3✔
2425
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2426
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2427
                                peerAddrCfg,
3✔
2428
                        )
3✔
2429
                        if err != nil {
3✔
2430
                                startErr = fmt.Errorf("unable to parse peer "+
×
2431
                                        "pubkey from config: %v", err)
×
2432
                                return
×
2433
                        }
×
2434
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2435
                        if err != nil {
3✔
2436
                                startErr = fmt.Errorf("unable to parse peer "+
×
2437
                                        "address provided as a config option: "+
×
2438
                                        "%v", err)
×
2439
                                return
×
2440
                        }
×
2441

2442
                        peerAddr := &lnwire.NetAddress{
3✔
2443
                                IdentityKey: parsedPubkey,
3✔
2444
                                Address:     addr,
3✔
2445
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2446
                        }
3✔
2447

3✔
2448
                        err = s.ConnectToPeer(
3✔
2449
                                peerAddr, true,
3✔
2450
                                s.cfg.ConnectionTimeout,
3✔
2451
                        )
3✔
2452
                        if err != nil {
3✔
2453
                                startErr = fmt.Errorf("unable to connect to "+
×
2454
                                        "peer address provided as a config "+
×
2455
                                        "option: %v", err)
×
2456
                                return
×
2457
                        }
×
2458
                }
2459

2460
                // Subscribe to NodeAnnouncements that advertise new addresses
2461
                // our persistent peers.
2462
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2463
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2464
                                "addr: %v", err)
×
2465

×
2466
                        startErr = err
×
2467
                        return
×
2468
                }
×
2469

2470
                // With all the relevant sub-systems started, we'll now attempt
2471
                // to establish persistent connections to our direct channel
2472
                // collaborators within the network. Before doing so however,
2473
                // we'll prune our set of link nodes found within the database
2474
                // to ensure we don't reconnect to any nodes we no longer have
2475
                // open channels with.
2476
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2477
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2478

×
2479
                        startErr = err
×
2480
                        return
×
2481
                }
×
2482

2483
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2484
                        srvrLog.Errorf("Failed to establish persistent "+
×
2485
                                "connections: %v", err)
×
2486
                }
×
2487

2488
                // setSeedList is a helper function that turns multiple DNS seed
2489
                // server tuples from the command line or config file into the
2490
                // data structure we need and does a basic formal sanity check
2491
                // in the process.
2492
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2493
                        if len(tuples) == 0 {
×
2494
                                return
×
2495
                        }
×
2496

2497
                        result := make([][2]string, len(tuples))
×
2498
                        for idx, tuple := range tuples {
×
2499
                                tuple = strings.TrimSpace(tuple)
×
2500
                                if len(tuple) == 0 {
×
2501
                                        return
×
2502
                                }
×
2503

2504
                                servers := strings.Split(tuple, ",")
×
2505
                                if len(servers) > 2 || len(servers) == 0 {
×
2506
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2507
                                                "seed tuple: %v", servers)
×
2508
                                        return
×
2509
                                }
×
2510

2511
                                copy(result[idx][:], servers)
×
2512
                        }
2513

2514
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2515
                }
2516

2517
                // Let users overwrite the DNS seed nodes. We only allow them
2518
                // for bitcoin mainnet/testnet/signet.
2519
                if s.cfg.Bitcoin.MainNet {
3✔
2520
                        setSeedList(
×
2521
                                s.cfg.Bitcoin.DNSSeeds,
×
2522
                                chainreg.BitcoinMainnetGenesis,
×
2523
                        )
×
2524
                }
×
2525
                if s.cfg.Bitcoin.TestNet3 {
3✔
2526
                        setSeedList(
×
2527
                                s.cfg.Bitcoin.DNSSeeds,
×
2528
                                chainreg.BitcoinTestnetGenesis,
×
2529
                        )
×
2530
                }
×
2531
                if s.cfg.Bitcoin.TestNet4 {
3✔
2532
                        setSeedList(
×
2533
                                s.cfg.Bitcoin.DNSSeeds,
×
2534
                                chainreg.BitcoinTestnet4Genesis,
×
2535
                        )
×
2536
                }
×
2537
                if s.cfg.Bitcoin.SigNet {
3✔
2538
                        setSeedList(
×
2539
                                s.cfg.Bitcoin.DNSSeeds,
×
2540
                                chainreg.BitcoinSignetGenesis,
×
2541
                        )
×
2542
                }
×
2543

2544
                // If network bootstrapping hasn't been disabled, then we'll
2545
                // configure the set of active bootstrappers, and launch a
2546
                // dedicated goroutine to maintain a set of persistent
2547
                // connections.
2548
                if !s.cfg.NoNetBootstrap {
6✔
2549
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2550
                        if err != nil {
3✔
2551
                                startErr = err
×
2552
                                return
×
2553
                        }
×
2554

2555
                        s.wg.Add(1)
3✔
2556
                        go s.peerBootstrapper(
3✔
2557
                                ctx, defaultMinPeers, bootstrappers,
3✔
2558
                        )
3✔
2559
                } else {
3✔
2560
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2561
                }
3✔
2562

2563
                // Start the blockbeat after all other subsystems have been
2564
                // started so they are ready to receive new blocks.
2565
                cleanup = cleanup.add(func() error {
3✔
2566
                        s.blockbeatDispatcher.Stop()
×
2567
                        return nil
×
2568
                })
×
2569
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2570
                        startErr = err
×
2571
                        return
×
2572
                }
×
2573

2574
                // Set the active flag now that we've completed the full
2575
                // startup.
2576
                atomic.StoreInt32(&s.active, 1)
3✔
2577
        })
2578

2579
        if startErr != nil {
3✔
2580
                cleanup.run()
×
2581
        }
×
2582
        return startErr
3✔
2583
}
2584

2585
// Stop gracefully shutsdown the main daemon server. This function will signal
2586
// any active goroutines, or helper objects to exit, then blocks until they've
2587
// all successfully exited. Additionally, any/all listeners are closed.
2588
// NOTE: This function is safe for concurrent access.
2589
func (s *server) Stop() error {
3✔
2590
        s.stop.Do(func() {
6✔
2591
                atomic.StoreInt32(&s.stopping, 1)
3✔
2592

3✔
2593
                ctx := context.Background()
3✔
2594

3✔
2595
                close(s.quit)
3✔
2596

3✔
2597
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2598
                s.connMgr.Stop()
3✔
2599

3✔
2600
                // Stop dispatching blocks to other systems immediately.
3✔
2601
                s.blockbeatDispatcher.Stop()
3✔
2602

3✔
2603
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2604
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2605
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2606
                }
×
2607
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2608
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2609
                }
×
2610
                if err := s.sphinx.Stop(); err != nil {
3✔
2611
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2612
                }
×
2613
                if err := s.invoices.Stop(); err != nil {
3✔
2614
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2615
                }
×
2616
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2617
                        srvrLog.Warnf("failed to stop interceptable "+
×
2618
                                "switch: %v", err)
×
2619
                }
×
2620
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2621
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2622
                                "modifier: %v", err)
×
2623
                }
×
2624
                if err := s.chanRouter.Stop(); err != nil {
3✔
2625
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2626
                }
×
2627
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2628
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2629
                }
×
2630
                if err := s.graphDB.Stop(); err != nil {
3✔
2631
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2632
                }
×
2633
                if err := s.chainArb.Stop(); err != nil {
3✔
2634
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2635
                }
×
2636
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2637
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2638
                }
×
2639
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2640
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2641
                                err)
×
2642
                }
×
2643
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2644
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2645
                }
×
2646
                if err := s.authGossiper.Stop(); err != nil {
3✔
2647
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2648
                }
×
2649
                if err := s.sweeper.Stop(); err != nil {
3✔
2650
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2651
                }
×
2652
                if err := s.txPublisher.Stop(); err != nil {
3✔
2653
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2654
                }
×
2655
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2656
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2657
                }
×
2658
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2659
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2660
                }
×
2661
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2662
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2663
                }
×
2664

2665
                // Update channel.backup file. Make sure to do it before
2666
                // stopping chanSubSwapper.
2667
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2668
                        ctx, s.chanStateDB, s.addrSource,
3✔
2669
                )
3✔
2670
                if err != nil {
3✔
2671
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2672
                                err)
×
2673
                } else {
3✔
2674
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2675
                        if err != nil {
6✔
2676
                                srvrLog.Warnf("Manual update of channel "+
3✔
2677
                                        "backup failed: %v", err)
3✔
2678
                        }
3✔
2679
                }
2680

2681
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2682
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2683
                }
×
2684
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2685
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2686
                }
×
2687
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2688
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2689
                                err)
×
2690
                }
×
2691
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2692
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2693
                                err)
×
2694
                }
×
2695
                s.missionController.StopStoreTickers()
3✔
2696

3✔
2697
                // Disconnect from each active peers to ensure that
3✔
2698
                // peerTerminationWatchers signal completion to each peer.
3✔
2699
                for _, peer := range s.Peers() {
6✔
2700
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2701
                        if err != nil {
3✔
2702
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2703
                                        "received error: %v", peer.IdentityKey(),
×
2704
                                        err,
×
2705
                                )
×
2706
                        }
×
2707
                }
2708

2709
                // Now that all connections have been torn down, stop the tower
2710
                // client which will reliably flush all queued states to the
2711
                // tower. If this is halted for any reason, the force quit timer
2712
                // will kick in and abort to allow this method to return.
2713
                if s.towerClientMgr != nil {
6✔
2714
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2715
                                srvrLog.Warnf("Unable to shut down tower "+
×
2716
                                        "client manager: %v", err)
×
2717
                        }
×
2718
                }
2719

2720
                if s.hostAnn != nil {
3✔
2721
                        if err := s.hostAnn.Stop(); err != nil {
×
2722
                                srvrLog.Warnf("unable to shut down host "+
×
2723
                                        "annoucner: %v", err)
×
2724
                        }
×
2725
                }
2726

2727
                if s.livenessMonitor != nil {
6✔
2728
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2729
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2730
                                        "monitor: %v", err)
×
2731
                        }
×
2732
                }
2733

2734
                // Wait for all lingering goroutines to quit.
2735
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2736
                s.wg.Wait()
3✔
2737

3✔
2738
                srvrLog.Debug("Stopping buffer pools...")
3✔
2739
                s.sigPool.Stop()
3✔
2740
                s.writePool.Stop()
3✔
2741
                s.readPool.Stop()
3✔
2742
        })
2743

2744
        return nil
3✔
2745
}
2746

2747
// Stopped returns true if the server has been instructed to shutdown.
2748
// NOTE: This function is safe for concurrent access.
2749
func (s *server) Stopped() bool {
3✔
2750
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2751
}
3✔
2752

2753
// configurePortForwarding attempts to set up port forwarding for the different
2754
// ports that the server will be listening on.
2755
//
2756
// NOTE: This should only be used when using some kind of NAT traversal to
2757
// automatically set up forwarding rules.
2758
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2759
        ip, err := s.natTraversal.ExternalIP()
×
2760
        if err != nil {
×
2761
                return nil, err
×
2762
        }
×
2763
        s.lastDetectedIP = ip
×
2764

×
2765
        externalIPs := make([]string, 0, len(ports))
×
2766
        for _, port := range ports {
×
2767
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2768
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2769
                        continue
×
2770
                }
2771

2772
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2773
                externalIPs = append(externalIPs, hostIP)
×
2774
        }
2775

2776
        return externalIPs, nil
×
2777
}
2778

2779
// removePortForwarding attempts to clear the forwarding rules for the different
2780
// ports the server is currently listening on.
2781
//
2782
// NOTE: This should only be used when using some kind of NAT traversal to
2783
// automatically set up forwarding rules.
2784
func (s *server) removePortForwarding() {
×
2785
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2786
        for _, port := range forwardedPorts {
×
2787
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2788
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2789
                                "port %d: %v", port, err)
×
2790
                }
×
2791
        }
2792
}
2793

2794
// watchExternalIP continuously checks for an updated external IP address every
2795
// 15 minutes. Once a new IP address has been detected, it will automatically
2796
// handle port forwarding rules and send updated node announcements to the
2797
// currently connected peers.
2798
//
2799
// NOTE: This MUST be run as a goroutine.
2800
func (s *server) watchExternalIP() {
×
2801
        defer s.wg.Done()
×
2802

×
2803
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2804
        // up by the server.
×
2805
        defer s.removePortForwarding()
×
2806

×
2807
        // Keep track of the external IPs set by the user to avoid replacing
×
2808
        // them when detecting a new IP.
×
2809
        ipsSetByUser := make(map[string]struct{})
×
2810
        for _, ip := range s.cfg.ExternalIPs {
×
2811
                ipsSetByUser[ip.String()] = struct{}{}
×
2812
        }
×
2813

2814
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2815

×
2816
        ticker := time.NewTicker(15 * time.Minute)
×
2817
        defer ticker.Stop()
×
2818
out:
×
2819
        for {
×
2820
                select {
×
2821
                case <-ticker.C:
×
2822
                        // We'll start off by making sure a new IP address has
×
2823
                        // been detected.
×
2824
                        ip, err := s.natTraversal.ExternalIP()
×
2825
                        if err != nil {
×
2826
                                srvrLog.Debugf("Unable to retrieve the "+
×
2827
                                        "external IP address: %v", err)
×
2828
                                continue
×
2829
                        }
2830

2831
                        // Periodically renew the NAT port forwarding.
2832
                        for _, port := range forwardedPorts {
×
2833
                                err := s.natTraversal.AddPortMapping(port)
×
2834
                                if err != nil {
×
2835
                                        srvrLog.Warnf("Unable to automatically "+
×
2836
                                                "re-create port forwarding using %s: %v",
×
2837
                                                s.natTraversal.Name(), err)
×
2838
                                } else {
×
2839
                                        srvrLog.Debugf("Automatically re-created "+
×
2840
                                                "forwarding for port %d using %s to "+
×
2841
                                                "advertise external IP",
×
2842
                                                port, s.natTraversal.Name())
×
2843
                                }
×
2844
                        }
2845

2846
                        if ip.Equal(s.lastDetectedIP) {
×
2847
                                continue
×
2848
                        }
2849

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

×
2852
                        // Next, we'll craft the new addresses that will be
×
2853
                        // included in the new node announcement and advertised
×
2854
                        // to the network. Each address will consist of the new
×
2855
                        // IP detected and one of the currently advertised
×
2856
                        // ports.
×
2857
                        var newAddrs []net.Addr
×
2858
                        for _, port := range forwardedPorts {
×
2859
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2860
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2861
                                if err != nil {
×
2862
                                        srvrLog.Debugf("Unable to resolve "+
×
2863
                                                "host %v: %v", addr, err)
×
2864
                                        continue
×
2865
                                }
2866

2867
                                newAddrs = append(newAddrs, addr)
×
2868
                        }
2869

2870
                        // Skip the update if we weren't able to resolve any of
2871
                        // the new addresses.
2872
                        if len(newAddrs) == 0 {
×
2873
                                srvrLog.Debug("Skipping node announcement " +
×
2874
                                        "update due to not being able to " +
×
2875
                                        "resolve any new addresses")
×
2876
                                continue
×
2877
                        }
2878

2879
                        // Now, we'll need to update the addresses in our node's
2880
                        // announcement in order to propagate the update
2881
                        // throughout the network. We'll only include addresses
2882
                        // that have a different IP from the previous one, as
2883
                        // the previous IP is no longer valid.
2884
                        currentNodeAnn := s.getNodeAnnouncement()
×
2885

×
2886
                        for _, addr := range currentNodeAnn.Addresses {
×
2887
                                host, _, err := net.SplitHostPort(addr.String())
×
2888
                                if err != nil {
×
2889
                                        srvrLog.Debugf("Unable to determine "+
×
2890
                                                "host from address %v: %v",
×
2891
                                                addr, err)
×
2892
                                        continue
×
2893
                                }
2894

2895
                                // We'll also make sure to include external IPs
2896
                                // set manually by the user.
2897
                                _, setByUser := ipsSetByUser[addr.String()]
×
2898
                                if setByUser || host != s.lastDetectedIP.String() {
×
2899
                                        newAddrs = append(newAddrs, addr)
×
2900
                                }
×
2901
                        }
2902

2903
                        // Then, we'll generate a new timestamped node
2904
                        // announcement with the updated addresses and broadcast
2905
                        // it to our peers.
2906
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2907
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2908
                        )
×
2909
                        if err != nil {
×
2910
                                srvrLog.Debugf("Unable to generate new node "+
×
2911
                                        "announcement: %v", err)
×
2912
                                continue
×
2913
                        }
2914

2915
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2916
                        if err != nil {
×
2917
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2918
                                        "announcement to peers: %v", err)
×
2919
                                continue
×
2920
                        }
2921

2922
                        // Finally, update the last IP seen to the current one.
2923
                        s.lastDetectedIP = ip
×
2924
                case <-s.quit:
×
2925
                        break out
×
2926
                }
2927
        }
2928
}
2929

2930
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2931
// based on the server, and currently active bootstrap mechanisms as defined
2932
// within the current configuration.
2933
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2934
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2935

3✔
2936
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2937

3✔
2938
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2939
        // this can be used by default if we've already partially seeded the
3✔
2940
        // network.
3✔
2941
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2942
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2943
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2944
        )
3✔
2945
        if err != nil {
3✔
2946
                return nil, err
×
2947
        }
×
2948
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2949

3✔
2950
        // If this isn't using simnet or regtest mode, then one of our
3✔
2951
        // additional bootstrapping sources will be the set of running DNS
3✔
2952
        // seeds.
3✔
2953
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2954
                //nolint:ll
×
2955
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2956

×
2957
                // If we have a set of DNS seeds for this chain, then we'll add
×
2958
                // it as an additional bootstrapping source.
×
2959
                if ok {
×
2960
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2961
                                "seeds: %v", dnsSeeds)
×
2962

×
2963
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2964
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2965
                        )
×
2966
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2967
                }
×
2968
        }
2969

2970
        return bootStrappers, nil
3✔
2971
}
2972

2973
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2974
// needs to ignore, which is made of three parts,
2975
//   - the node itself needs to be skipped as it doesn't make sense to connect
2976
//     to itself.
2977
//   - the peers that already have connections with, as in s.peersByPub.
2978
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2979
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
2980
        s.mu.RLock()
3✔
2981
        defer s.mu.RUnlock()
3✔
2982

3✔
2983
        ignore := make(map[autopilot.NodeID]struct{})
3✔
2984

3✔
2985
        // We should ignore ourselves from bootstrapping.
3✔
2986
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
2987
        ignore[selfKey] = struct{}{}
3✔
2988

3✔
2989
        // Ignore all connected peers.
3✔
2990
        for _, peer := range s.peersByPub {
3✔
2991
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2992
                ignore[nID] = struct{}{}
×
2993
        }
×
2994

2995
        // Ignore all persistent peers as they have a dedicated reconnecting
2996
        // process.
2997
        for pubKeyStr := range s.persistentPeers {
3✔
2998
                var nID autopilot.NodeID
×
2999
                copy(nID[:], []byte(pubKeyStr))
×
3000
                ignore[nID] = struct{}{}
×
3001
        }
×
3002

3003
        return ignore
3✔
3004
}
3005

3006
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3007
// and maintain a target minimum number of outbound connections. With this
3008
// invariant, we ensure that our node is connected to a diverse set of peers
3009
// and that nodes newly joining the network receive an up to date network view
3010
// as soon as possible.
3011
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3012
        bootstrappers []discovery.NetworkPeerBootstrapper) {
3✔
3013

3✔
3014
        defer s.wg.Done()
3✔
3015

3✔
3016
        // Before we continue, init the ignore peers map.
3✔
3017
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3018

3✔
3019
        // We'll start off by aggressively attempting connections to peers in
3✔
3020
        // order to be a part of the network as soon as possible.
3✔
3021
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
3✔
3022

3✔
3023
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3024
        // peers.
3✔
3025
        //
3✔
3026
        // We'll use a 15 second backoff, and double the time every time an
3✔
3027
        // epoch fails up to a ceiling.
3✔
3028
        backOff := time.Second * 15
3✔
3029

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

3✔
3035
        // We'll use the number of attempts and errors to determine if we need
3✔
3036
        // to increase the time between discovery epochs.
3✔
3037
        var epochErrors uint32 // To be used atomically.
3✔
3038
        var epochAttempts uint32
3✔
3039

3✔
3040
        for {
6✔
3041
                select {
3✔
3042
                // The ticker has just woken us up, so we'll need to check if
3043
                // we need to attempt to connect our to any more peers.
3044
                case <-sampleTicker.C:
×
3045
                        // Obtain the current number of peers, so we can gauge
×
3046
                        // if we need to sample more peers or not.
×
3047
                        s.mu.RLock()
×
3048
                        numActivePeers := uint32(len(s.peersByPub))
×
3049
                        s.mu.RUnlock()
×
3050

×
3051
                        // If we have enough peers, then we can loop back
×
3052
                        // around to the next round as we're done here.
×
3053
                        if numActivePeers >= numTargetPeers {
×
3054
                                continue
×
3055
                        }
3056

3057
                        // If all of our attempts failed during this last back
3058
                        // off period, then will increase our backoff to 5
3059
                        // minute ceiling to avoid an excessive number of
3060
                        // queries
3061
                        //
3062
                        // TODO(roasbeef): add reverse policy too?
3063

3064
                        if epochAttempts > 0 &&
×
3065
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3066

×
3067
                                sampleTicker.Stop()
×
3068

×
3069
                                backOff *= 2
×
3070
                                if backOff > bootstrapBackOffCeiling {
×
3071
                                        backOff = bootstrapBackOffCeiling
×
3072
                                }
×
3073

3074
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3075
                                        "%v", backOff)
×
3076
                                sampleTicker = time.NewTicker(backOff)
×
3077
                                continue
×
3078
                        }
3079

3080
                        atomic.StoreUint32(&epochErrors, 0)
×
3081
                        epochAttempts = 0
×
3082

×
3083
                        // Since we know need more peers, we'll compute the
×
3084
                        // exact number we need to reach our threshold.
×
3085
                        numNeeded := numTargetPeers - numActivePeers
×
3086

×
3087
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3088
                                "peers", numNeeded)
×
3089

×
3090
                        // With the number of peers we need calculated, we'll
×
3091
                        // query the network bootstrappers to sample a set of
×
3092
                        // random addrs for us.
×
3093
                        //
×
3094
                        // Before we continue, get a copy of the ignore peers
×
3095
                        // map.
×
3096
                        ignoreList = s.createBootstrapIgnorePeers()
×
3097

×
3098
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3099
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3100
                        )
×
3101
                        if err != nil {
×
3102
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3103
                                        "peers: %v", err)
×
3104
                                continue
×
3105
                        }
3106

3107
                        // Finally, we'll launch a new goroutine for each
3108
                        // prospective peer candidates.
3109
                        for _, addr := range peerAddrs {
×
3110
                                epochAttempts++
×
3111

×
3112
                                go func(a *lnwire.NetAddress) {
×
3113
                                        // TODO(roasbeef): can do AS, subnet,
×
3114
                                        // country diversity, etc
×
3115
                                        errChan := make(chan error, 1)
×
3116
                                        s.connectToPeer(
×
3117
                                                a, errChan,
×
3118
                                                s.cfg.ConnectionTimeout,
×
3119
                                        )
×
3120
                                        select {
×
3121
                                        case err := <-errChan:
×
3122
                                                if err == nil {
×
3123
                                                        return
×
3124
                                                }
×
3125

3126
                                                srvrLog.Errorf("Unable to "+
×
3127
                                                        "connect to %v: %v",
×
3128
                                                        a, err)
×
3129
                                                atomic.AddUint32(&epochErrors, 1)
×
3130
                                        case <-s.quit:
×
3131
                                        }
3132
                                }(addr)
3133
                        }
3134
                case <-s.quit:
3✔
3135
                        return
3✔
3136
                }
3137
        }
3138
}
3139

3140
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3141
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3142
// query back off each time we encounter a failure.
3143
const bootstrapBackOffCeiling = time.Minute * 5
3144

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

3✔
3152
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3153
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3154

3✔
3155
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3156
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3157
        var delaySignal <-chan time.Time
3✔
3158
        delayTime := time.Second * 2
3✔
3159

3✔
3160
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3161
        // then the main peer bootstrap logic.
3✔
3162
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3163

3✔
3164
        for attempts := 0; ; attempts++ {
6✔
3165
                // Check if the server has been requested to shut down in order
3✔
3166
                // to prevent blocking.
3✔
3167
                if s.Stopped() {
3✔
3168
                        return
×
3169
                }
×
3170

3171
                // We can exit our aggressive initial peer bootstrapping stage
3172
                // if we've reached out target number of peers.
3173
                s.mu.RLock()
3✔
3174
                numActivePeers := uint32(len(s.peersByPub))
3✔
3175
                s.mu.RUnlock()
3✔
3176

3✔
3177
                if numActivePeers >= numTargetPeers {
6✔
3178
                        return
3✔
3179
                }
3✔
3180

3181
                if attempts > 0 {
3✔
UNCOV
3182
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3183
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3184
                                attempts)
×
UNCOV
3185

×
UNCOV
3186
                        // We've completed at least one iterating and haven't
×
UNCOV
3187
                        // finished, so we'll start to insert a delay period
×
UNCOV
3188
                        // between each attempt.
×
UNCOV
3189
                        delaySignal = time.After(delayTime)
×
UNCOV
3190
                        select {
×
UNCOV
3191
                        case <-delaySignal:
×
UNCOV
3192
                        case <-s.quit:
×
UNCOV
3193
                                return
×
3194
                        }
3195

3196
                        // After our delay, we'll double the time we wait up to
3197
                        // the max back off period.
UNCOV
3198
                        delayTime *= 2
×
UNCOV
3199
                        if delayTime > backOffCeiling {
×
3200
                                delayTime = backOffCeiling
×
3201
                        }
×
3202
                }
3203

3204
                // Otherwise, we'll request for the remaining number of peers
3205
                // in order to reach our target.
3206
                peersNeeded := numTargetPeers - numActivePeers
3✔
3207
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3208
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3209
                )
3✔
3210
                if err != nil {
3✔
UNCOV
3211
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3212
                                "peers: %v", err)
×
UNCOV
3213
                        continue
×
3214
                }
3215

3216
                // Then, we'll attempt to establish a connection to the
3217
                // different peer addresses retrieved by our bootstrappers.
3218
                var wg sync.WaitGroup
3✔
3219
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3220
                        wg.Add(1)
3✔
3221
                        go func(addr *lnwire.NetAddress) {
6✔
3222
                                defer wg.Done()
3✔
3223

3✔
3224
                                errChan := make(chan error, 1)
3✔
3225
                                go s.connectToPeer(
3✔
3226
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3227
                                )
3✔
3228

3✔
3229
                                // We'll only allow this connection attempt to
3✔
3230
                                // take up to 3 seconds. This allows us to move
3✔
3231
                                // quickly by discarding peers that are slowing
3✔
3232
                                // us down.
3✔
3233
                                select {
3✔
3234
                                case err := <-errChan:
3✔
3235
                                        if err == nil {
6✔
3236
                                                return
3✔
3237
                                        }
3✔
3238
                                        srvrLog.Errorf("Unable to connect to "+
×
3239
                                                "%v: %v", addr, err)
×
3240
                                // TODO: tune timeout? 3 seconds might be *too*
3241
                                // aggressive but works well.
3242
                                case <-time.After(3 * time.Second):
×
3243
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3244
                                                "to not establishing a "+
×
3245
                                                "connection within 3 seconds",
×
3246
                                                addr)
×
3247
                                case <-s.quit:
×
3248
                                }
3249
                        }(bootstrapAddr)
3250
                }
3251

3252
                wg.Wait()
3✔
3253
        }
3254
}
3255

3256
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3257
// order to listen for inbound connections over Tor.
3258
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3259
        // Determine the different ports the server is listening on. The onion
×
3260
        // service's virtual port will map to these ports and one will be picked
×
3261
        // at random when the onion service is being accessed.
×
3262
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3263
        for _, listenAddr := range s.listenAddrs {
×
3264
                port := listenAddr.(*net.TCPAddr).Port
×
3265
                listenPorts = append(listenPorts, port)
×
3266
        }
×
3267

3268
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3269
        if err != nil {
×
3270
                return err
×
3271
        }
×
3272

3273
        // Once the port mapping has been set, we can go ahead and automatically
3274
        // create our onion service. The service's private key will be saved to
3275
        // disk in order to regain access to this service when restarting `lnd`.
3276
        onionCfg := tor.AddOnionConfig{
×
3277
                VirtualPort: defaultPeerPort,
×
3278
                TargetPorts: listenPorts,
×
3279
                Store: tor.NewOnionFile(
×
3280
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3281
                        encrypter,
×
3282
                ),
×
3283
        }
×
3284

×
3285
        switch {
×
3286
        case s.cfg.Tor.V2:
×
3287
                onionCfg.Type = tor.V2
×
3288
        case s.cfg.Tor.V3:
×
3289
                onionCfg.Type = tor.V3
×
3290
        }
3291

3292
        addr, err := s.torController.AddOnion(onionCfg)
×
3293
        if err != nil {
×
3294
                return err
×
3295
        }
×
3296

3297
        // Now that the onion service has been created, we'll add the onion
3298
        // address it can be reached at to our list of advertised addresses.
3299
        newNodeAnn, err := s.genNodeAnnouncement(
×
3300
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3301
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3302
                },
×
3303
        )
3304
        if err != nil {
×
3305
                return fmt.Errorf("unable to generate new node "+
×
3306
                        "announcement: %v", err)
×
3307
        }
×
3308

3309
        // Finally, we'll update the on-disk version of our announcement so it
3310
        // will eventually propagate to nodes in the network.
3311
        selfNode := &models.LightningNode{
×
3312
                HaveNodeAnnouncement: true,
×
3313
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3314
                Addresses:            newNodeAnn.Addresses,
×
3315
                Alias:                newNodeAnn.Alias.String(),
×
3316
                Features: lnwire.NewFeatureVector(
×
3317
                        newNodeAnn.Features, lnwire.Features,
×
3318
                ),
×
3319
                Color:        newNodeAnn.RGBColor,
×
3320
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3321
        }
×
3322
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3323
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3324
                return fmt.Errorf("can't set self node: %w", err)
×
3325
        }
×
3326

3327
        return nil
×
3328
}
3329

3330
// findChannel finds a channel given a public key and ChannelID. It is an
3331
// optimization that is quicker than seeking for a channel given only the
3332
// ChannelID.
3333
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3334
        *channeldb.OpenChannel, error) {
3✔
3335

3✔
3336
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3337
        if err != nil {
3✔
3338
                return nil, err
×
3339
        }
×
3340

3341
        for _, channel := range nodeChans {
6✔
3342
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3343
                        return channel, nil
3✔
3344
                }
3✔
3345
        }
3346

3347
        return nil, fmt.Errorf("unable to find channel")
3✔
3348
}
3349

3350
// getNodeAnnouncement fetches the current, fully signed node announcement.
3351
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3352
        s.mu.Lock()
3✔
3353
        defer s.mu.Unlock()
3✔
3354

3✔
3355
        return *s.currentNodeAnn
3✔
3356
}
3✔
3357

3358
// genNodeAnnouncement generates and returns the current fully signed node
3359
// announcement. The time stamp of the announcement will be updated in order
3360
// to ensure it propagates through the network.
3361
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3362
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3363

3✔
3364
        s.mu.Lock()
3✔
3365
        defer s.mu.Unlock()
3✔
3366

3✔
3367
        // Create a shallow copy of the current node announcement to work on.
3✔
3368
        // This ensures the original announcement remains unchanged
3✔
3369
        // until the new announcement is fully signed and valid.
3✔
3370
        newNodeAnn := *s.currentNodeAnn
3✔
3371

3✔
3372
        // First, try to update our feature manager with the updated set of
3✔
3373
        // features.
3✔
3374
        if features != nil {
6✔
3375
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3376
                        feature.SetNodeAnn: features,
3✔
3377
                }
3✔
3378
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3379
                if err != nil {
6✔
3380
                        return lnwire.NodeAnnouncement{}, err
3✔
3381
                }
3✔
3382

3383
                // If we could successfully update our feature manager, add
3384
                // an update modifier to include these new features to our
3385
                // set.
3386
                modifiers = append(
3✔
3387
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3388
                )
3✔
3389
        }
3390

3391
        // Always update the timestamp when refreshing to ensure the update
3392
        // propagates.
3393
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3394

3✔
3395
        // Apply the requested changes to the node announcement.
3✔
3396
        for _, modifier := range modifiers {
6✔
3397
                modifier(&newNodeAnn)
3✔
3398
        }
3✔
3399

3400
        // Sign a new update after applying all of the passed modifiers.
3401
        err := netann.SignNodeAnnouncement(
3✔
3402
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3403
        )
3✔
3404
        if err != nil {
3✔
3405
                return lnwire.NodeAnnouncement{}, err
×
3406
        }
×
3407

3408
        // If signing succeeds, update the current announcement.
3409
        *s.currentNodeAnn = newNodeAnn
3✔
3410

3✔
3411
        return *s.currentNodeAnn, nil
3✔
3412
}
3413

3414
// updateAndBroadcastSelfNode generates a new node announcement
3415
// applying the giving modifiers and updating the time stamp
3416
// to ensure it propagates through the network. Then it broadcasts
3417
// it to the network.
3418
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3419
        features *lnwire.RawFeatureVector,
3420
        modifiers ...netann.NodeAnnModifier) error {
3✔
3421

3✔
3422
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3423
        if err != nil {
6✔
3424
                return fmt.Errorf("unable to generate new node "+
3✔
3425
                        "announcement: %v", err)
3✔
3426
        }
3✔
3427

3428
        // Update the on-disk version of our announcement.
3429
        // Load and modify self node istead of creating anew instance so we
3430
        // don't risk overwriting any existing values.
3431
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3432
        if err != nil {
3✔
3433
                return fmt.Errorf("unable to get current source node: %w", err)
×
3434
        }
×
3435

3436
        selfNode.HaveNodeAnnouncement = true
3✔
3437
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3438
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3439
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3440
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3441
        selfNode.Color = newNodeAnn.RGBColor
3✔
3442
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3443

3✔
3444
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
3445

3✔
3446
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
3447
                return fmt.Errorf("can't set self node: %w", err)
×
3448
        }
×
3449

3450
        // Finally, propagate it to the nodes in the network.
3451
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3452
        if err != nil {
3✔
3453
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3454
                        "announcement to peers: %v", err)
×
3455
                return err
×
3456
        }
×
3457

3458
        return nil
3✔
3459
}
3460

3461
type nodeAddresses struct {
3462
        pubKey    *btcec.PublicKey
3463
        addresses []net.Addr
3464
}
3465

3466
// establishPersistentConnections attempts to establish persistent connections
3467
// to all our direct channel collaborators. In order to promote liveness of our
3468
// active channels, we instruct the connection manager to attempt to establish
3469
// and maintain persistent connections to all our direct channel counterparties.
3470
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3471
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3472
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3473
        // since other PubKey forms can't be compared.
3✔
3474
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3475

3✔
3476
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3477
        // attempt to connect to based on our set of previous connections. Set
3✔
3478
        // the reconnection port to the default peer port.
3✔
3479
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3480
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3481
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3482
        }
×
3483

3484
        for _, node := range linkNodes {
6✔
3485
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3486
                nodeAddrs := &nodeAddresses{
3✔
3487
                        pubKey:    node.IdentityPub,
3✔
3488
                        addresses: node.Addresses,
3✔
3489
                }
3✔
3490
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3491
        }
3✔
3492

3493
        // After checking our previous connections for addresses to connect to,
3494
        // iterate through the nodes in our channel graph to find addresses
3495
        // that have been added via NodeAnnouncement messages.
3496
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3497
        // each of the nodes.
3498
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3499
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3500
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3501

3✔
3502
                // If the remote party has announced the channel to us, but we
3✔
3503
                // haven't yet, then we won't have a policy. However, we don't
3✔
3504
                // need this to connect to the peer, so we'll log it and move on.
3✔
3505
                if !havePolicy {
3✔
3506
                        srvrLog.Warnf("No channel policy found for "+
×
3507
                                "ChannelPoint(%v): ", chanPoint)
×
3508
                }
×
3509

3510
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3511

3✔
3512
                // Add all unique addresses from channel
3✔
3513
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3514
                // connect to for this peer.
3✔
3515
                addrSet := make(map[string]net.Addr)
3✔
3516
                for _, addr := range channelPeer.Addresses {
6✔
3517
                        switch addr.(type) {
3✔
3518
                        case *net.TCPAddr:
3✔
3519
                                addrSet[addr.String()] = addr
3✔
3520

3521
                        // We'll only attempt to connect to Tor addresses if Tor
3522
                        // outbound support is enabled.
3523
                        case *tor.OnionAddr:
×
3524
                                if s.cfg.Tor.Active {
×
3525
                                        addrSet[addr.String()] = addr
×
3526
                                }
×
3527
                        }
3528
                }
3529

3530
                // If this peer is also recorded as a link node, we'll add any
3531
                // additional addresses that have not already been selected.
3532
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3533
                if ok {
6✔
3534
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3535
                                switch lnAddress.(type) {
3✔
3536
                                case *net.TCPAddr:
3✔
3537
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3538

3539
                                // We'll only attempt to connect to Tor
3540
                                // addresses if Tor outbound support is enabled.
3541
                                case *tor.OnionAddr:
×
3542
                                        if s.cfg.Tor.Active {
×
3543
                                                //nolint:ll
×
3544
                                                addrSet[lnAddress.String()] = lnAddress
×
3545
                                        }
×
3546
                                }
3547
                        }
3548
                }
3549

3550
                // Construct a slice of the deduped addresses.
3551
                var addrs []net.Addr
3✔
3552
                for _, addr := range addrSet {
6✔
3553
                        addrs = append(addrs, addr)
3✔
3554
                }
3✔
3555

3556
                n := &nodeAddresses{
3✔
3557
                        addresses: addrs,
3✔
3558
                }
3✔
3559
                n.pubKey, err = channelPeer.PubKey()
3✔
3560
                if err != nil {
3✔
3561
                        return err
×
3562
                }
×
3563

3564
                graphAddrs[pubStr] = n
3✔
3565
                return nil
3✔
3566
        }
3567
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3568
                ctx, forEachSrcNodeChan, func() {
6✔
3569
                        clear(graphAddrs)
3✔
3570
                },
3✔
3571
        )
3572
        if err != nil {
3✔
3573
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3574
                        "%v", err)
×
3575

×
3576
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3577
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3578

×
3579
                        return err
×
3580
                }
×
3581
        }
3582

3583
        // Combine the addresses from the link nodes and the channel graph.
3584
        for pubStr, nodeAddr := range graphAddrs {
6✔
3585
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3586
        }
3✔
3587

3588
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3589
                len(nodeAddrsMap))
3✔
3590

3✔
3591
        // Acquire and hold server lock until all persistent connection requests
3✔
3592
        // have been recorded and sent to the connection manager.
3✔
3593
        s.mu.Lock()
3✔
3594
        defer s.mu.Unlock()
3✔
3595

3✔
3596
        // Iterate through the combined list of addresses from prior links and
3✔
3597
        // node announcements and attempt to reconnect to each node.
3✔
3598
        var numOutboundConns int
3✔
3599
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3600
                // Add this peer to the set of peers we should maintain a
3✔
3601
                // persistent connection with. We set the value to false to
3✔
3602
                // indicate that we should not continue to reconnect if the
3✔
3603
                // number of channels returns to zero, since this peer has not
3✔
3604
                // been requested as perm by the user.
3✔
3605
                s.persistentPeers[pubStr] = false
3✔
3606
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3607
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3608
                }
3✔
3609

3610
                for _, address := range nodeAddr.addresses {
6✔
3611
                        // Create a wrapper address which couples the IP and
3✔
3612
                        // the pubkey so the brontide authenticated connection
3✔
3613
                        // can be established.
3✔
3614
                        lnAddr := &lnwire.NetAddress{
3✔
3615
                                IdentityKey: nodeAddr.pubKey,
3✔
3616
                                Address:     address,
3✔
3617
                        }
3✔
3618

3✔
3619
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3620
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3621
                }
3✔
3622

3623
                // We'll connect to the first 10 peers immediately, then
3624
                // randomly stagger any remaining connections if the
3625
                // stagger initial reconnect flag is set. This ensures
3626
                // that mobile nodes or nodes with a small number of
3627
                // channels obtain connectivity quickly, but larger
3628
                // nodes are able to disperse the costs of connecting to
3629
                // all peers at once.
3630
                if numOutboundConns < numInstantInitReconnect ||
3✔
3631
                        !s.cfg.StaggerInitialReconnect {
6✔
3632

3✔
3633
                        go s.connectToPersistentPeer(pubStr)
3✔
3634
                } else {
3✔
3635
                        go s.delayInitialReconnect(pubStr)
×
3636
                }
×
3637

3638
                numOutboundConns++
3✔
3639
        }
3640

3641
        return nil
3✔
3642
}
3643

3644
// delayInitialReconnect will attempt a reconnection to the given peer after
3645
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3646
//
3647
// NOTE: This method MUST be run as a goroutine.
3648
func (s *server) delayInitialReconnect(pubStr string) {
×
3649
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3650
        select {
×
3651
        case <-time.After(delay):
×
3652
                s.connectToPersistentPeer(pubStr)
×
3653
        case <-s.quit:
×
3654
        }
3655
}
3656

3657
// prunePersistentPeerConnection removes all internal state related to
3658
// persistent connections to a peer within the server. This is used to avoid
3659
// persistent connection retries to peers we do not have any open channels with.
3660
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
3✔
3661
        pubKeyStr := string(compressedPubKey[:])
3✔
3662

3✔
3663
        s.mu.Lock()
3✔
3664
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3665
                delete(s.persistentPeers, pubKeyStr)
3✔
3666
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3667
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3668
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3669
                s.mu.Unlock()
3✔
3670

3✔
3671
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3672
                        "peer has no open channels", compressedPubKey)
3✔
3673

3✔
3674
                return
3✔
3675
        }
3✔
3676
        s.mu.Unlock()
3✔
3677
}
3678

3679
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3680
// is instead used to remove persistent peer state for a peer that has been
3681
// disconnected for good cause by the server. Currently, a gossip ban from
3682
// sending garbage and the server running out of restricted-access
3683
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3684
// future, this function may expand when more ban criteria is added.
3685
//
3686
// NOTE: The server's write lock MUST be held when this is called.
3687
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3688
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3689
                delete(s.persistentPeers, remotePub)
×
3690
                delete(s.persistentPeersBackoff, remotePub)
×
3691
                delete(s.persistentPeerAddrs, remotePub)
×
3692
                s.cancelConnReqs(remotePub, nil)
×
3693
        }
×
3694
}
3695

3696
// BroadcastMessage sends a request to the server to broadcast a set of
3697
// messages to all peers other than the one specified by the `skips` parameter.
3698
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3699
// the target peers.
3700
//
3701
// NOTE: This function is safe for concurrent access.
3702
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3703
        msgs ...lnwire.Message) error {
3✔
3704

3✔
3705
        // Filter out peers found in the skips map. We synchronize access to
3✔
3706
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3707
        // exact set of peers present at the time of invocation.
3✔
3708
        s.mu.RLock()
3✔
3709
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3710
        for pubStr, sPeer := range s.peersByPub {
6✔
3711
                if skips != nil {
6✔
3712
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3713
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3714
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3715
                                continue
3✔
3716
                        }
3717
                }
3718

3719
                peers = append(peers, sPeer)
3✔
3720
        }
3721
        s.mu.RUnlock()
3✔
3722

3✔
3723
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3724
        // all messages to each of peers.
3✔
3725
        var wg sync.WaitGroup
3✔
3726
        for _, sPeer := range peers {
6✔
3727
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3728
                        sPeer.PubKey())
3✔
3729

3✔
3730
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3731
                wg.Add(1)
3✔
3732
                s.wg.Add(1)
3✔
3733
                go func(p lnpeer.Peer) {
6✔
3734
                        defer s.wg.Done()
3✔
3735
                        defer wg.Done()
3✔
3736

3✔
3737
                        p.SendMessageLazy(false, msgs...)
3✔
3738
                }(sPeer)
3✔
3739
        }
3740

3741
        // Wait for all messages to have been dispatched before returning to
3742
        // caller.
3743
        wg.Wait()
3✔
3744

3✔
3745
        return nil
3✔
3746
}
3747

3748
// NotifyWhenOnline can be called by other subsystems to get notified when a
3749
// particular peer comes online. The peer itself is sent across the peerChan.
3750
//
3751
// NOTE: This function is safe for concurrent access.
3752
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3753
        peerChan chan<- lnpeer.Peer) {
3✔
3754

3✔
3755
        s.mu.Lock()
3✔
3756

3✔
3757
        // Compute the target peer's identifier.
3✔
3758
        pubStr := string(peerKey[:])
3✔
3759

3✔
3760
        // Check if peer is connected.
3✔
3761
        peer, ok := s.peersByPub[pubStr]
3✔
3762
        if ok {
6✔
3763
                // Unlock here so that the mutex isn't held while we are
3✔
3764
                // waiting for the peer to become active.
3✔
3765
                s.mu.Unlock()
3✔
3766

3✔
3767
                // Wait until the peer signals that it is actually active
3✔
3768
                // rather than only in the server's maps.
3✔
3769
                select {
3✔
3770
                case <-peer.ActiveSignal():
3✔
UNCOV
3771
                case <-peer.QuitSignal():
×
UNCOV
3772
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3773
                        // and return.
×
UNCOV
3774
                        s.mu.Lock()
×
UNCOV
3775
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3776
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3777
                        )
×
UNCOV
3778
                        s.mu.Unlock()
×
UNCOV
3779
                        return
×
3780
                }
3781

3782
                // Connected, can return early.
3783
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3784

3✔
3785
                select {
3✔
3786
                case peerChan <- peer:
3✔
3787
                case <-s.quit:
×
3788
                }
3789

3790
                return
3✔
3791
        }
3792

3793
        // Not connected, store this listener such that it can be notified when
3794
        // the peer comes online.
3795
        s.peerConnectedListeners[pubStr] = append(
3✔
3796
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3797
        )
3✔
3798
        s.mu.Unlock()
3✔
3799
}
3800

3801
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3802
// the given public key has been disconnected. The notification is signaled by
3803
// closing the channel returned.
3804
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3805
        s.mu.Lock()
3✔
3806
        defer s.mu.Unlock()
3✔
3807

3✔
3808
        c := make(chan struct{})
3✔
3809

3✔
3810
        // If the peer is already offline, we can immediately trigger the
3✔
3811
        // notification.
3✔
3812
        peerPubKeyStr := string(peerPubKey[:])
3✔
3813
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3814
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3815
                close(c)
×
3816
                return c
×
3817
        }
×
3818

3819
        // Otherwise, the peer is online, so we'll keep track of the channel to
3820
        // trigger the notification once the server detects the peer
3821
        // disconnects.
3822
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3823
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3824
        )
3✔
3825

3✔
3826
        return c
3✔
3827
}
3828

3829
// FindPeer will return the peer that corresponds to the passed in public key.
3830
// This function is used by the funding manager, allowing it to update the
3831
// daemon's local representation of the remote peer.
3832
//
3833
// NOTE: This function is safe for concurrent access.
3834
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3835
        s.mu.RLock()
3✔
3836
        defer s.mu.RUnlock()
3✔
3837

3✔
3838
        pubStr := string(peerKey.SerializeCompressed())
3✔
3839

3✔
3840
        return s.findPeerByPubStr(pubStr)
3✔
3841
}
3✔
3842

3843
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3844
// which should be a string representation of the peer's serialized, compressed
3845
// public key.
3846
//
3847
// NOTE: This function is safe for concurrent access.
3848
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3849
        s.mu.RLock()
3✔
3850
        defer s.mu.RUnlock()
3✔
3851

3✔
3852
        return s.findPeerByPubStr(pubStr)
3✔
3853
}
3✔
3854

3855
// findPeerByPubStr is an internal method that retrieves the specified peer from
3856
// the server's internal state using.
3857
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3858
        peer, ok := s.peersByPub[pubStr]
3✔
3859
        if !ok {
6✔
3860
                return nil, ErrPeerNotConnected
3✔
3861
        }
3✔
3862

3863
        return peer, nil
3✔
3864
}
3865

3866
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3867
// exponential backoff. If no previous backoff was known, the default is
3868
// returned.
3869
func (s *server) nextPeerBackoff(pubStr string,
3870
        startTime time.Time) time.Duration {
3✔
3871

3✔
3872
        // Now, determine the appropriate backoff to use for the retry.
3✔
3873
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3874
        if !ok {
6✔
3875
                // If an existing backoff was unknown, use the default.
3✔
3876
                return s.cfg.MinBackoff
3✔
3877
        }
3✔
3878

3879
        // If the peer failed to start properly, we'll just use the previous
3880
        // backoff to compute the subsequent randomized exponential backoff
3881
        // duration. This will roughly double on average.
3882
        if startTime.IsZero() {
3✔
3883
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3884
        }
×
3885

3886
        // The peer succeeded in starting. If the connection didn't last long
3887
        // enough to be considered stable, we'll continue to back off retries
3888
        // with this peer.
3889
        connDuration := time.Since(startTime)
3✔
3890
        if connDuration < defaultStableConnDuration {
6✔
3891
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3892
        }
3✔
3893

3894
        // The peer succeed in starting and this was stable peer, so we'll
3895
        // reduce the timeout duration by the length of the connection after
3896
        // applying randomized exponential backoff. We'll only apply this in the
3897
        // case that:
3898
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3899
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3900
        if relaxedBackoff > s.cfg.MinBackoff {
×
3901
                return relaxedBackoff
×
3902
        }
×
3903

3904
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3905
        // the stable connection lasted much longer than our previous backoff.
3906
        // To reward such good behavior, we'll reconnect after the default
3907
        // timeout.
3908
        return s.cfg.MinBackoff
×
3909
}
3910

3911
// shouldDropLocalConnection determines if our local connection to a remote peer
3912
// should be dropped in the case of concurrent connection establishment. In
3913
// order to deterministically decide which connection should be dropped, we'll
3914
// utilize the ordering of the local and remote public key. If we didn't use
3915
// such a tie breaker, then we risk _both_ connections erroneously being
3916
// dropped.
3917
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3918
        localPubBytes := local.SerializeCompressed()
×
3919
        remotePubPbytes := remote.SerializeCompressed()
×
3920

×
3921
        // The connection that comes from the node with a "smaller" pubkey
×
3922
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3923
        // should drop our established connection.
×
3924
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3925
}
×
3926

3927
// InboundPeerConnected initializes a new peer in response to a new inbound
3928
// connection.
3929
//
3930
// NOTE: This function is safe for concurrent access.
3931
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3932
        // Exit early if we have already been instructed to shutdown, this
3✔
3933
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3934
        if s.Stopped() {
3✔
3935
                return
×
3936
        }
×
3937

3938
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3939
        pubSer := nodePub.SerializeCompressed()
3✔
3940
        pubStr := string(pubSer)
3✔
3941

3✔
3942
        var pubBytes [33]byte
3✔
3943
        copy(pubBytes[:], pubSer)
3✔
3944

3✔
3945
        s.mu.Lock()
3✔
3946
        defer s.mu.Unlock()
3✔
3947

3✔
3948
        // If we already have an outbound connection to this peer, then ignore
3✔
3949
        // this new connection.
3✔
3950
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3951
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3952
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3953
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3954

3✔
3955
                conn.Close()
3✔
3956
                return
3✔
3957
        }
3✔
3958

3959
        // If we already have a valid connection that is scheduled to take
3960
        // precedence once the prior peer has finished disconnecting, we'll
3961
        // ignore this connection.
3962
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3963
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3964
                        "scheduled", conn.RemoteAddr(), p)
×
3965
                conn.Close()
×
3966
                return
×
3967
        }
×
3968

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

3✔
3971
        // Check to see if we already have a connection with this peer. If so,
3✔
3972
        // we may need to drop our existing connection. This prevents us from
3✔
3973
        // having duplicate connections to the same peer. We forgo adding a
3✔
3974
        // default case as we expect these to be the only error values returned
3✔
3975
        // from findPeerByPubStr.
3✔
3976
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3977
        switch err {
3✔
3978
        case ErrPeerNotConnected:
3✔
3979
                // We were unable to locate an existing connection with the
3✔
3980
                // target peer, proceed to connect.
3✔
3981
                s.cancelConnReqs(pubStr, nil)
3✔
3982
                s.peerConnected(conn, nil, true)
3✔
3983

3984
        case nil:
3✔
3985
                ctx := btclog.WithCtx(
3✔
3986
                        context.TODO(),
3✔
3987
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
3988
                )
3✔
3989

3✔
3990
                // We already have a connection with the incoming peer. If the
3✔
3991
                // connection we've already established should be kept and is
3✔
3992
                // not of the same type of the new connection (inbound), then
3✔
3993
                // we'll close out the new connection s.t there's only a single
3✔
3994
                // connection between us.
3✔
3995
                localPub := s.identityECDH.PubKey()
3✔
3996
                if !connectedPeer.Inbound() &&
3✔
3997
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
3998

×
3999
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4000
                                "peer, but already have outbound "+
×
4001
                                "connection, dropping conn",
×
4002
                                fmt.Errorf("already have outbound conn"))
×
4003
                        conn.Close()
×
4004
                        return
×
4005
                }
×
4006

4007
                // Otherwise, if we should drop the connection, then we'll
4008
                // disconnect our already connected peer.
4009
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4010

3✔
4011
                s.cancelConnReqs(pubStr, nil)
3✔
4012

3✔
4013
                // Remove the current peer from the server's internal state and
3✔
4014
                // signal that the peer termination watcher does not need to
3✔
4015
                // execute for this peer.
3✔
4016
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4017
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4018
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4019
                        s.peerConnected(conn, nil, true)
3✔
4020
                }
3✔
4021
        }
4022
}
4023

4024
// OutboundPeerConnected initializes a new peer in response to a new outbound
4025
// connection.
4026
// NOTE: This function is safe for concurrent access.
4027
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4028
        // Exit early if we have already been instructed to shutdown, this
3✔
4029
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4030
        if s.Stopped() {
3✔
4031
                return
×
4032
        }
×
4033

4034
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4035
        pubSer := nodePub.SerializeCompressed()
3✔
4036
        pubStr := string(pubSer)
3✔
4037

3✔
4038
        var pubBytes [33]byte
3✔
4039
        copy(pubBytes[:], pubSer)
3✔
4040

3✔
4041
        s.mu.Lock()
3✔
4042
        defer s.mu.Unlock()
3✔
4043

3✔
4044
        // If we already have an inbound connection to this peer, then ignore
3✔
4045
        // this new connection.
3✔
4046
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4047
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4048
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4049
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4050

3✔
4051
                if connReq != nil {
6✔
4052
                        s.connMgr.Remove(connReq.ID())
3✔
4053
                }
3✔
4054
                conn.Close()
3✔
4055
                return
3✔
4056
        }
4057
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4058
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4059
                s.connMgr.Remove(connReq.ID())
×
4060
                conn.Close()
×
4061
                return
×
4062
        }
×
4063

4064
        // If we already have a valid connection that is scheduled to take
4065
        // precedence once the prior peer has finished disconnecting, we'll
4066
        // ignore this connection.
4067
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4068
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4069

×
4070
                if connReq != nil {
×
4071
                        s.connMgr.Remove(connReq.ID())
×
4072
                }
×
4073

4074
                conn.Close()
×
4075
                return
×
4076
        }
4077

4078
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4079
                conn.RemoteAddr())
3✔
4080

3✔
4081
        if connReq != nil {
6✔
4082
                // A successful connection was returned by the connmgr.
3✔
4083
                // Immediately cancel all pending requests, excluding the
3✔
4084
                // outbound connection we just established.
3✔
4085
                ignore := connReq.ID()
3✔
4086
                s.cancelConnReqs(pubStr, &ignore)
3✔
4087
        } else {
6✔
4088
                // This was a successful connection made by some other
3✔
4089
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4090
                s.cancelConnReqs(pubStr, nil)
3✔
4091
        }
3✔
4092

4093
        // If we already have a connection with this peer, decide whether or not
4094
        // we need to drop the stale connection. We forgo adding a default case
4095
        // as we expect these to be the only error values returned from
4096
        // findPeerByPubStr.
4097
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4098
        switch err {
3✔
4099
        case ErrPeerNotConnected:
3✔
4100
                // We were unable to locate an existing connection with the
3✔
4101
                // target peer, proceed to connect.
3✔
4102
                s.peerConnected(conn, connReq, false)
3✔
4103

4104
        case nil:
3✔
4105
                ctx := btclog.WithCtx(
3✔
4106
                        context.TODO(),
3✔
4107
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4108
                )
3✔
4109

3✔
4110
                // We already have a connection with the incoming peer. If the
3✔
4111
                // connection we've already established should be kept and is
3✔
4112
                // not of the same type of the new connection (outbound), then
3✔
4113
                // we'll close out the new connection s.t there's only a single
3✔
4114
                // connection between us.
3✔
4115
                localPub := s.identityECDH.PubKey()
3✔
4116
                if connectedPeer.Inbound() &&
3✔
4117
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4118

×
4119
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4120
                                "to peer, but already have inbound "+
×
4121
                                "connection, dropping conn",
×
4122
                                fmt.Errorf("already have inbound conn"))
×
4123
                        if connReq != nil {
×
4124
                                s.connMgr.Remove(connReq.ID())
×
4125
                        }
×
4126
                        conn.Close()
×
4127
                        return
×
4128
                }
4129

4130
                // Otherwise, _their_ connection should be dropped. So we'll
4131
                // disconnect the peer and send the now obsolete peer to the
4132
                // server for garbage collection.
4133
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4134

3✔
4135
                // Remove the current peer from the server's internal state and
3✔
4136
                // signal that the peer termination watcher does not need to
3✔
4137
                // execute for this peer.
3✔
4138
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4139
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4140
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4141
                        s.peerConnected(conn, connReq, false)
3✔
4142
                }
3✔
4143
        }
4144
}
4145

4146
// UnassignedConnID is the default connection ID that a request can have before
4147
// it actually is submitted to the connmgr.
4148
// TODO(conner): move into connmgr package, or better, add connmgr method for
4149
// generating atomic IDs
4150
const UnassignedConnID uint64 = 0
4151

4152
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4153
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4154
// Afterwards, each connection request removed from the connmgr. The caller can
4155
// optionally specify a connection ID to ignore, which prevents us from
4156
// canceling a successful request. All persistent connreqs for the provided
4157
// pubkey are discarded after the operationjw.
4158
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4159
        // First, cancel any lingering persistent retry attempts, which will
3✔
4160
        // prevent retries for any with backoffs that are still maturing.
3✔
4161
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4162
                close(cancelChan)
3✔
4163
                delete(s.persistentRetryCancels, pubStr)
3✔
4164
        }
3✔
4165

4166
        // Next, check to see if we have any outstanding persistent connection
4167
        // requests to this peer. If so, then we'll remove all of these
4168
        // connection requests, and also delete the entry from the map.
4169
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4170
        if !ok {
6✔
4171
                return
3✔
4172
        }
3✔
4173

4174
        for _, connReq := range connReqs {
6✔
4175
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4176

3✔
4177
                // Atomically capture the current request identifier.
3✔
4178
                connID := connReq.ID()
3✔
4179

3✔
4180
                // Skip any zero IDs, this indicates the request has not
3✔
4181
                // yet been schedule.
3✔
4182
                if connID == UnassignedConnID {
3✔
4183
                        continue
×
4184
                }
4185

4186
                // Skip a particular connection ID if instructed.
4187
                if skip != nil && connID == *skip {
6✔
4188
                        continue
3✔
4189
                }
4190

4191
                s.connMgr.Remove(connID)
3✔
4192
        }
4193

4194
        delete(s.persistentConnReqs, pubStr)
3✔
4195
}
4196

4197
// handleCustomMessage dispatches an incoming custom peers message to
4198
// subscribers.
4199
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4200
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4201
                peer, msg.Type)
3✔
4202

3✔
4203
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4204
                Peer: peer,
3✔
4205
                Msg:  msg,
3✔
4206
        })
3✔
4207
}
3✔
4208

4209
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4210
// messages.
4211
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4212
        return s.customMessageServer.Subscribe()
3✔
4213
}
3✔
4214

4215
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4216
// the channelNotifier's NotifyOpenChannelEvent.
4217
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4218
        remotePub *btcec.PublicKey) {
3✔
4219

3✔
4220
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4221
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4222
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
3✔
4223
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
3✔
4224
        }
3✔
4225

4226
        // Notify subscribers about this open channel event.
4227
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4228
}
4229

4230
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4231
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4232
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4233
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4234

3✔
4235
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4236
        // peer.
3✔
4237
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4238
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4239
                        "channel[%v] pending open",
×
4240
                        remotePub.SerializeCompressed(), op)
×
4241
        }
×
4242

4243
        // Notify subscribers about this event.
4244
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4245
}
4246

4247
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4248
// calls the channelNotifier's NotifyFundingTimeout.
4249
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4250
        remotePub *btcec.PublicKey) {
3✔
4251

3✔
4252
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4253
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4254
        if err != nil {
3✔
4255
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4256
                        "channel[%v] pending close",
×
4257
                        remotePub.SerializeCompressed(), op)
×
4258
        }
×
4259

4260
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4261
                // If we encounter an error while attempting to disconnect the
×
4262
                // peer, log the error.
×
4263
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4264
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4265
                }
×
4266
        }
4267

4268
        // Notify subscribers about this event.
4269
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4270
}
4271

4272
// peerConnected is a function that handles initialization a newly connected
4273
// peer by adding it to the server's global list of all active peers, and
4274
// starting all the goroutines the peer needs to function properly. The inbound
4275
// boolean should be true if the peer initiated the connection to us.
4276
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4277
        inbound bool) {
3✔
4278

3✔
4279
        brontideConn := conn.(*brontide.Conn)
3✔
4280
        addr := conn.RemoteAddr()
3✔
4281
        pubKey := brontideConn.RemotePub()
3✔
4282

3✔
4283
        // Only restrict access for inbound connections, which means if the
3✔
4284
        // remote node's public key is banned or the restricted slots are used
3✔
4285
        // up, we will drop the connection.
3✔
4286
        //
3✔
4287
        // TODO(yy): Consider perform this check in
3✔
4288
        // `peerAccessMan.addPeerAccess`.
3✔
4289
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4290
        if inbound && err != nil {
3✔
4291
                pubSer := pubKey.SerializeCompressed()
×
4292

×
4293
                // Clean up the persistent peer maps if we're dropping this
×
4294
                // connection.
×
4295
                s.bannedPersistentPeerConnection(string(pubSer))
×
4296

×
4297
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4298
                        "of restricted-access connection slots: %v.", pubSer,
×
4299
                        err)
×
4300

×
4301
                conn.Close()
×
4302

×
4303
                return
×
4304
        }
×
4305

4306
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4307
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4308

3✔
4309
        peerAddr := &lnwire.NetAddress{
3✔
4310
                IdentityKey: pubKey,
3✔
4311
                Address:     addr,
3✔
4312
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4313
        }
3✔
4314

3✔
4315
        // With the brontide connection established, we'll now craft the feature
3✔
4316
        // vectors to advertise to the remote node.
3✔
4317
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4318
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4319

3✔
4320
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4321
        // found, create a fresh buffer.
3✔
4322
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4323
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4324
        if !ok {
6✔
4325
                var err error
3✔
4326
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4327
                if err != nil {
3✔
4328
                        srvrLog.Errorf("unable to create peer %v", err)
×
4329
                        return
×
4330
                }
×
4331
        }
4332

4333
        // If we directly set the peer.Config TowerClient member to the
4334
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4335
        // the peer.Config's TowerClient member will not evaluate to nil even
4336
        // though the underlying value is nil. To avoid this gotcha which can
4337
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4338
        // TowerClient if needed.
4339
        var towerClient wtclient.ClientManager
3✔
4340
        if s.towerClientMgr != nil {
6✔
4341
                towerClient = s.towerClientMgr
3✔
4342
        }
3✔
4343

4344
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4345
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4346

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

3✔
4390
                        return s.genNodeAnnouncement(nil)
3✔
4391
                },
3✔
4392

4393
                PongBuf: s.pongBuf,
4394

4395
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4396

4397
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4398

4399
                FundingManager: s.fundingMgr,
4400

4401
                Hodl:                    s.cfg.Hodl,
4402
                UnsafeReplay:            s.cfg.UnsafeReplay,
4403
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4404
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4405
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4406
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4407
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4408
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4409
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4410
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4411
                HandleCustomMessage:    s.handleCustomMessage,
4412
                GetAliases:             s.aliasMgr.GetAliases,
4413
                RequestAlias:           s.aliasMgr.RequestAlias,
4414
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4415
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4416
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4417
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4418
                MaxFeeExposure:         thresholdMSats,
4419
                Quit:                   s.quit,
4420
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4421
                AuxSigner:              s.implCfg.AuxSigner,
4422
                MsgRouter:              s.implCfg.MsgRouter,
4423
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4424
                AuxResolver:            s.implCfg.AuxContractResolver,
4425
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4426
                ShouldFwdExpEndorsement: func() bool {
3✔
4427
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4428
                                return false
3✔
4429
                        }
3✔
4430

4431
                        return clock.NewDefaultClock().Now().Before(
3✔
4432
                                EndorsementExperimentEnd,
3✔
4433
                        )
3✔
4434
                },
4435
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4436
        }
4437

4438
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4439
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4440

3✔
4441
        p := peer.NewBrontide(pCfg)
3✔
4442

3✔
4443
        // Update the access manager with the access permission for this peer.
3✔
4444
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4445

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

3✔
4449
        s.addPeer(p)
3✔
4450

3✔
4451
        // Once we have successfully added the peer to the server, we can
3✔
4452
        // delete the previous error buffer from the server's map of error
3✔
4453
        // buffers.
3✔
4454
        delete(s.peerErrors, pkStr)
3✔
4455

3✔
4456
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4457
        // includes sending and receiving Init messages, which would be a DOS
3✔
4458
        // vector if we held the server's mutex throughout the procedure.
3✔
4459
        s.wg.Add(1)
3✔
4460
        go s.peerInitializer(p)
3✔
4461
}
4462

4463
// addPeer adds the passed peer to the server's global state of all active
4464
// peers.
4465
func (s *server) addPeer(p *peer.Brontide) {
3✔
4466
        if p == nil {
3✔
4467
                return
×
4468
        }
×
4469

4470
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4471

3✔
4472
        // Ignore new peers if we're shutting down.
3✔
4473
        if s.Stopped() {
3✔
4474
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4475
                        pubBytes)
×
4476
                p.Disconnect(ErrServerShuttingDown)
×
4477

×
4478
                return
×
4479
        }
×
4480

4481
        // Track the new peer in our indexes so we can quickly look it up either
4482
        // according to its public key, or its peer ID.
4483
        // TODO(roasbeef): pipe all requests through to the
4484
        // queryHandler/peerManager
4485

4486
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4487
        // be human-readable.
4488
        pubStr := string(pubBytes)
3✔
4489

3✔
4490
        s.peersByPub[pubStr] = p
3✔
4491

3✔
4492
        if p.Inbound() {
6✔
4493
                s.inboundPeers[pubStr] = p
3✔
4494
        } else {
6✔
4495
                s.outboundPeers[pubStr] = p
3✔
4496
        }
3✔
4497

4498
        // Inform the peer notifier of a peer online event so that it can be reported
4499
        // to clients listening for peer events.
4500
        var pubKey [33]byte
3✔
4501
        copy(pubKey[:], pubBytes)
3✔
4502
}
4503

4504
// peerInitializer asynchronously starts a newly connected peer after it has
4505
// been added to the server's peer map. This method sets up a
4506
// peerTerminationWatcher for the given peer, and ensures that it executes even
4507
// if the peer failed to start. In the event of a successful connection, this
4508
// method reads the negotiated, local feature-bits and spawns the appropriate
4509
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4510
// be signaled of the new peer once the method returns.
4511
//
4512
// NOTE: This MUST be launched as a goroutine.
4513
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4514
        defer s.wg.Done()
3✔
4515

3✔
4516
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4517

3✔
4518
        // Avoid initializing peers while the server is exiting.
3✔
4519
        if s.Stopped() {
3✔
4520
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4521
                        pubBytes)
×
4522
                return
×
4523
        }
×
4524

4525
        // Create a channel that will be used to signal a successful start of
4526
        // the link. This prevents the peer termination watcher from beginning
4527
        // its duty too early.
4528
        ready := make(chan struct{})
3✔
4529

3✔
4530
        // Before starting the peer, launch a goroutine to watch for the
3✔
4531
        // unexpected termination of this peer, which will ensure all resources
3✔
4532
        // are properly cleaned up, and re-establish persistent connections when
3✔
4533
        // necessary. The peer termination watcher will be short circuited if
3✔
4534
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4535
        // that the server has already handled the removal of this peer.
3✔
4536
        s.wg.Add(1)
3✔
4537
        go s.peerTerminationWatcher(p, ready)
3✔
4538

3✔
4539
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4540
        // will unblock the peerTerminationWatcher.
3✔
4541
        if err := p.Start(); err != nil {
6✔
4542
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4543

3✔
4544
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4545
                return
3✔
4546
        }
3✔
4547

4548
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4549
        // was successful, and to begin watching the peer's wait group.
4550
        close(ready)
3✔
4551

3✔
4552
        s.mu.Lock()
3✔
4553
        defer s.mu.Unlock()
3✔
4554

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

3✔
4558
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4559
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4560
        pubStr := string(pubBytes)
3✔
4561
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4562
                select {
3✔
4563
                case peerChan <- p:
3✔
4564
                case <-s.quit:
×
4565
                        return
×
4566
                }
4567
        }
4568
        delete(s.peerConnectedListeners, pubStr)
3✔
4569

3✔
4570
        // Since the peer has been fully initialized, now it's time to notify
3✔
4571
        // the RPC about the peer online event.
3✔
4572
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4573
}
4574

4575
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4576
// and then cleans up all resources allocated to the peer, notifies relevant
4577
// sub-systems of its demise, and finally handles re-connecting to the peer if
4578
// it's persistent. If the server intentionally disconnects a peer, it should
4579
// have a corresponding entry in the ignorePeerTermination map which will cause
4580
// the cleanup routine to exit early. The passed `ready` chan is used to
4581
// synchronize when WaitForDisconnect should begin watching on the peer's
4582
// waitgroup. The ready chan should only be signaled if the peer starts
4583
// successfully, otherwise the peer should be disconnected instead.
4584
//
4585
// NOTE: This MUST be launched as a goroutine.
4586
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4587
        defer s.wg.Done()
3✔
4588

3✔
4589
        ctx := btclog.WithCtx(
3✔
4590
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4591
        )
3✔
4592

3✔
4593
        p.WaitForDisconnect(ready)
3✔
4594

3✔
4595
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4596

3✔
4597
        // If the server is exiting then we can bail out early ourselves as all
3✔
4598
        // the other sub-systems will already be shutting down.
3✔
4599
        if s.Stopped() {
6✔
4600
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4601
                return
3✔
4602
        }
3✔
4603

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

3✔
4610
        pubKey := p.IdentityKey()
3✔
4611

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

3✔
4616
        // Tell the switch to remove all links associated with this peer.
3✔
4617
        // Passing nil as the target link indicates that all links associated
3✔
4618
        // with this interface should be closed.
3✔
4619
        //
3✔
4620
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4621
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4622
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4623
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4624
        }
×
4625

4626
        for _, link := range links {
6✔
4627
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4628
        }
3✔
4629

4630
        s.mu.Lock()
3✔
4631
        defer s.mu.Unlock()
3✔
4632

3✔
4633
        // If there were any notification requests for when this peer
3✔
4634
        // disconnected, we can trigger them now.
3✔
4635
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4636
        pubStr := string(pubKey.SerializeCompressed())
3✔
4637
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4638
                close(offlineChan)
3✔
4639
        }
3✔
4640
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4641

3✔
4642
        // If the server has already removed this peer, we can short circuit the
3✔
4643
        // peer termination watcher and skip cleanup.
3✔
4644
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4645
                delete(s.ignorePeerTermination, p)
3✔
4646

3✔
4647
                pubKey := p.PubKey()
3✔
4648
                pubStr := string(pubKey[:])
3✔
4649

3✔
4650
                // If a connection callback is present, we'll go ahead and
3✔
4651
                // execute it now that previous peer has fully disconnected. If
3✔
4652
                // the callback is not present, this likely implies the peer was
3✔
4653
                // purposefully disconnected via RPC, and that no reconnect
3✔
4654
                // should be attempted.
3✔
4655
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4656
                if ok {
6✔
4657
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4658
                        connCallback()
3✔
4659
                }
3✔
4660
                return
3✔
4661
        }
4662

4663
        // First, cleanup any remaining state the server has regarding the peer
4664
        // in question.
4665
        s.removePeerUnsafe(ctx, p)
3✔
4666

3✔
4667
        // Next, check to see if this is a persistent peer or not.
3✔
4668
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4669
                return
3✔
4670
        }
3✔
4671

4672
        // Get the last address that we used to connect to the peer.
4673
        addrs := []net.Addr{
3✔
4674
                p.NetAddress().Address,
3✔
4675
        }
3✔
4676

3✔
4677
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4678
        // reconnection purposes.
3✔
4679
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4680
        switch {
3✔
4681
        // We found advertised addresses, so use them.
4682
        case err == nil:
3✔
4683
                addrs = advertisedAddrs
3✔
4684

4685
        // The peer doesn't have an advertised address.
4686
        case err == errNoAdvertisedAddr:
3✔
4687
                // If it is an outbound peer then we fall back to the existing
3✔
4688
                // peer address.
3✔
4689
                if !p.Inbound() {
6✔
4690
                        break
3✔
4691
                }
4692

4693
                // Fall back to the existing peer address if
4694
                // we're not accepting connections over Tor.
4695
                if s.torController == nil {
6✔
4696
                        break
3✔
4697
                }
4698

4699
                // If we are, the peer's address won't be known
4700
                // to us (we'll see a private address, which is
4701
                // the address used by our onion service to dial
4702
                // to lnd), so we don't have enough information
4703
                // to attempt a reconnect.
4704
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4705
                        "to inbound peer without advertised address")
×
4706
                return
×
4707

4708
        // We came across an error retrieving an advertised
4709
        // address, log it, and fall back to the existing peer
4710
        // address.
4711
        default:
3✔
4712
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4713
                        "address for peer", err)
3✔
4714
        }
4715

4716
        // Make an easy lookup map so that we can check if an address
4717
        // is already in the address list that we have stored for this peer.
4718
        existingAddrs := make(map[string]bool)
3✔
4719
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4720
                existingAddrs[addr.String()] = true
3✔
4721
        }
3✔
4722

4723
        // Add any missing addresses for this peer to persistentPeerAddr.
4724
        for _, addr := range addrs {
6✔
4725
                if existingAddrs[addr.String()] {
3✔
4726
                        continue
×
4727
                }
4728

4729
                s.persistentPeerAddrs[pubStr] = append(
3✔
4730
                        s.persistentPeerAddrs[pubStr],
3✔
4731
                        &lnwire.NetAddress{
3✔
4732
                                IdentityKey: p.IdentityKey(),
3✔
4733
                                Address:     addr,
3✔
4734
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4735
                        },
3✔
4736
                )
3✔
4737
        }
4738

4739
        // Record the computed backoff in the backoff map.
4740
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4741
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4742

3✔
4743
        // Initialize a retry canceller for this peer if one does not
3✔
4744
        // exist.
3✔
4745
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4746
        if !ok {
6✔
4747
                cancelChan = make(chan struct{})
3✔
4748
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4749
        }
3✔
4750

4751
        // We choose not to wait group this go routine since the Connect
4752
        // call can stall for arbitrarily long if we shutdown while an
4753
        // outbound connection attempt is being made.
4754
        go func() {
6✔
4755
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4756
                        "re-establishment to persistent peer",
3✔
4757
                        "reconnecting_in", backoff)
3✔
4758

3✔
4759
                select {
3✔
4760
                case <-time.After(backoff):
3✔
4761
                case <-cancelChan:
3✔
4762
                        return
3✔
4763
                case <-s.quit:
3✔
4764
                        return
3✔
4765
                }
4766

4767
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4768
                        "connection")
3✔
4769

3✔
4770
                s.connectToPersistentPeer(pubStr)
3✔
4771
        }()
4772
}
4773

4774
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4775
// to connect to the peer. It creates connection requests if there are
4776
// currently none for a given address and it removes old connection requests
4777
// if the associated address is no longer in the latest address list for the
4778
// peer.
4779
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4780
        s.mu.Lock()
3✔
4781
        defer s.mu.Unlock()
3✔
4782

3✔
4783
        // Create an easy lookup map of the addresses we have stored for the
3✔
4784
        // peer. We will remove entries from this map if we have existing
3✔
4785
        // connection requests for the associated address and then any leftover
3✔
4786
        // entries will indicate which addresses we should create new
3✔
4787
        // connection requests for.
3✔
4788
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4789
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4790
                addrMap[addr.String()] = addr
3✔
4791
        }
3✔
4792

4793
        // Go through each of the existing connection requests and
4794
        // check if they correspond to the latest set of addresses. If
4795
        // there is a connection requests that does not use one of the latest
4796
        // advertised addresses then remove that connection request.
4797
        var updatedConnReqs []*connmgr.ConnReq
3✔
4798
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4799
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4800

3✔
4801
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4802
                // If the existing connection request is using one of the
4803
                // latest advertised addresses for the peer then we add it to
4804
                // updatedConnReqs and remove the associated address from
4805
                // addrMap so that we don't recreate this connReq later on.
4806
                case true:
×
4807
                        updatedConnReqs = append(
×
4808
                                updatedConnReqs, connReq,
×
4809
                        )
×
4810
                        delete(addrMap, lnAddr)
×
4811

4812
                // If the existing connection request is using an address that
4813
                // is not one of the latest advertised addresses for the peer
4814
                // then we remove the connecting request from the connection
4815
                // manager.
4816
                case false:
3✔
4817
                        srvrLog.Info(
3✔
4818
                                "Removing conn req:", connReq.Addr.String(),
3✔
4819
                        )
3✔
4820
                        s.connMgr.Remove(connReq.ID())
3✔
4821
                }
4822
        }
4823

4824
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4825

3✔
4826
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4827
        if !ok {
6✔
4828
                cancelChan = make(chan struct{})
3✔
4829
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4830
        }
3✔
4831

4832
        // Any addresses left in addrMap are new ones that we have not made
4833
        // connection requests for. So create new connection requests for those.
4834
        // If there is more than one address in the address map, stagger the
4835
        // creation of the connection requests for those.
4836
        go func() {
6✔
4837
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4838
                defer ticker.Stop()
3✔
4839

3✔
4840
                for _, addr := range addrMap {
6✔
4841
                        // Send the persistent connection request to the
3✔
4842
                        // connection manager, saving the request itself so we
3✔
4843
                        // can cancel/restart the process as needed.
3✔
4844
                        connReq := &connmgr.ConnReq{
3✔
4845
                                Addr:      addr,
3✔
4846
                                Permanent: true,
3✔
4847
                        }
3✔
4848

3✔
4849
                        s.mu.Lock()
3✔
4850
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4851
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4852
                        )
3✔
4853
                        s.mu.Unlock()
3✔
4854

3✔
4855
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4856
                                "channel peer %v", addr)
3✔
4857

3✔
4858
                        go s.connMgr.Connect(connReq)
3✔
4859

3✔
4860
                        select {
3✔
4861
                        case <-s.quit:
3✔
4862
                                return
3✔
4863
                        case <-cancelChan:
3✔
4864
                                return
3✔
4865
                        case <-ticker.C:
3✔
4866
                        }
4867
                }
4868
        }()
4869
}
4870

4871
// removePeerUnsafe removes the passed peer from the server's state of all
4872
// active peers.
4873
//
4874
// NOTE: Server mutex must be held when calling this function.
4875
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4876
        if p == nil {
3✔
4877
                return
×
4878
        }
×
4879

4880
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4881

3✔
4882
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4883
        // will be disconnected in the server shutdown process.
3✔
4884
        if s.Stopped() {
3✔
4885
                return
×
4886
        }
×
4887

4888
        // Capture the peer's public key and string representation.
4889
        pKey := p.PubKey()
3✔
4890
        pubSer := pKey[:]
3✔
4891
        pubStr := string(pubSer)
3✔
4892

3✔
4893
        delete(s.peersByPub, pubStr)
3✔
4894

3✔
4895
        if p.Inbound() {
6✔
4896
                delete(s.inboundPeers, pubStr)
3✔
4897
        } else {
6✔
4898
                delete(s.outboundPeers, pubStr)
3✔
4899
        }
3✔
4900

4901
        // When removing the peer we make sure to disconnect it asynchronously
4902
        // to avoid blocking the main server goroutine because it is holding the
4903
        // server's mutex. Disconnecting the peer might block and wait until the
4904
        // peer has fully started up. This can happen if an inbound and outbound
4905
        // race condition occurs.
4906
        s.wg.Add(1)
3✔
4907
        go func() {
6✔
4908
                defer s.wg.Done()
3✔
4909

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

3✔
4912
                // If this peer had an active persistent connection request,
3✔
4913
                // remove it.
3✔
4914
                if p.ConnReq() != nil {
6✔
4915
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4916
                }
3✔
4917

4918
                // Remove the peer's access permission from the access manager.
4919
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4920
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4921

3✔
4922
                // Copy the peer's error buffer across to the server if it has
3✔
4923
                // any items in it so that we can restore peer errors across
3✔
4924
                // connections. We need to look up the error after the peer has
3✔
4925
                // been disconnected because we write the error in the
3✔
4926
                // `Disconnect` method.
3✔
4927
                s.mu.Lock()
3✔
4928
                if p.ErrorBuffer().Total() > 0 {
6✔
4929
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4930
                }
3✔
4931
                s.mu.Unlock()
3✔
4932

3✔
4933
                // Inform the peer notifier of a peer offline event so that it
3✔
4934
                // can be reported to clients listening for peer events.
3✔
4935
                var pubKey [33]byte
3✔
4936
                copy(pubKey[:], pubSer)
3✔
4937

3✔
4938
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4939
        }()
4940
}
4941

4942
// ConnectToPeer requests that the server connect to a Lightning Network peer
4943
// at the specified address. This function will *block* until either a
4944
// connection is established, or the initial handshake process fails.
4945
//
4946
// NOTE: This function is safe for concurrent access.
4947
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4948
        perm bool, timeout time.Duration) error {
3✔
4949

3✔
4950
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4951

3✔
4952
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4953
        // better granularity.  In certain conditions, this method requires
3✔
4954
        // making an outbound connection to a remote peer, which requires the
3✔
4955
        // lock to be released, and subsequently reacquired.
3✔
4956
        s.mu.Lock()
3✔
4957

3✔
4958
        // Ensure we're not already connected to this peer.
3✔
4959
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4960

3✔
4961
        // When there's no error it means we already have a connection with this
3✔
4962
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4963
        // set, we will ignore the existing connection and continue.
3✔
4964
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4965
                s.mu.Unlock()
3✔
4966
                return &errPeerAlreadyConnected{peer: peer}
3✔
4967
        }
3✔
4968

4969
        // Peer was not found, continue to pursue connection with peer.
4970

4971
        // If there's already a pending connection request for this pubkey,
4972
        // then we ignore this request to ensure we don't create a redundant
4973
        // connection.
4974
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4975
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4976
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4977
        }
3✔
4978

4979
        // If there's not already a pending or active connection to this node,
4980
        // then instruct the connection manager to attempt to establish a
4981
        // persistent connection to the peer.
4982
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4983
        if perm {
6✔
4984
                connReq := &connmgr.ConnReq{
3✔
4985
                        Addr:      addr,
3✔
4986
                        Permanent: true,
3✔
4987
                }
3✔
4988

3✔
4989
                // Since the user requested a permanent connection, we'll set
3✔
4990
                // the entry to true which will tell the server to continue
3✔
4991
                // reconnecting even if the number of channels with this peer is
3✔
4992
                // zero.
3✔
4993
                s.persistentPeers[targetPub] = true
3✔
4994
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4995
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4996
                }
3✔
4997
                s.persistentConnReqs[targetPub] = append(
3✔
4998
                        s.persistentConnReqs[targetPub], connReq,
3✔
4999
                )
3✔
5000
                s.mu.Unlock()
3✔
5001

3✔
5002
                go s.connMgr.Connect(connReq)
3✔
5003

3✔
5004
                return nil
3✔
5005
        }
5006
        s.mu.Unlock()
3✔
5007

3✔
5008
        // If we're not making a persistent connection, then we'll attempt to
3✔
5009
        // connect to the target peer. If the we can't make the connection, or
3✔
5010
        // the crypto negotiation breaks down, then return an error to the
3✔
5011
        // caller.
3✔
5012
        errChan := make(chan error, 1)
3✔
5013
        s.connectToPeer(addr, errChan, timeout)
3✔
5014

3✔
5015
        select {
3✔
5016
        case err := <-errChan:
3✔
5017
                return err
3✔
5018
        case <-s.quit:
×
5019
                return ErrServerShuttingDown
×
5020
        }
5021
}
5022

5023
// connectToPeer establishes a connection to a remote peer. errChan is used to
5024
// notify the caller if the connection attempt has failed. Otherwise, it will be
5025
// closed.
5026
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5027
        errChan chan<- error, timeout time.Duration) {
3✔
5028

3✔
5029
        conn, err := brontide.Dial(
3✔
5030
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5031
        )
3✔
5032
        if err != nil {
6✔
5033
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5034
                select {
3✔
5035
                case errChan <- err:
3✔
5036
                case <-s.quit:
×
5037
                }
5038
                return
3✔
5039
        }
5040

5041
        close(errChan)
3✔
5042

3✔
5043
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5044
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5045

3✔
5046
        s.OutboundPeerConnected(nil, conn)
3✔
5047
}
5048

5049
// DisconnectPeer sends the request to server to close the connection with peer
5050
// identified by public key.
5051
//
5052
// NOTE: This function is safe for concurrent access.
5053
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5054
        pubBytes := pubKey.SerializeCompressed()
3✔
5055
        pubStr := string(pubBytes)
3✔
5056

3✔
5057
        s.mu.Lock()
3✔
5058
        defer s.mu.Unlock()
3✔
5059

3✔
5060
        // Check that were actually connected to this peer. If not, then we'll
3✔
5061
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5062
        // currently connected to.
3✔
5063
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5064
        if err == ErrPeerNotConnected {
6✔
5065
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5066
        }
3✔
5067

5068
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5069

3✔
5070
        s.cancelConnReqs(pubStr, nil)
3✔
5071

3✔
5072
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5073
        // them from this map so we don't attempt to re-connect after we
3✔
5074
        // disconnect.
3✔
5075
        delete(s.persistentPeers, pubStr)
3✔
5076
        delete(s.persistentPeersBackoff, pubStr)
3✔
5077

3✔
5078
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5079
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5080
        //
3✔
5081
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5082
        // goroutine because we might hold the server's mutex.
3✔
5083
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5084

3✔
5085
        return nil
3✔
5086
}
5087

5088
// OpenChannel sends a request to the server to open a channel to the specified
5089
// peer identified by nodeKey with the passed channel funding parameters.
5090
//
5091
// NOTE: This function is safe for concurrent access.
5092
func (s *server) OpenChannel(
5093
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5094

3✔
5095
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5096
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5097
        // not blocked if the caller is not reading the updates.
3✔
5098
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5099
        req.Err = make(chan error, 1)
3✔
5100

3✔
5101
        // First attempt to locate the target peer to open a channel with, if
3✔
5102
        // we're unable to locate the peer then this request will fail.
3✔
5103
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5104
        s.mu.RLock()
3✔
5105
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5106
        if !ok {
3✔
5107
                s.mu.RUnlock()
×
5108

×
5109
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5110
                return req.Updates, req.Err
×
5111
        }
×
5112
        req.Peer = peer
3✔
5113
        s.mu.RUnlock()
3✔
5114

3✔
5115
        // We'll wait until the peer is active before beginning the channel
3✔
5116
        // opening process.
3✔
5117
        select {
3✔
5118
        case <-peer.ActiveSignal():
3✔
5119
        case <-peer.QuitSignal():
×
5120
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5121
                return req.Updates, req.Err
×
5122
        case <-s.quit:
×
5123
                req.Err <- ErrServerShuttingDown
×
5124
                return req.Updates, req.Err
×
5125
        }
5126

5127
        // If the fee rate wasn't specified at this point we fail the funding
5128
        // because of the missing fee rate information. The caller of the
5129
        // `OpenChannel` method needs to make sure that default values for the
5130
        // fee rate are set beforehand.
5131
        if req.FundingFeePerKw == 0 {
3✔
5132
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5133
                        "the channel opening transaction")
×
5134

×
5135
                return req.Updates, req.Err
×
5136
        }
×
5137

5138
        // Spawn a goroutine to send the funding workflow request to the funding
5139
        // manager. This allows the server to continue handling queries instead
5140
        // of blocking on this request which is exported as a synchronous
5141
        // request to the outside world.
5142
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5143

3✔
5144
        return req.Updates, req.Err
3✔
5145
}
5146

5147
// Peers returns a slice of all active peers.
5148
//
5149
// NOTE: This function is safe for concurrent access.
5150
func (s *server) Peers() []*peer.Brontide {
3✔
5151
        s.mu.RLock()
3✔
5152
        defer s.mu.RUnlock()
3✔
5153

3✔
5154
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5155
        for _, peer := range s.peersByPub {
6✔
5156
                peers = append(peers, peer)
3✔
5157
        }
3✔
5158

5159
        return peers
3✔
5160
}
5161

5162
// computeNextBackoff uses a truncated exponential backoff to compute the next
5163
// backoff using the value of the exiting backoff. The returned duration is
5164
// randomized in either direction by 1/20 to prevent tight loops from
5165
// stabilizing.
5166
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5167
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5168
        nextBackoff := 2 * currBackoff
3✔
5169
        if nextBackoff > maxBackoff {
6✔
5170
                nextBackoff = maxBackoff
3✔
5171
        }
3✔
5172

5173
        // Using 1/10 of our duration as a margin, compute a random offset to
5174
        // avoid the nodes entering connection cycles.
5175
        margin := nextBackoff / 10
3✔
5176

3✔
5177
        var wiggle big.Int
3✔
5178
        wiggle.SetUint64(uint64(margin))
3✔
5179
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5180
                // Randomizing is not mission critical, so we'll just return the
×
5181
                // current backoff.
×
5182
                return nextBackoff
×
5183
        }
×
5184

5185
        // Otherwise add in our wiggle, but subtract out half of the margin so
5186
        // that the backoff can tweaked by 1/20 in either direction.
5187
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5188
}
5189

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

5194
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5195
func (s *server) fetchNodeAdvertisedAddrs(ctx context.Context,
5196
        pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5197

3✔
5198
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5199
        if err != nil {
3✔
5200
                return nil, err
×
5201
        }
×
5202

5203
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5204
        if err != nil {
6✔
5205
                return nil, err
3✔
5206
        }
3✔
5207

5208
        if len(node.Addresses) == 0 {
6✔
5209
                return nil, errNoAdvertisedAddr
3✔
5210
        }
3✔
5211

5212
        return node.Addresses, nil
3✔
5213
}
5214

5215
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5216
// channel update for a target channel.
5217
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5218
        *lnwire.ChannelUpdate1, error) {
3✔
5219

3✔
5220
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5221
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5222
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5223
                if err != nil {
6✔
5224
                        return nil, err
3✔
5225
                }
3✔
5226

5227
                return netann.ExtractChannelUpdate(
3✔
5228
                        ourPubKey[:], info, edge1, edge2,
3✔
5229
                )
3✔
5230
        }
5231
}
5232

5233
// applyChannelUpdate applies the channel update to the different sub-systems of
5234
// the server. The useAlias boolean denotes whether or not to send an alias in
5235
// place of the real SCID.
5236
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5237
        op *wire.OutPoint, useAlias bool) error {
3✔
5238

3✔
5239
        var (
3✔
5240
                peerAlias    *lnwire.ShortChannelID
3✔
5241
                defaultAlias lnwire.ShortChannelID
3✔
5242
        )
3✔
5243

3✔
5244
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5245

3✔
5246
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5247
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5248
        if useAlias {
6✔
5249
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5250
                if foundAlias != defaultAlias {
6✔
5251
                        peerAlias = &foundAlias
3✔
5252
                }
3✔
5253
        }
5254

5255
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5256
                update, discovery.RemoteAlias(peerAlias),
3✔
5257
        )
3✔
5258
        select {
3✔
5259
        case err := <-errChan:
3✔
5260
                return err
3✔
5261
        case <-s.quit:
×
5262
                return ErrServerShuttingDown
×
5263
        }
5264
}
5265

5266
// SendCustomMessage sends a custom message to the peer with the specified
5267
// pubkey.
5268
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5269
        data []byte) error {
3✔
5270

3✔
5271
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5272
        if err != nil {
6✔
5273
                return err
3✔
5274
        }
3✔
5275

5276
        // We'll wait until the peer is active.
5277
        select {
3✔
5278
        case <-peer.ActiveSignal():
3✔
5279
        case <-peer.QuitSignal():
×
5280
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5281
        case <-s.quit:
×
5282
                return ErrServerShuttingDown
×
5283
        }
5284

5285
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5286
        if err != nil {
6✔
5287
                return err
3✔
5288
        }
3✔
5289

5290
        // Send the message as low-priority. For now we assume that all
5291
        // application-defined message are low priority.
5292
        return peer.SendMessageLazy(true, msg)
3✔
5293
}
5294

5295
// newSweepPkScriptGen creates closure that generates a new public key script
5296
// which should be used to sweep any funds into the on-chain wallet.
5297
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5298
// (p2wkh) output.
5299
func newSweepPkScriptGen(
5300
        wallet lnwallet.WalletController,
5301
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5302

3✔
5303
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5304
                sweepAddr, err := wallet.NewAddress(
3✔
5305
                        lnwallet.TaprootPubkey, false,
3✔
5306
                        lnwallet.DefaultAccountName,
3✔
5307
                )
3✔
5308
                if err != nil {
3✔
5309
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5310
                }
×
5311

5312
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5313
                if err != nil {
3✔
5314
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5315
                }
×
5316

5317
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5318
                        wallet, netParams, addr,
3✔
5319
                )
3✔
5320
                if err != nil {
3✔
5321
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5322
                }
×
5323

5324
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5325
                        DeliveryAddress: addr,
3✔
5326
                        InternalKey:     internalKeyDesc,
3✔
5327
                })
3✔
5328
        }
5329
}
5330

5331
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5332
// finished.
5333
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5334
        // Get a list of closed channels.
3✔
5335
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5336
        if err != nil {
3✔
5337
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5338
                return nil
×
5339
        }
×
5340

5341
        // Save the SCIDs in a map.
5342
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5343
        for _, c := range channels {
6✔
5344
                // If the channel is not pending, its FC has been finalized.
3✔
5345
                if !c.IsPending {
6✔
5346
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5347
                }
3✔
5348
        }
5349

5350
        // Double check whether the reported closed channel has indeed finished
5351
        // closing.
5352
        //
5353
        // NOTE: There are misalignments regarding when a channel's FC is
5354
        // marked as finalized. We double check the pending channels to make
5355
        // sure the returned SCIDs are indeed terminated.
5356
        //
5357
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5358
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5359
        if err != nil {
3✔
5360
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5361
                return nil
×
5362
        }
×
5363

5364
        for _, c := range pendings {
6✔
5365
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5366
                        continue
3✔
5367
                }
5368

5369
                // If the channel is still reported as pending, remove it from
5370
                // the map.
5371
                delete(closedSCIDs, c.ShortChannelID)
×
5372

×
5373
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5374
                        c.ShortChannelID)
×
5375
        }
5376

5377
        return closedSCIDs
3✔
5378
}
5379

5380
// getStartingBeat returns the current beat. This is used during the startup to
5381
// initialize blockbeat consumers.
5382
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5383
        // beat is the current blockbeat.
3✔
5384
        var beat *chainio.Beat
3✔
5385

3✔
5386
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5387
        // we will skip fetching the best block.
3✔
5388
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5389
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5390
                        "mode")
×
5391

×
5392
                return &chainio.Beat{}, nil
×
5393
        }
×
5394

5395
        // We should get a notification with the current best block immediately
5396
        // by passing a nil block.
5397
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5398
        if err != nil {
3✔
5399
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5400
        }
×
5401
        defer blockEpochs.Cancel()
3✔
5402

3✔
5403
        // We registered for the block epochs with a nil request. The notifier
3✔
5404
        // should send us the current best block immediately. So we need to
3✔
5405
        // wait for it here because we need to know the current best height.
3✔
5406
        select {
3✔
5407
        case bestBlock := <-blockEpochs.Epochs:
3✔
5408
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5409
                        bestBlock.Hash, bestBlock.Height)
3✔
5410

3✔
5411
                // Update the current blockbeat.
3✔
5412
                beat = chainio.NewBeat(*bestBlock)
3✔
5413

5414
        case <-s.quit:
×
5415
                srvrLog.Debug("LND shutting down")
×
5416
        }
5417

5418
        return beat, nil
3✔
5419
}
5420

5421
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5422
// point has an active RBF chan closer.
5423
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5424
        chanPoint wire.OutPoint) bool {
3✔
5425

3✔
5426
        pubBytes := peerPub.SerializeCompressed()
3✔
5427

3✔
5428
        s.mu.RLock()
3✔
5429
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5430
        s.mu.RUnlock()
3✔
5431
        if !ok {
3✔
5432
                return false
×
5433
        }
×
5434

5435
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5436
}
5437

5438
// attemptCoopRbfFeeBump attempts to look up the active chan closer for a
5439
// channel given the outpoint. If found, we'll attempt to do a fee bump,
5440
// returning channels used for updates. If the channel isn't currently active
5441
// (p2p connection established), then his function will return an error.
5442
func (s *server) attemptCoopRbfFeeBump(ctx context.Context,
5443
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5444
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
3✔
5445

3✔
5446
        // First, we'll attempt to look up the channel based on it's
3✔
5447
        // ChannelPoint.
3✔
5448
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5449
        if err != nil {
3✔
5450
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5451
        }
×
5452

5453
        // From the channel, we can now get the pubkey of the peer, then use
5454
        // that to eventually get the chan closer.
5455
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5456

3✔
5457
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5458
        s.mu.RLock()
3✔
5459
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5460
        s.mu.RUnlock()
3✔
5461
        if !ok {
3✔
5462
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5463
                        "not online", chanPoint)
×
5464
        }
×
5465

5466
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5467
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5468
        )
3✔
5469
        if err != nil {
3✔
5470
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5471
                        "%w", err)
×
5472
        }
×
5473

5474
        return closeUpdates, nil
3✔
5475
}
5476

5477
// AttemptRBFCloseUpdate attempts to trigger a new RBF iteration for a co-op
5478
// close update. This route it to be used only if the target channel in question
5479
// is no longer active in the link. This can happen when we restart while we
5480
// already have done a single RBF co-op close iteration.
5481
func (s *server) AttemptRBFCloseUpdate(ctx context.Context,
5482
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5483
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
3✔
5484

3✔
5485
        // If the channel is present in the switch, then the request should flow
3✔
5486
        // through the switch instead.
3✔
5487
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5488
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5489
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5490
                        "invalid request", chanPoint)
×
5491
        }
×
5492

5493
        // At this point, we know that the channel isn't present in the link, so
5494
        // we'll check to see if we have an entry in the active chan closer map.
5495
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5496
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5497
        )
3✔
5498
        if err != nil {
3✔
5499
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5500
                        "ChannelPoint(%v)", chanPoint)
×
5501
        }
×
5502

5503
        return updates, nil
3✔
5504
}
5505

5506
// setSelfNode configures and sets the server's self node. It sets the node
5507
// announcement, signs it, and updates the source node in the graph. When
5508
// determining values such as color and alias, the method prioritizes values
5509
// set in the config, then values previously persisted on disk, and finally
5510
// falls back to the defaults.
5511
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5512
        listenAddrs []net.Addr) error {
3✔
5513

3✔
5514
        // If we were requested to automatically configure port forwarding,
3✔
5515
        // we'll use the ports that the server will be listening on.
3✔
5516
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
3✔
5517
        for _, ip := range s.cfg.ExternalIPs {
6✔
5518
                externalIPStrings = append(externalIPStrings, ip.String())
3✔
5519
        }
3✔
5520
        if s.natTraversal != nil {
3✔
NEW
5521
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
NEW
5522
                for _, listenAddr := range listenAddrs {
×
NEW
5523
                        // At this point, the listen addresses should have
×
NEW
5524
                        // already been normalized, so it's safe to ignore the
×
NEW
5525
                        // errors.
×
NEW
5526
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
NEW
5527
                        port, _ := strconv.Atoi(portStr)
×
NEW
5528

×
NEW
5529
                        listenPorts = append(listenPorts, uint16(port))
×
NEW
5530
                }
×
5531

NEW
5532
                ips, err := s.configurePortForwarding(listenPorts...)
×
NEW
5533
                if err != nil {
×
NEW
5534
                        srvrLog.Errorf("Unable to automatically set up port "+
×
NEW
5535
                                "forwarding using %s: %v",
×
NEW
5536
                                s.natTraversal.Name(), err)
×
NEW
5537
                } else {
×
NEW
5538
                        srvrLog.Infof("Automatically set up port forwarding "+
×
NEW
5539
                                "using %s to advertise external IP",
×
NEW
5540
                                s.natTraversal.Name())
×
NEW
5541
                        externalIPStrings = append(externalIPStrings, ips...)
×
NEW
5542
                }
×
5543
        }
5544

5545
        // Normalize the external IP strings to net.Addr.
5546
        addrs, err := lncfg.NormalizeAddresses(
3✔
5547
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5548
                s.cfg.net.ResolveTCPAddr,
3✔
5549
        )
3✔
5550
        if err != nil {
3✔
NEW
5551
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
NEW
5552
        }
×
5553

5554
        // To avoid having duplicate addresses, we'll only add addresses from
5555
        // the source node that are not already in our address list yet. We
5556
        // create this map for quick lookup.
5557
        addressMap := make(map[string]struct{}, len(addrs))
3✔
5558
        // Populate the map with the existing addresses.
3✔
5559
        for _, existingAddr := range addrs {
6✔
5560
                addressMap[existingAddr.String()] = struct{}{}
3✔
5561
        }
3✔
5562

5563
        // Parse the color from config. We will update this later if the config
5564
        // color is not changed from default (#3399FF) and we have a value in
5565
        // the source node.
5566
        color, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5567
        if err != nil {
3✔
NEW
5568
                return fmt.Errorf("unable to parse color: %w", err)
×
NEW
5569
        }
×
5570

5571
        var (
3✔
5572
                alias          = s.cfg.Alias
3✔
5573
                nodeLastUpdate = time.Now()
3✔
5574
        )
3✔
5575

3✔
5576
        srcNode, err := s.graphDB.SourceNode(ctx)
3✔
5577
        switch {
3✔
5578
        case err == nil:
3✔
5579
                // If we have a source node persisted in the DB already, then we
3✔
5580
                // just need to make sure that the new LastUpdate time is at
3✔
5581
                // least one second after the last update time.
3✔
5582
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
5583
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
5584
                }
3✔
5585

5586
                // If the color is not changed from default, it means that we
5587
                // didn't specify a different color in the config. We'll use the
5588
                // source node's color.
5589
                if s.cfg.Color == defaultColor {
6✔
5590
                        color = srcNode.Color
3✔
5591
                }
3✔
5592

5593
                // If an alias is not specified in the config, we'll use the
5594
                // source node's alias.
5595
                if alias == "" {
6✔
5596
                        alias = srcNode.Alias
3✔
5597
                }
3✔
5598

5599
                // Append unique addresses from the source node to the address
5600
                // list.
5601
                for _, addr := range srcNode.Addresses {
6✔
5602
                        if _, found := addressMap[addr.String()]; !found {
6✔
5603
                                addrs = append(addrs, addr)
3✔
5604
                                addressMap[addr.String()] = struct{}{}
3✔
5605
                        }
3✔
5606
                }
5607

5608
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5609
                // If an alias is not specified in the config, we'll use the
3✔
5610
                // default, which is the first 10 bytes of the serialized
3✔
5611
                // pubkey.
3✔
5612
                if alias == "" {
6✔
5613
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5614
                }
3✔
5615

5616
        // If the above cases are not matched, then we have an unhandled non
5617
        // nil error.
NEW
5618
        default:
×
NEW
5619
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5620
        }
5621

5622
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5623
        if err != nil {
3✔
NEW
5624
                return err
×
NEW
5625
        }
×
5626

5627
        // TODO(abdulkbk): potentially find a way to use the source node's
5628
        // features in the self node.
5629
        selfNode := &models.LightningNode{
3✔
5630
                HaveNodeAnnouncement: true,
3✔
5631
                LastUpdate:           nodeLastUpdate,
3✔
5632
                Addresses:            addrs,
3✔
5633
                Alias:                nodeAlias.String(),
3✔
5634
                Color:                color,
3✔
5635
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
5636
        }
3✔
5637

3✔
5638
        copy(selfNode.PubKeyBytes[:], nodePub[:])
3✔
5639

3✔
5640
        // Based on the disk representation of the node announcement generated
3✔
5641
        // above, we'll generate a node announcement that can go out on the
3✔
5642
        // network so we can properly sign it.
3✔
5643
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5644
        if err != nil {
3✔
NEW
5645
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
NEW
5646
        }
×
5647

5648
        // With the announcement generated, we'll sign it to properly
5649
        // authenticate the message on the network.
5650
        authSig, err := netann.SignAnnouncement(
3✔
5651
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5652
        )
3✔
5653
        if err != nil {
3✔
NEW
5654
                return fmt.Errorf("unable to generate signature for self node "+
×
NEW
5655
                        "announcement: %v", err)
×
NEW
5656
        }
×
5657

5658
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5659
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5660
                selfNode.AuthSigBytes,
3✔
5661
        )
3✔
5662
        if err != nil {
3✔
NEW
5663
                return err
×
NEW
5664
        }
×
5665

5666
        // Finally, we'll update the representation on disk, and update our
5667
        // cached in-memory version as well.
5668
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
NEW
5669
                return fmt.Errorf("can't set self node: %w", err)
×
NEW
5670
        }
×
5671

5672
        s.currentNodeAnn = nodeAnn
3✔
5673

3✔
5674
        return nil
3✔
5675
}
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