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

lightningnetwork / lnd / 15959600311

29 Jun 2025 09:33PM UTC coverage: 67.577% (-0.03%) from 67.606%
15959600311

Pull #8825

github

web-flow
Merge b3542eca4 into 6290edf14
Pull Request #8825: lnd: use persisted node announcement settings across restarts

44 of 49 new or added lines in 1 file covered. (89.8%)

92 existing lines in 17 files now uncovered.

135081 of 199891 relevant lines covered (67.58%)

21854.87 hits per line

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

69.82
/server.go
1
package lnd
2

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/rand"
7
        "encoding/hex"
8
        "fmt"
9
        "image/color"
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/go-errors/errors"
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/lnwallet"
61
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
62
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
63
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
64
        "github.com/lightningnetwork/lnd/lnwire"
65
        "github.com/lightningnetwork/lnd/nat"
66
        "github.com/lightningnetwork/lnd/netann"
67
        "github.com/lightningnetwork/lnd/peer"
68
        "github.com/lightningnetwork/lnd/peernotifier"
69
        "github.com/lightningnetwork/lnd/pool"
70
        "github.com/lightningnetwork/lnd/queue"
71
        "github.com/lightningnetwork/lnd/routing"
72
        "github.com/lightningnetwork/lnd/routing/localchans"
73
        "github.com/lightningnetwork/lnd/routing/route"
74
        "github.com/lightningnetwork/lnd/subscribe"
75
        "github.com/lightningnetwork/lnd/sweep"
76
        "github.com/lightningnetwork/lnd/ticker"
77
        "github.com/lightningnetwork/lnd/tor"
78
        "github.com/lightningnetwork/lnd/walletunlocker"
79
        "github.com/lightningnetwork/lnd/watchtower/blob"
80
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
81
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
82
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
83
)
84

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

229
        start sync.Once
230
        stop  sync.Once
231

232
        cfg *Config
233

234
        implCfg *ImplementationCfg
235

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

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

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

247
        chanStatusMgr *netann.ChanStatusManager
248

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

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

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

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

269
        mu sync.RWMutex
270

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

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

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

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

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

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

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

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

321
        cc *chainreg.ChainControl
322

323
        fundingMgr *funding.Manager
324

325
        graphDB *graphdb.ChannelGraph
326

327
        chanStateDB *channeldb.ChannelStateDB
328

329
        addrSource channeldb.AddrSource
330

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

335
        invoicesDB invoices.InvoiceDB
336

337
        aliasMgr *aliasmgr.Manager
338

339
        htlcSwitch *htlcswitch.Switch
340

341
        interceptableSwitch *htlcswitch.InterceptableSwitch
342

343
        invoices *invoices.InvoiceRegistry
344

345
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
346

347
        channelNotifier *channelnotifier.ChannelNotifier
348

349
        peerNotifier *peernotifier.PeerNotifier
350

351
        htlcNotifier *htlcswitch.HtlcNotifier
352

353
        witnessBeacon contractcourt.WitnessBeacon
354

355
        breachArbitrator *contractcourt.BreachArbitrator
356

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

360
        graphBuilder *graph.Builder
361

362
        chanRouter *routing.ChannelRouter
363

364
        controlTower routing.ControlTower
365

366
        authGossiper *discovery.AuthenticatedGossiper
367

368
        localChanMgr *localchans.Manager
369

370
        utxoNursery *contractcourt.UtxoNursery
371

372
        sweeper *sweep.UtxoSweeper
373

374
        chainArb *contractcourt.ChainArbitrator
375

376
        sphinx *hop.OnionProcessor
377

378
        towerClientMgr *wtclient.Manager
379

380
        connMgr *connmgr.ConnManager
381

382
        sigPool *lnwallet.SigPool
383

384
        writePool *pool.Write
385

386
        readPool *pool.Read
387

388
        tlsManager *TLSManager
389

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

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

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

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

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

412
        hostAnn *netann.HostAnnouncer
413

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

417
        customMessageServer *subscribe.Server
418

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

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

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

429
        quit chan struct{}
430

431
        wg sync.WaitGroup
432
}
433

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

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

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

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

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

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

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

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

489
                                        s.mu.Lock()
3✔
490

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

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

505
                                        s.mu.Unlock()
3✔
506

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

513
        return nil
3✔
514
}
515

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

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

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

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

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

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

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

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

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

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

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

3✔
596
        var serializedPubKey [33]byte
3✔
597
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
598

3✔
599
        netParams := cfg.ActiveNetParams.Params
3✔
600

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

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

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

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

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

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

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

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

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

3✔
670
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
671

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

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

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

3✔
697
                listenAddrs: listenAddrs,
3✔
698

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

3✔
703
                torController: torController,
3✔
704

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

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

3✔
721
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
722

3✔
723
                customMessageServer: subscribe.NewServer(),
3✔
724

3✔
725
                tlsManager: tlsManager,
3✔
726

3✔
727
                featureMgr: featureMgr,
3✔
728
                quit:       make(chan struct{}),
3✔
729
        }
3✔
730

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

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

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

3✔
755
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
756

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

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

766
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
767

3✔
768
                return nil
3✔
769
        }
770

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

930
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
931
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
932

3✔
933
        // We'll now reconstruct a node announcement based on our current
3✔
934
        // configuration so we can send it out as a sort of heart beat within
3✔
935
        // the network.
3✔
936
        color, alias, addresses, err := s.getNodeAnnFields(
3✔
937
                ctx, selfAddrs, serializedPubKey,
3✔
938
        )
3✔
939
        if err != nil {
3✔
940
                return nil, err
×
941
        }
×
942

943
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
944
        if err != nil {
3✔
945
                return nil, err
×
946
        }
×
947
        selfNode := &models.LightningNode{
3✔
948
                HaveNodeAnnouncement: true,
3✔
949
                LastUpdate:           time.Now(),
3✔
950
                Addresses:            addresses,
3✔
951
                Alias:                nodeAlias.String(),
3✔
952
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
953
                Color:                color,
3✔
954
        }
3✔
955
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
956

3✔
957
        // Based on the disk representation of the node announcement generated
3✔
958
        // above, we'll generate a node announcement that can go out on the
3✔
959
        // network so we can properly sign it.
3✔
960
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
961
        if err != nil {
3✔
962
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
963
        }
×
964

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

982
        // Finally, we'll update the representation on disk, and update our
983
        // cached in-memory version as well.
984
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
985
                return nil, fmt.Errorf("can't set self node: %w", err)
×
986
        }
×
987
        s.currentNodeAnn = nodeAnn
3✔
988

3✔
989
        // The router will get access to the payment ID sequencer, such that it
3✔
990
        // can generate unique payment IDs.
3✔
991
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
992
        if err != nil {
3✔
993
                return nil, err
×
994
        }
×
995

996
        // Instantiate mission control with config from the sub server.
997
        //
998
        // TODO(joostjager): When we are further in the process of moving to sub
999
        // servers, the mission control instance itself can be moved there too.
1000
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1001

3✔
1002
        // We only initialize a probability estimator if there's no custom one.
3✔
1003
        var estimator routing.Estimator
3✔
1004
        if cfg.Estimator != nil {
3✔
1005
                estimator = cfg.Estimator
×
1006
        } else {
3✔
1007
                switch routingConfig.ProbabilityEstimatorType {
3✔
1008
                case routing.AprioriEstimatorName:
3✔
1009
                        aCfg := routingConfig.AprioriConfig
3✔
1010
                        aprioriConfig := routing.AprioriConfig{
3✔
1011
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1012
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1013
                                AprioriWeight:         aCfg.Weight,
3✔
1014
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1015
                        }
3✔
1016

3✔
1017
                        estimator, err = routing.NewAprioriEstimator(
3✔
1018
                                aprioriConfig,
3✔
1019
                        )
3✔
1020
                        if err != nil {
3✔
1021
                                return nil, err
×
1022
                        }
×
1023

1024
                case routing.BimodalEstimatorName:
×
1025
                        bCfg := routingConfig.BimodalConfig
×
1026
                        bimodalConfig := routing.BimodalConfig{
×
1027
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1028
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1029
                                        bCfg.Scale,
×
1030
                                ),
×
1031
                                BimodalDecayTime: bCfg.DecayTime,
×
1032
                        }
×
1033

×
1034
                        estimator, err = routing.NewBimodalEstimator(
×
1035
                                bimodalConfig,
×
1036
                        )
×
1037
                        if err != nil {
×
1038
                                return nil, err
×
1039
                        }
×
1040

1041
                default:
×
1042
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1043
                                routingConfig.ProbabilityEstimatorType)
×
1044
                }
1045
        }
1046

1047
        mcCfg := &routing.MissionControlConfig{
3✔
1048
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1049
                Estimator:               estimator,
3✔
1050
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1051
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1052
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1053
        }
3✔
1054

3✔
1055
        s.missionController, err = routing.NewMissionController(
3✔
1056
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1057
        )
3✔
1058
        if err != nil {
3✔
1059
                return nil, fmt.Errorf("can't create mission control "+
×
1060
                        "manager: %w", err)
×
1061
        }
×
1062
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1063
                routing.DefaultMissionControlNamespace,
3✔
1064
        )
3✔
1065
        if err != nil {
3✔
1066
                return nil, fmt.Errorf("can't create mission control in the "+
×
1067
                        "default namespace: %w", err)
×
1068
        }
×
1069

1070
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1071
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1072
                int64(routingConfig.AttemptCost),
3✔
1073
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1074
                routingConfig.MinRouteProbability)
3✔
1075

3✔
1076
        pathFindingConfig := routing.PathFindingConfig{
3✔
1077
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1078
                        routingConfig.AttemptCost,
3✔
1079
                ),
3✔
1080
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1081
                MinProbability: routingConfig.MinRouteProbability,
3✔
1082
        }
3✔
1083

3✔
1084
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1085
        if err != nil {
3✔
1086
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1087
        }
×
1088
        paymentSessionSource := &routing.SessionSource{
3✔
1089
                GraphSessionFactory: dbs.GraphDB,
3✔
1090
                SourceNode:          sourceNode,
3✔
1091
                MissionControl:      s.defaultMC,
3✔
1092
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1093
                PathFindingConfig:   pathFindingConfig,
3✔
1094
        }
3✔
1095

3✔
1096
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1097

3✔
1098
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1099

3✔
1100
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1101
                cfg.Routing.StrictZombiePruning
3✔
1102

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

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

1140
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1141
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1142
        if err != nil {
3✔
1143
                return nil, err
×
1144
        }
×
1145
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1146
        if err != nil {
3✔
1147
                return nil, err
×
1148
        }
×
1149

1150
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1151

3✔
1152
        s.authGossiper = discovery.New(discovery.Config{
3✔
1153
                Graph:                 s.graphBuilder,
3✔
1154
                ChainIO:               s.cc.ChainIO,
3✔
1155
                Notifier:              s.cc.ChainNotifier,
3✔
1156
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1157
                Broadcast:             s.BroadcastMessage,
3✔
1158
                ChanSeries:            chanSeries,
3✔
1159
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1160
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1161
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1162
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1163
                        error) {
3✔
1164

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

1196
        accessCfg := &accessManConfig{
3✔
1197
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1198
                        error) {
6✔
1199

3✔
1200
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1201
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1202
                                genesisHash[:],
3✔
1203
                        )
3✔
1204
                },
3✔
1205
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1206
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1207
        }
1208

1209
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1210
        if err != nil {
3✔
1211
                return nil, err
×
1212
        }
×
1213

1214
        s.peerAccessMan = peerAccessMan
3✔
1215

3✔
1216
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1217
        //nolint:ll
3✔
1218
        s.localChanMgr = &localchans.Manager{
3✔
1219
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1220
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1221
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1222
                        *models.ChannelEdgePolicy) error) error {
6✔
1223

3✔
1224
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1225
                                func(c *models.ChannelEdgeInfo,
3✔
1226
                                        e *models.ChannelEdgePolicy,
3✔
1227
                                        _ *models.ChannelEdgePolicy) error {
6✔
1228

3✔
1229
                                        // NOTE: The invoked callback here may
3✔
1230
                                        // receive a nil channel policy.
3✔
1231
                                        return cb(c, e)
3✔
1232
                                },
3✔
1233
                        )
1234
                },
1235
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1236
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1237
                FetchChannel:              s.chanStateDB.FetchChannel,
1238
                AddEdge: func(ctx context.Context,
1239
                        edge *models.ChannelEdgeInfo) error {
×
1240

×
1241
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1242
                },
×
1243
        }
1244

1245
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1246
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1247
        )
3✔
1248
        if err != nil {
3✔
1249
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1250
                return nil, err
×
1251
        }
×
1252

1253
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1254
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1255
        )
3✔
1256
        if err != nil {
3✔
1257
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1258
                return nil, err
×
1259
        }
×
1260

1261
        aggregator := sweep.NewBudgetAggregator(
3✔
1262
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1263
                s.implCfg.AuxSweeper,
3✔
1264
        )
3✔
1265

3✔
1266
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1267
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1268
                Wallet:     cc.Wallet,
3✔
1269
                Estimator:  cc.FeeEstimator,
3✔
1270
                Notifier:   cc.ChainNotifier,
3✔
1271
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1272
        })
3✔
1273

3✔
1274
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1275
                FeeEstimator: cc.FeeEstimator,
3✔
1276
                GenSweepScript: newSweepPkScriptGen(
3✔
1277
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1278
                ),
3✔
1279
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1280
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1281
                Mempool:              cc.MempoolNotifier,
3✔
1282
                Notifier:             cc.ChainNotifier,
3✔
1283
                Store:                sweeperStore,
3✔
1284
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1285
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1286
                Aggregator:           aggregator,
3✔
1287
                Publisher:            s.txPublisher,
3✔
1288
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1289
        })
3✔
1290

3✔
1291
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1292
                ChainIO:             cc.ChainIO,
3✔
1293
                ConfDepth:           1,
3✔
1294
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1295
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1296
                Notifier:            cc.ChainNotifier,
3✔
1297
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1298
                Store:               utxnStore,
3✔
1299
                SweepInput:          s.sweeper.SweepInput,
3✔
1300
                Budget:              s.cfg.Sweeper.Budget,
3✔
1301
        })
3✔
1302

3✔
1303
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1304
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1305
                closureType contractcourt.ChannelCloseType) {
6✔
1306
                // TODO(conner): Properly respect the update and error channels
3✔
1307
                // returned by CloseLink.
3✔
1308

3✔
1309
                // Instruct the switch to close the channel.  Provide no close out
3✔
1310
                // delivery script or target fee per kw because user input is not
3✔
1311
                // available when the remote peer closes the channel.
3✔
1312
                s.htlcSwitch.CloseLink(
3✔
1313
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1314
                )
3✔
1315
        }
3✔
1316

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

3✔
1321
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1322
                &contractcourt.BreachConfig{
3✔
1323
                        CloseLink: closeLink,
3✔
1324
                        DB:        s.chanStateDB,
3✔
1325
                        Estimator: s.cc.FeeEstimator,
3✔
1326
                        GenSweepScript: newSweepPkScriptGen(
3✔
1327
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1328
                        ),
3✔
1329
                        Notifier:           cc.ChainNotifier,
3✔
1330
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1331
                        ContractBreaches:   contractBreaches,
3✔
1332
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1333
                        Store: contractcourt.NewRetributionStore(
3✔
1334
                                dbs.ChanStateDB,
3✔
1335
                        ),
3✔
1336
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1337
                },
3✔
1338
        )
3✔
1339

3✔
1340
        //nolint:ll
3✔
1341
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1342
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1343
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1344
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1345
                NewSweepAddr: func() ([]byte, error) {
3✔
1346
                        addr, err := newSweepPkScriptGen(
×
1347
                                cc.Wallet, netParams,
×
1348
                        )().Unpack()
×
1349
                        if err != nil {
×
1350
                                return nil, err
×
1351
                        }
×
1352

1353
                        return addr.DeliveryAddress, nil
×
1354
                },
1355
                PublishTx: cc.Wallet.PublishTransaction,
1356
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1357
                        for _, msg := range msgs {
6✔
1358
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1359
                                if err != nil {
3✔
1360
                                        return err
×
1361
                                }
×
1362
                        }
1363
                        return nil
3✔
1364
                },
1365
                IncubateOutputs: func(chanPoint wire.OutPoint,
1366
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1367
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1368
                        broadcastHeight uint32,
1369
                        deadlineHeight fn.Option[int32]) error {
3✔
1370

3✔
1371
                        return s.utxoNursery.IncubateOutputs(
3✔
1372
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1373
                                broadcastHeight, deadlineHeight,
3✔
1374
                        )
3✔
1375
                },
3✔
1376
                PreimageDB:   s.witnessBeacon,
1377
                Notifier:     cc.ChainNotifier,
1378
                Mempool:      cc.MempoolNotifier,
1379
                Signer:       cc.Wallet.Cfg.Signer,
1380
                FeeEstimator: cc.FeeEstimator,
1381
                ChainIO:      cc.ChainIO,
1382
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1383
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1384
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1385
                        return nil
3✔
1386
                },
3✔
1387
                IsOurAddress: cc.Wallet.IsOurAddress,
1388
                ContractBreach: func(chanPoint wire.OutPoint,
1389
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1390

3✔
1391
                        // processACK will handle the BreachArbitrator ACKing
3✔
1392
                        // the event.
3✔
1393
                        finalErr := make(chan error, 1)
3✔
1394
                        processACK := func(brarErr error) {
6✔
1395
                                if brarErr != nil {
3✔
1396
                                        finalErr <- brarErr
×
1397
                                        return
×
1398
                                }
×
1399

1400
                                // If the BreachArbitrator successfully handled
1401
                                // the event, we can signal that the handoff
1402
                                // was successful.
1403
                                finalErr <- nil
3✔
1404
                        }
1405

1406
                        event := &contractcourt.ContractBreachEvent{
3✔
1407
                                ChanPoint:         chanPoint,
3✔
1408
                                ProcessACK:        processACK,
3✔
1409
                                BreachRetribution: breachRet,
3✔
1410
                        }
3✔
1411

3✔
1412
                        // Send the contract breach event to the
3✔
1413
                        // BreachArbitrator.
3✔
1414
                        select {
3✔
1415
                        case contractBreaches <- event:
3✔
1416
                        case <-s.quit:
×
1417
                                return ErrServerShuttingDown
×
1418
                        }
1419

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

1445
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1446
                QueryIncomingCircuit: func(
1447
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1448

3✔
1449
                        // Get the circuit map.
3✔
1450
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1451

3✔
1452
                        // Lookup the outgoing circuit.
3✔
1453
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1454
                        if pc == nil {
5✔
1455
                                return nil
2✔
1456
                        }
2✔
1457

1458
                        return &pc.Incoming
3✔
1459
                },
1460
                AuxLeafStore: implCfg.AuxLeafStore,
1461
                AuxSigner:    implCfg.AuxSigner,
1462
                AuxResolver:  implCfg.AuxContractResolver,
1463
        }, dbs.ChanStateDB)
1464

1465
        // Select the configuration and funding parameters for Bitcoin.
1466
        chainCfg := cfg.Bitcoin
3✔
1467
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1468
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1469

3✔
1470
        var chanIDSeed [32]byte
3✔
1471
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1472
                return nil, err
×
1473
        }
×
1474

1475
        // Wrap the DeleteChannelEdges method so that the funding manager can
1476
        // use it without depending on several layers of indirection.
1477
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1478
                *models.ChannelEdgePolicy, error) {
6✔
1479

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

1493
                // Grab our key to find our policy.
1494
                var ourKey [33]byte
3✔
1495
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1496

3✔
1497
                var ourPolicy *models.ChannelEdgePolicy
3✔
1498
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1499
                        ourPolicy = e1
3✔
1500
                } else {
6✔
1501
                        ourPolicy = e2
3✔
1502
                }
3✔
1503

1504
                if ourPolicy == nil {
3✔
1505
                        // Something is wrong, so return an error.
×
1506
                        return nil, fmt.Errorf("we don't have an edge")
×
1507
                }
×
1508

1509
                err = s.graphDB.DeleteChannelEdges(
3✔
1510
                        false, false, scid.ToUint64(),
3✔
1511
                )
3✔
1512
                return ourPolicy, err
3✔
1513
        }
1514

1515
        // For the reservationTimeout and the zombieSweeperInterval different
1516
        // values are set in case we are in a dev environment so enhance test
1517
        // capacilities.
1518
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1519
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1520

3✔
1521
        // Get the development config for funding manager. If we are not in
3✔
1522
        // development mode, this would be nil.
3✔
1523
        var devCfg *funding.DevConfig
3✔
1524
        if lncfg.IsDevBuild() {
6✔
1525
                devCfg = &funding.DevConfig{
3✔
1526
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1527
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1528
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1529
                }
3✔
1530

3✔
1531
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1532
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1533

3✔
1534
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1535
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1536
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1537
        }
3✔
1538

1539
        //nolint:ll
1540
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1541
                Dev:                devCfg,
3✔
1542
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1543
                IDKey:              nodeKeyDesc.PubKey,
3✔
1544
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1545
                Wallet:             cc.Wallet,
3✔
1546
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1547
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1548
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1549
                },
3✔
1550
                Notifier:     cc.ChainNotifier,
1551
                ChannelDB:    s.chanStateDB,
1552
                FeeEstimator: cc.FeeEstimator,
1553
                SignMessage:  cc.MsgSigner.SignMessage,
1554
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1555
                        error) {
3✔
1556

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

3✔
1577
                        // In case the user has explicitly specified
3✔
1578
                        // a default value for the number of
3✔
1579
                        // confirmations, we use it.
3✔
1580
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1581
                        if defaultConf != 0 {
6✔
1582
                                return defaultConf
3✔
1583
                        }
3✔
1584

1585
                        minConf := uint64(3)
×
1586
                        maxConf := uint64(6)
×
1587

×
1588
                        // If this is a wumbo channel, then we'll require the
×
1589
                        // max amount of confirmations.
×
1590
                        if chanAmt > MaxFundingAmount {
×
1591
                                return uint16(maxConf)
×
1592
                        }
×
1593

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

3✔
1616
                        // In case the user has explicitly specified
3✔
1617
                        // a default value for the remote delay, we
3✔
1618
                        // use it.
3✔
1619
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1620
                        if defaultDelay > 0 {
6✔
1621
                                return defaultDelay
3✔
1622
                        }
3✔
1623

1624
                        // If this is a wumbo channel, then we'll require the
1625
                        // max value.
1626
                        if chanAmt > MaxFundingAmount {
×
1627
                                return maxRemoteDelay
×
1628
                        }
×
1629

1630
                        // If not we scale according to channel size.
1631
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1632
                                chanAmt / MaxFundingAmount)
×
1633
                        if delay < minRemoteDelay {
×
1634
                                delay = minRemoteDelay
×
1635
                        }
×
1636
                        if delay > maxRemoteDelay {
×
1637
                                delay = maxRemoteDelay
×
1638
                        }
×
1639
                        return delay
×
1640
                },
1641
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1642
                        peerKey *btcec.PublicKey) error {
3✔
1643

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

3✔
1657
                        // With that taken care of, we'll send this channel to
3✔
1658
                        // the chain arb so it can react to on-chain events.
3✔
1659
                        return s.chainArb.WatchNewChannel(channel)
3✔
1660
                },
1661
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1662
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1663
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1664
                },
3✔
1665
                RequiredRemoteChanReserve: func(chanAmt,
1666
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1667

3✔
1668
                        // By default, we'll require the remote peer to maintain
3✔
1669
                        // at least 1% of the total channel capacity at all
3✔
1670
                        // times. If this value ends up dipping below the dust
3✔
1671
                        // limit, then we'll use the dust limit itself as the
3✔
1672
                        // reserve as required by BOLT #2.
3✔
1673
                        reserve := chanAmt / 100
3✔
1674
                        if reserve < dustLimit {
6✔
1675
                                reserve = dustLimit
3✔
1676
                        }
3✔
1677

1678
                        return reserve
3✔
1679
                },
1680
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1681
                        // By default, we'll allow the remote peer to fully
3✔
1682
                        // utilize the full bandwidth of the channel, minus our
3✔
1683
                        // required reserve.
3✔
1684
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1685
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1686
                },
3✔
1687
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1688
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1689
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1690
                        }
3✔
1691

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

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

1743
        // Assemble a peer notifier which will provide clients with subscriptions
1744
        // to peer online and offline events.
1745
        s.peerNotifier = peernotifier.New()
3✔
1746

3✔
1747
        // Create a channel event store which monitors all open channels.
3✔
1748
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1749
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1750
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1751
                },
3✔
1752
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1753
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1754
                },
3✔
1755
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1756
                Clock:           clock.NewDefaultClock(),
1757
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1758
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1759
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1760
        })
1761

1762
        if cfg.WtClient.Active {
6✔
1763
                policy := wtpolicy.DefaultPolicy()
3✔
1764
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1765

3✔
1766
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1767
                // protocol operations on sat/kw.
3✔
1768
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1769
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1770
                )
3✔
1771

3✔
1772
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1773

3✔
1774
                if err := policy.Validate(); err != nil {
3✔
1775
                        return nil, err
×
1776
                }
×
1777

1778
                // authDial is the wrapper around the btrontide.Dial for the
1779
                // watchtower.
1780
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1781
                        netAddr *lnwire.NetAddress,
3✔
1782
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1783

3✔
1784
                        return brontide.Dial(
3✔
1785
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1786
                        )
3✔
1787
                }
3✔
1788

1789
                // buildBreachRetribution is a call-back that can be used to
1790
                // query the BreachRetribution info and channel type given a
1791
                // channel ID and commitment height.
1792
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1793
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1794
                        channeldb.ChannelType, error) {
6✔
1795

3✔
1796
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1797
                                nil, chanID,
3✔
1798
                        )
3✔
1799
                        if err != nil {
3✔
1800
                                return nil, 0, err
×
1801
                        }
×
1802

1803
                        br, err := lnwallet.NewBreachRetribution(
3✔
1804
                                channel, commitHeight, 0, nil,
3✔
1805
                                implCfg.AuxLeafStore,
3✔
1806
                                implCfg.AuxContractResolver,
3✔
1807
                        )
3✔
1808
                        if err != nil {
3✔
1809
                                return nil, 0, err
×
1810
                        }
×
1811

1812
                        return br, channel.ChanType, nil
3✔
1813
                }
1814

1815
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1816

3✔
1817
                // Copy the policy for legacy channels and set the blob flag
3✔
1818
                // signalling support for anchor channels.
3✔
1819
                anchorPolicy := policy
3✔
1820
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1821

3✔
1822
                // Copy the policy for legacy channels and set the blob flag
3✔
1823
                // signalling support for taproot channels.
3✔
1824
                taprootPolicy := policy
3✔
1825
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1826
                        blob.FlagTaprootChannel,
3✔
1827
                )
3✔
1828

3✔
1829
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1830
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1831
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1832
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1833
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1834
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1835
                                error) {
6✔
1836

3✔
1837
                                return s.channelNotifier.
3✔
1838
                                        SubscribeChannelEvents()
3✔
1839
                        },
3✔
1840
                        Signer: cc.Wallet.Cfg.Signer,
1841
                        NewAddress: func() ([]byte, error) {
3✔
1842
                                addr, err := newSweepPkScriptGen(
3✔
1843
                                        cc.Wallet, netParams,
3✔
1844
                                )().Unpack()
3✔
1845
                                if err != nil {
3✔
1846
                                        return nil, err
×
1847
                                }
×
1848

1849
                                return addr.DeliveryAddress, nil
3✔
1850
                        },
1851
                        SecretKeyRing:      s.cc.KeyRing,
1852
                        Dial:               cfg.net.Dial,
1853
                        AuthDial:           authDial,
1854
                        DB:                 dbs.TowerClientDB,
1855
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1856
                        MinBackoff:         10 * time.Second,
1857
                        MaxBackoff:         5 * time.Minute,
1858
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1859
                }, policy, anchorPolicy, taprootPolicy)
1860
                if err != nil {
3✔
1861
                        return nil, err
×
1862
                }
×
1863
        }
1864

1865
        if len(cfg.ExternalHosts) != 0 {
3✔
1866
                advertisedIPs := make(map[string]struct{})
×
1867
                for _, addr := range s.currentNodeAnn.Addresses {
×
1868
                        advertisedIPs[addr.String()] = struct{}{}
×
1869
                }
×
1870

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

×
1885
                                        return s.genNodeAnnouncement(
×
1886
                                                nil, modifier...,
×
1887
                                        )
×
1888
                                }),
×
1889
                })
1890
        }
1891

1892
        // Create liveness monitor.
1893
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1894

3✔
1895
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1896
        for i, listenAddr := range listenAddrs {
6✔
1897
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1898
                // doesn't need to call the general lndResolveTCP function
3✔
1899
                // since we are resolving a local address.
3✔
1900

3✔
1901
                // RESOLVE: We are actually partially accepting inbound
3✔
1902
                // connection requests when we call NewListener.
3✔
1903
                listeners[i], err = brontide.NewListener(
3✔
1904
                        nodeKeyECDH, listenAddr.String(),
3✔
1905
                        // TODO(yy): remove this check and unify the inbound
3✔
1906
                        // connection check inside `InboundPeerConnected`.
3✔
1907
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1908
                )
3✔
1909
                if err != nil {
3✔
1910
                        return nil, err
×
1911
                }
×
1912
        }
1913

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

3✔
1932
        // Finally, register the subsystems in blockbeat.
3✔
1933
        s.registerBlockConsumers()
3✔
1934

3✔
1935
        return s, nil
3✔
1936
}
1937

1938
// UpdateRoutingConfig is a callback function to update the routing config
1939
// values in the main cfg.
1940
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1941
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1942

3✔
1943
        switch c := cfg.Estimator.Config().(type) {
3✔
1944
        case routing.AprioriConfig:
3✔
1945
                routerCfg.ProbabilityEstimatorType =
3✔
1946
                        routing.AprioriEstimatorName
3✔
1947

3✔
1948
                targetCfg := routerCfg.AprioriConfig
3✔
1949
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1950
                targetCfg.Weight = c.AprioriWeight
3✔
1951
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1952
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1953

1954
        case routing.BimodalConfig:
3✔
1955
                routerCfg.ProbabilityEstimatorType =
3✔
1956
                        routing.BimodalEstimatorName
3✔
1957

3✔
1958
                targetCfg := routerCfg.BimodalConfig
3✔
1959
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1960
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1961
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1962
        }
1963

1964
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1965
}
1966

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

1986
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1987
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1988
// may differ from what is on disk.
1989
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1990
        error) {
3✔
1991

3✔
1992
        data, err := u.DataToSign()
3✔
1993
        if err != nil {
3✔
1994
                return nil, err
×
1995
        }
×
1996

1997
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1998
}
1999

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

3✔
2013
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2014
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2015
                srvrLog.Info("Disabling chain backend checks for " +
×
2016
                        "nochainbackend mode")
×
2017

×
2018
                chainBackendAttempts = 0
×
2019
        }
×
2020

2021
        chainHealthCheck := healthcheck.NewObservation(
3✔
2022
                "chain backend",
3✔
2023
                cc.HealthCheck,
3✔
2024
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2025
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2026
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2027
                chainBackendAttempts,
3✔
2028
        )
3✔
2029

3✔
2030
        diskCheck := healthcheck.NewObservation(
3✔
2031
                "disk space",
3✔
2032
                func() error {
3✔
2033
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2034
                                cfg.LndDir,
×
2035
                        )
×
2036
                        if err != nil {
×
2037
                                return err
×
2038
                        }
×
2039

2040
                        // If we have more free space than we require,
2041
                        // we return a nil error.
2042
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2043
                                return nil
×
2044
                        }
×
2045

2046
                        return fmt.Errorf("require: %v free space, got: %v",
×
2047
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2048
                                free)
×
2049
                },
2050
                cfg.HealthChecks.DiskCheck.Interval,
2051
                cfg.HealthChecks.DiskCheck.Timeout,
2052
                cfg.HealthChecks.DiskCheck.Backoff,
2053
                cfg.HealthChecks.DiskCheck.Attempts,
2054
        )
2055

2056
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2057
                "tls",
3✔
2058
                func() error {
3✔
2059
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2060
                                s.cc.KeyRing,
×
2061
                        )
×
2062
                        if err != nil {
×
2063
                                return err
×
2064
                        }
×
2065
                        if expired {
×
2066
                                return fmt.Errorf("TLS certificate is "+
×
2067
                                        "expired as of %v", expTime)
×
2068
                        }
×
2069

2070
                        // If the certificate is not outdated, no error needs
2071
                        // to be returned
2072
                        return nil
×
2073
                },
2074
                cfg.HealthChecks.TLSCheck.Interval,
2075
                cfg.HealthChecks.TLSCheck.Timeout,
2076
                cfg.HealthChecks.TLSCheck.Backoff,
2077
                cfg.HealthChecks.TLSCheck.Attempts,
2078
        )
2079

2080
        checks := []*healthcheck.Observation{
3✔
2081
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2082
        }
3✔
2083

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

2106
        // If remote signing is enabled, add the healthcheck for the remote
2107
        // signing RPC interface.
2108
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2109
                // Because we have two cascading timeouts here, we need to add
3✔
2110
                // some slack to the "outer" one of them in case the "inner"
3✔
2111
                // returns exactly on time.
3✔
2112
                overhead := time.Millisecond * 10
3✔
2113

3✔
2114
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2115
                        "remote signer connection",
3✔
2116
                        rpcwallet.HealthCheck(
3✔
2117
                                s.cfg.RemoteSigner,
3✔
2118

3✔
2119
                                // For the health check we might to be even
3✔
2120
                                // stricter than the initial/normal connect, so
3✔
2121
                                // we use the health check timeout here.
3✔
2122
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2123
                        ),
3✔
2124
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2125
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2126
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2127
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2128
                )
3✔
2129
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2130
        }
3✔
2131

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

×
2150
                                leader, err := leaderElector.IsLeader(
×
2151
                                        timeoutCtx,
×
2152
                                )
×
2153
                                if err != nil {
×
2154
                                        return fmt.Errorf("unable to check if "+
×
2155
                                                "still leader: %v", err)
×
2156
                                }
×
2157

2158
                                if !leader {
×
2159
                                        srvrLog.Debug("Not the current leader")
×
2160
                                        return fmt.Errorf("not the current " +
×
2161
                                                "leader")
×
2162
                                }
×
2163

2164
                                return nil
×
2165
                        },
2166
                        cfg.HealthChecks.LeaderCheck.Interval,
2167
                        cfg.HealthChecks.LeaderCheck.Timeout,
2168
                        cfg.HealthChecks.LeaderCheck.Backoff,
2169
                        cfg.HealthChecks.LeaderCheck.Attempts,
2170
                )
2171

2172
                checks = append(checks, leaderCheck)
×
2173
        }
2174

2175
        // If we have not disabled all of our health checks, we create a
2176
        // liveness monitor with our configured checks.
2177
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2178
                &healthcheck.Config{
3✔
2179
                        Checks:   checks,
3✔
2180
                        Shutdown: srvrLog.Criticalf,
3✔
2181
                },
3✔
2182
        )
3✔
2183
}
2184

2185
// Started returns true if the server has been started, and false otherwise.
2186
// NOTE: This function is safe for concurrent access.
2187
func (s *server) Started() bool {
3✔
2188
        return atomic.LoadInt32(&s.active) != 0
3✔
2189
}
3✔
2190

2191
// cleaner is used to aggregate "cleanup" functions during an operation that
2192
// starts several subsystems. In case one of the subsystem fails to start
2193
// and a proper resource cleanup is required, the "run" method achieves this
2194
// by running all these added "cleanup" functions.
2195
type cleaner []func() error
2196

2197
// add is used to add a cleanup function to be called when
2198
// the run function is executed.
2199
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2200
        return append(c, cleanup)
3✔
2201
}
3✔
2202

2203
// run is used to run all the previousely added cleanup functions.
2204
func (c cleaner) run() {
×
2205
        for i := len(c) - 1; i >= 0; i-- {
×
2206
                if err := c[i](); err != nil {
×
2207
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2208
                }
×
2209
        }
2210
}
2211

2212
// startLowLevelServices starts the low-level services of the server. These
2213
// services must be started successfully before running the main server. The
2214
// services are,
2215
// 1. the chain notifier.
2216
//
2217
// TODO(yy): identify and add more low-level services here.
2218
func (s *server) startLowLevelServices() error {
3✔
2219
        var startErr error
3✔
2220

3✔
2221
        cleanup := cleaner{}
3✔
2222

3✔
2223
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2224
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2225
                startErr = err
×
2226
        }
×
2227

2228
        if startErr != nil {
3✔
2229
                cleanup.run()
×
2230
        }
×
2231

2232
        return startErr
3✔
2233
}
2234

2235
// Start starts the main daemon server, all requested listeners, and any helper
2236
// goroutines.
2237
// NOTE: This function is safe for concurrent access.
2238
//
2239
//nolint:funlen
2240
func (s *server) Start(ctx context.Context) error {
3✔
2241
        // Get the current blockbeat.
3✔
2242
        beat, err := s.getStartingBeat()
3✔
2243
        if err != nil {
3✔
2244
                return err
×
2245
        }
×
2246

2247
        var startErr error
3✔
2248

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

3✔
2254
        s.start.Do(func() {
6✔
2255
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2256
                if err := s.customMessageServer.Start(); err != nil {
3✔
2257
                        startErr = err
×
2258
                        return
×
2259
                }
×
2260

2261
                if s.hostAnn != nil {
3✔
2262
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2263
                        if err := s.hostAnn.Start(); err != nil {
×
2264
                                startErr = err
×
2265
                                return
×
2266
                        }
×
2267
                }
2268

2269
                if s.livenessMonitor != nil {
6✔
2270
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2271
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2272
                                startErr = err
×
2273
                                return
×
2274
                        }
×
2275
                }
2276

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

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

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

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

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

2312
                cleanup = cleanup.add(func() error {
3✔
2313
                        return s.peerNotifier.Stop()
×
2314
                })
×
2315
                if err := s.peerNotifier.Start(); err != nil {
3✔
2316
                        startErr = err
×
2317
                        return
×
2318
                }
×
2319

2320
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2321
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2322
                        startErr = err
×
2323
                        return
×
2324
                }
×
2325

2326
                if s.towerClientMgr != nil {
6✔
2327
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2328
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2329
                                startErr = err
×
2330
                                return
×
2331
                        }
×
2332
                }
2333

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

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

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

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

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

2364
                // htlcSwitch must be started before chainArb since the latter
2365
                // relies on htlcSwitch to deliver resolution message upon
2366
                // start.
2367
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2368
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2369
                        startErr = err
×
2370
                        return
×
2371
                }
×
2372

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

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

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

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

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

2403
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2404
                if err := s.chanRouter.Start(); err != nil {
3✔
2405
                        startErr = err
×
2406
                        return
×
2407
                }
×
2408
                // The authGossiper depends on the chanRouter and therefore
2409
                // should be started after it.
2410
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2411
                if err := s.authGossiper.Start(); err != nil {
3✔
2412
                        startErr = err
×
2413
                        return
×
2414
                }
×
2415

2416
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2417
                if err := s.invoices.Start(); err != nil {
3✔
2418
                        startErr = err
×
2419
                        return
×
2420
                }
×
2421

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

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

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

2440
                cleanup.add(func() error {
3✔
2441
                        s.missionController.StopStoreTickers()
×
2442
                        return nil
×
2443
                })
×
2444
                s.missionController.RunStoreTickers()
3✔
2445

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

2478
                // chanSubSwapper must be started after the `channelNotifier`
2479
                // because it depends on channel events as a synchronization
2480
                // point.
2481
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2482
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2483
                        startErr = err
×
2484
                        return
×
2485
                }
×
2486

2487
                if s.torController != nil {
3✔
2488
                        cleanup = cleanup.add(s.torController.Stop)
×
2489
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2490
                                startErr = err
×
2491
                                return
×
2492
                        }
×
2493
                }
2494

2495
                if s.natTraversal != nil {
3✔
2496
                        s.wg.Add(1)
×
2497
                        go s.watchExternalIP()
×
2498
                }
×
2499

2500
                // Start connmgr last to prevent connections before init.
2501
                cleanup = cleanup.add(func() error {
3✔
2502
                        s.connMgr.Stop()
×
2503
                        return nil
×
2504
                })
×
2505

2506
                // RESOLVE: s.connMgr.Start() is called here, but
2507
                // brontide.NewListener() is called in newServer. This means
2508
                // that we are actually listening and partially accepting
2509
                // inbound connections even before the connMgr starts.
2510
                //
2511
                // TODO(yy): move the log into the connMgr's `Start` method.
2512
                srvrLog.Info("connMgr starting...")
3✔
2513
                s.connMgr.Start()
3✔
2514
                srvrLog.Debug("connMgr started")
3✔
2515

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

2535
                        peerAddr := &lnwire.NetAddress{
3✔
2536
                                IdentityKey: parsedPubkey,
3✔
2537
                                Address:     addr,
3✔
2538
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2539
                        }
3✔
2540

3✔
2541
                        err = s.ConnectToPeer(
3✔
2542
                                peerAddr, true,
3✔
2543
                                s.cfg.ConnectionTimeout,
3✔
2544
                        )
3✔
2545
                        if err != nil {
3✔
2546
                                startErr = fmt.Errorf("unable to connect to "+
×
2547
                                        "peer address provided as a config "+
×
2548
                                        "option: %v", err)
×
2549
                                return
×
2550
                        }
×
2551
                }
2552

2553
                // Subscribe to NodeAnnouncements that advertise new addresses
2554
                // our persistent peers.
2555
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2556
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2557
                                "addr: %v", err)
×
2558

×
2559
                        startErr = err
×
2560
                        return
×
2561
                }
×
2562

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

×
2572
                        startErr = err
×
2573
                        return
×
2574
                }
×
2575

2576
                if err := s.establishPersistentConnections(); err != nil {
3✔
2577
                        srvrLog.Errorf("Failed to establish persistent "+
×
2578
                                "connections: %v", err)
×
2579
                }
×
2580

2581
                // setSeedList is a helper function that turns multiple DNS seed
2582
                // server tuples from the command line or config file into the
2583
                // data structure we need and does a basic formal sanity check
2584
                // in the process.
2585
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2586
                        if len(tuples) == 0 {
×
2587
                                return
×
2588
                        }
×
2589

2590
                        result := make([][2]string, len(tuples))
×
2591
                        for idx, tuple := range tuples {
×
2592
                                tuple = strings.TrimSpace(tuple)
×
2593
                                if len(tuple) == 0 {
×
2594
                                        return
×
2595
                                }
×
2596

2597
                                servers := strings.Split(tuple, ",")
×
2598
                                if len(servers) > 2 || len(servers) == 0 {
×
2599
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2600
                                                "seed tuple: %v", servers)
×
2601
                                        return
×
2602
                                }
×
2603

2604
                                copy(result[idx][:], servers)
×
2605
                        }
2606

2607
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2608
                }
2609

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

2637
                // If network bootstrapping hasn't been disabled, then we'll
2638
                // configure the set of active bootstrappers, and launch a
2639
                // dedicated goroutine to maintain a set of persistent
2640
                // connections.
2641
                if !s.cfg.NoNetBootstrap {
6✔
2642
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2643
                        if err != nil {
3✔
2644
                                startErr = err
×
2645
                                return
×
2646
                        }
×
2647

2648
                        s.wg.Add(1)
3✔
2649
                        go s.peerBootstrapper(
3✔
2650
                                ctx, defaultMinPeers, bootstrappers,
3✔
2651
                        )
3✔
2652
                } else {
3✔
2653
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2654
                }
3✔
2655

2656
                // Start the blockbeat after all other subsystems have been
2657
                // started so they are ready to receive new blocks.
2658
                cleanup = cleanup.add(func() error {
3✔
2659
                        s.blockbeatDispatcher.Stop()
×
2660
                        return nil
×
2661
                })
×
2662
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2663
                        startErr = err
×
2664
                        return
×
2665
                }
×
2666

2667
                // Set the active flag now that we've completed the full
2668
                // startup.
2669
                atomic.StoreInt32(&s.active, 1)
3✔
2670
        })
2671

2672
        if startErr != nil {
3✔
2673
                cleanup.run()
×
2674
        }
×
2675
        return startErr
3✔
2676
}
2677

2678
// Stop gracefully shutsdown the main daemon server. This function will signal
2679
// any active goroutines, or helper objects to exit, then blocks until they've
2680
// all successfully exited. Additionally, any/all listeners are closed.
2681
// NOTE: This function is safe for concurrent access.
2682
func (s *server) Stop() error {
3✔
2683
        s.stop.Do(func() {
6✔
2684
                atomic.StoreInt32(&s.stopping, 1)
3✔
2685

3✔
2686
                ctx := context.Background()
3✔
2687

3✔
2688
                close(s.quit)
3✔
2689

3✔
2690
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2691
                s.connMgr.Stop()
3✔
2692

3✔
2693
                // Stop dispatching blocks to other systems immediately.
3✔
2694
                s.blockbeatDispatcher.Stop()
3✔
2695

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

2758
                // Update channel.backup file. Make sure to do it before
2759
                // stopping chanSubSwapper.
2760
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2761
                        ctx, s.chanStateDB, s.addrSource,
3✔
2762
                )
3✔
2763
                if err != nil {
3✔
2764
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2765
                                err)
×
2766
                } else {
3✔
2767
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2768
                        if err != nil {
6✔
2769
                                srvrLog.Warnf("Manual update of channel "+
3✔
2770
                                        "backup failed: %v", err)
3✔
2771
                        }
3✔
2772
                }
2773

2774
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2775
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2776
                }
×
2777
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2778
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2779
                }
×
2780
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2781
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2782
                                err)
×
2783
                }
×
2784
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2785
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2786
                                err)
×
2787
                }
×
2788
                s.missionController.StopStoreTickers()
3✔
2789

3✔
2790
                // Disconnect from each active peers to ensure that
3✔
2791
                // peerTerminationWatchers signal completion to each peer.
3✔
2792
                for _, peer := range s.Peers() {
6✔
2793
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2794
                        if err != nil {
3✔
2795
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2796
                                        "received error: %v", peer.IdentityKey(),
×
2797
                                        err,
×
2798
                                )
×
2799
                        }
×
2800
                }
2801

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

2813
                if s.hostAnn != nil {
3✔
2814
                        if err := s.hostAnn.Stop(); err != nil {
×
2815
                                srvrLog.Warnf("unable to shut down host "+
×
2816
                                        "annoucner: %v", err)
×
2817
                        }
×
2818
                }
2819

2820
                if s.livenessMonitor != nil {
6✔
2821
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2822
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2823
                                        "monitor: %v", err)
×
2824
                        }
×
2825
                }
2826

2827
                // Wait for all lingering goroutines to quit.
2828
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2829
                s.wg.Wait()
3✔
2830

3✔
2831
                srvrLog.Debug("Stopping buffer pools...")
3✔
2832
                s.sigPool.Stop()
3✔
2833
                s.writePool.Stop()
3✔
2834
                s.readPool.Stop()
3✔
2835
        })
2836

2837
        return nil
3✔
2838
}
2839

2840
// Stopped returns true if the server has been instructed to shutdown.
2841
// NOTE: This function is safe for concurrent access.
2842
func (s *server) Stopped() bool {
3✔
2843
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2844
}
3✔
2845

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

×
2858
        externalIPs := make([]string, 0, len(ports))
×
2859
        for _, port := range ports {
×
2860
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2861
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2862
                        continue
×
2863
                }
2864

2865
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2866
                externalIPs = append(externalIPs, hostIP)
×
2867
        }
2868

2869
        return externalIPs, nil
×
2870
}
2871

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

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

×
2896
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2897
        // up by the server.
×
2898
        defer s.removePortForwarding()
×
2899

×
2900
        // Keep track of the external IPs set by the user to avoid replacing
×
2901
        // them when detecting a new IP.
×
2902
        ipsSetByUser := make(map[string]struct{})
×
2903
        for _, ip := range s.cfg.ExternalIPs {
×
2904
                ipsSetByUser[ip.String()] = struct{}{}
×
2905
        }
×
2906

2907
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2908

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

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

2939
                        if ip.Equal(s.lastDetectedIP) {
×
2940
                                continue
×
2941
                        }
2942

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

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

2960
                                newAddrs = append(newAddrs, addr)
×
2961
                        }
2962

2963
                        // Skip the update if we weren't able to resolve any of
2964
                        // the new addresses.
2965
                        if len(newAddrs) == 0 {
×
2966
                                srvrLog.Debug("Skipping node announcement " +
×
2967
                                        "update due to not being able to " +
×
2968
                                        "resolve any new addresses")
×
2969
                                continue
×
2970
                        }
2971

2972
                        // Now, we'll need to update the addresses in our node's
2973
                        // announcement in order to propagate the update
2974
                        // throughout the network. We'll only include addresses
2975
                        // that have a different IP from the previous one, as
2976
                        // the previous IP is no longer valid.
2977
                        currentNodeAnn := s.getNodeAnnouncement()
×
2978

×
2979
                        for _, addr := range currentNodeAnn.Addresses {
×
2980
                                host, _, err := net.SplitHostPort(addr.String())
×
2981
                                if err != nil {
×
2982
                                        srvrLog.Debugf("Unable to determine "+
×
2983
                                                "host from address %v: %v",
×
2984
                                                addr, err)
×
2985
                                        continue
×
2986
                                }
2987

2988
                                // We'll also make sure to include external IPs
2989
                                // set manually by the user.
2990
                                _, setByUser := ipsSetByUser[addr.String()]
×
2991
                                if setByUser || host != s.lastDetectedIP.String() {
×
2992
                                        newAddrs = append(newAddrs, addr)
×
2993
                                }
×
2994
                        }
2995

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

3008
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3009
                        if err != nil {
×
3010
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3011
                                        "announcement to peers: %v", err)
×
3012
                                continue
×
3013
                        }
3014

3015
                        // Finally, update the last IP seen to the current one.
3016
                        s.lastDetectedIP = ip
×
3017
                case <-s.quit:
×
3018
                        break out
×
3019
                }
3020
        }
3021
}
3022

3023
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3024
// based on the server, and currently active bootstrap mechanisms as defined
3025
// within the current configuration.
3026
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
3027
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
3028

3✔
3029
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3030

3✔
3031
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
3032
        // this can be used by default if we've already partially seeded the
3✔
3033
        // network.
3✔
3034
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
3035
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
3✔
3036
        if err != nil {
3✔
3037
                return nil, err
×
3038
        }
×
3039
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
3040

3✔
3041
        // If this isn't simnet mode, then one of our additional bootstrapping
3✔
3042
        // sources will be the set of running DNS seeds.
3✔
3043
        if !s.cfg.Bitcoin.SimNet {
6✔
3044
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
3✔
3045

3✔
3046
                // If we have a set of DNS seeds for this chain, then we'll add
3✔
3047
                // it as an additional bootstrapping source.
3✔
3048
                if ok {
3✔
3049
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3050
                                "seeds: %v", dnsSeeds)
×
3051

×
3052
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3053
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3054
                        )
×
3055
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3056
                }
×
3057
        }
3058

3059
        return bootStrappers, nil
3✔
3060
}
3061

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

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

3✔
3074
        // We should ignore ourselves from bootstrapping.
3✔
3075
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3076
        ignore[selfKey] = struct{}{}
3✔
3077

3✔
3078
        // Ignore all connected peers.
3✔
3079
        for _, peer := range s.peersByPub {
3✔
3080
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3081
                ignore[nID] = struct{}{}
×
3082
        }
×
3083

3084
        // Ignore all persistent peers as they have a dedicated reconnecting
3085
        // process.
3086
        for pubKeyStr := range s.persistentPeers {
3✔
3087
                var nID autopilot.NodeID
×
3088
                copy(nID[:], []byte(pubKeyStr))
×
3089
                ignore[nID] = struct{}{}
×
3090
        }
×
3091

3092
        return ignore
3✔
3093
}
3094

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

3✔
3103
        defer s.wg.Done()
3✔
3104

3✔
3105
        // Before we continue, init the ignore peers map.
3✔
3106
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3107

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

3✔
3112
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3113
        // peers.
3✔
3114
        //
3✔
3115
        // We'll use a 15 second backoff, and double the time every time an
3✔
3116
        // epoch fails up to a ceiling.
3✔
3117
        backOff := time.Second * 15
3✔
3118

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

3✔
3124
        // We'll use the number of attempts and errors to determine if we need
3✔
3125
        // to increase the time between discovery epochs.
3✔
3126
        var epochErrors uint32 // To be used atomically.
3✔
3127
        var epochAttempts uint32
3✔
3128

3✔
3129
        for {
6✔
3130
                select {
3✔
3131
                // The ticker has just woken us up, so we'll need to check if
3132
                // we need to attempt to connect our to any more peers.
3133
                case <-sampleTicker.C:
×
3134
                        // Obtain the current number of peers, so we can gauge
×
3135
                        // if we need to sample more peers or not.
×
3136
                        s.mu.RLock()
×
3137
                        numActivePeers := uint32(len(s.peersByPub))
×
3138
                        s.mu.RUnlock()
×
3139

×
3140
                        // If we have enough peers, then we can loop back
×
3141
                        // around to the next round as we're done here.
×
3142
                        if numActivePeers >= numTargetPeers {
×
3143
                                continue
×
3144
                        }
3145

3146
                        // If all of our attempts failed during this last back
3147
                        // off period, then will increase our backoff to 5
3148
                        // minute ceiling to avoid an excessive number of
3149
                        // queries
3150
                        //
3151
                        // TODO(roasbeef): add reverse policy too?
3152

3153
                        if epochAttempts > 0 &&
×
3154
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3155

×
3156
                                sampleTicker.Stop()
×
3157

×
3158
                                backOff *= 2
×
3159
                                if backOff > bootstrapBackOffCeiling {
×
3160
                                        backOff = bootstrapBackOffCeiling
×
3161
                                }
×
3162

3163
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3164
                                        "%v", backOff)
×
3165
                                sampleTicker = time.NewTicker(backOff)
×
3166
                                continue
×
3167
                        }
3168

3169
                        atomic.StoreUint32(&epochErrors, 0)
×
3170
                        epochAttempts = 0
×
3171

×
3172
                        // Since we know need more peers, we'll compute the
×
3173
                        // exact number we need to reach our threshold.
×
3174
                        numNeeded := numTargetPeers - numActivePeers
×
3175

×
3176
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3177
                                "peers", numNeeded)
×
3178

×
3179
                        // With the number of peers we need calculated, we'll
×
3180
                        // query the network bootstrappers to sample a set of
×
3181
                        // random addrs for us.
×
3182
                        //
×
3183
                        // Before we continue, get a copy of the ignore peers
×
3184
                        // map.
×
3185
                        ignoreList = s.createBootstrapIgnorePeers()
×
3186

×
3187
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3188
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3189
                        )
×
3190
                        if err != nil {
×
3191
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3192
                                        "peers: %v", err)
×
3193
                                continue
×
3194
                        }
3195

3196
                        // Finally, we'll launch a new goroutine for each
3197
                        // prospective peer candidates.
3198
                        for _, addr := range peerAddrs {
×
3199
                                epochAttempts++
×
3200

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

3215
                                                srvrLog.Errorf("Unable to "+
×
3216
                                                        "connect to %v: %v",
×
3217
                                                        a, err)
×
3218
                                                atomic.AddUint32(&epochErrors, 1)
×
3219
                                        case <-s.quit:
×
3220
                                        }
3221
                                }(addr)
3222
                        }
3223
                case <-s.quit:
3✔
3224
                        return
3✔
3225
                }
3226
        }
3227
}
3228

3229
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3230
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3231
// query back off each time we encounter a failure.
3232
const bootstrapBackOffCeiling = time.Minute * 5
3233

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

3✔
3241
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3242
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3243

3✔
3244
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3245
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3246
        var delaySignal <-chan time.Time
3✔
3247
        delayTime := time.Second * 2
3✔
3248

3✔
3249
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3250
        // then the main peer bootstrap logic.
3✔
3251
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3252

3✔
3253
        for attempts := 0; ; attempts++ {
6✔
3254
                // Check if the server has been requested to shut down in order
3✔
3255
                // to prevent blocking.
3✔
3256
                if s.Stopped() {
3✔
3257
                        return
×
3258
                }
×
3259

3260
                // We can exit our aggressive initial peer bootstrapping stage
3261
                // if we've reached out target number of peers.
3262
                s.mu.RLock()
3✔
3263
                numActivePeers := uint32(len(s.peersByPub))
3✔
3264
                s.mu.RUnlock()
3✔
3265

3✔
3266
                if numActivePeers >= numTargetPeers {
6✔
3267
                        return
3✔
3268
                }
3✔
3269

3270
                if attempts > 0 {
4✔
3271
                        srvrLog.Debugf("Waiting %v before trying to locate "+
1✔
3272
                                "bootstrap peers (attempt #%v)", delayTime,
1✔
3273
                                attempts)
1✔
3274

1✔
3275
                        // We've completed at least one iterating and haven't
1✔
3276
                        // finished, so we'll start to insert a delay period
1✔
3277
                        // between each attempt.
1✔
3278
                        delaySignal = time.After(delayTime)
1✔
3279
                        select {
1✔
3280
                        case <-delaySignal:
1✔
3281
                        case <-s.quit:
×
3282
                                return
×
3283
                        }
3284

3285
                        // After our delay, we'll double the time we wait up to
3286
                        // the max back off period.
3287
                        delayTime *= 2
1✔
3288
                        if delayTime > backOffCeiling {
1✔
3289
                                delayTime = backOffCeiling
×
3290
                        }
×
3291
                }
3292

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

3305
                // Then, we'll attempt to establish a connection to the
3306
                // different peer addresses retrieved by our bootstrappers.
3307
                var wg sync.WaitGroup
3✔
3308
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3309
                        wg.Add(1)
3✔
3310
                        go func(addr *lnwire.NetAddress) {
6✔
3311
                                defer wg.Done()
3✔
3312

3✔
3313
                                errChan := make(chan error, 1)
3✔
3314
                                go s.connectToPeer(
3✔
3315
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3316
                                )
3✔
3317

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

3341
                wg.Wait()
3✔
3342
        }
3343
}
3344

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

3357
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3358
        if err != nil {
×
3359
                return err
×
3360
        }
×
3361

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

×
3374
        switch {
×
3375
        case s.cfg.Tor.V2:
×
3376
                onionCfg.Type = tor.V2
×
3377
        case s.cfg.Tor.V3:
×
3378
                onionCfg.Type = tor.V3
×
3379
        }
3380

3381
        addr, err := s.torController.AddOnion(onionCfg)
×
3382
        if err != nil {
×
3383
                return err
×
3384
        }
×
3385

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

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

3416
        return nil
×
3417
}
3418

3419
// findChannel finds a channel given a public key and ChannelID. It is an
3420
// optimization that is quicker than seeking for a channel given only the
3421
// ChannelID.
3422
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3423
        *channeldb.OpenChannel, error) {
3✔
3424

3✔
3425
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3426
        if err != nil {
3✔
3427
                return nil, err
×
3428
        }
×
3429

3430
        for _, channel := range nodeChans {
6✔
3431
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3432
                        return channel, nil
3✔
3433
                }
3✔
3434
        }
3435

3436
        return nil, fmt.Errorf("unable to find channel")
3✔
3437
}
3438

3439
// getNodeAnnouncement fetches the current, fully signed node announcement.
3440
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3441
        s.mu.Lock()
3✔
3442
        defer s.mu.Unlock()
3✔
3443

3✔
3444
        return *s.currentNodeAnn
3✔
3445
}
3✔
3446

3447
// genNodeAnnouncement generates and returns the current fully signed node
3448
// announcement. The time stamp of the announcement will be updated in order
3449
// to ensure it propagates through the network.
3450
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3451
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3452

3✔
3453
        s.mu.Lock()
3✔
3454
        defer s.mu.Unlock()
3✔
3455

3✔
3456
        // Create a shallow copy of the current node announcement to work on.
3✔
3457
        // This ensures the original announcement remains unchanged
3✔
3458
        // until the new announcement is fully signed and valid.
3✔
3459
        newNodeAnn := *s.currentNodeAnn
3✔
3460

3✔
3461
        // First, try to update our feature manager with the updated set of
3✔
3462
        // features.
3✔
3463
        if features != nil {
6✔
3464
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3465
                        feature.SetNodeAnn: features,
3✔
3466
                }
3✔
3467
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3468
                if err != nil {
6✔
3469
                        return lnwire.NodeAnnouncement{}, err
3✔
3470
                }
3✔
3471

3472
                // If we could successfully update our feature manager, add
3473
                // an update modifier to include these new features to our
3474
                // set.
3475
                modifiers = append(
3✔
3476
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3477
                )
3✔
3478
        }
3479

3480
        // Always update the timestamp when refreshing to ensure the update
3481
        // propagates.
3482
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3483

3✔
3484
        // Apply the requested changes to the node announcement.
3✔
3485
        for _, modifier := range modifiers {
6✔
3486
                modifier(&newNodeAnn)
3✔
3487
        }
3✔
3488

3489
        // Sign a new update after applying all of the passed modifiers.
3490
        err := netann.SignNodeAnnouncement(
3✔
3491
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3492
        )
3✔
3493
        if err != nil {
3✔
3494
                return lnwire.NodeAnnouncement{}, err
×
3495
        }
×
3496

3497
        // If signing succeeds, update the current announcement.
3498
        *s.currentNodeAnn = newNodeAnn
3✔
3499

3✔
3500
        return *s.currentNodeAnn, nil
3✔
3501
}
3502

3503
// updateAndBroadcastSelfNode generates a new node announcement
3504
// applying the giving modifiers and updating the time stamp
3505
// to ensure it propagates through the network. Then it broadcasts
3506
// it to the network.
3507
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3508
        features *lnwire.RawFeatureVector,
3509
        modifiers ...netann.NodeAnnModifier) error {
3✔
3510

3✔
3511
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3512
        if err != nil {
6✔
3513
                return fmt.Errorf("unable to generate new node "+
3✔
3514
                        "announcement: %v", err)
3✔
3515
        }
3✔
3516

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

3525
        selfNode.HaveNodeAnnouncement = true
3✔
3526
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3527
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3528
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3529
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3530
        selfNode.Color = newNodeAnn.RGBColor
3✔
3531
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3532

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

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

3539
        // Finally, propagate it to the nodes in the network.
3540
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3541
        if err != nil {
3✔
3542
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3543
                        "announcement to peers: %v", err)
×
3544
                return err
×
3545
        }
×
3546

3547
        return nil
3✔
3548
}
3549

3550
type nodeAddresses struct {
3551
        pubKey    *btcec.PublicKey
3552
        addresses []net.Addr
3553
}
3554

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

3✔
3565
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3566
        // attempt to connect to based on our set of previous connections. Set
3✔
3567
        // the reconnection port to the default peer port.
3✔
3568
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3569
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3570
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3571
        }
×
3572

3573
        for _, node := range linkNodes {
6✔
3574
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3575
                nodeAddrs := &nodeAddresses{
3✔
3576
                        pubKey:    node.IdentityPub,
3✔
3577
                        addresses: node.Addresses,
3✔
3578
                }
3✔
3579
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3580
        }
3✔
3581

3582
        // After checking our previous connections for addresses to connect to,
3583
        // iterate through the nodes in our channel graph to find addresses
3584
        // that have been added via NodeAnnouncement messages.
3585
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3586
        // each of the nodes.
3587
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3588
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3589

3✔
3590
                // If the remote party has announced the channel to us, but we
3✔
3591
                // haven't yet, then we won't have a policy. However, we don't
3✔
3592
                // need this to connect to the peer, so we'll log it and move on.
3✔
3593
                if !havePolicy {
3✔
3594
                        srvrLog.Warnf("No channel policy found for "+
×
3595
                                "ChannelPoint(%v): ", chanPoint)
×
3596
                }
×
3597

3598
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3599

3✔
3600
                // Add all unique addresses from channel
3✔
3601
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3602
                // connect to for this peer.
3✔
3603
                addrSet := make(map[string]net.Addr)
3✔
3604
                for _, addr := range channelPeer.Addresses {
6✔
3605
                        switch addr.(type) {
3✔
3606
                        case *net.TCPAddr:
3✔
3607
                                addrSet[addr.String()] = addr
3✔
3608

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

3618
                // If this peer is also recorded as a link node, we'll add any
3619
                // additional addresses that have not already been selected.
3620
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3621
                if ok {
6✔
3622
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3623
                                switch lnAddress.(type) {
3✔
3624
                                case *net.TCPAddr:
3✔
3625
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3626

3627
                                // We'll only attempt to connect to Tor
3628
                                // addresses if Tor outbound support is enabled.
3629
                                case *tor.OnionAddr:
×
3630
                                        if s.cfg.Tor.Active {
×
3631
                                                addrSet[lnAddress.String()] = lnAddress
×
3632
                                        }
×
3633
                                }
3634
                        }
3635
                }
3636

3637
                // Construct a slice of the deduped addresses.
3638
                var addrs []net.Addr
3✔
3639
                for _, addr := range addrSet {
6✔
3640
                        addrs = append(addrs, addr)
3✔
3641
                }
3✔
3642

3643
                n := &nodeAddresses{
3✔
3644
                        addresses: addrs,
3✔
3645
                }
3✔
3646
                n.pubKey, err = channelPeer.PubKey()
3✔
3647
                if err != nil {
3✔
3648
                        return err
×
3649
                }
×
3650

3651
                nodeAddrsMap[pubStr] = n
3✔
3652
                return nil
3✔
3653
        })
3654
        if err != nil {
3✔
3655
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3656
                        "%v", err)
×
3657

×
3658
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3659
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3660

×
3661
                        return err
×
3662
                }
×
3663
        }
3664

3665
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3666
                len(nodeAddrsMap))
3✔
3667

3✔
3668
        // Acquire and hold server lock until all persistent connection requests
3✔
3669
        // have been recorded and sent to the connection manager.
3✔
3670
        s.mu.Lock()
3✔
3671
        defer s.mu.Unlock()
3✔
3672

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

3687
                for _, address := range nodeAddr.addresses {
6✔
3688
                        // Create a wrapper address which couples the IP and
3✔
3689
                        // the pubkey so the brontide authenticated connection
3✔
3690
                        // can be established.
3✔
3691
                        lnAddr := &lnwire.NetAddress{
3✔
3692
                                IdentityKey: nodeAddr.pubKey,
3✔
3693
                                Address:     address,
3✔
3694
                        }
3✔
3695

3✔
3696
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3697
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3698
                }
3✔
3699

3700
                // We'll connect to the first 10 peers immediately, then
3701
                // randomly stagger any remaining connections if the
3702
                // stagger initial reconnect flag is set. This ensures
3703
                // that mobile nodes or nodes with a small number of
3704
                // channels obtain connectivity quickly, but larger
3705
                // nodes are able to disperse the costs of connecting to
3706
                // all peers at once.
3707
                if numOutboundConns < numInstantInitReconnect ||
3✔
3708
                        !s.cfg.StaggerInitialReconnect {
6✔
3709

3✔
3710
                        go s.connectToPersistentPeer(pubStr)
3✔
3711
                } else {
3✔
3712
                        go s.delayInitialReconnect(pubStr)
×
3713
                }
×
3714

3715
                numOutboundConns++
3✔
3716
        }
3717

3718
        return nil
3✔
3719
}
3720

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

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

3✔
3740
        s.mu.Lock()
3✔
3741
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3742
                delete(s.persistentPeers, pubKeyStr)
3✔
3743
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3744
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3745
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3746
                s.mu.Unlock()
3✔
3747

3✔
3748
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3749
                        "peer has no open channels", compressedPubKey)
3✔
3750

3✔
3751
                return
3✔
3752
        }
3✔
3753
        s.mu.Unlock()
3✔
3754
}
3755

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

3773
// BroadcastMessage sends a request to the server to broadcast a set of
3774
// messages to all peers other than the one specified by the `skips` parameter.
3775
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3776
// the target peers.
3777
//
3778
// NOTE: This function is safe for concurrent access.
3779
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3780
        msgs ...lnwire.Message) error {
3✔
3781

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

3796
                peers = append(peers, sPeer)
3✔
3797
        }
3798
        s.mu.RUnlock()
3✔
3799

3✔
3800
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3801
        // all messages to each of peers.
3✔
3802
        var wg sync.WaitGroup
3✔
3803
        for _, sPeer := range peers {
6✔
3804
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3805
                        sPeer.PubKey())
3✔
3806

3✔
3807
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3808
                wg.Add(1)
3✔
3809
                s.wg.Add(1)
3✔
3810
                go func(p lnpeer.Peer) {
6✔
3811
                        defer s.wg.Done()
3✔
3812
                        defer wg.Done()
3✔
3813

3✔
3814
                        p.SendMessageLazy(false, msgs...)
3✔
3815
                }(sPeer)
3✔
3816
        }
3817

3818
        // Wait for all messages to have been dispatched before returning to
3819
        // caller.
3820
        wg.Wait()
3✔
3821

3✔
3822
        return nil
3✔
3823
}
3824

3825
// NotifyWhenOnline can be called by other subsystems to get notified when a
3826
// particular peer comes online. The peer itself is sent across the peerChan.
3827
//
3828
// NOTE: This function is safe for concurrent access.
3829
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3830
        peerChan chan<- lnpeer.Peer) {
3✔
3831

3✔
3832
        s.mu.Lock()
3✔
3833

3✔
3834
        // Compute the target peer's identifier.
3✔
3835
        pubStr := string(peerKey[:])
3✔
3836

3✔
3837
        // Check if peer is connected.
3✔
3838
        peer, ok := s.peersByPub[pubStr]
3✔
3839
        if ok {
6✔
3840
                // Unlock here so that the mutex isn't held while we are
3✔
3841
                // waiting for the peer to become active.
3✔
3842
                s.mu.Unlock()
3✔
3843

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

3859
                // Connected, can return early.
3860
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3861

3✔
3862
                select {
3✔
3863
                case peerChan <- peer:
3✔
3864
                case <-s.quit:
×
3865
                }
3866

3867
                return
3✔
3868
        }
3869

3870
        // Not connected, store this listener such that it can be notified when
3871
        // the peer comes online.
3872
        s.peerConnectedListeners[pubStr] = append(
3✔
3873
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3874
        )
3✔
3875
        s.mu.Unlock()
3✔
3876
}
3877

3878
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3879
// the given public key has been disconnected. The notification is signaled by
3880
// closing the channel returned.
3881
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3882
        s.mu.Lock()
3✔
3883
        defer s.mu.Unlock()
3✔
3884

3✔
3885
        c := make(chan struct{})
3✔
3886

3✔
3887
        // If the peer is already offline, we can immediately trigger the
3✔
3888
        // notification.
3✔
3889
        peerPubKeyStr := string(peerPubKey[:])
3✔
3890
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3891
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3892
                close(c)
×
3893
                return c
×
3894
        }
×
3895

3896
        // Otherwise, the peer is online, so we'll keep track of the channel to
3897
        // trigger the notification once the server detects the peer
3898
        // disconnects.
3899
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3900
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3901
        )
3✔
3902

3✔
3903
        return c
3✔
3904
}
3905

3906
// FindPeer will return the peer that corresponds to the passed in public key.
3907
// This function is used by the funding manager, allowing it to update the
3908
// daemon's local representation of the remote peer.
3909
//
3910
// NOTE: This function is safe for concurrent access.
3911
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3912
        s.mu.RLock()
3✔
3913
        defer s.mu.RUnlock()
3✔
3914

3✔
3915
        pubStr := string(peerKey.SerializeCompressed())
3✔
3916

3✔
3917
        return s.findPeerByPubStr(pubStr)
3✔
3918
}
3✔
3919

3920
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3921
// which should be a string representation of the peer's serialized, compressed
3922
// public key.
3923
//
3924
// NOTE: This function is safe for concurrent access.
3925
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3926
        s.mu.RLock()
3✔
3927
        defer s.mu.RUnlock()
3✔
3928

3✔
3929
        return s.findPeerByPubStr(pubStr)
3✔
3930
}
3✔
3931

3932
// findPeerByPubStr is an internal method that retrieves the specified peer from
3933
// the server's internal state using.
3934
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3935
        peer, ok := s.peersByPub[pubStr]
3✔
3936
        if !ok {
6✔
3937
                return nil, ErrPeerNotConnected
3✔
3938
        }
3✔
3939

3940
        return peer, nil
3✔
3941
}
3942

3943
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3944
// exponential backoff. If no previous backoff was known, the default is
3945
// returned.
3946
func (s *server) nextPeerBackoff(pubStr string,
3947
        startTime time.Time) time.Duration {
3✔
3948

3✔
3949
        // Now, determine the appropriate backoff to use for the retry.
3✔
3950
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3951
        if !ok {
6✔
3952
                // If an existing backoff was unknown, use the default.
3✔
3953
                return s.cfg.MinBackoff
3✔
3954
        }
3✔
3955

3956
        // If the peer failed to start properly, we'll just use the previous
3957
        // backoff to compute the subsequent randomized exponential backoff
3958
        // duration. This will roughly double on average.
3959
        if startTime.IsZero() {
3✔
3960
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3961
        }
×
3962

3963
        // The peer succeeded in starting. If the connection didn't last long
3964
        // enough to be considered stable, we'll continue to back off retries
3965
        // with this peer.
3966
        connDuration := time.Since(startTime)
3✔
3967
        if connDuration < defaultStableConnDuration {
6✔
3968
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3969
        }
3✔
3970

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

3981
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3982
        // the stable connection lasted much longer than our previous backoff.
3983
        // To reward such good behavior, we'll reconnect after the default
3984
        // timeout.
3985
        return s.cfg.MinBackoff
×
3986
}
3987

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

×
3998
        // The connection that comes from the node with a "smaller" pubkey
×
3999
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4000
        // should drop our established connection.
×
4001
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4002
}
×
4003

4004
// InboundPeerConnected initializes a new peer in response to a new inbound
4005
// connection.
4006
//
4007
// NOTE: This function is safe for concurrent access.
4008
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4009
        // Exit early if we have already been instructed to shutdown, this
3✔
4010
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4011
        if s.Stopped() {
3✔
4012
                return
×
4013
        }
×
4014

4015
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4016
        pubSer := nodePub.SerializeCompressed()
3✔
4017
        pubStr := string(pubSer)
3✔
4018

3✔
4019
        var pubBytes [33]byte
3✔
4020
        copy(pubBytes[:], pubSer)
3✔
4021

3✔
4022
        s.mu.Lock()
3✔
4023
        defer s.mu.Unlock()
3✔
4024

3✔
4025
        // If we already have an outbound connection to this peer, then ignore
3✔
4026
        // this new connection.
3✔
4027
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4028
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4029
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4030
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4031

3✔
4032
                conn.Close()
3✔
4033
                return
3✔
4034
        }
3✔
4035

4036
        // If we already have a valid connection that is scheduled to take
4037
        // precedence once the prior peer has finished disconnecting, we'll
4038
        // ignore this connection.
4039
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4040
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4041
                        "scheduled", conn.RemoteAddr(), p)
×
4042
                conn.Close()
×
4043
                return
×
4044
        }
×
4045

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

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

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

×
4071
                        srvrLog.Warnf("Received inbound connection from "+
×
4072
                                "peer %v, but already have outbound "+
×
4073
                                "connection, dropping conn", connectedPeer)
×
4074
                        conn.Close()
×
4075
                        return
×
4076
                }
×
4077

4078
                // Otherwise, if we should drop the connection, then we'll
4079
                // disconnect our already connected peer.
4080
                srvrLog.Debugf("Disconnecting stale connection to %v",
3✔
4081
                        connectedPeer)
3✔
4082

3✔
4083
                s.cancelConnReqs(pubStr, nil)
3✔
4084

3✔
4085
                // Remove the current peer from the server's internal state and
3✔
4086
                // signal that the peer termination watcher does not need to
3✔
4087
                // execute for this peer.
3✔
4088
                s.removePeerUnsafe(connectedPeer)
3✔
4089
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4090
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4091
                        s.peerConnected(conn, nil, true)
3✔
4092
                }
3✔
4093
        }
4094
}
4095

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

4106
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4107
        pubSer := nodePub.SerializeCompressed()
3✔
4108
        pubStr := string(pubSer)
3✔
4109

3✔
4110
        var pubBytes [33]byte
3✔
4111
        copy(pubBytes[:], pubSer)
3✔
4112

3✔
4113
        s.mu.Lock()
3✔
4114
        defer s.mu.Unlock()
3✔
4115

3✔
4116
        // If we already have an inbound connection to this peer, then ignore
3✔
4117
        // this new connection.
3✔
4118
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4119
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4120
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4121
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4122

3✔
4123
                if connReq != nil {
6✔
4124
                        s.connMgr.Remove(connReq.ID())
3✔
4125
                }
3✔
4126
                conn.Close()
3✔
4127
                return
3✔
4128
        }
4129
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4130
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4131
                s.connMgr.Remove(connReq.ID())
×
4132
                conn.Close()
×
4133
                return
×
4134
        }
×
4135

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

×
4142
                if connReq != nil {
×
4143
                        s.connMgr.Remove(connReq.ID())
×
4144
                }
×
4145

4146
                conn.Close()
×
4147
                return
×
4148
        }
4149

4150
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4151
                conn.RemoteAddr())
3✔
4152

3✔
4153
        if connReq != nil {
6✔
4154
                // A successful connection was returned by the connmgr.
3✔
4155
                // Immediately cancel all pending requests, excluding the
3✔
4156
                // outbound connection we just established.
3✔
4157
                ignore := connReq.ID()
3✔
4158
                s.cancelConnReqs(pubStr, &ignore)
3✔
4159
        } else {
6✔
4160
                // This was a successful connection made by some other
3✔
4161
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4162
                s.cancelConnReqs(pubStr, nil)
3✔
4163
        }
3✔
4164

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4282
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4283
// the channelNotifier's NotifyOpenChannelEvent.
4284
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4285
        remotePub *btcec.PublicKey) {
3✔
4286

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

4293
        // Notify subscribers about this open channel event.
4294
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4295
}
4296

4297
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4298
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4299
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4300
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4301

3✔
4302
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4303
        // peer.
3✔
4304
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4305
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4306
                        "channel[%v] pending open",
×
4307
                        remotePub.SerializeCompressed(), op)
×
4308
        }
×
4309

4310
        // Notify subscribers about this event.
4311
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4312
}
4313

4314
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4315
// calls the channelNotifier's NotifyFundingTimeout.
4316
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4317
        remotePub *btcec.PublicKey) {
3✔
4318

3✔
4319
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4320
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4321
        if err != nil {
3✔
4322
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4323
                        "channel[%v] pending close",
×
4324
                        remotePub.SerializeCompressed(), op)
×
4325
        }
×
4326

4327
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4328
                // If we encounter an error while attempting to disconnect the
×
4329
                // peer, log the error.
×
4330
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4331
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4332
                }
×
4333
        }
4334

4335
        // Notify subscribers about this event.
4336
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4337
}
4338

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

3✔
4346
        brontideConn := conn.(*brontide.Conn)
3✔
4347
        addr := conn.RemoteAddr()
3✔
4348
        pubKey := brontideConn.RemotePub()
3✔
4349

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

×
4360
                // Clean up the persistent peer maps if we're dropping this
×
4361
                // connection.
×
4362
                s.bannedPersistentPeerConnection(string(pubSer))
×
4363

×
4364
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4365
                        "of restricted-access connection slots: %v.", pubSer,
×
4366
                        err)
×
4367

×
4368
                conn.Close()
×
4369

×
4370
                return
×
4371
        }
×
4372

4373
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4374
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4375

3✔
4376
        peerAddr := &lnwire.NetAddress{
3✔
4377
                IdentityKey: pubKey,
3✔
4378
                Address:     addr,
3✔
4379
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4380
        }
3✔
4381

3✔
4382
        // With the brontide connection established, we'll now craft the feature
3✔
4383
        // vectors to advertise to the remote node.
3✔
4384
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4385
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4386

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

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

4411
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4412
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4413

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

3✔
4457
                        return s.genNodeAnnouncement(nil)
3✔
4458
                },
3✔
4459

4460
                PongBuf: s.pongBuf,
4461

4462
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4463

4464
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4465

4466
                FundingManager: s.fundingMgr,
4467

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

4497
                        return clock.NewDefaultClock().Now().Before(
3✔
4498
                                EndorsementExperimentEnd,
3✔
4499
                        )
3✔
4500
                },
4501
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4502
        }
4503

4504
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4505
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4506

3✔
4507
        p := peer.NewBrontide(pCfg)
3✔
4508

3✔
4509
        // Update the access manager with the access permission for this peer.
3✔
4510
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4511

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

3✔
4515
        s.addPeer(p)
3✔
4516

3✔
4517
        // Once we have successfully added the peer to the server, we can
3✔
4518
        // delete the previous error buffer from the server's map of error
3✔
4519
        // buffers.
3✔
4520
        delete(s.peerErrors, pkStr)
3✔
4521

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

4529
// addPeer adds the passed peer to the server's global state of all active
4530
// peers.
4531
func (s *server) addPeer(p *peer.Brontide) {
3✔
4532
        if p == nil {
3✔
4533
                return
×
4534
        }
×
4535

4536
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4537

3✔
4538
        // Ignore new peers if we're shutting down.
3✔
4539
        if s.Stopped() {
3✔
4540
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4541
                        pubBytes)
×
4542
                p.Disconnect(ErrServerShuttingDown)
×
4543

×
4544
                return
×
4545
        }
×
4546

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

4552
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4553
        // be human-readable.
4554
        pubStr := string(pubBytes)
3✔
4555

3✔
4556
        s.peersByPub[pubStr] = p
3✔
4557

3✔
4558
        if p.Inbound() {
6✔
4559
                s.inboundPeers[pubStr] = p
3✔
4560
        } else {
6✔
4561
                s.outboundPeers[pubStr] = p
3✔
4562
        }
3✔
4563

4564
        // Inform the peer notifier of a peer online event so that it can be reported
4565
        // to clients listening for peer events.
4566
        var pubKey [33]byte
3✔
4567
        copy(pubKey[:], pubBytes)
3✔
4568

3✔
4569
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4570
}
4571

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

3✔
4584
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4585

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

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

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

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

3✔
4612
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4613
                return
3✔
4614
        }
3✔
4615

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

3✔
4620
        s.mu.Lock()
3✔
4621
        defer s.mu.Unlock()
3✔
4622

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

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

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

3✔
4653
        ctx := context.TODO()
3✔
4654

3✔
4655
        p.WaitForDisconnect(ready)
3✔
4656

3✔
4657
        srvrLog.Debugf("Peer %v has been disconnected", p)
3✔
4658

3✔
4659
        // If the server is exiting then we can bail out early ourselves as all
3✔
4660
        // the other sub-systems will already be shutting down.
3✔
4661
        if s.Stopped() {
6✔
4662
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4663
                return
3✔
4664
        }
3✔
4665

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

3✔
4672
        pubKey := p.IdentityKey()
3✔
4673

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

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

4688
        for _, link := range links {
6✔
4689
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4690
        }
3✔
4691

4692
        s.mu.Lock()
3✔
4693
        defer s.mu.Unlock()
3✔
4694

3✔
4695
        // If there were any notification requests for when this peer
3✔
4696
        // disconnected, we can trigger them now.
3✔
4697
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4698
        pubStr := string(pubKey.SerializeCompressed())
3✔
4699
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4700
                close(offlineChan)
3✔
4701
        }
3✔
4702
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4703

3✔
4704
        // If the server has already removed this peer, we can short circuit the
3✔
4705
        // peer termination watcher and skip cleanup.
3✔
4706
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4707
                delete(s.ignorePeerTermination, p)
3✔
4708

3✔
4709
                pubKey := p.PubKey()
3✔
4710
                pubStr := string(pubKey[:])
3✔
4711

3✔
4712
                // If a connection callback is present, we'll go ahead and
3✔
4713
                // execute it now that previous peer has fully disconnected. If
3✔
4714
                // the callback is not present, this likely implies the peer was
3✔
4715
                // purposefully disconnected via RPC, and that no reconnect
3✔
4716
                // should be attempted.
3✔
4717
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4718
                if ok {
6✔
4719
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4720
                        connCallback()
3✔
4721
                }
3✔
4722
                return
3✔
4723
        }
4724

4725
        // First, cleanup any remaining state the server has regarding the peer
4726
        // in question.
4727
        s.removePeerUnsafe(p)
3✔
4728

3✔
4729
        // Next, check to see if this is a persistent peer or not.
3✔
4730
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4731
                return
3✔
4732
        }
3✔
4733

4734
        // Get the last address that we used to connect to the peer.
4735
        addrs := []net.Addr{
3✔
4736
                p.NetAddress().Address,
3✔
4737
        }
3✔
4738

3✔
4739
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4740
        // reconnection purposes.
3✔
4741
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4742
        switch {
3✔
4743
        // We found advertised addresses, so use them.
4744
        case err == nil:
3✔
4745
                addrs = advertisedAddrs
3✔
4746

4747
        // The peer doesn't have an advertised address.
4748
        case err == errNoAdvertisedAddr:
3✔
4749
                // If it is an outbound peer then we fall back to the existing
3✔
4750
                // peer address.
3✔
4751
                if !p.Inbound() {
6✔
4752
                        break
3✔
4753
                }
4754

4755
                // Fall back to the existing peer address if
4756
                // we're not accepting connections over Tor.
4757
                if s.torController == nil {
6✔
4758
                        break
3✔
4759
                }
4760

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

4771
        // We came across an error retrieving an advertised
4772
        // address, log it, and fall back to the existing peer
4773
        // address.
4774
        default:
3✔
4775
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4776
                        "address for node %x: %v", p.PubKey(),
3✔
4777
                        err)
3✔
4778
        }
4779

4780
        // Make an easy lookup map so that we can check if an address
4781
        // is already in the address list that we have stored for this peer.
4782
        existingAddrs := make(map[string]bool)
3✔
4783
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4784
                existingAddrs[addr.String()] = true
3✔
4785
        }
3✔
4786

4787
        // Add any missing addresses for this peer to persistentPeerAddr.
4788
        for _, addr := range addrs {
6✔
4789
                if existingAddrs[addr.String()] {
3✔
4790
                        continue
×
4791
                }
4792

4793
                s.persistentPeerAddrs[pubStr] = append(
3✔
4794
                        s.persistentPeerAddrs[pubStr],
3✔
4795
                        &lnwire.NetAddress{
3✔
4796
                                IdentityKey: p.IdentityKey(),
3✔
4797
                                Address:     addr,
3✔
4798
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4799
                        },
3✔
4800
                )
3✔
4801
        }
4802

4803
        // Record the computed backoff in the backoff map.
4804
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4805
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4806

3✔
4807
        // Initialize a retry canceller for this peer if one does not
3✔
4808
        // exist.
3✔
4809
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4810
        if !ok {
6✔
4811
                cancelChan = make(chan struct{})
3✔
4812
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4813
        }
3✔
4814

4815
        // We choose not to wait group this go routine since the Connect
4816
        // call can stall for arbitrarily long if we shutdown while an
4817
        // outbound connection attempt is being made.
4818
        go func() {
6✔
4819
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4820
                        "persistent peer %x in %s",
3✔
4821
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4822

3✔
4823
                select {
3✔
4824
                case <-time.After(backoff):
3✔
4825
                case <-cancelChan:
3✔
4826
                        return
3✔
4827
                case <-s.quit:
3✔
4828
                        return
3✔
4829
                }
4830

4831
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4832
                        "connection to peer %x",
3✔
4833
                        p.IdentityKey().SerializeCompressed())
3✔
4834

3✔
4835
                s.connectToPersistentPeer(pubStr)
3✔
4836
        }()
4837
}
4838

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

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

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

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

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

4889
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4890

3✔
4891
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4892
        if !ok {
6✔
4893
                cancelChan = make(chan struct{})
3✔
4894
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4895
        }
3✔
4896

4897
        // Any addresses left in addrMap are new ones that we have not made
4898
        // connection requests for. So create new connection requests for those.
4899
        // If there is more than one address in the address map, stagger the
4900
        // creation of the connection requests for those.
4901
        go func() {
6✔
4902
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4903
                defer ticker.Stop()
3✔
4904

3✔
4905
                for _, addr := range addrMap {
6✔
4906
                        // Send the persistent connection request to the
3✔
4907
                        // connection manager, saving the request itself so we
3✔
4908
                        // can cancel/restart the process as needed.
3✔
4909
                        connReq := &connmgr.ConnReq{
3✔
4910
                                Addr:      addr,
3✔
4911
                                Permanent: true,
3✔
4912
                        }
3✔
4913

3✔
4914
                        s.mu.Lock()
3✔
4915
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4916
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4917
                        )
3✔
4918
                        s.mu.Unlock()
3✔
4919

3✔
4920
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4921
                                "channel peer %v", addr)
3✔
4922

3✔
4923
                        go s.connMgr.Connect(connReq)
3✔
4924

3✔
4925
                        select {
3✔
4926
                        case <-s.quit:
3✔
4927
                                return
3✔
4928
                        case <-cancelChan:
3✔
4929
                                return
3✔
4930
                        case <-ticker.C:
3✔
4931
                        }
4932
                }
4933
        }()
4934
}
4935

4936
// removePeerUnsafe removes the passed peer from the server's state of all
4937
// active peers.
4938
//
4939
// NOTE: Server mutex must be held when calling this function.
4940
func (s *server) removePeerUnsafe(p *peer.Brontide) {
3✔
4941
        if p == nil {
3✔
4942
                return
×
4943
        }
×
4944

4945
        srvrLog.Debugf("Removing peer %v", p)
3✔
4946

3✔
4947
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4948
        // will be disconnected in the server shutdown process.
3✔
4949
        if s.Stopped() {
3✔
4950
                return
×
4951
        }
×
4952

4953
        // Capture the peer's public key and string representation.
4954
        pKey := p.PubKey()
3✔
4955
        pubSer := pKey[:]
3✔
4956
        pubStr := string(pubSer)
3✔
4957

3✔
4958
        delete(s.peersByPub, pubStr)
3✔
4959

3✔
4960
        if p.Inbound() {
6✔
4961
                delete(s.inboundPeers, pubStr)
3✔
4962
        } else {
6✔
4963
                delete(s.outboundPeers, pubStr)
3✔
4964
        }
3✔
4965

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

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

3✔
4977
                // If this peer had an active persistent connection request,
3✔
4978
                // remove it.
3✔
4979
                if p.ConnReq() != nil {
6✔
4980
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4981
                }
3✔
4982

4983
                // Remove the peer's access permission from the access manager.
4984
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4985
                s.peerAccessMan.removePeerAccess(peerPubStr)
3✔
4986

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

3✔
4998
                // Inform the peer notifier of a peer offline event so that it
3✔
4999
                // can be reported to clients listening for peer events.
3✔
5000
                var pubKey [33]byte
3✔
5001
                copy(pubKey[:], pubSer)
3✔
5002

3✔
5003
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5004
        }()
5005
}
5006

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

3✔
5015
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5016

3✔
5017
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5018
        // better granularity.  In certain conditions, this method requires
3✔
5019
        // making an outbound connection to a remote peer, which requires the
3✔
5020
        // lock to be released, and subsequently reacquired.
3✔
5021
        s.mu.Lock()
3✔
5022

3✔
5023
        // Ensure we're not already connected to this peer.
3✔
5024
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5025

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

5034
        // Peer was not found, continue to pursue connection with peer.
5035

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

5044
        // If there's not already a pending or active connection to this node,
5045
        // then instruct the connection manager to attempt to establish a
5046
        // persistent connection to the peer.
5047
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5048
        if perm {
6✔
5049
                connReq := &connmgr.ConnReq{
3✔
5050
                        Addr:      addr,
3✔
5051
                        Permanent: true,
3✔
5052
                }
3✔
5053

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

3✔
5067
                go s.connMgr.Connect(connReq)
3✔
5068

3✔
5069
                return nil
3✔
5070
        }
5071
        s.mu.Unlock()
3✔
5072

3✔
5073
        // If we're not making a persistent connection, then we'll attempt to
3✔
5074
        // connect to the target peer. If the we can't make the connection, or
3✔
5075
        // the crypto negotiation breaks down, then return an error to the
3✔
5076
        // caller.
3✔
5077
        errChan := make(chan error, 1)
3✔
5078
        s.connectToPeer(addr, errChan, timeout)
3✔
5079

3✔
5080
        select {
3✔
5081
        case err := <-errChan:
3✔
5082
                return err
3✔
5083
        case <-s.quit:
×
5084
                return ErrServerShuttingDown
×
5085
        }
5086
}
5087

5088
// connectToPeer establishes a connection to a remote peer. errChan is used to
5089
// notify the caller if the connection attempt has failed. Otherwise, it will be
5090
// closed.
5091
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5092
        errChan chan<- error, timeout time.Duration) {
3✔
5093

3✔
5094
        conn, err := brontide.Dial(
3✔
5095
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5096
        )
3✔
5097
        if err != nil {
6✔
5098
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5099
                select {
3✔
5100
                case errChan <- err:
3✔
5101
                case <-s.quit:
×
5102
                }
5103
                return
3✔
5104
        }
5105

5106
        close(errChan)
3✔
5107

3✔
5108
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5109
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5110

3✔
5111
        s.OutboundPeerConnected(nil, conn)
3✔
5112
}
5113

5114
// DisconnectPeer sends the request to server to close the connection with peer
5115
// identified by public key.
5116
//
5117
// NOTE: This function is safe for concurrent access.
5118
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5119
        pubBytes := pubKey.SerializeCompressed()
3✔
5120
        pubStr := string(pubBytes)
3✔
5121

3✔
5122
        s.mu.Lock()
3✔
5123
        defer s.mu.Unlock()
3✔
5124

3✔
5125
        // Check that were actually connected to this peer. If not, then we'll
3✔
5126
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5127
        // currently connected to.
3✔
5128
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5129
        if err == ErrPeerNotConnected {
6✔
5130
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5131
        }
3✔
5132

5133
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5134

3✔
5135
        s.cancelConnReqs(pubStr, nil)
3✔
5136

3✔
5137
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5138
        // them from this map so we don't attempt to re-connect after we
3✔
5139
        // disconnect.
3✔
5140
        delete(s.persistentPeers, pubStr)
3✔
5141
        delete(s.persistentPeersBackoff, pubStr)
3✔
5142

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

3✔
5150
        return nil
3✔
5151
}
5152

5153
// OpenChannel sends a request to the server to open a channel to the specified
5154
// peer identified by nodeKey with the passed channel funding parameters.
5155
//
5156
// NOTE: This function is safe for concurrent access.
5157
func (s *server) OpenChannel(
5158
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5159

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

3✔
5166
        // First attempt to locate the target peer to open a channel with, if
3✔
5167
        // we're unable to locate the peer then this request will fail.
3✔
5168
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5169
        s.mu.RLock()
3✔
5170
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5171
        if !ok {
3✔
5172
                s.mu.RUnlock()
×
5173

×
5174
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5175
                return req.Updates, req.Err
×
5176
        }
×
5177
        req.Peer = peer
3✔
5178
        s.mu.RUnlock()
3✔
5179

3✔
5180
        // We'll wait until the peer is active before beginning the channel
3✔
5181
        // opening process.
3✔
5182
        select {
3✔
5183
        case <-peer.ActiveSignal():
3✔
5184
        case <-peer.QuitSignal():
×
5185
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5186
                return req.Updates, req.Err
×
5187
        case <-s.quit:
×
5188
                req.Err <- ErrServerShuttingDown
×
5189
                return req.Updates, req.Err
×
5190
        }
5191

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

×
5200
                return req.Updates, req.Err
×
5201
        }
×
5202

5203
        // Spawn a goroutine to send the funding workflow request to the funding
5204
        // manager. This allows the server to continue handling queries instead
5205
        // of blocking on this request which is exported as a synchronous
5206
        // request to the outside world.
5207
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5208

3✔
5209
        return req.Updates, req.Err
3✔
5210
}
5211

5212
// Peers returns a slice of all active peers.
5213
//
5214
// NOTE: This function is safe for concurrent access.
5215
func (s *server) Peers() []*peer.Brontide {
3✔
5216
        s.mu.RLock()
3✔
5217
        defer s.mu.RUnlock()
3✔
5218

3✔
5219
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5220
        for _, peer := range s.peersByPub {
6✔
5221
                peers = append(peers, peer)
3✔
5222
        }
3✔
5223

5224
        return peers
3✔
5225
}
5226

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

5238
        // Using 1/10 of our duration as a margin, compute a random offset to
5239
        // avoid the nodes entering connection cycles.
5240
        margin := nextBackoff / 10
3✔
5241

3✔
5242
        var wiggle big.Int
3✔
5243
        wiggle.SetUint64(uint64(margin))
3✔
5244
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5245
                // Randomizing is not mission critical, so we'll just return the
×
5246
                // current backoff.
×
5247
                return nextBackoff
×
5248
        }
×
5249

5250
        // Otherwise add in our wiggle, but subtract out half of the margin so
5251
        // that the backoff can tweaked by 1/20 in either direction.
5252
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5253
}
5254

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

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

3✔
5263
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5264
        if err != nil {
3✔
5265
                return nil, err
×
5266
        }
×
5267

5268
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5269
        if err != nil {
6✔
5270
                return nil, err
3✔
5271
        }
3✔
5272

5273
        if len(node.Addresses) == 0 {
6✔
5274
                return nil, errNoAdvertisedAddr
3✔
5275
        }
3✔
5276

5277
        return node.Addresses, nil
3✔
5278
}
5279

5280
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5281
// channel update for a target channel.
5282
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5283
        *lnwire.ChannelUpdate1, error) {
3✔
5284

3✔
5285
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5286
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5287
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5288
                if err != nil {
6✔
5289
                        return nil, err
3✔
5290
                }
3✔
5291

5292
                return netann.ExtractChannelUpdate(
3✔
5293
                        ourPubKey[:], info, edge1, edge2,
3✔
5294
                )
3✔
5295
        }
5296
}
5297

5298
// applyChannelUpdate applies the channel update to the different sub-systems of
5299
// the server. The useAlias boolean denotes whether or not to send an alias in
5300
// place of the real SCID.
5301
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5302
        op *wire.OutPoint, useAlias bool) error {
3✔
5303

3✔
5304
        var (
3✔
5305
                peerAlias    *lnwire.ShortChannelID
3✔
5306
                defaultAlias lnwire.ShortChannelID
3✔
5307
        )
3✔
5308

3✔
5309
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5310

3✔
5311
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5312
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5313
        if useAlias {
6✔
5314
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5315
                if foundAlias != defaultAlias {
6✔
5316
                        peerAlias = &foundAlias
3✔
5317
                }
3✔
5318
        }
5319

5320
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5321
                update, discovery.RemoteAlias(peerAlias),
3✔
5322
        )
3✔
5323
        select {
3✔
5324
        case err := <-errChan:
3✔
5325
                return err
3✔
5326
        case <-s.quit:
×
5327
                return ErrServerShuttingDown
×
5328
        }
5329
}
5330

5331
// SendCustomMessage sends a custom message to the peer with the specified
5332
// pubkey.
5333
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5334
        data []byte) error {
3✔
5335

3✔
5336
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5337
        if err != nil {
3✔
5338
                return err
×
5339
        }
×
5340

5341
        // We'll wait until the peer is active.
5342
        select {
3✔
5343
        case <-peer.ActiveSignal():
3✔
5344
        case <-peer.QuitSignal():
×
5345
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5346
        case <-s.quit:
×
5347
                return ErrServerShuttingDown
×
5348
        }
5349

5350
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5351
        if err != nil {
6✔
5352
                return err
3✔
5353
        }
3✔
5354

5355
        // Send the message as low-priority. For now we assume that all
5356
        // application-defined message are low priority.
5357
        return peer.SendMessageLazy(true, msg)
3✔
5358
}
5359

5360
// newSweepPkScriptGen creates closure that generates a new public key script
5361
// which should be used to sweep any funds into the on-chain wallet.
5362
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5363
// (p2wkh) output.
5364
func newSweepPkScriptGen(
5365
        wallet lnwallet.WalletController,
5366
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5367

3✔
5368
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5369
                sweepAddr, err := wallet.NewAddress(
3✔
5370
                        lnwallet.TaprootPubkey, false,
3✔
5371
                        lnwallet.DefaultAccountName,
3✔
5372
                )
3✔
5373
                if err != nil {
3✔
5374
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5375
                }
×
5376

5377
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5378
                if err != nil {
3✔
5379
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5380
                }
×
5381

5382
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5383
                        wallet, netParams, addr,
3✔
5384
                )
3✔
5385
                if err != nil {
3✔
5386
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5387
                }
×
5388

5389
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5390
                        DeliveryAddress: addr,
3✔
5391
                        InternalKey:     internalKeyDesc,
3✔
5392
                })
3✔
5393
        }
5394
}
5395

5396
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5397
// finished.
5398
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5399
        // Get a list of closed channels.
3✔
5400
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5401
        if err != nil {
3✔
5402
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5403
                return nil
×
5404
        }
×
5405

5406
        // Save the SCIDs in a map.
5407
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5408
        for _, c := range channels {
6✔
5409
                // If the channel is not pending, its FC has been finalized.
3✔
5410
                if !c.IsPending {
6✔
5411
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5412
                }
3✔
5413
        }
5414

5415
        // Double check whether the reported closed channel has indeed finished
5416
        // closing.
5417
        //
5418
        // NOTE: There are misalignments regarding when a channel's FC is
5419
        // marked as finalized. We double check the pending channels to make
5420
        // sure the returned SCIDs are indeed terminated.
5421
        //
5422
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5423
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5424
        if err != nil {
3✔
5425
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5426
                return nil
×
5427
        }
×
5428

5429
        for _, c := range pendings {
6✔
5430
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5431
                        continue
3✔
5432
                }
5433

5434
                // If the channel is still reported as pending, remove it from
5435
                // the map.
5436
                delete(closedSCIDs, c.ShortChannelID)
×
5437

×
5438
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5439
                        c.ShortChannelID)
×
5440
        }
5441

5442
        return closedSCIDs
3✔
5443
}
5444

5445
// getStartingBeat returns the current beat. This is used during the startup to
5446
// initialize blockbeat consumers.
5447
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5448
        // beat is the current blockbeat.
3✔
5449
        var beat *chainio.Beat
3✔
5450

3✔
5451
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5452
        // we will skip fetching the best block.
3✔
5453
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5454
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5455
                        "mode")
×
5456

×
5457
                return &chainio.Beat{}, nil
×
5458
        }
×
5459

5460
        // We should get a notification with the current best block immediately
5461
        // by passing a nil block.
5462
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5463
        if err != nil {
3✔
5464
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5465
        }
×
5466
        defer blockEpochs.Cancel()
3✔
5467

3✔
5468
        // We registered for the block epochs with a nil request. The notifier
3✔
5469
        // should send us the current best block immediately. So we need to
3✔
5470
        // wait for it here because we need to know the current best height.
3✔
5471
        select {
3✔
5472
        case bestBlock := <-blockEpochs.Epochs:
3✔
5473
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5474
                        bestBlock.Hash, bestBlock.Height)
3✔
5475

3✔
5476
                // Update the current blockbeat.
3✔
5477
                beat = chainio.NewBeat(*bestBlock)
3✔
5478

5479
        case <-s.quit:
×
5480
                srvrLog.Debug("LND shutting down")
×
5481
        }
5482

5483
        return beat, nil
3✔
5484
}
5485

5486
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5487
// point has an active RBF chan closer.
5488
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5489
        chanPoint wire.OutPoint) bool {
3✔
5490

3✔
5491
        pubBytes := peerPub.SerializeCompressed()
3✔
5492

3✔
5493
        s.mu.RLock()
3✔
5494
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5495
        s.mu.RUnlock()
3✔
5496
        if !ok {
3✔
5497
                return false
×
5498
        }
×
5499

5500
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5501
}
5502

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

3✔
5511
        // First, we'll attempt to look up the channel based on it's
3✔
5512
        // ChannelPoint.
3✔
5513
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5514
        if err != nil {
3✔
5515
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5516
        }
×
5517

5518
        // From the channel, we can now get the pubkey of the peer, then use
5519
        // that to eventually get the chan closer.
5520
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5521

3✔
5522
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5523
        s.mu.RLock()
3✔
5524
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5525
        s.mu.RUnlock()
3✔
5526
        if !ok {
3✔
5527
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5528
                        "not online", chanPoint)
×
5529
        }
×
5530

5531
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5532
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5533
        )
3✔
5534
        if err != nil {
3✔
5535
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5536
                        "%w", err)
×
5537
        }
×
5538

5539
        return closeUpdates, nil
3✔
5540
}
5541

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

3✔
5550
        // If the channel is present in the switch, then the request should flow
3✔
5551
        // through the switch instead.
3✔
5552
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5553
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5554
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5555
                        "invalid request", chanPoint)
×
5556
        }
×
5557

5558
        // At this point, we know that the channel isn't present in the link, so
5559
        // we'll check to see if we have an entry in the active chan closer map.
5560
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5561
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5562
        )
3✔
5563
        if err != nil {
3✔
5564
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5565
                        "ChannelPoint(%v)", chanPoint)
×
5566
        }
×
5567

5568
        return updates, nil
3✔
5569
}
5570

5571
// getNodeAnnFields populates the alias, color, and addresses. This is used
5572
// during startup to construct the initial node announcement.
5573
func (s *server) getNodeAnnFields(ctx context.Context, selfAddrs []net.Addr,
5574
        serializedPubKey [33]byte) (color.RGBA, string, []net.Addr, error) {
3✔
5575

3✔
5576
        var (
3✔
5577
                color color.RGBA
3✔
5578
                alias = s.cfg.Alias
3✔
5579
                addrs = selfAddrs
3✔
5580
                err   error
3✔
5581
        )
3✔
5582

3✔
5583
        // Parse the color from config. We will update this later if the config
3✔
5584
        // color is not changed from default (#3399FF) and we have a value in
3✔
5585
        // the source node.
3✔
5586
        color, err = lncfg.ParseHexColor(s.cfg.Color)
3✔
5587
        if err != nil {
3✔
NEW
5588
                return color, "", nil, fmt.Errorf("unable to parse color: %w",
×
NEW
5589
                        err)
×
NEW
5590
        }
×
5591

5592
        // Fetch the source node from the graphDB. If it exists, we'll use its
5593
        // values for our initial node announcement else we'll use the default
5594
        // config values.
5595
        sourceNode, err := s.graphDB.SourceNode(ctx)
3✔
5596
        switch {
3✔
5597
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5598
                // If an alias was not set, we'll set it to the first 10 bytes
3✔
5599
                // of the serialized public key.
3✔
5600
                if alias == "" {
6✔
5601
                        alias = hex.EncodeToString(serializedPubKey[:10])
3✔
5602
                }
3✔
5603

5604
                return color, alias, addrs, nil
3✔
5605

NEW
5606
        case err != nil:
×
NEW
5607
                return color, "", nil, err
×
5608
        }
5609

5610
        // If the color is not changed from default, it means that we didn't
5611
        // specify a different color in the config. We'll use the source node's
5612
        // color.
5613
        if s.cfg.Color == defaultColor {
6✔
5614
                color = sourceNode.Color
3✔
5615
        }
3✔
5616

5617
        // If an alias is not specified in the config, we'll use the source
5618
        // node's alias.
5619
        if alias == "" {
6✔
5620
                alias = sourceNode.Alias
3✔
5621
        }
3✔
5622

5623
        // To avoid having duplicate addresses, we'll only add addresses from
5624
        // the source node that are not already in our address list yet.
5625
        addressMap := make(map[string]struct{}, len(addrs))
3✔
5626
        // Populate the map with the existing addresses.
3✔
5627
        for _, existingAddr := range addrs {
6✔
5628
                addressMap[existingAddr.String()] = struct{}{}
3✔
5629
        }
3✔
5630
        // Append unique addresses from the source node to the address list.
5631
        for _, addr := range sourceNode.Addresses {
6✔
5632
                if _, found := addressMap[addr.String()]; !found {
6✔
5633
                        addrs = append(addrs, addr)
3✔
5634
                        addressMap[addr.String()] = struct{}{}
3✔
5635
                }
3✔
5636
        }
5637

5638
        return color, alias, addrs, nil
3✔
5639
}
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