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

lightningnetwork / lnd / 17010123862

16 Aug 2025 03:41PM UTC coverage: 66.764% (-0.001%) from 66.765%
17010123862

Pull #8825

github

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

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

83 existing lines in 19 files now uncovered.

135966 of 203651 relevant lines covered (66.76%)

21529.3 hits per line

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

69.57
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

231
        start sync.Once
232
        stop  sync.Once
233

234
        cfg *Config
235

236
        implCfg *ImplementationCfg
237

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

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

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

249
        chanStatusMgr *netann.ChanStatusManager
250

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

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

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

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

271
        mu sync.RWMutex
272

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

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

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

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

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

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

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

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

323
        cc *chainreg.ChainControl
324

325
        fundingMgr *funding.Manager
326

327
        graphDB *graphdb.ChannelGraph
328

329
        chanStateDB *channeldb.ChannelStateDB
330

331
        addrSource channeldb.AddrSource
332

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

337
        invoicesDB invoices.InvoiceDB
338

339
        // kvPaymentsDB is the DB that contains all functions for managing
340
        // payments.
341
        //
342
        // TODO(ziggie): Replace with interface.
343
        kvPaymentsDB *paymentsdb.KVPaymentsDB
344

345
        aliasMgr *aliasmgr.Manager
346

347
        htlcSwitch *htlcswitch.Switch
348

349
        interceptableSwitch *htlcswitch.InterceptableSwitch
350

351
        invoices *invoices.InvoiceRegistry
352

353
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
354

355
        channelNotifier *channelnotifier.ChannelNotifier
356

357
        peerNotifier *peernotifier.PeerNotifier
358

359
        htlcNotifier *htlcswitch.HtlcNotifier
360

361
        witnessBeacon contractcourt.WitnessBeacon
362

363
        breachArbitrator *contractcourt.BreachArbitrator
364

365
        missionController *routing.MissionController
366
        defaultMC         *routing.MissionControl
367

368
        graphBuilder *graph.Builder
369

370
        chanRouter *routing.ChannelRouter
371

372
        controlTower routing.ControlTower
373

374
        authGossiper *discovery.AuthenticatedGossiper
375

376
        localChanMgr *localchans.Manager
377

378
        utxoNursery *contractcourt.UtxoNursery
379

380
        sweeper *sweep.UtxoSweeper
381

382
        chainArb *contractcourt.ChainArbitrator
383

384
        sphinx *hop.OnionProcessor
385

386
        towerClientMgr *wtclient.Manager
387

388
        connMgr *connmgr.ConnManager
389

390
        sigPool *lnwallet.SigPool
391

392
        writePool *pool.Write
393

394
        readPool *pool.Read
395

396
        tlsManager *TLSManager
397

398
        // featureMgr dispatches feature vectors for various contexts within the
399
        // daemon.
400
        featureMgr *feature.Manager
401

402
        // currentNodeAnn is the node announcement that has been broadcast to
403
        // the network upon startup, if the attributes of the node (us) has
404
        // changed since last start.
405
        currentNodeAnn *lnwire.NodeAnnouncement
406

407
        // chansToRestore is the set of channels that upon starting, the server
408
        // should attempt to restore/recover.
409
        chansToRestore walletunlocker.ChannelsToRecover
410

411
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
412
        // backups are consistent at all times. It interacts with the
413
        // channelNotifier to be notified of newly opened and closed channels.
414
        chanSubSwapper *chanbackup.SubSwapper
415

416
        // chanEventStore tracks the behaviour of channels and their remote peers to
417
        // provide insights into their health and performance.
418
        chanEventStore *chanfitness.ChannelEventStore
419

420
        hostAnn *netann.HostAnnouncer
421

422
        // livenessMonitor monitors that lnd has access to critical resources.
423
        livenessMonitor *healthcheck.Monitor
424

425
        customMessageServer *subscribe.Server
426

427
        // txPublisher is a publisher with fee-bumping capability.
428
        txPublisher *sweep.TxPublisher
429

430
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
431
        // of new blocks.
432
        blockbeatDispatcher *chainio.BlockbeatDispatcher
433

434
        // peerAccessMan implements peer access controls.
435
        peerAccessMan *accessMan
436

437
        quit chan struct{}
438

439
        wg sync.WaitGroup
440
}
441

442
// updatePersistentPeerAddrs subscribes to topology changes and stores
443
// advertised addresses for any NodeAnnouncements from our persisted peers.
444
func (s *server) updatePersistentPeerAddrs() error {
3✔
445
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
446
        if err != nil {
3✔
447
                return err
×
448
        }
×
449

450
        s.wg.Add(1)
3✔
451
        go func() {
6✔
452
                defer func() {
6✔
453
                        graphSub.Cancel()
3✔
454
                        s.wg.Done()
3✔
455
                }()
3✔
456

457
                for {
6✔
458
                        select {
3✔
459
                        case <-s.quit:
3✔
460
                                return
3✔
461

462
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
463
                                // If the router is shutting down, then we will
3✔
464
                                // as well.
3✔
465
                                if !ok {
3✔
466
                                        return
×
467
                                }
×
468

469
                                for _, update := range topChange.NodeUpdates {
6✔
470
                                        pubKeyStr := string(
3✔
471
                                                update.IdentityKey.
3✔
472
                                                        SerializeCompressed(),
3✔
473
                                        )
3✔
474

3✔
475
                                        // We only care about updates from
3✔
476
                                        // our persistentPeers.
3✔
477
                                        s.mu.RLock()
3✔
478
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
479
                                        s.mu.RUnlock()
3✔
480
                                        if !ok {
6✔
481
                                                continue
3✔
482
                                        }
483

484
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
485
                                                len(update.Addresses))
3✔
486

3✔
487
                                        for _, addr := range update.Addresses {
6✔
488
                                                addrs = append(addrs,
3✔
489
                                                        &lnwire.NetAddress{
3✔
490
                                                                IdentityKey: update.IdentityKey,
3✔
491
                                                                Address:     addr,
3✔
492
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
493
                                                        },
3✔
494
                                                )
3✔
495
                                        }
3✔
496

497
                                        s.mu.Lock()
3✔
498

3✔
499
                                        // Update the stored addresses for this
3✔
500
                                        // to peer to reflect the new set.
3✔
501
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
502

3✔
503
                                        // If there are no outstanding
3✔
504
                                        // connection requests for this peer
3✔
505
                                        // then our work is done since we are
3✔
506
                                        // not currently trying to connect to
3✔
507
                                        // them.
3✔
508
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
509
                                                s.mu.Unlock()
3✔
510
                                                continue
3✔
511
                                        }
512

513
                                        s.mu.Unlock()
3✔
514

3✔
515
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
516
                                }
517
                        }
518
                }
519
        }()
520

521
        return nil
3✔
522
}
523

524
// CustomMessage is a custom message that is received from a peer.
525
type CustomMessage struct {
526
        // Peer is the peer pubkey
527
        Peer [33]byte
528

529
        // Msg is the custom wire message.
530
        Msg *lnwire.Custom
531
}
532

533
// parseAddr parses an address from its string format to a net.Addr.
534
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
535
        var (
3✔
536
                host string
3✔
537
                port int
3✔
538
        )
3✔
539

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

557
        if tor.IsOnionHost(host) {
3✔
558
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
559
        }
×
560

561
        // If the host is part of a TCP address, we'll use the network
562
        // specific ResolveTCPAddr function in order to resolve these
563
        // addresses over Tor in order to prevent leaking your real IP
564
        // address.
565
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
566
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
567
}
568

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

3✔
574
        return func(a net.Addr) (net.Conn, error) {
6✔
575
                lnAddr := a.(*lnwire.NetAddress)
3✔
576
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
577
        }
3✔
578
}
579

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

3✔
593
        var (
3✔
594
                err         error
3✔
595
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
596

3✔
597
                // We just derived the full descriptor, so we know the public
3✔
598
                // key is set on it.
3✔
599
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
600
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
601
                )
3✔
602
        )
3✔
603

3✔
604
        netParams := cfg.ActiveNetParams.Params
3✔
605

3✔
606
        // Initialize the sphinx router.
3✔
607
        replayLog := htlcswitch.NewDecayedLog(
3✔
608
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
609
        )
3✔
610
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
611

3✔
612
        writeBufferPool := pool.NewWriteBuffer(
3✔
613
                pool.DefaultWriteBufferGCInterval,
3✔
614
                pool.DefaultWriteBufferExpiryInterval,
3✔
615
        )
3✔
616

3✔
617
        writePool := pool.NewWrite(
3✔
618
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
619
        )
3✔
620

3✔
621
        readBufferPool := pool.NewReadBuffer(
3✔
622
                pool.DefaultReadBufferGCInterval,
3✔
623
                pool.DefaultReadBufferExpiryInterval,
3✔
624
        )
3✔
625

3✔
626
        readPool := pool.NewRead(
3✔
627
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
628
        )
3✔
629

3✔
630
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
631
        // controller, then we'll exit as this is incompatible.
3✔
632
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
633
                implCfg.AuxFundingController.IsNone() {
3✔
634

×
635
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
636
                        "overlay channels are not supported " +
×
637
                        "in a standalone lnd build")
×
638
        }
×
639

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

663
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
664
        registryConfig := invoices.RegistryConfig{
3✔
665
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
666
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
667
                Clock:                       clock.NewDefaultClock(),
3✔
668
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
669
                AcceptAMP:                   cfg.AcceptAMP,
3✔
670
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
671
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
672
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
673
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
674
        }
3✔
675

3✔
676
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
677

3✔
678
        s := &server{
3✔
679
                cfg:            cfg,
3✔
680
                implCfg:        implCfg,
3✔
681
                graphDB:        dbs.GraphDB,
3✔
682
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
683
                addrSource:     addrSource,
3✔
684
                miscDB:         dbs.ChanStateDB,
3✔
685
                invoicesDB:     dbs.InvoiceDB,
3✔
686
                kvPaymentsDB:   dbs.KVPaymentsDB,
3✔
687
                cc:             cc,
3✔
688
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
689
                writePool:      writePool,
3✔
690
                readPool:       readPool,
3✔
691
                chansToRestore: chansToRestore,
3✔
692

3✔
693
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
694
                        cc.ChainNotifier,
3✔
695
                ),
3✔
696
                channelNotifier: channelnotifier.New(
3✔
697
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
698
                ),
3✔
699

3✔
700
                identityECDH:   nodeKeyECDH,
3✔
701
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
702
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
703

3✔
704
                listenAddrs: listenAddrs,
3✔
705

3✔
706
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
707
                // schedule
3✔
708
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
709

3✔
710
                torController: torController,
3✔
711

3✔
712
                persistentPeers:         make(map[string]bool),
3✔
713
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
714
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
715
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
716
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
717
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
718
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
719
                scheduledPeerConnection: make(map[string]func()),
3✔
720
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
721

3✔
722
                peersByPub:                make(map[string]*peer.Brontide),
3✔
723
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
724
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
725
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
726
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
727

3✔
728
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
729

3✔
730
                customMessageServer: subscribe.NewServer(),
3✔
731

3✔
732
                tlsManager: tlsManager,
3✔
733

3✔
734
                featureMgr: featureMgr,
3✔
735
                quit:       make(chan struct{}),
3✔
736
        }
3✔
737

3✔
738
        // Start the low-level services once they are initialized.
3✔
739
        //
3✔
740
        // TODO(yy): break the server startup into four steps,
3✔
741
        // 1. init the low-level services.
3✔
742
        // 2. start the low-level services.
3✔
743
        // 3. init the high-level services.
3✔
744
        // 4. start the high-level services.
3✔
745
        if err := s.startLowLevelServices(); err != nil {
3✔
746
                return nil, err
×
747
        }
×
748

749
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
750
        if err != nil {
3✔
751
                return nil, err
×
752
        }
×
753

754
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
755
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
756
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
757
        )
3✔
758
        s.invoices = invoices.NewRegistry(
3✔
759
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
760
        )
3✔
761

3✔
762
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
763

3✔
764
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
765
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
766

3✔
767
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
768
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
769
                if err != nil {
3✔
770
                        return err
×
771
                }
×
772

773
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
774

3✔
775
                return nil
3✔
776
        }
777

778
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
779
        if err != nil {
3✔
780
                return nil, err
×
781
        }
×
782

783
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
784
                DB:                   dbs.ChanStateDB,
3✔
785
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
786
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
787
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
788
                LocalChannelClose: func(pubKey []byte,
3✔
789
                        request *htlcswitch.ChanClose) {
6✔
790

3✔
791
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
792
                        if err != nil {
3✔
793
                                srvrLog.Errorf("unable to close channel, peer"+
×
794
                                        " with %v id can't be found: %v",
×
795
                                        pubKey, err,
×
796
                                )
×
797
                                return
×
798
                        }
×
799

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

835
        s.witnessBeacon = newPreimageBeacon(
3✔
836
                dbs.ChanStateDB.NewWitnessCache(),
3✔
837
                s.interceptableSwitch.ForwardPacket,
3✔
838
        )
3✔
839

3✔
840
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
841
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
842
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
843
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
844
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
845
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
846
                MessageSigner:            s.nodeSigner,
3✔
847
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
848
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
849
                DB:                       s.chanStateDB,
3✔
850
                Graph:                    dbs.GraphDB,
3✔
851
        }
3✔
852

3✔
853
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
854
        if err != nil {
3✔
855
                return nil, err
×
856
        }
×
857
        s.chanStatusMgr = chanStatusMgr
3✔
858

3✔
859
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
860
        // port forwarding for users behind a NAT.
3✔
861
        if cfg.NAT {
3✔
862
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
863

×
864
                discoveryTimeout := time.Duration(10 * time.Second)
×
865

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

×
880
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
881
                                "enabled device")
×
882

×
883
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
884
                        if err != nil {
×
885
                                err := fmt.Errorf("unable to discover a "+
×
886
                                        "NAT-PMP enabled device on the local "+
×
887
                                        "network: %v", err)
×
888
                                srvrLog.Error(err)
×
889
                                return nil, err
×
890
                        }
×
891

892
                        s.natTraversal = pmp
×
893
                }
894
        }
895

896
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
897
        // Set the self node which represents our node in the graph.
3✔
898
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
899
        if err != nil {
3✔
900
                return nil, err
×
901
        }
×
902

903
        // The router will get access to the payment ID sequencer, such that it
904
        // can generate unique payment IDs.
905
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
906
        if err != nil {
3✔
907
                return nil, err
×
908
        }
×
909

910
        // Instantiate mission control with config from the sub server.
911
        //
912
        // TODO(joostjager): When we are further in the process of moving to sub
913
        // servers, the mission control instance itself can be moved there too.
914
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
915

3✔
916
        // We only initialize a probability estimator if there's no custom one.
3✔
917
        var estimator routing.Estimator
3✔
918
        if cfg.Estimator != nil {
3✔
919
                estimator = cfg.Estimator
×
920
        } else {
3✔
921
                switch routingConfig.ProbabilityEstimatorType {
3✔
922
                case routing.AprioriEstimatorName:
3✔
923
                        aCfg := routingConfig.AprioriConfig
3✔
924
                        aprioriConfig := routing.AprioriConfig{
3✔
925
                                AprioriHopProbability: aCfg.HopProbability,
3✔
926
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
927
                                AprioriWeight:         aCfg.Weight,
3✔
928
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
929
                        }
3✔
930

3✔
931
                        estimator, err = routing.NewAprioriEstimator(
3✔
932
                                aprioriConfig,
3✔
933
                        )
3✔
934
                        if err != nil {
3✔
935
                                return nil, err
×
936
                        }
×
937

938
                case routing.BimodalEstimatorName:
×
939
                        bCfg := routingConfig.BimodalConfig
×
940
                        bimodalConfig := routing.BimodalConfig{
×
941
                                BimodalNodeWeight: bCfg.NodeWeight,
×
942
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
943
                                        bCfg.Scale,
×
944
                                ),
×
945
                                BimodalDecayTime: bCfg.DecayTime,
×
946
                        }
×
947

×
948
                        estimator, err = routing.NewBimodalEstimator(
×
949
                                bimodalConfig,
×
950
                        )
×
951
                        if err != nil {
×
952
                                return nil, err
×
953
                        }
×
954

955
                default:
×
956
                        return nil, fmt.Errorf("unknown estimator type %v",
×
957
                                routingConfig.ProbabilityEstimatorType)
×
958
                }
959
        }
960

961
        mcCfg := &routing.MissionControlConfig{
3✔
962
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
963
                Estimator:               estimator,
3✔
964
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
965
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
966
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
967
        }
3✔
968

3✔
969
        s.missionController, err = routing.NewMissionController(
3✔
970
                dbs.ChanStateDB, nodePubKey, mcCfg,
3✔
971
        )
3✔
972
        if err != nil {
3✔
973
                return nil, fmt.Errorf("can't create mission control "+
×
974
                        "manager: %w", err)
×
975
        }
×
976
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
977
                routing.DefaultMissionControlNamespace,
3✔
978
        )
3✔
979
        if err != nil {
3✔
980
                return nil, fmt.Errorf("can't create mission control in the "+
×
981
                        "default namespace: %w", err)
×
982
        }
×
983

984
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
985
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
986
                int64(routingConfig.AttemptCost),
3✔
987
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
988
                routingConfig.MinRouteProbability)
3✔
989

3✔
990
        pathFindingConfig := routing.PathFindingConfig{
3✔
991
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
992
                        routingConfig.AttemptCost,
3✔
993
                ),
3✔
994
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
995
                MinProbability: routingConfig.MinRouteProbability,
3✔
996
        }
3✔
997

3✔
998
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
999
        if err != nil {
3✔
1000
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1001
        }
×
1002
        paymentSessionSource := &routing.SessionSource{
3✔
1003
                GraphSessionFactory: dbs.GraphDB,
3✔
1004
                SourceNode:          sourceNode,
3✔
1005
                MissionControl:      s.defaultMC,
3✔
1006
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1007
                PathFindingConfig:   pathFindingConfig,
3✔
1008
        }
3✔
1009

3✔
1010
        s.controlTower = routing.NewControlTower(dbs.KVPaymentsDB)
3✔
1011

3✔
1012
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1013
                cfg.Routing.StrictZombiePruning
3✔
1014

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

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

1052
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1053
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1054
        if err != nil {
3✔
1055
                return nil, err
×
1056
        }
×
1057
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1058
        if err != nil {
3✔
1059
                return nil, err
×
1060
        }
×
1061

1062
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1063

3✔
1064
        s.authGossiper = discovery.New(discovery.Config{
3✔
1065
                Graph:                 s.graphBuilder,
3✔
1066
                ChainIO:               s.cc.ChainIO,
3✔
1067
                Notifier:              s.cc.ChainNotifier,
3✔
1068
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1069
                Broadcast:             s.BroadcastMessage,
3✔
1070
                ChanSeries:            chanSeries,
3✔
1071
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1072
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1073
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1074
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1075
                        error) {
3✔
1076

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

1109
        accessCfg := &accessManConfig{
3✔
1110
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1111
                        error) {
6✔
1112

3✔
1113
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1114
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1115
                                genesisHash[:],
3✔
1116
                        )
3✔
1117
                },
3✔
1118
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1119
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1120
        }
1121

1122
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1123
        if err != nil {
3✔
1124
                return nil, err
×
1125
        }
×
1126

1127
        s.peerAccessMan = peerAccessMan
3✔
1128

3✔
1129
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1130
        //nolint:ll
3✔
1131
        s.localChanMgr = &localchans.Manager{
3✔
1132
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1133
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1134
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1135
                        cb func(*models.ChannelEdgeInfo,
3✔
1136
                                *models.ChannelEdgePolicy) error,
3✔
1137
                        reset func()) error {
6✔
1138

3✔
1139
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1140
                                func(c *models.ChannelEdgeInfo,
3✔
1141
                                        e *models.ChannelEdgePolicy,
3✔
1142
                                        _ *models.ChannelEdgePolicy) error {
6✔
1143

3✔
1144
                                        // NOTE: The invoked callback here may
3✔
1145
                                        // receive a nil channel policy.
3✔
1146
                                        return cb(c, e)
3✔
1147
                                }, reset,
3✔
1148
                        )
1149
                },
1150
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1151
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1152
                FetchChannel:              s.chanStateDB.FetchChannel,
1153
                AddEdge: func(ctx context.Context,
1154
                        edge *models.ChannelEdgeInfo) error {
×
1155

×
1156
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1157
                },
×
1158
        }
1159

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

1168
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1169
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1170
        )
3✔
1171
        if err != nil {
3✔
1172
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1173
                return nil, err
×
1174
        }
×
1175

1176
        aggregator := sweep.NewBudgetAggregator(
3✔
1177
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1178
                s.implCfg.AuxSweeper,
3✔
1179
        )
3✔
1180

3✔
1181
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1182
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1183
                Wallet:     cc.Wallet,
3✔
1184
                Estimator:  cc.FeeEstimator,
3✔
1185
                Notifier:   cc.ChainNotifier,
3✔
1186
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1187
        })
3✔
1188

3✔
1189
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1190
                FeeEstimator: cc.FeeEstimator,
3✔
1191
                GenSweepScript: newSweepPkScriptGen(
3✔
1192
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1193
                ),
3✔
1194
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1195
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1196
                Mempool:              cc.MempoolNotifier,
3✔
1197
                Notifier:             cc.ChainNotifier,
3✔
1198
                Store:                sweeperStore,
3✔
1199
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1200
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1201
                Aggregator:           aggregator,
3✔
1202
                Publisher:            s.txPublisher,
3✔
1203
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1204
        })
3✔
1205

3✔
1206
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1207
                ChainIO:             cc.ChainIO,
3✔
1208
                ConfDepth:           1,
3✔
1209
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1210
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1211
                Notifier:            cc.ChainNotifier,
3✔
1212
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1213
                Store:               utxnStore,
3✔
1214
                SweepInput:          s.sweeper.SweepInput,
3✔
1215
                Budget:              s.cfg.Sweeper.Budget,
3✔
1216
        })
3✔
1217

3✔
1218
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1219
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1220
                closureType contractcourt.ChannelCloseType) {
6✔
1221
                // TODO(conner): Properly respect the update and error channels
3✔
1222
                // returned by CloseLink.
3✔
1223

3✔
1224
                // Instruct the switch to close the channel.  Provide no close out
3✔
1225
                // delivery script or target fee per kw because user input is not
3✔
1226
                // available when the remote peer closes the channel.
3✔
1227
                s.htlcSwitch.CloseLink(
3✔
1228
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1229
                )
3✔
1230
        }
3✔
1231

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

3✔
1236
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1237
                &contractcourt.BreachConfig{
3✔
1238
                        CloseLink: closeLink,
3✔
1239
                        DB:        s.chanStateDB,
3✔
1240
                        Estimator: s.cc.FeeEstimator,
3✔
1241
                        GenSweepScript: newSweepPkScriptGen(
3✔
1242
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1243
                        ),
3✔
1244
                        Notifier:           cc.ChainNotifier,
3✔
1245
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1246
                        ContractBreaches:   contractBreaches,
3✔
1247
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1248
                        Store: contractcourt.NewRetributionStore(
3✔
1249
                                dbs.ChanStateDB,
3✔
1250
                        ),
3✔
1251
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1252
                },
3✔
1253
        )
3✔
1254

3✔
1255
        //nolint:ll
3✔
1256
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1257
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1258
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1259
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1260
                NewSweepAddr: func() ([]byte, error) {
3✔
1261
                        addr, err := newSweepPkScriptGen(
×
1262
                                cc.Wallet, netParams,
×
1263
                        )().Unpack()
×
1264
                        if err != nil {
×
1265
                                return nil, err
×
1266
                        }
×
1267

1268
                        return addr.DeliveryAddress, nil
×
1269
                },
1270
                PublishTx: cc.Wallet.PublishTransaction,
1271
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1272
                        for _, msg := range msgs {
6✔
1273
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1274
                                if err != nil {
3✔
1275
                                        return err
×
1276
                                }
×
1277
                        }
1278
                        return nil
3✔
1279
                },
1280
                IncubateOutputs: func(chanPoint wire.OutPoint,
1281
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1282
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1283
                        broadcastHeight uint32,
1284
                        deadlineHeight fn.Option[int32]) error {
3✔
1285

3✔
1286
                        return s.utxoNursery.IncubateOutputs(
3✔
1287
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1288
                                broadcastHeight, deadlineHeight,
3✔
1289
                        )
3✔
1290
                },
3✔
1291
                PreimageDB:   s.witnessBeacon,
1292
                Notifier:     cc.ChainNotifier,
1293
                Mempool:      cc.MempoolNotifier,
1294
                Signer:       cc.Wallet.Cfg.Signer,
1295
                FeeEstimator: cc.FeeEstimator,
1296
                ChainIO:      cc.ChainIO,
1297
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1298
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1299
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1300
                        return nil
3✔
1301
                },
3✔
1302
                IsOurAddress: cc.Wallet.IsOurAddress,
1303
                ContractBreach: func(chanPoint wire.OutPoint,
1304
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1305

3✔
1306
                        // processACK will handle the BreachArbitrator ACKing
3✔
1307
                        // the event.
3✔
1308
                        finalErr := make(chan error, 1)
3✔
1309
                        processACK := func(brarErr error) {
6✔
1310
                                if brarErr != nil {
3✔
1311
                                        finalErr <- brarErr
×
1312
                                        return
×
1313
                                }
×
1314

1315
                                // If the BreachArbitrator successfully handled
1316
                                // the event, we can signal that the handoff
1317
                                // was successful.
1318
                                finalErr <- nil
3✔
1319
                        }
1320

1321
                        event := &contractcourt.ContractBreachEvent{
3✔
1322
                                ChanPoint:         chanPoint,
3✔
1323
                                ProcessACK:        processACK,
3✔
1324
                                BreachRetribution: breachRet,
3✔
1325
                        }
3✔
1326

3✔
1327
                        // Send the contract breach event to the
3✔
1328
                        // BreachArbitrator.
3✔
1329
                        select {
3✔
1330
                        case contractBreaches <- event:
3✔
1331
                        case <-s.quit:
×
1332
                                return ErrServerShuttingDown
×
1333
                        }
1334

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

1360
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1361
                QueryIncomingCircuit: func(
1362
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1363

3✔
1364
                        // Get the circuit map.
3✔
1365
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1366

3✔
1367
                        // Lookup the outgoing circuit.
3✔
1368
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1369
                        if pc == nil {
5✔
1370
                                return nil
2✔
1371
                        }
2✔
1372

1373
                        return &pc.Incoming
3✔
1374
                },
1375
                AuxLeafStore: implCfg.AuxLeafStore,
1376
                AuxSigner:    implCfg.AuxSigner,
1377
                AuxResolver:  implCfg.AuxContractResolver,
1378
        }, dbs.ChanStateDB)
1379

1380
        // Select the configuration and funding parameters for Bitcoin.
1381
        chainCfg := cfg.Bitcoin
3✔
1382
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1383
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1384

3✔
1385
        var chanIDSeed [32]byte
3✔
1386
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1387
                return nil, err
×
1388
        }
×
1389

1390
        // Wrap the DeleteChannelEdges method so that the funding manager can
1391
        // use it without depending on several layers of indirection.
1392
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1393
                *models.ChannelEdgePolicy, error) {
6✔
1394

3✔
1395
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1396
                        scid.ToUint64(),
3✔
1397
                )
3✔
1398
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1399
                        // This is unlikely but there is a slim chance of this
×
1400
                        // being hit if lnd was killed via SIGKILL and the
×
1401
                        // funding manager was stepping through the delete
×
1402
                        // alias edge logic.
×
1403
                        return nil, nil
×
1404
                } else if err != nil {
3✔
1405
                        return nil, err
×
1406
                }
×
1407

1408
                // Grab our key to find our policy.
1409
                var ourKey [33]byte
3✔
1410
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1411

3✔
1412
                var ourPolicy *models.ChannelEdgePolicy
3✔
1413
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1414
                        ourPolicy = e1
3✔
1415
                } else {
6✔
1416
                        ourPolicy = e2
3✔
1417
                }
3✔
1418

1419
                if ourPolicy == nil {
3✔
1420
                        // Something is wrong, so return an error.
×
1421
                        return nil, fmt.Errorf("we don't have an edge")
×
1422
                }
×
1423

1424
                err = s.graphDB.DeleteChannelEdges(
3✔
1425
                        false, false, scid.ToUint64(),
3✔
1426
                )
3✔
1427
                return ourPolicy, err
3✔
1428
        }
1429

1430
        // For the reservationTimeout and the zombieSweeperInterval different
1431
        // values are set in case we are in a dev environment so enhance test
1432
        // capacilities.
1433
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1434
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1435

3✔
1436
        // Get the development config for funding manager. If we are not in
3✔
1437
        // development mode, this would be nil.
3✔
1438
        var devCfg *funding.DevConfig
3✔
1439
        if lncfg.IsDevBuild() {
6✔
1440
                devCfg = &funding.DevConfig{
3✔
1441
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1442
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1443
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1444
                }
3✔
1445

3✔
1446
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1447
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1448

3✔
1449
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1450
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1451
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1452
        }
3✔
1453

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

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

3✔
1492
                        // In case the user has explicitly specified
3✔
1493
                        // a default value for the number of
3✔
1494
                        // confirmations, we use it.
3✔
1495
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1496
                        if defaultConf != 0 {
6✔
1497
                                return defaultConf
3✔
1498
                        }
3✔
1499

1500
                        minConf := uint64(3)
×
1501
                        maxConf := uint64(6)
×
1502

×
1503
                        // If this is a wumbo channel, then we'll require the
×
1504
                        // max amount of confirmations.
×
1505
                        if chanAmt > MaxFundingAmount {
×
1506
                                return uint16(maxConf)
×
1507
                        }
×
1508

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

3✔
1531
                        // In case the user has explicitly specified
3✔
1532
                        // a default value for the remote delay, we
3✔
1533
                        // use it.
3✔
1534
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1535
                        if defaultDelay > 0 {
6✔
1536
                                return defaultDelay
3✔
1537
                        }
3✔
1538

1539
                        // If this is a wumbo channel, then we'll require the
1540
                        // max value.
1541
                        if chanAmt > MaxFundingAmount {
×
1542
                                return maxRemoteDelay
×
1543
                        }
×
1544

1545
                        // If not we scale according to channel size.
1546
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1547
                                chanAmt / MaxFundingAmount)
×
1548
                        if delay < minRemoteDelay {
×
1549
                                delay = minRemoteDelay
×
1550
                        }
×
1551
                        if delay > maxRemoteDelay {
×
1552
                                delay = maxRemoteDelay
×
1553
                        }
×
1554
                        return delay
×
1555
                },
1556
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1557
                        peerKey *btcec.PublicKey) error {
3✔
1558

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

3✔
1572
                        // With that taken care of, we'll send this channel to
3✔
1573
                        // the chain arb so it can react to on-chain events.
3✔
1574
                        return s.chainArb.WatchNewChannel(channel)
3✔
1575
                },
1576
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1577
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1578
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1579
                },
3✔
1580
                RequiredRemoteChanReserve: func(chanAmt,
1581
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1582

3✔
1583
                        // By default, we'll require the remote peer to maintain
3✔
1584
                        // at least 1% of the total channel capacity at all
3✔
1585
                        // times. If this value ends up dipping below the dust
3✔
1586
                        // limit, then we'll use the dust limit itself as the
3✔
1587
                        // reserve as required by BOLT #2.
3✔
1588
                        reserve := chanAmt / 100
3✔
1589
                        if reserve < dustLimit {
6✔
1590
                                reserve = dustLimit
3✔
1591
                        }
3✔
1592

1593
                        return reserve
3✔
1594
                },
1595
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1596
                        // By default, we'll allow the remote peer to fully
3✔
1597
                        // utilize the full bandwidth of the channel, minus our
3✔
1598
                        // required reserve.
3✔
1599
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1600
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1601
                },
3✔
1602
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1603
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1604
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1605
                        }
3✔
1606

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

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

1658
        // Assemble a peer notifier which will provide clients with subscriptions
1659
        // to peer online and offline events.
1660
        s.peerNotifier = peernotifier.New()
3✔
1661

3✔
1662
        // Create a channel event store which monitors all open channels.
3✔
1663
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1664
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1665
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1666
                },
3✔
1667
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1668
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1669
                },
3✔
1670
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1671
                Clock:           clock.NewDefaultClock(),
1672
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1673
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1674
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1675
        })
1676

1677
        if cfg.WtClient.Active {
6✔
1678
                policy := wtpolicy.DefaultPolicy()
3✔
1679
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1680

3✔
1681
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1682
                // protocol operations on sat/kw.
3✔
1683
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1684
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1685
                )
3✔
1686

3✔
1687
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1688

3✔
1689
                if err := policy.Validate(); err != nil {
3✔
1690
                        return nil, err
×
1691
                }
×
1692

1693
                // authDial is the wrapper around the btrontide.Dial for the
1694
                // watchtower.
1695
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1696
                        netAddr *lnwire.NetAddress,
3✔
1697
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1698

3✔
1699
                        return brontide.Dial(
3✔
1700
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1701
                        )
3✔
1702
                }
3✔
1703

1704
                // buildBreachRetribution is a call-back that can be used to
1705
                // query the BreachRetribution info and channel type given a
1706
                // channel ID and commitment height.
1707
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1708
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1709
                        channeldb.ChannelType, error) {
6✔
1710

3✔
1711
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1712
                                nil, chanID,
3✔
1713
                        )
3✔
1714
                        if err != nil {
3✔
1715
                                return nil, 0, err
×
1716
                        }
×
1717

1718
                        br, err := lnwallet.NewBreachRetribution(
3✔
1719
                                channel, commitHeight, 0, nil,
3✔
1720
                                implCfg.AuxLeafStore,
3✔
1721
                                implCfg.AuxContractResolver,
3✔
1722
                        )
3✔
1723
                        if err != nil {
3✔
1724
                                return nil, 0, err
×
1725
                        }
×
1726

1727
                        return br, channel.ChanType, nil
3✔
1728
                }
1729

1730
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1731

3✔
1732
                // Copy the policy for legacy channels and set the blob flag
3✔
1733
                // signalling support for anchor channels.
3✔
1734
                anchorPolicy := policy
3✔
1735
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1736

3✔
1737
                // Copy the policy for legacy channels and set the blob flag
3✔
1738
                // signalling support for taproot channels.
3✔
1739
                taprootPolicy := policy
3✔
1740
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1741
                        blob.FlagTaprootChannel,
3✔
1742
                )
3✔
1743

3✔
1744
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1745
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1746
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1747
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1748
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1749
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1750
                                error) {
6✔
1751

3✔
1752
                                return s.channelNotifier.
3✔
1753
                                        SubscribeChannelEvents()
3✔
1754
                        },
3✔
1755
                        Signer: cc.Wallet.Cfg.Signer,
1756
                        NewAddress: func() ([]byte, error) {
3✔
1757
                                addr, err := newSweepPkScriptGen(
3✔
1758
                                        cc.Wallet, netParams,
3✔
1759
                                )().Unpack()
3✔
1760
                                if err != nil {
3✔
1761
                                        return nil, err
×
1762
                                }
×
1763

1764
                                return addr.DeliveryAddress, nil
3✔
1765
                        },
1766
                        SecretKeyRing:      s.cc.KeyRing,
1767
                        Dial:               cfg.net.Dial,
1768
                        AuthDial:           authDial,
1769
                        DB:                 dbs.TowerClientDB,
1770
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1771
                        MinBackoff:         10 * time.Second,
1772
                        MaxBackoff:         5 * time.Minute,
1773
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1774
                }, policy, anchorPolicy, taprootPolicy)
1775
                if err != nil {
3✔
1776
                        return nil, err
×
1777
                }
×
1778
        }
1779

1780
        if len(cfg.ExternalHosts) != 0 {
3✔
1781
                advertisedIPs := make(map[string]struct{})
×
1782
                for _, addr := range s.currentNodeAnn.Addresses {
×
1783
                        advertisedIPs[addr.String()] = struct{}{}
×
1784
                }
×
1785

1786
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1787
                        Hosts:         cfg.ExternalHosts,
×
1788
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1789
                        LookupHost: func(host string) (net.Addr, error) {
×
1790
                                return lncfg.ParseAddressString(
×
1791
                                        host, strconv.Itoa(defaultPeerPort),
×
1792
                                        cfg.net.ResolveTCPAddr,
×
1793
                                )
×
1794
                        },
×
1795
                        AdvertisedIPs: advertisedIPs,
1796
                        AnnounceNewIPs: netann.IPAnnouncer(
1797
                                func(modifier ...netann.NodeAnnModifier) (
1798
                                        lnwire.NodeAnnouncement, error) {
×
1799

×
1800
                                        return s.genNodeAnnouncement(
×
1801
                                                nil, modifier...,
×
1802
                                        )
×
1803
                                }),
×
1804
                })
1805
        }
1806

1807
        // Create liveness monitor.
1808
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1809

3✔
1810
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1811
        for i, listenAddr := range listenAddrs {
6✔
1812
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1813
                // doesn't need to call the general lndResolveTCP function
3✔
1814
                // since we are resolving a local address.
3✔
1815

3✔
1816
                // RESOLVE: We are actually partially accepting inbound
3✔
1817
                // connection requests when we call NewListener.
3✔
1818
                listeners[i], err = brontide.NewListener(
3✔
1819
                        nodeKeyECDH, listenAddr.String(),
3✔
1820
                        // TODO(yy): remove this check and unify the inbound
3✔
1821
                        // connection check inside `InboundPeerConnected`.
3✔
1822
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1823
                )
3✔
1824
                if err != nil {
3✔
1825
                        return nil, err
×
1826
                }
×
1827
        }
1828

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

3✔
1847
        // Finally, register the subsystems in blockbeat.
3✔
1848
        s.registerBlockConsumers()
3✔
1849

3✔
1850
        return s, nil
3✔
1851
}
1852

1853
// UpdateRoutingConfig is a callback function to update the routing config
1854
// values in the main cfg.
1855
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1856
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1857

3✔
1858
        switch c := cfg.Estimator.Config().(type) {
3✔
1859
        case routing.AprioriConfig:
3✔
1860
                routerCfg.ProbabilityEstimatorType =
3✔
1861
                        routing.AprioriEstimatorName
3✔
1862

3✔
1863
                targetCfg := routerCfg.AprioriConfig
3✔
1864
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1865
                targetCfg.Weight = c.AprioriWeight
3✔
1866
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1867
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1868

1869
        case routing.BimodalConfig:
3✔
1870
                routerCfg.ProbabilityEstimatorType =
3✔
1871
                        routing.BimodalEstimatorName
3✔
1872

3✔
1873
                targetCfg := routerCfg.BimodalConfig
3✔
1874
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1875
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1876
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1877
        }
1878

1879
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1880
}
1881

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

1901
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1902
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1903
// may differ from what is on disk.
1904
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1905
        error) {
3✔
1906

3✔
1907
        data, err := u.DataToSign()
3✔
1908
        if err != nil {
3✔
1909
                return nil, err
×
1910
        }
×
1911

1912
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1913
}
1914

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

3✔
1928
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1929
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1930
                srvrLog.Info("Disabling chain backend checks for " +
×
1931
                        "nochainbackend mode")
×
1932

×
1933
                chainBackendAttempts = 0
×
1934
        }
×
1935

1936
        chainHealthCheck := healthcheck.NewObservation(
3✔
1937
                "chain backend",
3✔
1938
                cc.HealthCheck,
3✔
1939
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1940
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1941
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1942
                chainBackendAttempts,
3✔
1943
        )
3✔
1944

3✔
1945
        diskCheck := healthcheck.NewObservation(
3✔
1946
                "disk space",
3✔
1947
                func() error {
3✔
1948
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1949
                                cfg.LndDir,
×
1950
                        )
×
1951
                        if err != nil {
×
1952
                                return err
×
1953
                        }
×
1954

1955
                        // If we have more free space than we require,
1956
                        // we return a nil error.
1957
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1958
                                return nil
×
1959
                        }
×
1960

1961
                        return fmt.Errorf("require: %v free space, got: %v",
×
1962
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1963
                                free)
×
1964
                },
1965
                cfg.HealthChecks.DiskCheck.Interval,
1966
                cfg.HealthChecks.DiskCheck.Timeout,
1967
                cfg.HealthChecks.DiskCheck.Backoff,
1968
                cfg.HealthChecks.DiskCheck.Attempts,
1969
        )
1970

1971
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1972
                "tls",
3✔
1973
                func() error {
3✔
1974
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1975
                                s.cc.KeyRing,
×
1976
                        )
×
1977
                        if err != nil {
×
1978
                                return err
×
1979
                        }
×
1980
                        if expired {
×
1981
                                return fmt.Errorf("TLS certificate is "+
×
1982
                                        "expired as of %v", expTime)
×
1983
                        }
×
1984

1985
                        // If the certificate is not outdated, no error needs
1986
                        // to be returned
1987
                        return nil
×
1988
                },
1989
                cfg.HealthChecks.TLSCheck.Interval,
1990
                cfg.HealthChecks.TLSCheck.Timeout,
1991
                cfg.HealthChecks.TLSCheck.Backoff,
1992
                cfg.HealthChecks.TLSCheck.Attempts,
1993
        )
1994

1995
        checks := []*healthcheck.Observation{
3✔
1996
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1997
        }
3✔
1998

3✔
1999
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2000
        if s.torController != nil {
3✔
2001
                torConnectionCheck := healthcheck.NewObservation(
×
2002
                        "tor connection",
×
2003
                        func() error {
×
2004
                                return healthcheck.CheckTorServiceStatus(
×
2005
                                        s.torController,
×
2006
                                        func() error {
×
2007
                                                return s.createNewHiddenService(
×
2008
                                                        context.TODO(),
×
2009
                                                )
×
2010
                                        },
×
2011
                                )
2012
                        },
2013
                        cfg.HealthChecks.TorConnection.Interval,
2014
                        cfg.HealthChecks.TorConnection.Timeout,
2015
                        cfg.HealthChecks.TorConnection.Backoff,
2016
                        cfg.HealthChecks.TorConnection.Attempts,
2017
                )
2018
                checks = append(checks, torConnectionCheck)
×
2019
        }
2020

2021
        // If remote signing is enabled, add the healthcheck for the remote
2022
        // signing RPC interface.
2023
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2024
                // Because we have two cascading timeouts here, we need to add
3✔
2025
                // some slack to the "outer" one of them in case the "inner"
3✔
2026
                // returns exactly on time.
3✔
2027
                overhead := time.Millisecond * 10
3✔
2028

3✔
2029
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2030
                        "remote signer connection",
3✔
2031
                        rpcwallet.HealthCheck(
3✔
2032
                                s.cfg.RemoteSigner,
3✔
2033

3✔
2034
                                // For the health check we might to be even
3✔
2035
                                // stricter than the initial/normal connect, so
3✔
2036
                                // we use the health check timeout here.
3✔
2037
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2038
                        ),
3✔
2039
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2040
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2041
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2042
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2043
                )
3✔
2044
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2045
        }
3✔
2046

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

×
2065
                                leader, err := leaderElector.IsLeader(
×
2066
                                        timeoutCtx,
×
2067
                                )
×
2068
                                if err != nil {
×
2069
                                        return fmt.Errorf("unable to check if "+
×
2070
                                                "still leader: %v", err)
×
2071
                                }
×
2072

2073
                                if !leader {
×
2074
                                        srvrLog.Debug("Not the current leader")
×
2075
                                        return fmt.Errorf("not the current " +
×
2076
                                                "leader")
×
2077
                                }
×
2078

2079
                                return nil
×
2080
                        },
2081
                        cfg.HealthChecks.LeaderCheck.Interval,
2082
                        cfg.HealthChecks.LeaderCheck.Timeout,
2083
                        cfg.HealthChecks.LeaderCheck.Backoff,
2084
                        cfg.HealthChecks.LeaderCheck.Attempts,
2085
                )
2086

2087
                checks = append(checks, leaderCheck)
×
2088
        }
2089

2090
        // If we have not disabled all of our health checks, we create a
2091
        // liveness monitor with our configured checks.
2092
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2093
                &healthcheck.Config{
3✔
2094
                        Checks:   checks,
3✔
2095
                        Shutdown: srvrLog.Criticalf,
3✔
2096
                },
3✔
2097
        )
3✔
2098
}
2099

2100
// Started returns true if the server has been started, and false otherwise.
2101
// NOTE: This function is safe for concurrent access.
2102
func (s *server) Started() bool {
3✔
2103
        return atomic.LoadInt32(&s.active) != 0
3✔
2104
}
3✔
2105

2106
// cleaner is used to aggregate "cleanup" functions during an operation that
2107
// starts several subsystems. In case one of the subsystem fails to start
2108
// and a proper resource cleanup is required, the "run" method achieves this
2109
// by running all these added "cleanup" functions.
2110
type cleaner []func() error
2111

2112
// add is used to add a cleanup function to be called when
2113
// the run function is executed.
2114
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2115
        return append(c, cleanup)
3✔
2116
}
3✔
2117

2118
// run is used to run all the previousely added cleanup functions.
2119
func (c cleaner) run() {
×
2120
        for i := len(c) - 1; i >= 0; i-- {
×
2121
                if err := c[i](); err != nil {
×
2122
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2123
                }
×
2124
        }
2125
}
2126

2127
// startLowLevelServices starts the low-level services of the server. These
2128
// services must be started successfully before running the main server. The
2129
// services are,
2130
// 1. the chain notifier.
2131
//
2132
// TODO(yy): identify and add more low-level services here.
2133
func (s *server) startLowLevelServices() error {
3✔
2134
        var startErr error
3✔
2135

3✔
2136
        cleanup := cleaner{}
3✔
2137

3✔
2138
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2139
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2140
                startErr = err
×
2141
        }
×
2142

2143
        if startErr != nil {
3✔
2144
                cleanup.run()
×
2145
        }
×
2146

2147
        return startErr
3✔
2148
}
2149

2150
// Start starts the main daemon server, all requested listeners, and any helper
2151
// goroutines.
2152
// NOTE: This function is safe for concurrent access.
2153
//
2154
//nolint:funlen
2155
func (s *server) Start(ctx context.Context) error {
3✔
2156
        // Get the current blockbeat.
3✔
2157
        beat, err := s.getStartingBeat()
3✔
2158
        if err != nil {
3✔
2159
                return err
×
2160
        }
×
2161

2162
        var startErr error
3✔
2163

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

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

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

2184
                if s.livenessMonitor != nil {
6✔
2185
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2186
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2187
                                startErr = err
×
2188
                                return
×
2189
                        }
×
2190
                }
2191

2192
                // Start the notification server. This is used so channel
2193
                // management goroutines can be notified when a funding
2194
                // transaction reaches a sufficient number of confirmations, or
2195
                // when the input for the funding transaction is spent in an
2196
                // attempt at an uncooperative close by the counterparty.
2197
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2198
                if err := s.sigPool.Start(); err != nil {
3✔
2199
                        startErr = err
×
2200
                        return
×
2201
                }
×
2202

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

2209
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2210
                if err := s.readPool.Start(); err != nil {
3✔
2211
                        startErr = err
×
2212
                        return
×
2213
                }
×
2214

2215
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2216
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2217
                        startErr = err
×
2218
                        return
×
2219
                }
×
2220

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

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

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

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

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

2255
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2256
                if err := s.sweeper.Start(beat); err != nil {
3✔
2257
                        startErr = err
×
2258
                        return
×
2259
                }
×
2260

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

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

2273
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2274
                if err := s.fundingMgr.Start(); err != nil {
3✔
2275
                        startErr = err
×
2276
                        return
×
2277
                }
×
2278

2279
                // htlcSwitch must be started before chainArb since the latter
2280
                // relies on htlcSwitch to deliver resolution message upon
2281
                // start.
2282
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2283
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2284
                        startErr = err
×
2285
                        return
×
2286
                }
×
2287

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

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

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

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

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

2318
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2319
                if err := s.chanRouter.Start(); err != nil {
3✔
2320
                        startErr = err
×
2321
                        return
×
2322
                }
×
2323
                // The authGossiper depends on the chanRouter and therefore
2324
                // should be started after it.
2325
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2326
                if err := s.authGossiper.Start(); err != nil {
3✔
2327
                        startErr = err
×
2328
                        return
×
2329
                }
×
2330

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

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

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

2349
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2350
                if err := s.chanEventStore.Start(); err != nil {
3✔
2351
                        startErr = err
×
2352
                        return
×
2353
                }
×
2354

2355
                cleanup.add(func() error {
3✔
2356
                        s.missionController.StopStoreTickers()
×
2357
                        return nil
×
2358
                })
×
2359
                s.missionController.RunStoreTickers()
3✔
2360

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

2393
                // chanSubSwapper must be started after the `channelNotifier`
2394
                // because it depends on channel events as a synchronization
2395
                // point.
2396
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2397
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2398
                        startErr = err
×
2399
                        return
×
2400
                }
×
2401

2402
                if s.torController != nil {
3✔
2403
                        cleanup = cleanup.add(s.torController.Stop)
×
2404
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2405
                                startErr = err
×
2406
                                return
×
2407
                        }
×
2408
                }
2409

2410
                if s.natTraversal != nil {
3✔
2411
                        s.wg.Add(1)
×
2412
                        go s.watchExternalIP()
×
2413
                }
×
2414

2415
                // Start connmgr last to prevent connections before init.
2416
                cleanup = cleanup.add(func() error {
3✔
2417
                        s.connMgr.Stop()
×
2418
                        return nil
×
2419
                })
×
2420

2421
                // RESOLVE: s.connMgr.Start() is called here, but
2422
                // brontide.NewListener() is called in newServer. This means
2423
                // that we are actually listening and partially accepting
2424
                // inbound connections even before the connMgr starts.
2425
                //
2426
                // TODO(yy): move the log into the connMgr's `Start` method.
2427
                srvrLog.Info("connMgr starting...")
3✔
2428
                s.connMgr.Start()
3✔
2429
                srvrLog.Debug("connMgr started")
3✔
2430

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

2450
                        peerAddr := &lnwire.NetAddress{
3✔
2451
                                IdentityKey: parsedPubkey,
3✔
2452
                                Address:     addr,
3✔
2453
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2454
                        }
3✔
2455

3✔
2456
                        err = s.ConnectToPeer(
3✔
2457
                                peerAddr, true,
3✔
2458
                                s.cfg.ConnectionTimeout,
3✔
2459
                        )
3✔
2460
                        if err != nil {
3✔
2461
                                startErr = fmt.Errorf("unable to connect to "+
×
2462
                                        "peer address provided as a config "+
×
2463
                                        "option: %v", err)
×
2464
                                return
×
2465
                        }
×
2466
                }
2467

2468
                // Subscribe to NodeAnnouncements that advertise new addresses
2469
                // our persistent peers.
2470
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2471
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2472
                                "addr: %v", err)
×
2473

×
2474
                        startErr = err
×
2475
                        return
×
2476
                }
×
2477

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

×
2487
                        startErr = err
×
2488
                        return
×
2489
                }
×
2490

2491
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2492
                        srvrLog.Errorf("Failed to establish persistent "+
×
2493
                                "connections: %v", err)
×
2494
                }
×
2495

2496
                // setSeedList is a helper function that turns multiple DNS seed
2497
                // server tuples from the command line or config file into the
2498
                // data structure we need and does a basic formal sanity check
2499
                // in the process.
2500
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2501
                        if len(tuples) == 0 {
×
2502
                                return
×
2503
                        }
×
2504

2505
                        result := make([][2]string, len(tuples))
×
2506
                        for idx, tuple := range tuples {
×
2507
                                tuple = strings.TrimSpace(tuple)
×
2508
                                if len(tuple) == 0 {
×
2509
                                        return
×
2510
                                }
×
2511

2512
                                servers := strings.Split(tuple, ",")
×
2513
                                if len(servers) > 2 || len(servers) == 0 {
×
2514
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2515
                                                "seed tuple: %v", servers)
×
2516
                                        return
×
2517
                                }
×
2518

2519
                                copy(result[idx][:], servers)
×
2520
                        }
2521

2522
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2523
                }
2524

2525
                // Let users overwrite the DNS seed nodes. We only allow them
2526
                // for bitcoin mainnet/testnet/signet.
2527
                if s.cfg.Bitcoin.MainNet {
3✔
2528
                        setSeedList(
×
2529
                                s.cfg.Bitcoin.DNSSeeds,
×
2530
                                chainreg.BitcoinMainnetGenesis,
×
2531
                        )
×
2532
                }
×
2533
                if s.cfg.Bitcoin.TestNet3 {
3✔
2534
                        setSeedList(
×
2535
                                s.cfg.Bitcoin.DNSSeeds,
×
2536
                                chainreg.BitcoinTestnetGenesis,
×
2537
                        )
×
2538
                }
×
2539
                if s.cfg.Bitcoin.TestNet4 {
3✔
2540
                        setSeedList(
×
2541
                                s.cfg.Bitcoin.DNSSeeds,
×
2542
                                chainreg.BitcoinTestnet4Genesis,
×
2543
                        )
×
2544
                }
×
2545
                if s.cfg.Bitcoin.SigNet {
3✔
2546
                        setSeedList(
×
2547
                                s.cfg.Bitcoin.DNSSeeds,
×
2548
                                chainreg.BitcoinSignetGenesis,
×
2549
                        )
×
2550
                }
×
2551

2552
                // If network bootstrapping hasn't been disabled, then we'll
2553
                // configure the set of active bootstrappers, and launch a
2554
                // dedicated goroutine to maintain a set of persistent
2555
                // connections.
2556
                if !s.cfg.NoNetBootstrap {
6✔
2557
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2558
                        if err != nil {
3✔
2559
                                startErr = err
×
2560
                                return
×
2561
                        }
×
2562

2563
                        s.wg.Add(1)
3✔
2564
                        go s.peerBootstrapper(
3✔
2565
                                ctx, defaultMinPeers, bootstrappers,
3✔
2566
                        )
3✔
2567
                } else {
3✔
2568
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2569
                }
3✔
2570

2571
                // Start the blockbeat after all other subsystems have been
2572
                // started so they are ready to receive new blocks.
2573
                cleanup = cleanup.add(func() error {
3✔
2574
                        s.blockbeatDispatcher.Stop()
×
2575
                        return nil
×
2576
                })
×
2577
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2578
                        startErr = err
×
2579
                        return
×
2580
                }
×
2581

2582
                // Set the active flag now that we've completed the full
2583
                // startup.
2584
                atomic.StoreInt32(&s.active, 1)
3✔
2585
        })
2586

2587
        if startErr != nil {
3✔
2588
                cleanup.run()
×
2589
        }
×
2590
        return startErr
3✔
2591
}
2592

2593
// Stop gracefully shutsdown the main daemon server. This function will signal
2594
// any active goroutines, or helper objects to exit, then blocks until they've
2595
// all successfully exited. Additionally, any/all listeners are closed.
2596
// NOTE: This function is safe for concurrent access.
2597
func (s *server) Stop() error {
3✔
2598
        s.stop.Do(func() {
6✔
2599
                atomic.StoreInt32(&s.stopping, 1)
3✔
2600

3✔
2601
                ctx := context.Background()
3✔
2602

3✔
2603
                close(s.quit)
3✔
2604

3✔
2605
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2606
                s.connMgr.Stop()
3✔
2607

3✔
2608
                // Stop dispatching blocks to other systems immediately.
3✔
2609
                s.blockbeatDispatcher.Stop()
3✔
2610

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

2673
                // Update channel.backup file. Make sure to do it before
2674
                // stopping chanSubSwapper.
2675
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2676
                        ctx, s.chanStateDB, s.addrSource,
3✔
2677
                )
3✔
2678
                if err != nil {
3✔
2679
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2680
                                err)
×
2681
                } else {
3✔
2682
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2683
                        if err != nil {
6✔
2684
                                srvrLog.Warnf("Manual update of channel "+
3✔
2685
                                        "backup failed: %v", err)
3✔
2686
                        }
3✔
2687
                }
2688

2689
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2690
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2691
                }
×
2692
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2693
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2694
                }
×
2695
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2696
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2697
                                err)
×
2698
                }
×
2699
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2700
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2701
                                err)
×
2702
                }
×
2703
                s.missionController.StopStoreTickers()
3✔
2704

3✔
2705
                // Disconnect from each active peers to ensure that
3✔
2706
                // peerTerminationWatchers signal completion to each peer.
3✔
2707
                for _, peer := range s.Peers() {
6✔
2708
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2709
                        if err != nil {
3✔
2710
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2711
                                        "received error: %v", peer.IdentityKey(),
×
2712
                                        err,
×
2713
                                )
×
2714
                        }
×
2715
                }
2716

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

2728
                if s.hostAnn != nil {
3✔
2729
                        if err := s.hostAnn.Stop(); err != nil {
×
2730
                                srvrLog.Warnf("unable to shut down host "+
×
2731
                                        "annoucner: %v", err)
×
2732
                        }
×
2733
                }
2734

2735
                if s.livenessMonitor != nil {
6✔
2736
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2737
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2738
                                        "monitor: %v", err)
×
2739
                        }
×
2740
                }
2741

2742
                // Wait for all lingering goroutines to quit.
2743
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2744
                s.wg.Wait()
3✔
2745

3✔
2746
                srvrLog.Debug("Stopping buffer pools...")
3✔
2747
                s.sigPool.Stop()
3✔
2748
                s.writePool.Stop()
3✔
2749
                s.readPool.Stop()
3✔
2750
        })
2751

2752
        return nil
3✔
2753
}
2754

2755
// Stopped returns true if the server has been instructed to shutdown.
2756
// NOTE: This function is safe for concurrent access.
2757
func (s *server) Stopped() bool {
3✔
2758
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2759
}
3✔
2760

2761
// configurePortForwarding attempts to set up port forwarding for the different
2762
// ports that the server will be listening on.
2763
//
2764
// NOTE: This should only be used when using some kind of NAT traversal to
2765
// automatically set up forwarding rules.
2766
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2767
        ip, err := s.natTraversal.ExternalIP()
×
2768
        if err != nil {
×
2769
                return nil, err
×
2770
        }
×
2771
        s.lastDetectedIP = ip
×
2772

×
2773
        externalIPs := make([]string, 0, len(ports))
×
2774
        for _, port := range ports {
×
2775
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2776
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2777
                        continue
×
2778
                }
2779

2780
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2781
                externalIPs = append(externalIPs, hostIP)
×
2782
        }
2783

2784
        return externalIPs, nil
×
2785
}
2786

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

2802
// watchExternalIP continuously checks for an updated external IP address every
2803
// 15 minutes. Once a new IP address has been detected, it will automatically
2804
// handle port forwarding rules and send updated node announcements to the
2805
// currently connected peers.
2806
//
2807
// NOTE: This MUST be run as a goroutine.
2808
func (s *server) watchExternalIP() {
×
2809
        defer s.wg.Done()
×
2810

×
2811
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2812
        // up by the server.
×
2813
        defer s.removePortForwarding()
×
2814

×
2815
        // Keep track of the external IPs set by the user to avoid replacing
×
2816
        // them when detecting a new IP.
×
2817
        ipsSetByUser := make(map[string]struct{})
×
2818
        for _, ip := range s.cfg.ExternalIPs {
×
2819
                ipsSetByUser[ip.String()] = struct{}{}
×
2820
        }
×
2821

2822
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2823

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

2839
                        // Periodically renew the NAT port forwarding.
2840
                        for _, port := range forwardedPorts {
×
2841
                                err := s.natTraversal.AddPortMapping(port)
×
2842
                                if err != nil {
×
2843
                                        srvrLog.Warnf("Unable to automatically "+
×
2844
                                                "re-create port forwarding using %s: %v",
×
2845
                                                s.natTraversal.Name(), err)
×
2846
                                } else {
×
2847
                                        srvrLog.Debugf("Automatically re-created "+
×
2848
                                                "forwarding for port %d using %s to "+
×
2849
                                                "advertise external IP",
×
2850
                                                port, s.natTraversal.Name())
×
2851
                                }
×
2852
                        }
2853

2854
                        if ip.Equal(s.lastDetectedIP) {
×
2855
                                continue
×
2856
                        }
2857

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

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

2875
                                newAddrs = append(newAddrs, addr)
×
2876
                        }
2877

2878
                        // Skip the update if we weren't able to resolve any of
2879
                        // the new addresses.
2880
                        if len(newAddrs) == 0 {
×
2881
                                srvrLog.Debug("Skipping node announcement " +
×
2882
                                        "update due to not being able to " +
×
2883
                                        "resolve any new addresses")
×
2884
                                continue
×
2885
                        }
2886

2887
                        // Now, we'll need to update the addresses in our node's
2888
                        // announcement in order to propagate the update
2889
                        // throughout the network. We'll only include addresses
2890
                        // that have a different IP from the previous one, as
2891
                        // the previous IP is no longer valid.
2892
                        currentNodeAnn := s.getNodeAnnouncement()
×
2893

×
2894
                        for _, addr := range currentNodeAnn.Addresses {
×
2895
                                host, _, err := net.SplitHostPort(addr.String())
×
2896
                                if err != nil {
×
2897
                                        srvrLog.Debugf("Unable to determine "+
×
2898
                                                "host from address %v: %v",
×
2899
                                                addr, err)
×
2900
                                        continue
×
2901
                                }
2902

2903
                                // We'll also make sure to include external IPs
2904
                                // set manually by the user.
2905
                                _, setByUser := ipsSetByUser[addr.String()]
×
2906
                                if setByUser || host != s.lastDetectedIP.String() {
×
2907
                                        newAddrs = append(newAddrs, addr)
×
2908
                                }
×
2909
                        }
2910

2911
                        // Then, we'll generate a new timestamped node
2912
                        // announcement with the updated addresses and broadcast
2913
                        // it to our peers.
2914
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2915
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2916
                        )
×
2917
                        if err != nil {
×
2918
                                srvrLog.Debugf("Unable to generate new node "+
×
2919
                                        "announcement: %v", err)
×
2920
                                continue
×
2921
                        }
2922

2923
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2924
                        if err != nil {
×
2925
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2926
                                        "announcement to peers: %v", err)
×
2927
                                continue
×
2928
                        }
2929

2930
                        // Finally, update the last IP seen to the current one.
2931
                        s.lastDetectedIP = ip
×
2932
                case <-s.quit:
×
2933
                        break out
×
2934
                }
2935
        }
2936
}
2937

2938
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2939
// based on the server, and currently active bootstrap mechanisms as defined
2940
// within the current configuration.
2941
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2942
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2943

3✔
2944
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2945

3✔
2946
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2947
        // this can be used by default if we've already partially seeded the
3✔
2948
        // network.
3✔
2949
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2950
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2951
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2952
        )
3✔
2953
        if err != nil {
3✔
2954
                return nil, err
×
2955
        }
×
2956
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2957

3✔
2958
        // If this isn't using simnet or regtest mode, then one of our
3✔
2959
        // additional bootstrapping sources will be the set of running DNS
3✔
2960
        // seeds.
3✔
2961
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2962
                //nolint:ll
×
2963
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2964

×
2965
                // If we have a set of DNS seeds for this chain, then we'll add
×
2966
                // it as an additional bootstrapping source.
×
2967
                if ok {
×
2968
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2969
                                "seeds: %v", dnsSeeds)
×
2970

×
2971
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2972
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2973
                        )
×
2974
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2975
                }
×
2976
        }
2977

2978
        return bootStrappers, nil
3✔
2979
}
2980

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

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

3✔
2993
        // We should ignore ourselves from bootstrapping.
3✔
2994
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
2995
        ignore[selfKey] = struct{}{}
3✔
2996

3✔
2997
        // Ignore all connected peers.
3✔
2998
        for _, peer := range s.peersByPub {
3✔
2999
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3000
                ignore[nID] = struct{}{}
×
3001
        }
×
3002

3003
        // Ignore all persistent peers as they have a dedicated reconnecting
3004
        // process.
3005
        for pubKeyStr := range s.persistentPeers {
3✔
3006
                var nID autopilot.NodeID
×
3007
                copy(nID[:], []byte(pubKeyStr))
×
3008
                ignore[nID] = struct{}{}
×
3009
        }
×
3010

3011
        return ignore
3✔
3012
}
3013

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

3✔
3022
        defer s.wg.Done()
3✔
3023

3✔
3024
        // Before we continue, init the ignore peers map.
3✔
3025
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3026

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

3✔
3031
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3032
        // peers.
3✔
3033
        //
3✔
3034
        // We'll use a 15 second backoff, and double the time every time an
3✔
3035
        // epoch fails up to a ceiling.
3✔
3036
        backOff := time.Second * 15
3✔
3037

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

3✔
3043
        // We'll use the number of attempts and errors to determine if we need
3✔
3044
        // to increase the time between discovery epochs.
3✔
3045
        var epochErrors uint32 // To be used atomically.
3✔
3046
        var epochAttempts uint32
3✔
3047

3✔
3048
        for {
6✔
3049
                select {
3✔
3050
                // The ticker has just woken us up, so we'll need to check if
3051
                // we need to attempt to connect our to any more peers.
3052
                case <-sampleTicker.C:
×
3053
                        // Obtain the current number of peers, so we can gauge
×
3054
                        // if we need to sample more peers or not.
×
3055
                        s.mu.RLock()
×
3056
                        numActivePeers := uint32(len(s.peersByPub))
×
3057
                        s.mu.RUnlock()
×
3058

×
3059
                        // If we have enough peers, then we can loop back
×
3060
                        // around to the next round as we're done here.
×
3061
                        if numActivePeers >= numTargetPeers {
×
3062
                                continue
×
3063
                        }
3064

3065
                        // If all of our attempts failed during this last back
3066
                        // off period, then will increase our backoff to 5
3067
                        // minute ceiling to avoid an excessive number of
3068
                        // queries
3069
                        //
3070
                        // TODO(roasbeef): add reverse policy too?
3071

3072
                        if epochAttempts > 0 &&
×
3073
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3074

×
3075
                                sampleTicker.Stop()
×
3076

×
3077
                                backOff *= 2
×
3078
                                if backOff > bootstrapBackOffCeiling {
×
3079
                                        backOff = bootstrapBackOffCeiling
×
3080
                                }
×
3081

3082
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3083
                                        "%v", backOff)
×
3084
                                sampleTicker = time.NewTicker(backOff)
×
3085
                                continue
×
3086
                        }
3087

3088
                        atomic.StoreUint32(&epochErrors, 0)
×
3089
                        epochAttempts = 0
×
3090

×
3091
                        // Since we know need more peers, we'll compute the
×
3092
                        // exact number we need to reach our threshold.
×
3093
                        numNeeded := numTargetPeers - numActivePeers
×
3094

×
3095
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3096
                                "peers", numNeeded)
×
3097

×
3098
                        // With the number of peers we need calculated, we'll
×
3099
                        // query the network bootstrappers to sample a set of
×
3100
                        // random addrs for us.
×
3101
                        //
×
3102
                        // Before we continue, get a copy of the ignore peers
×
3103
                        // map.
×
3104
                        ignoreList = s.createBootstrapIgnorePeers()
×
3105

×
3106
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3107
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3108
                        )
×
3109
                        if err != nil {
×
3110
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3111
                                        "peers: %v", err)
×
3112
                                continue
×
3113
                        }
3114

3115
                        // Finally, we'll launch a new goroutine for each
3116
                        // prospective peer candidates.
3117
                        for _, addr := range peerAddrs {
×
3118
                                epochAttempts++
×
3119

×
3120
                                go func(a *lnwire.NetAddress) {
×
3121
                                        // TODO(roasbeef): can do AS, subnet,
×
3122
                                        // country diversity, etc
×
3123
                                        errChan := make(chan error, 1)
×
3124
                                        s.connectToPeer(
×
3125
                                                a, errChan,
×
3126
                                                s.cfg.ConnectionTimeout,
×
3127
                                        )
×
3128
                                        select {
×
3129
                                        case err := <-errChan:
×
3130
                                                if err == nil {
×
3131
                                                        return
×
3132
                                                }
×
3133

3134
                                                srvrLog.Errorf("Unable to "+
×
3135
                                                        "connect to %v: %v",
×
3136
                                                        a, err)
×
3137
                                                atomic.AddUint32(&epochErrors, 1)
×
3138
                                        case <-s.quit:
×
3139
                                        }
3140
                                }(addr)
3141
                        }
3142
                case <-s.quit:
3✔
3143
                        return
3✔
3144
                }
3145
        }
3146
}
3147

3148
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3149
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3150
// query back off each time we encounter a failure.
3151
const bootstrapBackOffCeiling = time.Minute * 5
3152

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

3✔
3160
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3161
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3162

3✔
3163
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3164
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3165
        var delaySignal <-chan time.Time
3✔
3166
        delayTime := time.Second * 2
3✔
3167

3✔
3168
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3169
        // then the main peer bootstrap logic.
3✔
3170
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3171

3✔
3172
        for attempts := 0; ; attempts++ {
6✔
3173
                // Check if the server has been requested to shut down in order
3✔
3174
                // to prevent blocking.
3✔
3175
                if s.Stopped() {
3✔
3176
                        return
×
3177
                }
×
3178

3179
                // We can exit our aggressive initial peer bootstrapping stage
3180
                // if we've reached out target number of peers.
3181
                s.mu.RLock()
3✔
3182
                numActivePeers := uint32(len(s.peersByPub))
3✔
3183
                s.mu.RUnlock()
3✔
3184

3✔
3185
                if numActivePeers >= numTargetPeers {
6✔
3186
                        return
3✔
3187
                }
3✔
3188

3189
                if attempts > 0 {
3✔
UNCOV
3190
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3191
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3192
                                attempts)
×
UNCOV
3193

×
UNCOV
3194
                        // We've completed at least one iterating and haven't
×
UNCOV
3195
                        // finished, so we'll start to insert a delay period
×
UNCOV
3196
                        // between each attempt.
×
UNCOV
3197
                        delaySignal = time.After(delayTime)
×
UNCOV
3198
                        select {
×
UNCOV
3199
                        case <-delaySignal:
×
3200
                        case <-s.quit:
×
3201
                                return
×
3202
                        }
3203

3204
                        // After our delay, we'll double the time we wait up to
3205
                        // the max back off period.
UNCOV
3206
                        delayTime *= 2
×
UNCOV
3207
                        if delayTime > backOffCeiling {
×
3208
                                delayTime = backOffCeiling
×
3209
                        }
×
3210
                }
3211

3212
                // Otherwise, we'll request for the remaining number of peers
3213
                // in order to reach our target.
3214
                peersNeeded := numTargetPeers - numActivePeers
3✔
3215
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3216
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3217
                )
3✔
3218
                if err != nil {
3✔
UNCOV
3219
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3220
                                "peers: %v", err)
×
UNCOV
3221
                        continue
×
3222
                }
3223

3224
                // Then, we'll attempt to establish a connection to the
3225
                // different peer addresses retrieved by our bootstrappers.
3226
                var wg sync.WaitGroup
3✔
3227
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3228
                        wg.Add(1)
3✔
3229
                        go func(addr *lnwire.NetAddress) {
6✔
3230
                                defer wg.Done()
3✔
3231

3✔
3232
                                errChan := make(chan error, 1)
3✔
3233
                                go s.connectToPeer(
3✔
3234
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3235
                                )
3✔
3236

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

3260
                wg.Wait()
3✔
3261
        }
3262
}
3263

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

3276
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3277
        if err != nil {
×
3278
                return err
×
3279
        }
×
3280

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

×
3293
        switch {
×
3294
        case s.cfg.Tor.V2:
×
3295
                onionCfg.Type = tor.V2
×
3296
        case s.cfg.Tor.V3:
×
3297
                onionCfg.Type = tor.V3
×
3298
        }
3299

3300
        addr, err := s.torController.AddOnion(onionCfg)
×
3301
        if err != nil {
×
3302
                return err
×
3303
        }
×
3304

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

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

3335
        return nil
×
3336
}
3337

3338
// findChannel finds a channel given a public key and ChannelID. It is an
3339
// optimization that is quicker than seeking for a channel given only the
3340
// ChannelID.
3341
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3342
        *channeldb.OpenChannel, error) {
3✔
3343

3✔
3344
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3345
        if err != nil {
3✔
3346
                return nil, err
×
3347
        }
×
3348

3349
        for _, channel := range nodeChans {
6✔
3350
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3351
                        return channel, nil
3✔
3352
                }
3✔
3353
        }
3354

3355
        return nil, fmt.Errorf("unable to find channel")
3✔
3356
}
3357

3358
// getNodeAnnouncement fetches the current, fully signed node announcement.
3359
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3360
        s.mu.Lock()
3✔
3361
        defer s.mu.Unlock()
3✔
3362

3✔
3363
        return *s.currentNodeAnn
3✔
3364
}
3✔
3365

3366
// genNodeAnnouncement generates and returns the current fully signed node
3367
// announcement. The time stamp of the announcement will be updated in order
3368
// to ensure it propagates through the network.
3369
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3370
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3371

3✔
3372
        s.mu.Lock()
3✔
3373
        defer s.mu.Unlock()
3✔
3374

3✔
3375
        // Create a shallow copy of the current node announcement to work on.
3✔
3376
        // This ensures the original announcement remains unchanged
3✔
3377
        // until the new announcement is fully signed and valid.
3✔
3378
        newNodeAnn := *s.currentNodeAnn
3✔
3379

3✔
3380
        // First, try to update our feature manager with the updated set of
3✔
3381
        // features.
3✔
3382
        if features != nil {
6✔
3383
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3384
                        feature.SetNodeAnn: features,
3✔
3385
                }
3✔
3386
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3387
                if err != nil {
6✔
3388
                        return lnwire.NodeAnnouncement{}, err
3✔
3389
                }
3✔
3390

3391
                // If we could successfully update our feature manager, add
3392
                // an update modifier to include these new features to our
3393
                // set.
3394
                modifiers = append(
3✔
3395
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3396
                )
3✔
3397
        }
3398

3399
        // Always update the timestamp when refreshing to ensure the update
3400
        // propagates.
3401
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3402

3✔
3403
        // Apply the requested changes to the node announcement.
3✔
3404
        for _, modifier := range modifiers {
6✔
3405
                modifier(&newNodeAnn)
3✔
3406
        }
3✔
3407

3408
        // Sign a new update after applying all of the passed modifiers.
3409
        err := netann.SignNodeAnnouncement(
3✔
3410
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3411
        )
3✔
3412
        if err != nil {
3✔
3413
                return lnwire.NodeAnnouncement{}, err
×
3414
        }
×
3415

3416
        // If signing succeeds, update the current announcement.
3417
        *s.currentNodeAnn = newNodeAnn
3✔
3418

3✔
3419
        return *s.currentNodeAnn, nil
3✔
3420
}
3421

3422
// updateAndBroadcastSelfNode generates a new node announcement
3423
// applying the giving modifiers and updating the time stamp
3424
// to ensure it propagates through the network. Then it broadcasts
3425
// it to the network.
3426
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3427
        features *lnwire.RawFeatureVector,
3428
        modifiers ...netann.NodeAnnModifier) error {
3✔
3429

3✔
3430
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3431
        if err != nil {
6✔
3432
                return fmt.Errorf("unable to generate new node "+
3✔
3433
                        "announcement: %v", err)
3✔
3434
        }
3✔
3435

3436
        // Update the on-disk version of our announcement.
3437
        // Load and modify self node istead of creating anew instance so we
3438
        // don't risk overwriting any existing values.
3439
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3440
        if err != nil {
3✔
3441
                return fmt.Errorf("unable to get current source node: %w", err)
×
3442
        }
×
3443

3444
        selfNode.HaveNodeAnnouncement = true
3✔
3445
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3446
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3447
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3448
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3449
        selfNode.Color = newNodeAnn.RGBColor
3✔
3450
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3451

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

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

3458
        // Finally, propagate it to the nodes in the network.
3459
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3460
        if err != nil {
3✔
3461
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3462
                        "announcement to peers: %v", err)
×
3463
                return err
×
3464
        }
×
3465

3466
        return nil
3✔
3467
}
3468

3469
type nodeAddresses struct {
3470
        pubKey    *btcec.PublicKey
3471
        addresses []net.Addr
3472
}
3473

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

3✔
3484
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3485
        // attempt to connect to based on our set of previous connections. Set
3✔
3486
        // the reconnection port to the default peer port.
3✔
3487
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3488
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3489
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3490
        }
×
3491

3492
        for _, node := range linkNodes {
6✔
3493
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3494
                nodeAddrs := &nodeAddresses{
3✔
3495
                        pubKey:    node.IdentityPub,
3✔
3496
                        addresses: node.Addresses,
3✔
3497
                }
3✔
3498
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3499
        }
3✔
3500

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

3✔
3510
                // If the remote party has announced the channel to us, but we
3✔
3511
                // haven't yet, then we won't have a policy. However, we don't
3✔
3512
                // need this to connect to the peer, so we'll log it and move on.
3✔
3513
                if !havePolicy {
3✔
3514
                        srvrLog.Warnf("No channel policy found for "+
×
3515
                                "ChannelPoint(%v): ", chanPoint)
×
3516
                }
×
3517

3518
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3519

3✔
3520
                // Add all unique addresses from channel
3✔
3521
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3522
                // connect to for this peer.
3✔
3523
                addrSet := make(map[string]net.Addr)
3✔
3524
                for _, addr := range channelPeer.Addresses {
6✔
3525
                        switch addr.(type) {
3✔
3526
                        case *net.TCPAddr:
3✔
3527
                                addrSet[addr.String()] = addr
3✔
3528

3529
                        // We'll only attempt to connect to Tor addresses if Tor
3530
                        // outbound support is enabled.
3531
                        case *tor.OnionAddr:
×
3532
                                if s.cfg.Tor.Active {
×
3533
                                        addrSet[addr.String()] = addr
×
3534
                                }
×
3535
                        }
3536
                }
3537

3538
                // If this peer is also recorded as a link node, we'll add any
3539
                // additional addresses that have not already been selected.
3540
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3541
                if ok {
6✔
3542
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3543
                                switch lnAddress.(type) {
3✔
3544
                                case *net.TCPAddr:
3✔
3545
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3546

3547
                                // We'll only attempt to connect to Tor
3548
                                // addresses if Tor outbound support is enabled.
3549
                                case *tor.OnionAddr:
×
3550
                                        if s.cfg.Tor.Active {
×
3551
                                                //nolint:ll
×
3552
                                                addrSet[lnAddress.String()] = lnAddress
×
3553
                                        }
×
3554
                                }
3555
                        }
3556
                }
3557

3558
                // Construct a slice of the deduped addresses.
3559
                var addrs []net.Addr
3✔
3560
                for _, addr := range addrSet {
6✔
3561
                        addrs = append(addrs, addr)
3✔
3562
                }
3✔
3563

3564
                n := &nodeAddresses{
3✔
3565
                        addresses: addrs,
3✔
3566
                }
3✔
3567
                n.pubKey, err = channelPeer.PubKey()
3✔
3568
                if err != nil {
3✔
3569
                        return err
×
3570
                }
×
3571

3572
                graphAddrs[pubStr] = n
3✔
3573
                return nil
3✔
3574
        }
3575
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3576
                ctx, forEachSrcNodeChan, func() {
6✔
3577
                        clear(graphAddrs)
3✔
3578
                },
3✔
3579
        )
3580
        if err != nil {
3✔
3581
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3582
                        "%v", err)
×
3583

×
3584
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3585
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3586

×
3587
                        return err
×
3588
                }
×
3589
        }
3590

3591
        // Combine the addresses from the link nodes and the channel graph.
3592
        for pubStr, nodeAddr := range graphAddrs {
6✔
3593
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3594
        }
3✔
3595

3596
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3597
                len(nodeAddrsMap))
3✔
3598

3✔
3599
        // Acquire and hold server lock until all persistent connection requests
3✔
3600
        // have been recorded and sent to the connection manager.
3✔
3601
        s.mu.Lock()
3✔
3602
        defer s.mu.Unlock()
3✔
3603

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

3618
                for _, address := range nodeAddr.addresses {
6✔
3619
                        // Create a wrapper address which couples the IP and
3✔
3620
                        // the pubkey so the brontide authenticated connection
3✔
3621
                        // can be established.
3✔
3622
                        lnAddr := &lnwire.NetAddress{
3✔
3623
                                IdentityKey: nodeAddr.pubKey,
3✔
3624
                                Address:     address,
3✔
3625
                        }
3✔
3626

3✔
3627
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3628
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3629
                }
3✔
3630

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

3✔
3641
                        go s.connectToPersistentPeer(pubStr)
3✔
3642
                } else {
3✔
3643
                        go s.delayInitialReconnect(pubStr)
×
3644
                }
×
3645

3646
                numOutboundConns++
3✔
3647
        }
3648

3649
        return nil
3✔
3650
}
3651

3652
// delayInitialReconnect will attempt a reconnection to the given peer after
3653
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3654
//
3655
// NOTE: This method MUST be run as a goroutine.
3656
func (s *server) delayInitialReconnect(pubStr string) {
×
3657
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3658
        select {
×
3659
        case <-time.After(delay):
×
3660
                s.connectToPersistentPeer(pubStr)
×
3661
        case <-s.quit:
×
3662
        }
3663
}
3664

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

3✔
3671
        s.mu.Lock()
3✔
3672
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3673
                delete(s.persistentPeers, pubKeyStr)
3✔
3674
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3675
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3676
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3677
                s.mu.Unlock()
3✔
3678

3✔
3679
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3680
                        "peer has no open channels", compressedPubKey)
3✔
3681

3✔
3682
                return
3✔
3683
        }
3✔
3684
        s.mu.Unlock()
3✔
3685
}
3686

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

3704
// BroadcastMessage sends a request to the server to broadcast a set of
3705
// messages to all peers other than the one specified by the `skips` parameter.
3706
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3707
// the target peers.
3708
//
3709
// NOTE: This function is safe for concurrent access.
3710
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3711
        msgs ...lnwire.Message) error {
3✔
3712

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

3727
                peers = append(peers, sPeer)
3✔
3728
        }
3729
        s.mu.RUnlock()
3✔
3730

3✔
3731
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3732
        // all messages to each of peers.
3✔
3733
        var wg sync.WaitGroup
3✔
3734
        for _, sPeer := range peers {
6✔
3735
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3736
                        sPeer.PubKey())
3✔
3737

3✔
3738
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3739
                wg.Add(1)
3✔
3740
                s.wg.Add(1)
3✔
3741
                go func(p lnpeer.Peer) {
6✔
3742
                        defer s.wg.Done()
3✔
3743
                        defer wg.Done()
3✔
3744

3✔
3745
                        p.SendMessageLazy(false, msgs...)
3✔
3746
                }(sPeer)
3✔
3747
        }
3748

3749
        // Wait for all messages to have been dispatched before returning to
3750
        // caller.
3751
        wg.Wait()
3✔
3752

3✔
3753
        return nil
3✔
3754
}
3755

3756
// NotifyWhenOnline can be called by other subsystems to get notified when a
3757
// particular peer comes online. The peer itself is sent across the peerChan.
3758
//
3759
// NOTE: This function is safe for concurrent access.
3760
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3761
        peerChan chan<- lnpeer.Peer) {
3✔
3762

3✔
3763
        s.mu.Lock()
3✔
3764

3✔
3765
        // Compute the target peer's identifier.
3✔
3766
        pubStr := string(peerKey[:])
3✔
3767

3✔
3768
        // Check if peer is connected.
3✔
3769
        peer, ok := s.peersByPub[pubStr]
3✔
3770
        if ok {
6✔
3771
                // Unlock here so that the mutex isn't held while we are
3✔
3772
                // waiting for the peer to become active.
3✔
3773
                s.mu.Unlock()
3✔
3774

3✔
3775
                // Wait until the peer signals that it is actually active
3✔
3776
                // rather than only in the server's maps.
3✔
3777
                select {
3✔
3778
                case <-peer.ActiveSignal():
3✔
3779
                case <-peer.QuitSignal():
×
3780
                        // The peer quit, so we'll add the channel to the slice
×
3781
                        // and return.
×
3782
                        s.mu.Lock()
×
3783
                        s.peerConnectedListeners[pubStr] = append(
×
3784
                                s.peerConnectedListeners[pubStr], peerChan,
×
3785
                        )
×
3786
                        s.mu.Unlock()
×
3787
                        return
×
3788
                }
3789

3790
                // Connected, can return early.
3791
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3792

3✔
3793
                select {
3✔
3794
                case peerChan <- peer:
3✔
3795
                case <-s.quit:
2✔
3796
                }
3797

3798
                return
3✔
3799
        }
3800

3801
        // Not connected, store this listener such that it can be notified when
3802
        // the peer comes online.
3803
        s.peerConnectedListeners[pubStr] = append(
3✔
3804
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3805
        )
3✔
3806
        s.mu.Unlock()
3✔
3807
}
3808

3809
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3810
// the given public key has been disconnected. The notification is signaled by
3811
// closing the channel returned.
3812
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3813
        s.mu.Lock()
3✔
3814
        defer s.mu.Unlock()
3✔
3815

3✔
3816
        c := make(chan struct{})
3✔
3817

3✔
3818
        // If the peer is already offline, we can immediately trigger the
3✔
3819
        // notification.
3✔
3820
        peerPubKeyStr := string(peerPubKey[:])
3✔
3821
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3822
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3823
                close(c)
×
3824
                return c
×
3825
        }
×
3826

3827
        // Otherwise, the peer is online, so we'll keep track of the channel to
3828
        // trigger the notification once the server detects the peer
3829
        // disconnects.
3830
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3831
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3832
        )
3✔
3833

3✔
3834
        return c
3✔
3835
}
3836

3837
// FindPeer will return the peer that corresponds to the passed in public key.
3838
// This function is used by the funding manager, allowing it to update the
3839
// daemon's local representation of the remote peer.
3840
//
3841
// NOTE: This function is safe for concurrent access.
3842
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3843
        s.mu.RLock()
3✔
3844
        defer s.mu.RUnlock()
3✔
3845

3✔
3846
        pubStr := string(peerKey.SerializeCompressed())
3✔
3847

3✔
3848
        return s.findPeerByPubStr(pubStr)
3✔
3849
}
3✔
3850

3851
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3852
// which should be a string representation of the peer's serialized, compressed
3853
// public key.
3854
//
3855
// NOTE: This function is safe for concurrent access.
3856
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3857
        s.mu.RLock()
3✔
3858
        defer s.mu.RUnlock()
3✔
3859

3✔
3860
        return s.findPeerByPubStr(pubStr)
3✔
3861
}
3✔
3862

3863
// findPeerByPubStr is an internal method that retrieves the specified peer from
3864
// the server's internal state using.
3865
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3866
        peer, ok := s.peersByPub[pubStr]
3✔
3867
        if !ok {
6✔
3868
                return nil, ErrPeerNotConnected
3✔
3869
        }
3✔
3870

3871
        return peer, nil
3✔
3872
}
3873

3874
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3875
// exponential backoff. If no previous backoff was known, the default is
3876
// returned.
3877
func (s *server) nextPeerBackoff(pubStr string,
3878
        startTime time.Time) time.Duration {
3✔
3879

3✔
3880
        // Now, determine the appropriate backoff to use for the retry.
3✔
3881
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3882
        if !ok {
6✔
3883
                // If an existing backoff was unknown, use the default.
3✔
3884
                return s.cfg.MinBackoff
3✔
3885
        }
3✔
3886

3887
        // If the peer failed to start properly, we'll just use the previous
3888
        // backoff to compute the subsequent randomized exponential backoff
3889
        // duration. This will roughly double on average.
3890
        if startTime.IsZero() {
4✔
3891
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
1✔
3892
        }
1✔
3893

3894
        // The peer succeeded in starting. If the connection didn't last long
3895
        // enough to be considered stable, we'll continue to back off retries
3896
        // with this peer.
3897
        connDuration := time.Since(startTime)
3✔
3898
        if connDuration < defaultStableConnDuration {
6✔
3899
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3900
        }
3✔
3901

3902
        // The peer succeed in starting and this was stable peer, so we'll
3903
        // reduce the timeout duration by the length of the connection after
3904
        // applying randomized exponential backoff. We'll only apply this in the
3905
        // case that:
3906
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3907
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3908
        if relaxedBackoff > s.cfg.MinBackoff {
×
3909
                return relaxedBackoff
×
3910
        }
×
3911

3912
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3913
        // the stable connection lasted much longer than our previous backoff.
3914
        // To reward such good behavior, we'll reconnect after the default
3915
        // timeout.
3916
        return s.cfg.MinBackoff
×
3917
}
3918

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

×
3929
        // The connection that comes from the node with a "smaller" pubkey
×
3930
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3931
        // should drop our established connection.
×
3932
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3933
}
×
3934

3935
// InboundPeerConnected initializes a new peer in response to a new inbound
3936
// connection.
3937
//
3938
// NOTE: This function is safe for concurrent access.
3939
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3940
        // Exit early if we have already been instructed to shutdown, this
3✔
3941
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3942
        if s.Stopped() {
3✔
3943
                return
×
3944
        }
×
3945

3946
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3947
        pubSer := nodePub.SerializeCompressed()
3✔
3948
        pubStr := string(pubSer)
3✔
3949

3✔
3950
        var pubBytes [33]byte
3✔
3951
        copy(pubBytes[:], pubSer)
3✔
3952

3✔
3953
        s.mu.Lock()
3✔
3954
        defer s.mu.Unlock()
3✔
3955

3✔
3956
        // If we already have an outbound connection to this peer, then ignore
3✔
3957
        // this new connection.
3✔
3958
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3959
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3960
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3961
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3962

3✔
3963
                conn.Close()
3✔
3964
                return
3✔
3965
        }
3✔
3966

3967
        // If we already have a valid connection that is scheduled to take
3968
        // precedence once the prior peer has finished disconnecting, we'll
3969
        // ignore this connection.
3970
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3971
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3972
                        "scheduled", conn.RemoteAddr(), p)
×
3973
                conn.Close()
×
3974
                return
×
3975
        }
×
3976

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

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

3992
        case nil:
3✔
3993
                ctx := btclog.WithCtx(
3✔
3994
                        context.TODO(),
3✔
3995
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
3996
                )
3✔
3997

3✔
3998
                // We already have a connection with the incoming peer. If the
3✔
3999
                // connection we've already established should be kept and is
3✔
4000
                // not of the same type of the new connection (inbound), then
3✔
4001
                // we'll close out the new connection s.t there's only a single
3✔
4002
                // connection between us.
3✔
4003
                localPub := s.identityECDH.PubKey()
3✔
4004
                if !connectedPeer.Inbound() &&
3✔
4005
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4006

×
4007
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4008
                                "peer, but already have outbound "+
×
4009
                                "connection, dropping conn",
×
4010
                                fmt.Errorf("already have outbound conn"))
×
4011
                        conn.Close()
×
4012
                        return
×
4013
                }
×
4014

4015
                // Otherwise, if we should drop the connection, then we'll
4016
                // disconnect our already connected peer.
4017
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4018

3✔
4019
                s.cancelConnReqs(pubStr, nil)
3✔
4020

3✔
4021
                // Remove the current peer from the server's internal state and
3✔
4022
                // signal that the peer termination watcher does not need to
3✔
4023
                // execute for this peer.
3✔
4024
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4025
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4026
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4027
                        s.peerConnected(conn, nil, true)
3✔
4028
                }
3✔
4029
        }
4030
}
4031

4032
// OutboundPeerConnected initializes a new peer in response to a new outbound
4033
// connection.
4034
// NOTE: This function is safe for concurrent access.
4035
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4036
        // Exit early if we have already been instructed to shutdown, this
3✔
4037
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4038
        if s.Stopped() {
3✔
4039
                return
×
4040
        }
×
4041

4042
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4043
        pubSer := nodePub.SerializeCompressed()
3✔
4044
        pubStr := string(pubSer)
3✔
4045

3✔
4046
        var pubBytes [33]byte
3✔
4047
        copy(pubBytes[:], pubSer)
3✔
4048

3✔
4049
        s.mu.Lock()
3✔
4050
        defer s.mu.Unlock()
3✔
4051

3✔
4052
        // If we already have an inbound connection to this peer, then ignore
3✔
4053
        // this new connection.
3✔
4054
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4055
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4056
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4057
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4058

3✔
4059
                if connReq != nil {
6✔
4060
                        s.connMgr.Remove(connReq.ID())
3✔
4061
                }
3✔
4062
                conn.Close()
3✔
4063
                return
3✔
4064
        }
4065
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4066
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4067
                s.connMgr.Remove(connReq.ID())
×
4068
                conn.Close()
×
4069
                return
×
4070
        }
×
4071

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

×
4078
                if connReq != nil {
×
4079
                        s.connMgr.Remove(connReq.ID())
×
4080
                }
×
4081

4082
                conn.Close()
×
4083
                return
×
4084
        }
4085

4086
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4087
                conn.RemoteAddr())
3✔
4088

3✔
4089
        if connReq != nil {
6✔
4090
                // A successful connection was returned by the connmgr.
3✔
4091
                // Immediately cancel all pending requests, excluding the
3✔
4092
                // outbound connection we just established.
3✔
4093
                ignore := connReq.ID()
3✔
4094
                s.cancelConnReqs(pubStr, &ignore)
3✔
4095
        } else {
6✔
4096
                // This was a successful connection made by some other
3✔
4097
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4098
                s.cancelConnReqs(pubStr, nil)
3✔
4099
        }
3✔
4100

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

4112
        case nil:
3✔
4113
                ctx := btclog.WithCtx(
3✔
4114
                        context.TODO(),
3✔
4115
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4116
                )
3✔
4117

3✔
4118
                // We already have a connection with the incoming peer. If the
3✔
4119
                // connection we've already established should be kept and is
3✔
4120
                // not of the same type of the new connection (outbound), then
3✔
4121
                // we'll close out the new connection s.t there's only a single
3✔
4122
                // connection between us.
3✔
4123
                localPub := s.identityECDH.PubKey()
3✔
4124
                if connectedPeer.Inbound() &&
3✔
4125
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4126

×
4127
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4128
                                "to peer, but already have inbound "+
×
4129
                                "connection, dropping conn",
×
4130
                                fmt.Errorf("already have inbound conn"))
×
4131
                        if connReq != nil {
×
4132
                                s.connMgr.Remove(connReq.ID())
×
4133
                        }
×
4134
                        conn.Close()
×
4135
                        return
×
4136
                }
4137

4138
                // Otherwise, _their_ connection should be dropped. So we'll
4139
                // disconnect the peer and send the now obsolete peer to the
4140
                // server for garbage collection.
4141
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4142

3✔
4143
                // Remove the current peer from the server's internal state and
3✔
4144
                // signal that the peer termination watcher does not need to
3✔
4145
                // execute for this peer.
3✔
4146
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4147
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4148
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4149
                        s.peerConnected(conn, connReq, false)
3✔
4150
                }
3✔
4151
        }
4152
}
4153

4154
// UnassignedConnID is the default connection ID that a request can have before
4155
// it actually is submitted to the connmgr.
4156
// TODO(conner): move into connmgr package, or better, add connmgr method for
4157
// generating atomic IDs
4158
const UnassignedConnID uint64 = 0
4159

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

4174
        // Next, check to see if we have any outstanding persistent connection
4175
        // requests to this peer. If so, then we'll remove all of these
4176
        // connection requests, and also delete the entry from the map.
4177
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4178
        if !ok {
6✔
4179
                return
3✔
4180
        }
3✔
4181

4182
        for _, connReq := range connReqs {
6✔
4183
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4184

3✔
4185
                // Atomically capture the current request identifier.
3✔
4186
                connID := connReq.ID()
3✔
4187

3✔
4188
                // Skip any zero IDs, this indicates the request has not
3✔
4189
                // yet been schedule.
3✔
4190
                if connID == UnassignedConnID {
3✔
4191
                        continue
×
4192
                }
4193

4194
                // Skip a particular connection ID if instructed.
4195
                if skip != nil && connID == *skip {
6✔
4196
                        continue
3✔
4197
                }
4198

4199
                s.connMgr.Remove(connID)
3✔
4200
        }
4201

4202
        delete(s.persistentConnReqs, pubStr)
3✔
4203
}
4204

4205
// handleCustomMessage dispatches an incoming custom peers message to
4206
// subscribers.
4207
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4208
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4209
                peer, msg.Type)
3✔
4210

3✔
4211
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4212
                Peer: peer,
3✔
4213
                Msg:  msg,
3✔
4214
        })
3✔
4215
}
3✔
4216

4217
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4218
// messages.
4219
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4220
        return s.customMessageServer.Subscribe()
3✔
4221
}
3✔
4222

4223
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4224
// the channelNotifier's NotifyOpenChannelEvent.
4225
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4226
        remotePub *btcec.PublicKey) {
3✔
4227

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

4234
        // Notify subscribers about this open channel event.
4235
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4236
}
4237

4238
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4239
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4240
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4241
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4242

3✔
4243
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4244
        // peer.
3✔
4245
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4246
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4247
                        "channel[%v] pending open",
×
4248
                        remotePub.SerializeCompressed(), op)
×
4249
        }
×
4250

4251
        // Notify subscribers about this event.
4252
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4253
}
4254

4255
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4256
// calls the channelNotifier's NotifyFundingTimeout.
4257
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4258
        remotePub *btcec.PublicKey) {
3✔
4259

3✔
4260
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4261
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4262
        if err != nil {
3✔
4263
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4264
                        "channel[%v] pending close",
×
4265
                        remotePub.SerializeCompressed(), op)
×
4266
        }
×
4267

4268
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4269
                // If we encounter an error while attempting to disconnect the
×
4270
                // peer, log the error.
×
4271
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4272
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4273
                }
×
4274
        }
4275

4276
        // Notify subscribers about this event.
4277
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4278
}
4279

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

3✔
4287
        brontideConn := conn.(*brontide.Conn)
3✔
4288
        addr := conn.RemoteAddr()
3✔
4289
        pubKey := brontideConn.RemotePub()
3✔
4290

3✔
4291
        // Only restrict access for inbound connections, which means if the
3✔
4292
        // remote node's public key is banned or the restricted slots are used
3✔
4293
        // up, we will drop the connection.
3✔
4294
        //
3✔
4295
        // TODO(yy): Consider perform this check in
3✔
4296
        // `peerAccessMan.addPeerAccess`.
3✔
4297
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4298
        if inbound && err != nil {
3✔
4299
                pubSer := pubKey.SerializeCompressed()
×
4300

×
4301
                // Clean up the persistent peer maps if we're dropping this
×
4302
                // connection.
×
4303
                s.bannedPersistentPeerConnection(string(pubSer))
×
4304

×
4305
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4306
                        "of restricted-access connection slots: %v.", pubSer,
×
4307
                        err)
×
4308

×
4309
                conn.Close()
×
4310

×
4311
                return
×
4312
        }
×
4313

4314
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4315
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4316

3✔
4317
        peerAddr := &lnwire.NetAddress{
3✔
4318
                IdentityKey: pubKey,
3✔
4319
                Address:     addr,
3✔
4320
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4321
        }
3✔
4322

3✔
4323
        // With the brontide connection established, we'll now craft the feature
3✔
4324
        // vectors to advertise to the remote node.
3✔
4325
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4326
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4327

3✔
4328
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4329
        // found, create a fresh buffer.
3✔
4330
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4331
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4332
        if !ok {
6✔
4333
                var err error
3✔
4334
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4335
                if err != nil {
3✔
4336
                        srvrLog.Errorf("unable to create peer %v", err)
×
4337
                        return
×
4338
                }
×
4339
        }
4340

4341
        // If we directly set the peer.Config TowerClient member to the
4342
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4343
        // the peer.Config's TowerClient member will not evaluate to nil even
4344
        // though the underlying value is nil. To avoid this gotcha which can
4345
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4346
        // TowerClient if needed.
4347
        var towerClient wtclient.ClientManager
3✔
4348
        if s.towerClientMgr != nil {
6✔
4349
                towerClient = s.towerClientMgr
3✔
4350
        }
3✔
4351

4352
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4353
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4354

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

3✔
4398
                        return s.genNodeAnnouncement(nil)
3✔
4399
                },
3✔
4400

4401
                PongBuf: s.pongBuf,
4402

4403
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4404

4405
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4406

4407
                FundingManager: s.fundingMgr,
4408

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

4439
                        return clock.NewDefaultClock().Now().Before(
3✔
4440
                                EndorsementExperimentEnd,
3✔
4441
                        )
3✔
4442
                },
4443
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4444
        }
4445

4446
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4447
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4448

3✔
4449
        p := peer.NewBrontide(pCfg)
3✔
4450

3✔
4451
        // Update the access manager with the access permission for this peer.
3✔
4452
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4453

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

3✔
4457
        s.addPeer(p)
3✔
4458

3✔
4459
        // Once we have successfully added the peer to the server, we can
3✔
4460
        // delete the previous error buffer from the server's map of error
3✔
4461
        // buffers.
3✔
4462
        delete(s.peerErrors, pkStr)
3✔
4463

3✔
4464
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4465
        // includes sending and receiving Init messages, which would be a DOS
3✔
4466
        // vector if we held the server's mutex throughout the procedure.
3✔
4467
        s.wg.Add(1)
3✔
4468
        go s.peerInitializer(p)
3✔
4469
}
4470

4471
// addPeer adds the passed peer to the server's global state of all active
4472
// peers.
4473
func (s *server) addPeer(p *peer.Brontide) {
3✔
4474
        if p == nil {
3✔
4475
                return
×
4476
        }
×
4477

4478
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4479

3✔
4480
        // Ignore new peers if we're shutting down.
3✔
4481
        if s.Stopped() {
3✔
4482
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4483
                        pubBytes)
×
4484
                p.Disconnect(ErrServerShuttingDown)
×
4485

×
4486
                return
×
4487
        }
×
4488

4489
        // Track the new peer in our indexes so we can quickly look it up either
4490
        // according to its public key, or its peer ID.
4491
        // TODO(roasbeef): pipe all requests through to the
4492
        // queryHandler/peerManager
4493

4494
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4495
        // be human-readable.
4496
        pubStr := string(pubBytes)
3✔
4497

3✔
4498
        s.peersByPub[pubStr] = p
3✔
4499

3✔
4500
        if p.Inbound() {
6✔
4501
                s.inboundPeers[pubStr] = p
3✔
4502
        } else {
6✔
4503
                s.outboundPeers[pubStr] = p
3✔
4504
        }
3✔
4505

4506
        // Inform the peer notifier of a peer online event so that it can be reported
4507
        // to clients listening for peer events.
4508
        var pubKey [33]byte
3✔
4509
        copy(pubKey[:], pubBytes)
3✔
4510
}
4511

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

3✔
4524
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4525

3✔
4526
        // Avoid initializing peers while the server is exiting.
3✔
4527
        if s.Stopped() {
3✔
4528
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4529
                        pubBytes)
×
4530
                return
×
4531
        }
×
4532

4533
        // Create a channel that will be used to signal a successful start of
4534
        // the link. This prevents the peer termination watcher from beginning
4535
        // its duty too early.
4536
        ready := make(chan struct{})
3✔
4537

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

3✔
4547
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4548
        // will unblock the peerTerminationWatcher.
3✔
4549
        if err := p.Start(); err != nil {
6✔
4550
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4551

3✔
4552
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4553
                return
3✔
4554
        }
3✔
4555

4556
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4557
        // was successful, and to begin watching the peer's wait group.
4558
        close(ready)
3✔
4559

3✔
4560
        s.mu.Lock()
3✔
4561
        defer s.mu.Unlock()
3✔
4562

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

3✔
4566
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4567
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4568
        pubStr := string(pubBytes)
3✔
4569
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4570
                select {
3✔
4571
                case peerChan <- p:
3✔
4572
                case <-s.quit:
×
4573
                        return
×
4574
                }
4575
        }
4576
        delete(s.peerConnectedListeners, pubStr)
3✔
4577

3✔
4578
        // Since the peer has been fully initialized, now it's time to notify
3✔
4579
        // the RPC about the peer online event.
3✔
4580
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4581
}
4582

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

3✔
4597
        ctx := btclog.WithCtx(
3✔
4598
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4599
        )
3✔
4600

3✔
4601
        p.WaitForDisconnect(ready)
3✔
4602

3✔
4603
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4604

3✔
4605
        // If the server is exiting then we can bail out early ourselves as all
3✔
4606
        // the other sub-systems will already be shutting down.
3✔
4607
        if s.Stopped() {
6✔
4608
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4609
                return
3✔
4610
        }
3✔
4611

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

3✔
4618
        pubKey := p.IdentityKey()
3✔
4619

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

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

4634
        for _, link := range links {
6✔
4635
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4636
        }
3✔
4637

4638
        s.mu.Lock()
3✔
4639
        defer s.mu.Unlock()
3✔
4640

3✔
4641
        // If there were any notification requests for when this peer
3✔
4642
        // disconnected, we can trigger them now.
3✔
4643
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4644
        pubStr := string(pubKey.SerializeCompressed())
3✔
4645
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4646
                close(offlineChan)
3✔
4647
        }
3✔
4648
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4649

3✔
4650
        // If the server has already removed this peer, we can short circuit the
3✔
4651
        // peer termination watcher and skip cleanup.
3✔
4652
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4653
                delete(s.ignorePeerTermination, p)
3✔
4654

3✔
4655
                pubKey := p.PubKey()
3✔
4656
                pubStr := string(pubKey[:])
3✔
4657

3✔
4658
                // If a connection callback is present, we'll go ahead and
3✔
4659
                // execute it now that previous peer has fully disconnected. If
3✔
4660
                // the callback is not present, this likely implies the peer was
3✔
4661
                // purposefully disconnected via RPC, and that no reconnect
3✔
4662
                // should be attempted.
3✔
4663
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4664
                if ok {
6✔
4665
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4666
                        connCallback()
3✔
4667
                }
3✔
4668
                return
3✔
4669
        }
4670

4671
        // First, cleanup any remaining state the server has regarding the peer
4672
        // in question.
4673
        s.removePeerUnsafe(ctx, p)
3✔
4674

3✔
4675
        // Next, check to see if this is a persistent peer or not.
3✔
4676
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4677
                return
3✔
4678
        }
3✔
4679

4680
        // Get the last address that we used to connect to the peer.
4681
        addrs := []net.Addr{
3✔
4682
                p.NetAddress().Address,
3✔
4683
        }
3✔
4684

3✔
4685
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4686
        // reconnection purposes.
3✔
4687
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4688
        switch {
3✔
4689
        // We found advertised addresses, so use them.
4690
        case err == nil:
3✔
4691
                addrs = advertisedAddrs
3✔
4692

4693
        // The peer doesn't have an advertised address.
4694
        case err == errNoAdvertisedAddr:
3✔
4695
                // If it is an outbound peer then we fall back to the existing
3✔
4696
                // peer address.
3✔
4697
                if !p.Inbound() {
6✔
4698
                        break
3✔
4699
                }
4700

4701
                // Fall back to the existing peer address if
4702
                // we're not accepting connections over Tor.
4703
                if s.torController == nil {
6✔
4704
                        break
3✔
4705
                }
4706

4707
                // If we are, the peer's address won't be known
4708
                // to us (we'll see a private address, which is
4709
                // the address used by our onion service to dial
4710
                // to lnd), so we don't have enough information
4711
                // to attempt a reconnect.
4712
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4713
                        "to inbound peer without advertised address")
×
4714
                return
×
4715

4716
        // We came across an error retrieving an advertised
4717
        // address, log it, and fall back to the existing peer
4718
        // address.
4719
        default:
3✔
4720
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4721
                        "address for peer", err)
3✔
4722
        }
4723

4724
        // Make an easy lookup map so that we can check if an address
4725
        // is already in the address list that we have stored for this peer.
4726
        existingAddrs := make(map[string]bool)
3✔
4727
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4728
                existingAddrs[addr.String()] = true
3✔
4729
        }
3✔
4730

4731
        // Add any missing addresses for this peer to persistentPeerAddr.
4732
        for _, addr := range addrs {
6✔
4733
                if existingAddrs[addr.String()] {
3✔
4734
                        continue
×
4735
                }
4736

4737
                s.persistentPeerAddrs[pubStr] = append(
3✔
4738
                        s.persistentPeerAddrs[pubStr],
3✔
4739
                        &lnwire.NetAddress{
3✔
4740
                                IdentityKey: p.IdentityKey(),
3✔
4741
                                Address:     addr,
3✔
4742
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4743
                        },
3✔
4744
                )
3✔
4745
        }
4746

4747
        // Record the computed backoff in the backoff map.
4748
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4749
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4750

3✔
4751
        // Initialize a retry canceller for this peer if one does not
3✔
4752
        // exist.
3✔
4753
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4754
        if !ok {
6✔
4755
                cancelChan = make(chan struct{})
3✔
4756
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4757
        }
3✔
4758

4759
        // We choose not to wait group this go routine since the Connect
4760
        // call can stall for arbitrarily long if we shutdown while an
4761
        // outbound connection attempt is being made.
4762
        go func() {
6✔
4763
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4764
                        "re-establishment to persistent peer",
3✔
4765
                        "reconnecting_in", backoff)
3✔
4766

3✔
4767
                select {
3✔
4768
                case <-time.After(backoff):
3✔
4769
                case <-cancelChan:
3✔
4770
                        return
3✔
4771
                case <-s.quit:
3✔
4772
                        return
3✔
4773
                }
4774

4775
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4776
                        "connection")
3✔
4777

3✔
4778
                s.connectToPersistentPeer(pubStr)
3✔
4779
        }()
4780
}
4781

4782
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4783
// to connect to the peer. It creates connection requests if there are
4784
// currently none for a given address and it removes old connection requests
4785
// if the associated address is no longer in the latest address list for the
4786
// peer.
4787
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4788
        s.mu.Lock()
3✔
4789
        defer s.mu.Unlock()
3✔
4790

3✔
4791
        // Create an easy lookup map of the addresses we have stored for the
3✔
4792
        // peer. We will remove entries from this map if we have existing
3✔
4793
        // connection requests for the associated address and then any leftover
3✔
4794
        // entries will indicate which addresses we should create new
3✔
4795
        // connection requests for.
3✔
4796
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4797
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4798
                addrMap[addr.String()] = addr
3✔
4799
        }
3✔
4800

4801
        // Go through each of the existing connection requests and
4802
        // check if they correspond to the latest set of addresses. If
4803
        // there is a connection requests that does not use one of the latest
4804
        // advertised addresses then remove that connection request.
4805
        var updatedConnReqs []*connmgr.ConnReq
3✔
4806
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4807
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4808

3✔
4809
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4810
                // If the existing connection request is using one of the
4811
                // latest advertised addresses for the peer then we add it to
4812
                // updatedConnReqs and remove the associated address from
4813
                // addrMap so that we don't recreate this connReq later on.
4814
                case true:
×
4815
                        updatedConnReqs = append(
×
4816
                                updatedConnReqs, connReq,
×
4817
                        )
×
4818
                        delete(addrMap, lnAddr)
×
4819

4820
                // If the existing connection request is using an address that
4821
                // is not one of the latest advertised addresses for the peer
4822
                // then we remove the connecting request from the connection
4823
                // manager.
4824
                case false:
3✔
4825
                        srvrLog.Info(
3✔
4826
                                "Removing conn req:", connReq.Addr.String(),
3✔
4827
                        )
3✔
4828
                        s.connMgr.Remove(connReq.ID())
3✔
4829
                }
4830
        }
4831

4832
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4833

3✔
4834
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4835
        if !ok {
6✔
4836
                cancelChan = make(chan struct{})
3✔
4837
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4838
        }
3✔
4839

4840
        // Any addresses left in addrMap are new ones that we have not made
4841
        // connection requests for. So create new connection requests for those.
4842
        // If there is more than one address in the address map, stagger the
4843
        // creation of the connection requests for those.
4844
        go func() {
6✔
4845
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4846
                defer ticker.Stop()
3✔
4847

3✔
4848
                for _, addr := range addrMap {
6✔
4849
                        // Send the persistent connection request to the
3✔
4850
                        // connection manager, saving the request itself so we
3✔
4851
                        // can cancel/restart the process as needed.
3✔
4852
                        connReq := &connmgr.ConnReq{
3✔
4853
                                Addr:      addr,
3✔
4854
                                Permanent: true,
3✔
4855
                        }
3✔
4856

3✔
4857
                        s.mu.Lock()
3✔
4858
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4859
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4860
                        )
3✔
4861
                        s.mu.Unlock()
3✔
4862

3✔
4863
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4864
                                "channel peer %v", addr)
3✔
4865

3✔
4866
                        go s.connMgr.Connect(connReq)
3✔
4867

3✔
4868
                        select {
3✔
4869
                        case <-s.quit:
3✔
4870
                                return
3✔
4871
                        case <-cancelChan:
3✔
4872
                                return
3✔
4873
                        case <-ticker.C:
3✔
4874
                        }
4875
                }
4876
        }()
4877
}
4878

4879
// removePeerUnsafe removes the passed peer from the server's state of all
4880
// active peers.
4881
//
4882
// NOTE: Server mutex must be held when calling this function.
4883
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4884
        if p == nil {
3✔
4885
                return
×
4886
        }
×
4887

4888
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4889

3✔
4890
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4891
        // will be disconnected in the server shutdown process.
3✔
4892
        if s.Stopped() {
3✔
4893
                return
×
4894
        }
×
4895

4896
        // Capture the peer's public key and string representation.
4897
        pKey := p.PubKey()
3✔
4898
        pubSer := pKey[:]
3✔
4899
        pubStr := string(pubSer)
3✔
4900

3✔
4901
        delete(s.peersByPub, pubStr)
3✔
4902

3✔
4903
        if p.Inbound() {
6✔
4904
                delete(s.inboundPeers, pubStr)
3✔
4905
        } else {
6✔
4906
                delete(s.outboundPeers, pubStr)
3✔
4907
        }
3✔
4908

4909
        // When removing the peer we make sure to disconnect it asynchronously
4910
        // to avoid blocking the main server goroutine because it is holding the
4911
        // server's mutex. Disconnecting the peer might block and wait until the
4912
        // peer has fully started up. This can happen if an inbound and outbound
4913
        // race condition occurs.
4914
        s.wg.Add(1)
3✔
4915
        go func() {
6✔
4916
                defer s.wg.Done()
3✔
4917

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

3✔
4920
                // If this peer had an active persistent connection request,
3✔
4921
                // remove it.
3✔
4922
                if p.ConnReq() != nil {
6✔
4923
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4924
                }
3✔
4925

4926
                // Remove the peer's access permission from the access manager.
4927
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4928
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4929

3✔
4930
                // Copy the peer's error buffer across to the server if it has
3✔
4931
                // any items in it so that we can restore peer errors across
3✔
4932
                // connections. We need to look up the error after the peer has
3✔
4933
                // been disconnected because we write the error in the
3✔
4934
                // `Disconnect` method.
3✔
4935
                s.mu.Lock()
3✔
4936
                if p.ErrorBuffer().Total() > 0 {
6✔
4937
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4938
                }
3✔
4939
                s.mu.Unlock()
3✔
4940

3✔
4941
                // Inform the peer notifier of a peer offline event so that it
3✔
4942
                // can be reported to clients listening for peer events.
3✔
4943
                var pubKey [33]byte
3✔
4944
                copy(pubKey[:], pubSer)
3✔
4945

3✔
4946
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4947
        }()
4948
}
4949

4950
// ConnectToPeer requests that the server connect to a Lightning Network peer
4951
// at the specified address. This function will *block* until either a
4952
// connection is established, or the initial handshake process fails.
4953
//
4954
// NOTE: This function is safe for concurrent access.
4955
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4956
        perm bool, timeout time.Duration) error {
3✔
4957

3✔
4958
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4959

3✔
4960
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4961
        // better granularity.  In certain conditions, this method requires
3✔
4962
        // making an outbound connection to a remote peer, which requires the
3✔
4963
        // lock to be released, and subsequently reacquired.
3✔
4964
        s.mu.Lock()
3✔
4965

3✔
4966
        // Ensure we're not already connected to this peer.
3✔
4967
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4968

3✔
4969
        // When there's no error it means we already have a connection with this
3✔
4970
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4971
        // set, we will ignore the existing connection and continue.
3✔
4972
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4973
                s.mu.Unlock()
3✔
4974
                return &errPeerAlreadyConnected{peer: peer}
3✔
4975
        }
3✔
4976

4977
        // Peer was not found, continue to pursue connection with peer.
4978

4979
        // If there's already a pending connection request for this pubkey,
4980
        // then we ignore this request to ensure we don't create a redundant
4981
        // connection.
4982
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4983
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4984
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4985
        }
3✔
4986

4987
        // If there's not already a pending or active connection to this node,
4988
        // then instruct the connection manager to attempt to establish a
4989
        // persistent connection to the peer.
4990
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4991
        if perm {
6✔
4992
                connReq := &connmgr.ConnReq{
3✔
4993
                        Addr:      addr,
3✔
4994
                        Permanent: true,
3✔
4995
                }
3✔
4996

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

3✔
5010
                go s.connMgr.Connect(connReq)
3✔
5011

3✔
5012
                return nil
3✔
5013
        }
5014
        s.mu.Unlock()
3✔
5015

3✔
5016
        // If we're not making a persistent connection, then we'll attempt to
3✔
5017
        // connect to the target peer. If the we can't make the connection, or
3✔
5018
        // the crypto negotiation breaks down, then return an error to the
3✔
5019
        // caller.
3✔
5020
        errChan := make(chan error, 1)
3✔
5021
        s.connectToPeer(addr, errChan, timeout)
3✔
5022

3✔
5023
        select {
3✔
5024
        case err := <-errChan:
3✔
5025
                return err
3✔
5026
        case <-s.quit:
×
5027
                return ErrServerShuttingDown
×
5028
        }
5029
}
5030

5031
// connectToPeer establishes a connection to a remote peer. errChan is used to
5032
// notify the caller if the connection attempt has failed. Otherwise, it will be
5033
// closed.
5034
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5035
        errChan chan<- error, timeout time.Duration) {
3✔
5036

3✔
5037
        conn, err := brontide.Dial(
3✔
5038
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5039
        )
3✔
5040
        if err != nil {
6✔
5041
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5042
                select {
3✔
5043
                case errChan <- err:
3✔
5044
                case <-s.quit:
×
5045
                }
5046
                return
3✔
5047
        }
5048

5049
        close(errChan)
3✔
5050

3✔
5051
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5052
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5053

3✔
5054
        s.OutboundPeerConnected(nil, conn)
3✔
5055
}
5056

5057
// DisconnectPeer sends the request to server to close the connection with peer
5058
// identified by public key.
5059
//
5060
// NOTE: This function is safe for concurrent access.
5061
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5062
        pubBytes := pubKey.SerializeCompressed()
3✔
5063
        pubStr := string(pubBytes)
3✔
5064

3✔
5065
        s.mu.Lock()
3✔
5066
        defer s.mu.Unlock()
3✔
5067

3✔
5068
        // Check that were actually connected to this peer. If not, then we'll
3✔
5069
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5070
        // currently connected to.
3✔
5071
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5072
        if err == ErrPeerNotConnected {
6✔
5073
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5074
        }
3✔
5075

5076
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5077

3✔
5078
        s.cancelConnReqs(pubStr, nil)
3✔
5079

3✔
5080
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5081
        // them from this map so we don't attempt to re-connect after we
3✔
5082
        // disconnect.
3✔
5083
        delete(s.persistentPeers, pubStr)
3✔
5084
        delete(s.persistentPeersBackoff, pubStr)
3✔
5085

3✔
5086
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5087
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5088
        //
3✔
5089
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5090
        // goroutine because we might hold the server's mutex.
3✔
5091
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5092

3✔
5093
        return nil
3✔
5094
}
5095

5096
// OpenChannel sends a request to the server to open a channel to the specified
5097
// peer identified by nodeKey with the passed channel funding parameters.
5098
//
5099
// NOTE: This function is safe for concurrent access.
5100
func (s *server) OpenChannel(
5101
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5102

3✔
5103
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5104
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5105
        // not blocked if the caller is not reading the updates.
3✔
5106
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5107
        req.Err = make(chan error, 1)
3✔
5108

3✔
5109
        // First attempt to locate the target peer to open a channel with, if
3✔
5110
        // we're unable to locate the peer then this request will fail.
3✔
5111
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5112
        s.mu.RLock()
3✔
5113
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5114
        if !ok {
3✔
5115
                s.mu.RUnlock()
×
5116

×
5117
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5118
                return req.Updates, req.Err
×
5119
        }
×
5120
        req.Peer = peer
3✔
5121
        s.mu.RUnlock()
3✔
5122

3✔
5123
        // We'll wait until the peer is active before beginning the channel
3✔
5124
        // opening process.
3✔
5125
        select {
3✔
5126
        case <-peer.ActiveSignal():
3✔
5127
        case <-peer.QuitSignal():
×
5128
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5129
                return req.Updates, req.Err
×
5130
        case <-s.quit:
×
5131
                req.Err <- ErrServerShuttingDown
×
5132
                return req.Updates, req.Err
×
5133
        }
5134

5135
        // If the fee rate wasn't specified at this point we fail the funding
5136
        // because of the missing fee rate information. The caller of the
5137
        // `OpenChannel` method needs to make sure that default values for the
5138
        // fee rate are set beforehand.
5139
        if req.FundingFeePerKw == 0 {
3✔
5140
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5141
                        "the channel opening transaction")
×
5142

×
5143
                return req.Updates, req.Err
×
5144
        }
×
5145

5146
        // Spawn a goroutine to send the funding workflow request to the funding
5147
        // manager. This allows the server to continue handling queries instead
5148
        // of blocking on this request which is exported as a synchronous
5149
        // request to the outside world.
5150
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5151

3✔
5152
        return req.Updates, req.Err
3✔
5153
}
5154

5155
// Peers returns a slice of all active peers.
5156
//
5157
// NOTE: This function is safe for concurrent access.
5158
func (s *server) Peers() []*peer.Brontide {
3✔
5159
        s.mu.RLock()
3✔
5160
        defer s.mu.RUnlock()
3✔
5161

3✔
5162
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5163
        for _, peer := range s.peersByPub {
6✔
5164
                peers = append(peers, peer)
3✔
5165
        }
3✔
5166

5167
        return peers
3✔
5168
}
5169

5170
// computeNextBackoff uses a truncated exponential backoff to compute the next
5171
// backoff using the value of the exiting backoff. The returned duration is
5172
// randomized in either direction by 1/20 to prevent tight loops from
5173
// stabilizing.
5174
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5175
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5176
        nextBackoff := 2 * currBackoff
3✔
5177
        if nextBackoff > maxBackoff {
6✔
5178
                nextBackoff = maxBackoff
3✔
5179
        }
3✔
5180

5181
        // Using 1/10 of our duration as a margin, compute a random offset to
5182
        // avoid the nodes entering connection cycles.
5183
        margin := nextBackoff / 10
3✔
5184

3✔
5185
        var wiggle big.Int
3✔
5186
        wiggle.SetUint64(uint64(margin))
3✔
5187
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5188
                // Randomizing is not mission critical, so we'll just return the
×
5189
                // current backoff.
×
5190
                return nextBackoff
×
5191
        }
×
5192

5193
        // Otherwise add in our wiggle, but subtract out half of the margin so
5194
        // that the backoff can tweaked by 1/20 in either direction.
5195
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5196
}
5197

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

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

3✔
5206
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5207
        if err != nil {
3✔
5208
                return nil, err
×
5209
        }
×
5210

5211
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5212
        if err != nil {
6✔
5213
                return nil, err
3✔
5214
        }
3✔
5215

5216
        if len(node.Addresses) == 0 {
6✔
5217
                return nil, errNoAdvertisedAddr
3✔
5218
        }
3✔
5219

5220
        return node.Addresses, nil
3✔
5221
}
5222

5223
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5224
// channel update for a target channel.
5225
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5226
        *lnwire.ChannelUpdate1, error) {
3✔
5227

3✔
5228
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5229
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5230
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5231
                if err != nil {
6✔
5232
                        return nil, err
3✔
5233
                }
3✔
5234

5235
                return netann.ExtractChannelUpdate(
3✔
5236
                        ourPubKey[:], info, edge1, edge2,
3✔
5237
                )
3✔
5238
        }
5239
}
5240

5241
// applyChannelUpdate applies the channel update to the different sub-systems of
5242
// the server. The useAlias boolean denotes whether or not to send an alias in
5243
// place of the real SCID.
5244
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5245
        op *wire.OutPoint, useAlias bool) error {
3✔
5246

3✔
5247
        var (
3✔
5248
                peerAlias    *lnwire.ShortChannelID
3✔
5249
                defaultAlias lnwire.ShortChannelID
3✔
5250
        )
3✔
5251

3✔
5252
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5253

3✔
5254
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5255
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5256
        if useAlias {
6✔
5257
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5258
                if foundAlias != defaultAlias {
6✔
5259
                        peerAlias = &foundAlias
3✔
5260
                }
3✔
5261
        }
5262

5263
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5264
                update, discovery.RemoteAlias(peerAlias),
3✔
5265
        )
3✔
5266
        select {
3✔
5267
        case err := <-errChan:
3✔
5268
                return err
3✔
5269
        case <-s.quit:
×
5270
                return ErrServerShuttingDown
×
5271
        }
5272
}
5273

5274
// SendCustomMessage sends a custom message to the peer with the specified
5275
// pubkey.
5276
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5277
        data []byte) error {
3✔
5278

3✔
5279
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5280
        if err != nil {
6✔
5281
                return err
3✔
5282
        }
3✔
5283

5284
        // We'll wait until the peer is active.
5285
        select {
3✔
5286
        case <-peer.ActiveSignal():
3✔
5287
        case <-peer.QuitSignal():
×
5288
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5289
        case <-s.quit:
×
5290
                return ErrServerShuttingDown
×
5291
        }
5292

5293
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5294
        if err != nil {
6✔
5295
                return err
3✔
5296
        }
3✔
5297

5298
        // Send the message as low-priority. For now we assume that all
5299
        // application-defined message are low priority.
5300
        return peer.SendMessageLazy(true, msg)
3✔
5301
}
5302

5303
// newSweepPkScriptGen creates closure that generates a new public key script
5304
// which should be used to sweep any funds into the on-chain wallet.
5305
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5306
// (p2wkh) output.
5307
func newSweepPkScriptGen(
5308
        wallet lnwallet.WalletController,
5309
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5310

3✔
5311
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5312
                sweepAddr, err := wallet.NewAddress(
3✔
5313
                        lnwallet.TaprootPubkey, false,
3✔
5314
                        lnwallet.DefaultAccountName,
3✔
5315
                )
3✔
5316
                if err != nil {
3✔
5317
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5318
                }
×
5319

5320
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5321
                if err != nil {
3✔
5322
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5323
                }
×
5324

5325
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5326
                        wallet, netParams, addr,
3✔
5327
                )
3✔
5328
                if err != nil {
3✔
5329
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5330
                }
×
5331

5332
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5333
                        DeliveryAddress: addr,
3✔
5334
                        InternalKey:     internalKeyDesc,
3✔
5335
                })
3✔
5336
        }
5337
}
5338

5339
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5340
// finished.
5341
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5342
        // Get a list of closed channels.
3✔
5343
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5344
        if err != nil {
3✔
5345
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5346
                return nil
×
5347
        }
×
5348

5349
        // Save the SCIDs in a map.
5350
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5351
        for _, c := range channels {
6✔
5352
                // If the channel is not pending, its FC has been finalized.
3✔
5353
                if !c.IsPending {
6✔
5354
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5355
                }
3✔
5356
        }
5357

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

5372
        for _, c := range pendings {
6✔
5373
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5374
                        continue
3✔
5375
                }
5376

5377
                // If the channel is still reported as pending, remove it from
5378
                // the map.
5379
                delete(closedSCIDs, c.ShortChannelID)
×
5380

×
5381
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5382
                        c.ShortChannelID)
×
5383
        }
5384

5385
        return closedSCIDs
3✔
5386
}
5387

5388
// getStartingBeat returns the current beat. This is used during the startup to
5389
// initialize blockbeat consumers.
5390
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5391
        // beat is the current blockbeat.
3✔
5392
        var beat *chainio.Beat
3✔
5393

3✔
5394
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5395
        // we will skip fetching the best block.
3✔
5396
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5397
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5398
                        "mode")
×
5399

×
5400
                return &chainio.Beat{}, nil
×
5401
        }
×
5402

5403
        // We should get a notification with the current best block immediately
5404
        // by passing a nil block.
5405
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5406
        if err != nil {
3✔
5407
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5408
        }
×
5409
        defer blockEpochs.Cancel()
3✔
5410

3✔
5411
        // We registered for the block epochs with a nil request. The notifier
3✔
5412
        // should send us the current best block immediately. So we need to
3✔
5413
        // wait for it here because we need to know the current best height.
3✔
5414
        select {
3✔
5415
        case bestBlock := <-blockEpochs.Epochs:
3✔
5416
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5417
                        bestBlock.Hash, bestBlock.Height)
3✔
5418

3✔
5419
                // Update the current blockbeat.
3✔
5420
                beat = chainio.NewBeat(*bestBlock)
3✔
5421

5422
        case <-s.quit:
×
5423
                srvrLog.Debug("LND shutting down")
×
5424
        }
5425

5426
        return beat, nil
3✔
5427
}
5428

5429
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5430
// point has an active RBF chan closer.
5431
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5432
        chanPoint wire.OutPoint) bool {
3✔
5433

3✔
5434
        pubBytes := peerPub.SerializeCompressed()
3✔
5435

3✔
5436
        s.mu.RLock()
3✔
5437
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5438
        s.mu.RUnlock()
3✔
5439
        if !ok {
3✔
5440
                return false
×
5441
        }
×
5442

5443
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5444
}
5445

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

3✔
5454
        // First, we'll attempt to look up the channel based on it's
3✔
5455
        // ChannelPoint.
3✔
5456
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5457
        if err != nil {
3✔
5458
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5459
        }
×
5460

5461
        // From the channel, we can now get the pubkey of the peer, then use
5462
        // that to eventually get the chan closer.
5463
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5464

3✔
5465
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5466
        s.mu.RLock()
3✔
5467
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5468
        s.mu.RUnlock()
3✔
5469
        if !ok {
3✔
5470
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5471
                        "not online", chanPoint)
×
5472
        }
×
5473

5474
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5475
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5476
        )
3✔
5477
        if err != nil {
3✔
5478
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5479
                        "%w", err)
×
5480
        }
×
5481

5482
        return closeUpdates, nil
3✔
5483
}
5484

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

3✔
5493
        // If the channel is present in the switch, then the request should flow
3✔
5494
        // through the switch instead.
3✔
5495
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5496
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5497
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5498
                        "invalid request", chanPoint)
×
5499
        }
×
5500

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

5511
        return updates, nil
3✔
5512
}
5513

5514
// setSelfNode configures and sets the server's self node. It sets the node
5515
// announcement, signs it, and updates the source node in the graph. When
5516
// determining values such as color and alias, the method prioritizes values
5517
// set in the config, then values previously persisted on disk, and finally
5518
// falls back to the defaults.
5519
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5520
        listenAddrs []net.Addr) error {
3✔
5521

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

×
NEW
5537
                        listenPorts = append(listenPorts, uint16(port))
×
NEW
5538
                }
×
5539

NEW
5540
                ips, err := s.configurePortForwarding(listenPorts...)
×
NEW
5541
                if err != nil {
×
NEW
5542
                        srvrLog.Errorf("Unable to automatically set up port "+
×
NEW
5543
                                "forwarding using %s: %v",
×
NEW
5544
                                s.natTraversal.Name(), err)
×
NEW
5545
                } else {
×
NEW
5546
                        srvrLog.Infof("Automatically set up port forwarding "+
×
NEW
5547
                                "using %s to advertise external IP",
×
NEW
5548
                                s.natTraversal.Name())
×
NEW
5549
                        externalIPStrings = append(externalIPStrings, ips...)
×
NEW
5550
                }
×
5551
        }
5552

5553
        // Normalize the external IP strings to net.Addr.
5554
        addrs, err := lncfg.NormalizeAddresses(
3✔
5555
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5556
                s.cfg.net.ResolveTCPAddr,
3✔
5557
        )
3✔
5558
        if err != nil {
3✔
NEW
5559
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
NEW
5560
        }
×
5561

5562
        // To avoid having duplicate addresses, we'll only add addresses from
5563
        // the source node that are not already in our address list yet. We
5564
        // create this map for quick lookup.
5565
        addressMap := make(map[string]struct{}, len(addrs))
3✔
5566
        // Populate the map with the existing addresses.
3✔
5567
        for _, existingAddr := range addrs {
6✔
5568
                addressMap[existingAddr.String()] = struct{}{}
3✔
5569
        }
3✔
5570

5571
        // Parse the color from config. We will update this later if the config
5572
        // color is not changed from default (#3399FF) and we have a value in
5573
        // the source node.
5574
        color, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5575
        if err != nil {
3✔
NEW
5576
                return fmt.Errorf("unable to parse color: %w", err)
×
NEW
5577
        }
×
5578

5579
        var (
3✔
5580
                alias          = s.cfg.Alias
3✔
5581
                nodeLastUpdate = time.Now()
3✔
5582
        )
3✔
5583

3✔
5584
        srcNode, err := s.graphDB.SourceNode(ctx)
3✔
5585
        switch {
3✔
5586
        case err == nil:
3✔
5587
                // If we have a source node persisted in the DB already, then we
3✔
5588
                // just need to make sure that the new LastUpdate time is at
3✔
5589
                // least one second after the last update time.
3✔
5590
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
5591
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
5592
                }
3✔
5593

5594
                // If the color is not changed from default, it means that we
5595
                // didn't specify a different color in the config. We'll use the
5596
                // source node's color.
5597
                if s.cfg.Color == defaultColor {
6✔
5598
                        color = srcNode.Color
3✔
5599
                }
3✔
5600

5601
                // If an alias is not specified in the config, we'll use the
5602
                // source node's alias.
5603
                if alias == "" {
6✔
5604
                        alias = srcNode.Alias
3✔
5605
                }
3✔
5606

5607
                // Append unique addresses from the source node to the address
5608
                // list.
5609
                for _, addr := range srcNode.Addresses {
6✔
5610
                        if _, found := addressMap[addr.String()]; !found {
6✔
5611
                                addrs = append(addrs, addr)
3✔
5612
                                addressMap[addr.String()] = struct{}{}
3✔
5613
                        }
3✔
5614
                }
5615

5616
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5617
                // If an alias is not specified in the config, we'll use the
3✔
5618
                // default, which is the first 10 bytes of the serialized
3✔
5619
                // pubkey.
3✔
5620
                if alias == "" {
6✔
5621
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5622
                }
3✔
5623

5624
        // If the above cases are not matched, then we have an unhandled non
5625
        // nil error.
NEW
5626
        default:
×
NEW
5627
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5628
        }
5629

5630
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5631
        if err != nil {
3✔
NEW
5632
                return err
×
NEW
5633
        }
×
5634

5635
        // TODO(abdulkbk): potentially find a way to use the source node's
5636
        // features in the self node.
5637
        selfNode := &models.LightningNode{
3✔
5638
                HaveNodeAnnouncement: true,
3✔
5639
                LastUpdate:           nodeLastUpdate,
3✔
5640
                Addresses:            addrs,
3✔
5641
                Alias:                nodeAlias.String(),
3✔
5642
                Color:                color,
3✔
5643
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
5644
        }
3✔
5645

3✔
5646
        copy(selfNode.PubKeyBytes[:], nodePub[:])
3✔
5647

3✔
5648
        // Based on the disk representation of the node announcement generated
3✔
5649
        // above, we'll generate a node announcement that can go out on the
3✔
5650
        // network so we can properly sign it.
3✔
5651
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5652
        if err != nil {
3✔
NEW
5653
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
NEW
5654
        }
×
5655

5656
        // With the announcement generated, we'll sign it to properly
5657
        // authenticate the message on the network.
5658
        authSig, err := netann.SignAnnouncement(
3✔
5659
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5660
        )
3✔
5661
        if err != nil {
3✔
NEW
5662
                return fmt.Errorf("unable to generate signature for self node "+
×
NEW
5663
                        "announcement: %v", err)
×
NEW
5664
        }
×
5665

5666
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5667
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5668
                selfNode.AuthSigBytes,
3✔
5669
        )
3✔
5670
        if err != nil {
3✔
NEW
5671
                return err
×
NEW
5672
        }
×
5673

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

5680
        s.currentNodeAnn = nodeAnn
3✔
5681

3✔
5682
        return nil
3✔
5683
}
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