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

lightningnetwork / lnd / 18136218528

30 Sep 2025 04:07PM UTC coverage: 66.583% (+9.5%) from 57.132%
18136218528

Pull #9432

github

web-flow
Merge 31722ee16 into 90c96c7df
Pull Request #9432: multi: add upfront-shutdown-address to lnd.conf.

21 of 24 new or added lines in 3 files covered. (87.5%)

56 existing lines in 9 files now uncovered.

136725 of 205344 relevant lines covered (66.58%)

21273.83 hits per line

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

69.44
/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/chancloser"
64
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
65
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
66
        "github.com/lightningnetwork/lnd/lnwire"
67
        "github.com/lightningnetwork/lnd/nat"
68
        "github.com/lightningnetwork/lnd/netann"
69
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
70
        "github.com/lightningnetwork/lnd/peer"
71
        "github.com/lightningnetwork/lnd/peernotifier"
72
        "github.com/lightningnetwork/lnd/pool"
73
        "github.com/lightningnetwork/lnd/queue"
74
        "github.com/lightningnetwork/lnd/routing"
75
        "github.com/lightningnetwork/lnd/routing/localchans"
76
        "github.com/lightningnetwork/lnd/routing/route"
77
        "github.com/lightningnetwork/lnd/subscribe"
78
        "github.com/lightningnetwork/lnd/sweep"
79
        "github.com/lightningnetwork/lnd/ticker"
80
        "github.com/lightningnetwork/lnd/tor"
81
        "github.com/lightningnetwork/lnd/walletunlocker"
82
        "github.com/lightningnetwork/lnd/watchtower/blob"
83
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
84
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
85
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
86
)
87

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

232
        start sync.Once
233
        stop  sync.Once
234

235
        cfg *Config
236

237
        implCfg *ImplementationCfg
238

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

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

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

250
        chanStatusMgr *netann.ChanStatusManager
251

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

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

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

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

272
        mu sync.RWMutex
273

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

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

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

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

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

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

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

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

324
        cc *chainreg.ChainControl
325

326
        fundingMgr *funding.Manager
327

328
        graphDB *graphdb.ChannelGraph
329

330
        chanStateDB *channeldb.ChannelStateDB
331

332
        addrSource channeldb.AddrSource
333

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

338
        invoicesDB invoices.InvoiceDB
339

340
        // paymentsDB is the DB that contains all functions for managing
341
        // payments.
342
        paymentsDB paymentsdb.DB
343

344
        aliasMgr *aliasmgr.Manager
345

346
        htlcSwitch *htlcswitch.Switch
347

348
        interceptableSwitch *htlcswitch.InterceptableSwitch
349

350
        invoices *invoices.InvoiceRegistry
351

352
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
353

354
        channelNotifier *channelnotifier.ChannelNotifier
355

356
        peerNotifier *peernotifier.PeerNotifier
357

358
        htlcNotifier *htlcswitch.HtlcNotifier
359

360
        witnessBeacon contractcourt.WitnessBeacon
361

362
        breachArbitrator *contractcourt.BreachArbitrator
363

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

367
        graphBuilder *graph.Builder
368

369
        chanRouter *routing.ChannelRouter
370

371
        controlTower routing.ControlTower
372

373
        authGossiper *discovery.AuthenticatedGossiper
374

375
        localChanMgr *localchans.Manager
376

377
        utxoNursery *contractcourt.UtxoNursery
378

379
        sweeper *sweep.UtxoSweeper
380

381
        chainArb *contractcourt.ChainArbitrator
382

383
        sphinx *hop.OnionProcessor
384

385
        towerClientMgr *wtclient.Manager
386

387
        connMgr *connmgr.ConnManager
388

389
        sigPool *lnwallet.SigPool
390

391
        writePool *pool.Write
392

393
        readPool *pool.Read
394

395
        tlsManager *TLSManager
396

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

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

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

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

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

419
        hostAnn *netann.HostAnnouncer
420

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

424
        customMessageServer *subscribe.Server
425

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

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

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

436
        quit chan struct{}
437

438
        wg sync.WaitGroup
439
}
440

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

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

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

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

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

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

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

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

496
                                        s.mu.Lock()
3✔
497

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

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

512
                                        s.mu.Unlock()
3✔
513

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

520
        return nil
3✔
521
}
522

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
703
                listenAddrs: listenAddrs,
3✔
704

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

3✔
709
                torController: torController,
3✔
710

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

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

3✔
727
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
728

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

3✔
731
                tlsManager: tlsManager,
3✔
732

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

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

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

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

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

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

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

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

3✔
774
                return nil
3✔
775
        }
776

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1009
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
1010

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

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

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

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

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

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

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

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

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

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

1128
        s.peerAccessMan = peerAccessMan
3✔
1129

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1455
        // Attempt to parse the provided upfront-shutdown address (if any).
1456
        script, err := chancloser.ParseUpfrontShutdownAddress(
3✔
1457
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
3✔
1458
        )
3✔
1459
        if err != nil {
3✔
NEW
1460
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
NEW
1461
                        err)
×
NEW
1462
        }
×
1463

1464
        //nolint:ll
1465
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1466
                Dev:                devCfg,
3✔
1467
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1468
                IDKey:              nodeKeyDesc.PubKey,
3✔
1469
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1470
                Wallet:             cc.Wallet,
3✔
1471
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1472
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1473
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1474
                },
3✔
1475
                Notifier:     cc.ChainNotifier,
1476
                ChannelDB:    s.chanStateDB,
1477
                FeeEstimator: cc.FeeEstimator,
1478
                SignMessage:  cc.MsgSigner.SignMessage,
1479
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1480
                        error) {
3✔
1481

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

3✔
1502
                        // In case the user has explicitly specified
3✔
1503
                        // a default value for the number of
3✔
1504
                        // confirmations, we use it.
3✔
1505
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1506
                        if defaultConf != 0 {
6✔
1507
                                return defaultConf
3✔
1508
                        }
3✔
1509

1510
                        minConf := uint64(3)
×
1511
                        maxConf := uint64(6)
×
1512

×
1513
                        // If this is a wumbo channel, then we'll require the
×
1514
                        // max amount of confirmations.
×
1515
                        if chanAmt > MaxFundingAmount {
×
1516
                                return uint16(maxConf)
×
1517
                        }
×
1518

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

3✔
1541
                        // In case the user has explicitly specified
3✔
1542
                        // a default value for the remote delay, we
3✔
1543
                        // use it.
3✔
1544
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1545
                        if defaultDelay > 0 {
6✔
1546
                                return defaultDelay
3✔
1547
                        }
3✔
1548

1549
                        // If this is a wumbo channel, then we'll require the
1550
                        // max value.
1551
                        if chanAmt > MaxFundingAmount {
×
1552
                                return maxRemoteDelay
×
1553
                        }
×
1554

1555
                        // If not we scale according to channel size.
1556
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1557
                                chanAmt / MaxFundingAmount)
×
1558
                        if delay < minRemoteDelay {
×
1559
                                delay = minRemoteDelay
×
1560
                        }
×
1561
                        if delay > maxRemoteDelay {
×
1562
                                delay = maxRemoteDelay
×
1563
                        }
×
1564
                        return delay
×
1565
                },
1566
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1567
                        peerKey *btcec.PublicKey) error {
3✔
1568

3✔
1569
                        // First, we'll mark this new peer as a persistent peer
3✔
1570
                        // for re-connection purposes. If the peer is not yet
3✔
1571
                        // tracked or the user hasn't requested it to be perm,
3✔
1572
                        // we'll set false to prevent the server from continuing
3✔
1573
                        // to connect to this peer even if the number of
3✔
1574
                        // channels with this peer is zero.
3✔
1575
                        s.mu.Lock()
3✔
1576
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1577
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1578
                                s.persistentPeers[pubStr] = false
3✔
1579
                        }
3✔
1580
                        s.mu.Unlock()
3✔
1581

3✔
1582
                        // With that taken care of, we'll send this channel to
3✔
1583
                        // the chain arb so it can react to on-chain events.
3✔
1584
                        return s.chainArb.WatchNewChannel(channel)
3✔
1585
                },
1586
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1587
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1588
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1589
                },
3✔
1590
                RequiredRemoteChanReserve: func(chanAmt,
1591
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1592

3✔
1593
                        // By default, we'll require the remote peer to maintain
3✔
1594
                        // at least 1% of the total channel capacity at all
3✔
1595
                        // times. If this value ends up dipping below the dust
3✔
1596
                        // limit, then we'll use the dust limit itself as the
3✔
1597
                        // reserve as required by BOLT #2.
3✔
1598
                        reserve := chanAmt / 100
3✔
1599
                        if reserve < dustLimit {
6✔
1600
                                reserve = dustLimit
3✔
1601
                        }
3✔
1602

1603
                        return reserve
3✔
1604
                },
1605
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1606
                        // By default, we'll allow the remote peer to fully
3✔
1607
                        // utilize the full bandwidth of the channel, minus our
3✔
1608
                        // required reserve.
3✔
1609
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1610
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1611
                },
3✔
1612
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1613
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1614
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1615
                        }
3✔
1616

1617
                        // By default, we'll permit them to utilize the full
1618
                        // channel bandwidth.
1619
                        return uint16(input.MaxHTLCNumber / 2)
×
1620
                },
1621
                ZombieSweeperInterval:         zombieSweeperInterval,
1622
                ReservationTimeout:            reservationTimeout,
1623
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1624
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1625
                MaxPendingChannels:            cfg.MaxPendingChannels,
1626
                RejectPush:                    cfg.RejectPush,
1627
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1628
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1629
                OpenChannelPredicate:          chanPredicate,
1630
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1631
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1632
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1633
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1634
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1635
                DeleteAliasEdge:      deleteAliasEdge,
1636
                AliasManager:         s.aliasMgr,
1637
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1638
                AuxFundingController: implCfg.AuxFundingController,
1639
                AuxSigner:            implCfg.AuxSigner,
1640
                AuxResolver:          implCfg.AuxContractResolver,
1641
                AuxChannelNegotiator: implCfg.AuxChannelNegotiator,
1642
                ShutdownScript:       peer.ChooseAddr(script),
1643
        })
1644
        if err != nil {
3✔
1645
                return nil, err
×
1646
        }
×
1647

1648
        // Next, we'll assemble the sub-system that will maintain an on-disk
1649
        // static backup of the latest channel state.
1650
        chanNotifier := &channelNotifier{
3✔
1651
                chanNotifier: s.channelNotifier,
3✔
1652
                addrs:        s.addrSource,
3✔
1653
        }
3✔
1654
        backupFile := chanbackup.NewMultiFile(
3✔
1655
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1656
        )
3✔
1657
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1658
                ctx, s.chanStateDB, s.addrSource,
3✔
1659
        )
3✔
1660
        if err != nil {
3✔
1661
                return nil, err
×
1662
        }
×
1663
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1664
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1665
        )
3✔
1666
        if err != nil {
3✔
1667
                return nil, err
×
1668
        }
×
1669

1670
        // Assemble a peer notifier which will provide clients with subscriptions
1671
        // to peer online and offline events.
1672
        s.peerNotifier = peernotifier.New()
3✔
1673

3✔
1674
        // Create a channel event store which monitors all open channels.
3✔
1675
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1676
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1677
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1678
                },
3✔
1679
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1680
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1681
                },
3✔
1682
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1683
                Clock:           clock.NewDefaultClock(),
1684
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1685
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1686
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1687
        })
1688

1689
        if cfg.WtClient.Active {
6✔
1690
                policy := wtpolicy.DefaultPolicy()
3✔
1691
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1692

3✔
1693
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1694
                // protocol operations on sat/kw.
3✔
1695
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1696
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1697
                )
3✔
1698

3✔
1699
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1700

3✔
1701
                if err := policy.Validate(); err != nil {
3✔
1702
                        return nil, err
×
1703
                }
×
1704

1705
                // authDial is the wrapper around the btrontide.Dial for the
1706
                // watchtower.
1707
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1708
                        netAddr *lnwire.NetAddress,
3✔
1709
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1710

3✔
1711
                        return brontide.Dial(
3✔
1712
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1713
                        )
3✔
1714
                }
3✔
1715

1716
                // buildBreachRetribution is a call-back that can be used to
1717
                // query the BreachRetribution info and channel type given a
1718
                // channel ID and commitment height.
1719
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1720
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1721
                        channeldb.ChannelType, error) {
6✔
1722

3✔
1723
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1724
                                nil, chanID,
3✔
1725
                        )
3✔
1726
                        if err != nil {
3✔
1727
                                return nil, 0, err
×
1728
                        }
×
1729

1730
                        br, err := lnwallet.NewBreachRetribution(
3✔
1731
                                channel, commitHeight, 0, nil,
3✔
1732
                                implCfg.AuxLeafStore,
3✔
1733
                                implCfg.AuxContractResolver,
3✔
1734
                        )
3✔
1735
                        if err != nil {
3✔
1736
                                return nil, 0, err
×
1737
                        }
×
1738

1739
                        return br, channel.ChanType, nil
3✔
1740
                }
1741

1742
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1743

3✔
1744
                // Copy the policy for legacy channels and set the blob flag
3✔
1745
                // signalling support for anchor channels.
3✔
1746
                anchorPolicy := policy
3✔
1747
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1748

3✔
1749
                // Copy the policy for legacy channels and set the blob flag
3✔
1750
                // signalling support for taproot channels.
3✔
1751
                taprootPolicy := policy
3✔
1752
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1753
                        blob.FlagTaprootChannel,
3✔
1754
                )
3✔
1755

3✔
1756
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1757
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1758
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1759
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1760
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1761
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1762
                                error) {
6✔
1763

3✔
1764
                                return s.channelNotifier.
3✔
1765
                                        SubscribeChannelEvents()
3✔
1766
                        },
3✔
1767
                        Signer: cc.Wallet.Cfg.Signer,
1768
                        NewAddress: func() ([]byte, error) {
3✔
1769
                                addr, err := newSweepPkScriptGen(
3✔
1770
                                        cc.Wallet, netParams,
3✔
1771
                                )().Unpack()
3✔
1772
                                if err != nil {
3✔
1773
                                        return nil, err
×
1774
                                }
×
1775

1776
                                return addr.DeliveryAddress, nil
3✔
1777
                        },
1778
                        SecretKeyRing:      s.cc.KeyRing,
1779
                        Dial:               cfg.net.Dial,
1780
                        AuthDial:           authDial,
1781
                        DB:                 dbs.TowerClientDB,
1782
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1783
                        MinBackoff:         10 * time.Second,
1784
                        MaxBackoff:         5 * time.Minute,
1785
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1786
                }, policy, anchorPolicy, taprootPolicy)
1787
                if err != nil {
3✔
1788
                        return nil, err
×
1789
                }
×
1790
        }
1791

1792
        if len(cfg.ExternalHosts) != 0 {
3✔
1793
                advertisedIPs := make(map[string]struct{})
×
1794
                for _, addr := range s.currentNodeAnn.Addresses {
×
1795
                        advertisedIPs[addr.String()] = struct{}{}
×
1796
                }
×
1797

1798
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1799
                        Hosts:         cfg.ExternalHosts,
×
1800
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1801
                        LookupHost: func(host string) (net.Addr, error) {
×
1802
                                return lncfg.ParseAddressString(
×
1803
                                        host, strconv.Itoa(defaultPeerPort),
×
1804
                                        cfg.net.ResolveTCPAddr,
×
1805
                                )
×
1806
                        },
×
1807
                        AdvertisedIPs: advertisedIPs,
1808
                        AnnounceNewIPs: netann.IPAnnouncer(
1809
                                func(modifier ...netann.NodeAnnModifier) (
1810
                                        lnwire.NodeAnnouncement, error) {
×
1811

×
1812
                                        return s.genNodeAnnouncement(
×
1813
                                                nil, modifier...,
×
1814
                                        )
×
1815
                                }),
×
1816
                })
1817
        }
1818

1819
        // Create liveness monitor.
1820
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1821

3✔
1822
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1823
        for i, listenAddr := range listenAddrs {
6✔
1824
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1825
                // doesn't need to call the general lndResolveTCP function
3✔
1826
                // since we are resolving a local address.
3✔
1827

3✔
1828
                // RESOLVE: We are actually partially accepting inbound
3✔
1829
                // connection requests when we call NewListener.
3✔
1830
                listeners[i], err = brontide.NewListener(
3✔
1831
                        nodeKeyECDH, listenAddr.String(),
3✔
1832
                        // TODO(yy): remove this check and unify the inbound
3✔
1833
                        // connection check inside `InboundPeerConnected`.
3✔
1834
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1835
                )
3✔
1836
                if err != nil {
3✔
1837
                        return nil, err
×
1838
                }
×
1839
        }
1840

1841
        // Create the connection manager which will be responsible for
1842
        // maintaining persistent outbound connections and also accepting new
1843
        // incoming connections
1844
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1845
                Listeners:      listeners,
3✔
1846
                OnAccept:       s.InboundPeerConnected,
3✔
1847
                RetryDuration:  time.Second * 5,
3✔
1848
                TargetOutbound: 100,
3✔
1849
                Dial: noiseDial(
3✔
1850
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1851
                ),
3✔
1852
                OnConnection: s.OutboundPeerConnected,
3✔
1853
        })
3✔
1854
        if err != nil {
3✔
1855
                return nil, err
×
1856
        }
×
1857
        s.connMgr = cmgr
3✔
1858

3✔
1859
        // Finally, register the subsystems in blockbeat.
3✔
1860
        s.registerBlockConsumers()
3✔
1861

3✔
1862
        return s, nil
3✔
1863
}
1864

1865
// UpdateRoutingConfig is a callback function to update the routing config
1866
// values in the main cfg.
1867
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1868
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1869

3✔
1870
        switch c := cfg.Estimator.Config().(type) {
3✔
1871
        case routing.AprioriConfig:
3✔
1872
                routerCfg.ProbabilityEstimatorType =
3✔
1873
                        routing.AprioriEstimatorName
3✔
1874

3✔
1875
                targetCfg := routerCfg.AprioriConfig
3✔
1876
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1877
                targetCfg.Weight = c.AprioriWeight
3✔
1878
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1879
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1880

1881
        case routing.BimodalConfig:
3✔
1882
                routerCfg.ProbabilityEstimatorType =
3✔
1883
                        routing.BimodalEstimatorName
3✔
1884

3✔
1885
                targetCfg := routerCfg.BimodalConfig
3✔
1886
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1887
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1888
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1889
        }
1890

1891
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1892
}
1893

1894
// registerBlockConsumers registers the subsystems that consume block events.
1895
// By calling `RegisterQueue`, a list of subsystems are registered in the
1896
// blockbeat for block notifications. When a new block arrives, the subsystems
1897
// in the same queue are notified sequentially, and different queues are
1898
// notified concurrently.
1899
//
1900
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1901
// a new `RegisterQueue` call.
1902
func (s *server) registerBlockConsumers() {
3✔
1903
        // In this queue, when a new block arrives, it will be received and
3✔
1904
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1905
        consumers := []chainio.Consumer{
3✔
1906
                s.chainArb,
3✔
1907
                s.sweeper,
3✔
1908
                s.txPublisher,
3✔
1909
        }
3✔
1910
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1911
}
3✔
1912

1913
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1914
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1915
// may differ from what is on disk.
1916
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1917
        error) {
3✔
1918

3✔
1919
        data, err := u.DataToSign()
3✔
1920
        if err != nil {
3✔
1921
                return nil, err
×
1922
        }
×
1923

1924
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1925
}
1926

1927
// createLivenessMonitor creates a set of health checks using our configured
1928
// values and uses these checks to create a liveness monitor. Available
1929
// health checks,
1930
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1931
//   - diskCheck
1932
//   - tlsHealthCheck
1933
//   - torController, only created when tor is enabled.
1934
//
1935
// If a health check has been disabled by setting attempts to 0, our monitor
1936
// will not run it.
1937
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1938
        leaderElector cluster.LeaderElector) {
3✔
1939

3✔
1940
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1941
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1942
                srvrLog.Info("Disabling chain backend checks for " +
×
1943
                        "nochainbackend mode")
×
1944

×
1945
                chainBackendAttempts = 0
×
1946
        }
×
1947

1948
        chainHealthCheck := healthcheck.NewObservation(
3✔
1949
                "chain backend",
3✔
1950
                cc.HealthCheck,
3✔
1951
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1952
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1953
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1954
                chainBackendAttempts,
3✔
1955
        )
3✔
1956

3✔
1957
        diskCheck := healthcheck.NewObservation(
3✔
1958
                "disk space",
3✔
1959
                func() error {
3✔
1960
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1961
                                cfg.LndDir,
×
1962
                        )
×
1963
                        if err != nil {
×
1964
                                return err
×
1965
                        }
×
1966

1967
                        // If we have more free space than we require,
1968
                        // we return a nil error.
1969
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1970
                                return nil
×
1971
                        }
×
1972

1973
                        return fmt.Errorf("require: %v free space, got: %v",
×
1974
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1975
                                free)
×
1976
                },
1977
                cfg.HealthChecks.DiskCheck.Interval,
1978
                cfg.HealthChecks.DiskCheck.Timeout,
1979
                cfg.HealthChecks.DiskCheck.Backoff,
1980
                cfg.HealthChecks.DiskCheck.Attempts,
1981
        )
1982

1983
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1984
                "tls",
3✔
1985
                func() error {
3✔
1986
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1987
                                s.cc.KeyRing,
×
1988
                        )
×
1989
                        if err != nil {
×
1990
                                return err
×
1991
                        }
×
1992
                        if expired {
×
1993
                                return fmt.Errorf("TLS certificate is "+
×
1994
                                        "expired as of %v", expTime)
×
1995
                        }
×
1996

1997
                        // If the certificate is not outdated, no error needs
1998
                        // to be returned
1999
                        return nil
×
2000
                },
2001
                cfg.HealthChecks.TLSCheck.Interval,
2002
                cfg.HealthChecks.TLSCheck.Timeout,
2003
                cfg.HealthChecks.TLSCheck.Backoff,
2004
                cfg.HealthChecks.TLSCheck.Attempts,
2005
        )
2006

2007
        checks := []*healthcheck.Observation{
3✔
2008
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2009
        }
3✔
2010

3✔
2011
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2012
        if s.torController != nil {
3✔
2013
                torConnectionCheck := healthcheck.NewObservation(
×
2014
                        "tor connection",
×
2015
                        func() error {
×
2016
                                return healthcheck.CheckTorServiceStatus(
×
2017
                                        s.torController,
×
2018
                                        func() error {
×
2019
                                                return s.createNewHiddenService(
×
2020
                                                        context.TODO(),
×
2021
                                                )
×
2022
                                        },
×
2023
                                )
2024
                        },
2025
                        cfg.HealthChecks.TorConnection.Interval,
2026
                        cfg.HealthChecks.TorConnection.Timeout,
2027
                        cfg.HealthChecks.TorConnection.Backoff,
2028
                        cfg.HealthChecks.TorConnection.Attempts,
2029
                )
2030
                checks = append(checks, torConnectionCheck)
×
2031
        }
2032

2033
        // If remote signing is enabled, add the healthcheck for the remote
2034
        // signing RPC interface.
2035
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2036
                // Because we have two cascading timeouts here, we need to add
3✔
2037
                // some slack to the "outer" one of them in case the "inner"
3✔
2038
                // returns exactly on time.
3✔
2039
                overhead := time.Millisecond * 10
3✔
2040

3✔
2041
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2042
                        "remote signer connection",
3✔
2043
                        rpcwallet.HealthCheck(
3✔
2044
                                s.cfg.RemoteSigner,
3✔
2045

3✔
2046
                                // For the health check we might to be even
3✔
2047
                                // stricter than the initial/normal connect, so
3✔
2048
                                // we use the health check timeout here.
3✔
2049
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2050
                        ),
3✔
2051
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2052
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2053
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2054
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2055
                )
3✔
2056
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2057
        }
3✔
2058

2059
        // If we have a leader elector, we add a health check to ensure we are
2060
        // still the leader. During normal operation, we should always be the
2061
        // leader, but there are circumstances where this may change, such as
2062
        // when we lose network connectivity for long enough expiring out lease.
2063
        if leaderElector != nil {
3✔
2064
                leaderCheck := healthcheck.NewObservation(
×
2065
                        "leader status",
×
2066
                        func() error {
×
2067
                                // Check if we are still the leader. Note that
×
2068
                                // we don't need to use a timeout context here
×
2069
                                // as the healthcheck observer will handle the
×
2070
                                // timeout case for us.
×
2071
                                timeoutCtx, cancel := context.WithTimeout(
×
2072
                                        context.Background(),
×
2073
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2074
                                )
×
2075
                                defer cancel()
×
2076

×
2077
                                leader, err := leaderElector.IsLeader(
×
2078
                                        timeoutCtx,
×
2079
                                )
×
2080
                                if err != nil {
×
2081
                                        return fmt.Errorf("unable to check if "+
×
2082
                                                "still leader: %v", err)
×
2083
                                }
×
2084

2085
                                if !leader {
×
2086
                                        srvrLog.Debug("Not the current leader")
×
2087
                                        return fmt.Errorf("not the current " +
×
2088
                                                "leader")
×
2089
                                }
×
2090

2091
                                return nil
×
2092
                        },
2093
                        cfg.HealthChecks.LeaderCheck.Interval,
2094
                        cfg.HealthChecks.LeaderCheck.Timeout,
2095
                        cfg.HealthChecks.LeaderCheck.Backoff,
2096
                        cfg.HealthChecks.LeaderCheck.Attempts,
2097
                )
2098

2099
                checks = append(checks, leaderCheck)
×
2100
        }
2101

2102
        // If we have not disabled all of our health checks, we create a
2103
        // liveness monitor with our configured checks.
2104
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2105
                &healthcheck.Config{
3✔
2106
                        Checks:   checks,
3✔
2107
                        Shutdown: srvrLog.Criticalf,
3✔
2108
                },
3✔
2109
        )
3✔
2110
}
2111

2112
// Started returns true if the server has been started, and false otherwise.
2113
// NOTE: This function is safe for concurrent access.
2114
func (s *server) Started() bool {
3✔
2115
        return atomic.LoadInt32(&s.active) != 0
3✔
2116
}
3✔
2117

2118
// cleaner is used to aggregate "cleanup" functions during an operation that
2119
// starts several subsystems. In case one of the subsystem fails to start
2120
// and a proper resource cleanup is required, the "run" method achieves this
2121
// by running all these added "cleanup" functions.
2122
type cleaner []func() error
2123

2124
// add is used to add a cleanup function to be called when
2125
// the run function is executed.
2126
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2127
        return append(c, cleanup)
3✔
2128
}
3✔
2129

2130
// run is used to run all the previousely added cleanup functions.
2131
func (c cleaner) run() {
×
2132
        for i := len(c) - 1; i >= 0; i-- {
×
2133
                if err := c[i](); err != nil {
×
2134
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2135
                }
×
2136
        }
2137
}
2138

2139
// startLowLevelServices starts the low-level services of the server. These
2140
// services must be started successfully before running the main server. The
2141
// services are,
2142
// 1. the chain notifier.
2143
//
2144
// TODO(yy): identify and add more low-level services here.
2145
func (s *server) startLowLevelServices() error {
3✔
2146
        var startErr error
3✔
2147

3✔
2148
        cleanup := cleaner{}
3✔
2149

3✔
2150
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2151
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2152
                startErr = err
×
2153
        }
×
2154

2155
        if startErr != nil {
3✔
2156
                cleanup.run()
×
2157
        }
×
2158

2159
        return startErr
3✔
2160
}
2161

2162
// Start starts the main daemon server, all requested listeners, and any helper
2163
// goroutines.
2164
// NOTE: This function is safe for concurrent access.
2165
//
2166
//nolint:funlen
2167
func (s *server) Start(ctx context.Context) error {
3✔
2168
        // Get the current blockbeat.
3✔
2169
        beat, err := s.getStartingBeat()
3✔
2170
        if err != nil {
3✔
2171
                return err
×
2172
        }
×
2173

2174
        var startErr error
3✔
2175

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

3✔
2181
        s.start.Do(func() {
6✔
2182
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2183
                if err := s.customMessageServer.Start(); err != nil {
3✔
2184
                        startErr = err
×
2185
                        return
×
2186
                }
×
2187

2188
                if s.hostAnn != nil {
3✔
2189
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2190
                        if err := s.hostAnn.Start(); err != nil {
×
2191
                                startErr = err
×
2192
                                return
×
2193
                        }
×
2194
                }
2195

2196
                if s.livenessMonitor != nil {
6✔
2197
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2198
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2199
                                startErr = err
×
2200
                                return
×
2201
                        }
×
2202
                }
2203

2204
                // Start the notification server. This is used so channel
2205
                // management goroutines can be notified when a funding
2206
                // transaction reaches a sufficient number of confirmations, or
2207
                // when the input for the funding transaction is spent in an
2208
                // attempt at an uncooperative close by the counterparty.
2209
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2210
                if err := s.sigPool.Start(); err != nil {
3✔
2211
                        startErr = err
×
2212
                        return
×
2213
                }
×
2214

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

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

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

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

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

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

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

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

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

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

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

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

2291
                // htlcSwitch must be started before chainArb since the latter
2292
                // relies on htlcSwitch to deliver resolution message upon
2293
                // start.
2294
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2295
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2296
                        startErr = err
×
2297
                        return
×
2298
                }
×
2299

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

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

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

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

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

2330
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2331
                if err := s.chanRouter.Start(); err != nil {
3✔
2332
                        startErr = err
×
2333
                        return
×
2334
                }
×
2335
                // The authGossiper depends on the chanRouter and therefore
2336
                // should be started after it.
2337
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2338
                if err := s.authGossiper.Start(); err != nil {
3✔
2339
                        startErr = err
×
2340
                        return
×
2341
                }
×
2342

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

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

2355
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2356
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2357
                        startErr = err
×
2358
                        return
×
2359
                }
×
2360

2361
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2362
                if err := s.chanEventStore.Start(); err != nil {
3✔
2363
                        startErr = err
×
2364
                        return
×
2365
                }
×
2366

2367
                cleanup.add(func() error {
3✔
2368
                        s.missionController.StopStoreTickers()
×
2369
                        return nil
×
2370
                })
×
2371
                s.missionController.RunStoreTickers()
3✔
2372

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

2405
                // chanSubSwapper must be started after the `channelNotifier`
2406
                // because it depends on channel events as a synchronization
2407
                // point.
2408
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2409
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2410
                        startErr = err
×
2411
                        return
×
2412
                }
×
2413

2414
                if s.torController != nil {
3✔
2415
                        cleanup = cleanup.add(s.torController.Stop)
×
2416
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2417
                                startErr = err
×
2418
                                return
×
2419
                        }
×
2420
                }
2421

2422
                if s.natTraversal != nil {
3✔
2423
                        s.wg.Add(1)
×
2424
                        go s.watchExternalIP()
×
2425
                }
×
2426

2427
                // Start connmgr last to prevent connections before init.
2428
                cleanup = cleanup.add(func() error {
3✔
2429
                        s.connMgr.Stop()
×
2430
                        return nil
×
2431
                })
×
2432

2433
                // RESOLVE: s.connMgr.Start() is called here, but
2434
                // brontide.NewListener() is called in newServer. This means
2435
                // that we are actually listening and partially accepting
2436
                // inbound connections even before the connMgr starts.
2437
                //
2438
                // TODO(yy): move the log into the connMgr's `Start` method.
2439
                srvrLog.Info("connMgr starting...")
3✔
2440
                s.connMgr.Start()
3✔
2441
                srvrLog.Debug("connMgr started")
3✔
2442

3✔
2443
                // If peers are specified as a config option, we'll add those
3✔
2444
                // peers first.
3✔
2445
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2446
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2447
                                peerAddrCfg,
3✔
2448
                        )
3✔
2449
                        if err != nil {
3✔
2450
                                startErr = fmt.Errorf("unable to parse peer "+
×
2451
                                        "pubkey from config: %v", err)
×
2452
                                return
×
2453
                        }
×
2454
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2455
                        if err != nil {
3✔
2456
                                startErr = fmt.Errorf("unable to parse peer "+
×
2457
                                        "address provided as a config option: "+
×
2458
                                        "%v", err)
×
2459
                                return
×
2460
                        }
×
2461

2462
                        peerAddr := &lnwire.NetAddress{
3✔
2463
                                IdentityKey: parsedPubkey,
3✔
2464
                                Address:     addr,
3✔
2465
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2466
                        }
3✔
2467

3✔
2468
                        err = s.ConnectToPeer(
3✔
2469
                                peerAddr, true,
3✔
2470
                                s.cfg.ConnectionTimeout,
3✔
2471
                        )
3✔
2472
                        if err != nil {
3✔
2473
                                startErr = fmt.Errorf("unable to connect to "+
×
2474
                                        "peer address provided as a config "+
×
2475
                                        "option: %v", err)
×
2476
                                return
×
2477
                        }
×
2478
                }
2479

2480
                // Subscribe to NodeAnnouncements that advertise new addresses
2481
                // our persistent peers.
2482
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2483
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2484
                                "addr: %v", err)
×
2485

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

2490
                // With all the relevant sub-systems started, we'll now attempt
2491
                // to establish persistent connections to our direct channel
2492
                // collaborators within the network. Before doing so however,
2493
                // we'll prune our set of link nodes found within the database
2494
                // to ensure we don't reconnect to any nodes we no longer have
2495
                // open channels with.
2496
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2497
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2498

×
2499
                        startErr = err
×
2500
                        return
×
2501
                }
×
2502

2503
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2504
                        srvrLog.Errorf("Failed to establish persistent "+
×
2505
                                "connections: %v", err)
×
2506
                }
×
2507

2508
                // setSeedList is a helper function that turns multiple DNS seed
2509
                // server tuples from the command line or config file into the
2510
                // data structure we need and does a basic formal sanity check
2511
                // in the process.
2512
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2513
                        if len(tuples) == 0 {
×
2514
                                return
×
2515
                        }
×
2516

2517
                        result := make([][2]string, len(tuples))
×
2518
                        for idx, tuple := range tuples {
×
2519
                                tuple = strings.TrimSpace(tuple)
×
2520
                                if len(tuple) == 0 {
×
2521
                                        return
×
2522
                                }
×
2523

2524
                                servers := strings.Split(tuple, ",")
×
2525
                                if len(servers) > 2 || len(servers) == 0 {
×
2526
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2527
                                                "seed tuple: %v", servers)
×
2528
                                        return
×
2529
                                }
×
2530

2531
                                copy(result[idx][:], servers)
×
2532
                        }
2533

2534
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2535
                }
2536

2537
                // Let users overwrite the DNS seed nodes. We only allow them
2538
                // for bitcoin mainnet/testnet/signet.
2539
                if s.cfg.Bitcoin.MainNet {
3✔
2540
                        setSeedList(
×
2541
                                s.cfg.Bitcoin.DNSSeeds,
×
2542
                                chainreg.BitcoinMainnetGenesis,
×
2543
                        )
×
2544
                }
×
2545
                if s.cfg.Bitcoin.TestNet3 {
3✔
2546
                        setSeedList(
×
2547
                                s.cfg.Bitcoin.DNSSeeds,
×
2548
                                chainreg.BitcoinTestnetGenesis,
×
2549
                        )
×
2550
                }
×
2551
                if s.cfg.Bitcoin.TestNet4 {
3✔
2552
                        setSeedList(
×
2553
                                s.cfg.Bitcoin.DNSSeeds,
×
2554
                                chainreg.BitcoinTestnet4Genesis,
×
2555
                        )
×
2556
                }
×
2557
                if s.cfg.Bitcoin.SigNet {
3✔
2558
                        setSeedList(
×
2559
                                s.cfg.Bitcoin.DNSSeeds,
×
2560
                                chainreg.BitcoinSignetGenesis,
×
2561
                        )
×
2562
                }
×
2563

2564
                // If network bootstrapping hasn't been disabled, then we'll
2565
                // configure the set of active bootstrappers, and launch a
2566
                // dedicated goroutine to maintain a set of persistent
2567
                // connections.
2568
                if !s.cfg.NoNetBootstrap {
6✔
2569
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2570
                        if err != nil {
3✔
2571
                                startErr = err
×
2572
                                return
×
2573
                        }
×
2574

2575
                        s.wg.Add(1)
3✔
2576
                        go s.peerBootstrapper(
3✔
2577
                                ctx, defaultMinPeers, bootstrappers,
3✔
2578
                        )
3✔
2579
                } else {
3✔
2580
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2581
                }
3✔
2582

2583
                // Start the blockbeat after all other subsystems have been
2584
                // started so they are ready to receive new blocks.
2585
                cleanup = cleanup.add(func() error {
3✔
2586
                        s.blockbeatDispatcher.Stop()
×
2587
                        return nil
×
2588
                })
×
2589
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2590
                        startErr = err
×
2591
                        return
×
2592
                }
×
2593

2594
                // Set the active flag now that we've completed the full
2595
                // startup.
2596
                atomic.StoreInt32(&s.active, 1)
3✔
2597
        })
2598

2599
        if startErr != nil {
3✔
2600
                cleanup.run()
×
2601
        }
×
2602
        return startErr
3✔
2603
}
2604

2605
// Stop gracefully shutsdown the main daemon server. This function will signal
2606
// any active goroutines, or helper objects to exit, then blocks until they've
2607
// all successfully exited. Additionally, any/all listeners are closed.
2608
// NOTE: This function is safe for concurrent access.
2609
func (s *server) Stop() error {
3✔
2610
        s.stop.Do(func() {
6✔
2611
                atomic.StoreInt32(&s.stopping, 1)
3✔
2612

3✔
2613
                ctx := context.Background()
3✔
2614

3✔
2615
                close(s.quit)
3✔
2616

3✔
2617
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2618
                s.connMgr.Stop()
3✔
2619

3✔
2620
                // Stop dispatching blocks to other systems immediately.
3✔
2621
                s.blockbeatDispatcher.Stop()
3✔
2622

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

2685
                // Update channel.backup file. Make sure to do it before
2686
                // stopping chanSubSwapper.
2687
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2688
                        ctx, s.chanStateDB, s.addrSource,
3✔
2689
                )
3✔
2690
                if err != nil {
3✔
2691
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2692
                                err)
×
2693
                } else {
3✔
2694
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2695
                        if err != nil {
6✔
2696
                                srvrLog.Warnf("Manual update of channel "+
3✔
2697
                                        "backup failed: %v", err)
3✔
2698
                        }
3✔
2699
                }
2700

2701
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2702
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2703
                }
×
2704
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2705
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2706
                }
×
2707
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2708
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2709
                                err)
×
2710
                }
×
2711
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2712
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2713
                                err)
×
2714
                }
×
2715
                s.missionController.StopStoreTickers()
3✔
2716

3✔
2717
                // Disconnect from each active peers to ensure that
3✔
2718
                // peerTerminationWatchers signal completion to each peer.
3✔
2719
                for _, peer := range s.Peers() {
6✔
2720
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2721
                        if err != nil {
3✔
2722
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2723
                                        "received error: %v", peer.IdentityKey(),
×
2724
                                        err,
×
2725
                                )
×
2726
                        }
×
2727
                }
2728

2729
                // Now that all connections have been torn down, stop the tower
2730
                // client which will reliably flush all queued states to the
2731
                // tower. If this is halted for any reason, the force quit timer
2732
                // will kick in and abort to allow this method to return.
2733
                if s.towerClientMgr != nil {
6✔
2734
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2735
                                srvrLog.Warnf("Unable to shut down tower "+
×
2736
                                        "client manager: %v", err)
×
2737
                        }
×
2738
                }
2739

2740
                if s.hostAnn != nil {
3✔
2741
                        if err := s.hostAnn.Stop(); err != nil {
×
2742
                                srvrLog.Warnf("unable to shut down host "+
×
2743
                                        "annoucner: %v", err)
×
2744
                        }
×
2745
                }
2746

2747
                if s.livenessMonitor != nil {
6✔
2748
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2749
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2750
                                        "monitor: %v", err)
×
2751
                        }
×
2752
                }
2753

2754
                // Wait for all lingering goroutines to quit.
2755
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2756
                s.wg.Wait()
3✔
2757

3✔
2758
                srvrLog.Debug("Stopping buffer pools...")
3✔
2759
                s.sigPool.Stop()
3✔
2760
                s.writePool.Stop()
3✔
2761
                s.readPool.Stop()
3✔
2762
        })
2763

2764
        return nil
3✔
2765
}
2766

2767
// Stopped returns true if the server has been instructed to shutdown.
2768
// NOTE: This function is safe for concurrent access.
2769
func (s *server) Stopped() bool {
3✔
2770
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2771
}
3✔
2772

2773
// configurePortForwarding attempts to set up port forwarding for the different
2774
// ports that the server will be listening on.
2775
//
2776
// NOTE: This should only be used when using some kind of NAT traversal to
2777
// automatically set up forwarding rules.
2778
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2779
        ip, err := s.natTraversal.ExternalIP()
×
2780
        if err != nil {
×
2781
                return nil, err
×
2782
        }
×
2783
        s.lastDetectedIP = ip
×
2784

×
2785
        externalIPs := make([]string, 0, len(ports))
×
2786
        for _, port := range ports {
×
2787
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2788
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2789
                        continue
×
2790
                }
2791

2792
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2793
                externalIPs = append(externalIPs, hostIP)
×
2794
        }
2795

2796
        return externalIPs, nil
×
2797
}
2798

2799
// removePortForwarding attempts to clear the forwarding rules for the different
2800
// ports the server is currently listening on.
2801
//
2802
// NOTE: This should only be used when using some kind of NAT traversal to
2803
// automatically set up forwarding rules.
2804
func (s *server) removePortForwarding() {
×
2805
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2806
        for _, port := range forwardedPorts {
×
2807
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2808
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2809
                                "port %d: %v", port, err)
×
2810
                }
×
2811
        }
2812
}
2813

2814
// watchExternalIP continuously checks for an updated external IP address every
2815
// 15 minutes. Once a new IP address has been detected, it will automatically
2816
// handle port forwarding rules and send updated node announcements to the
2817
// currently connected peers.
2818
//
2819
// NOTE: This MUST be run as a goroutine.
2820
func (s *server) watchExternalIP() {
×
2821
        defer s.wg.Done()
×
2822

×
2823
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2824
        // up by the server.
×
2825
        defer s.removePortForwarding()
×
2826

×
2827
        // Keep track of the external IPs set by the user to avoid replacing
×
2828
        // them when detecting a new IP.
×
2829
        ipsSetByUser := make(map[string]struct{})
×
2830
        for _, ip := range s.cfg.ExternalIPs {
×
2831
                ipsSetByUser[ip.String()] = struct{}{}
×
2832
        }
×
2833

2834
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2835

×
2836
        ticker := time.NewTicker(15 * time.Minute)
×
2837
        defer ticker.Stop()
×
2838
out:
×
2839
        for {
×
2840
                select {
×
2841
                case <-ticker.C:
×
2842
                        // We'll start off by making sure a new IP address has
×
2843
                        // been detected.
×
2844
                        ip, err := s.natTraversal.ExternalIP()
×
2845
                        if err != nil {
×
2846
                                srvrLog.Debugf("Unable to retrieve the "+
×
2847
                                        "external IP address: %v", err)
×
2848
                                continue
×
2849
                        }
2850

2851
                        // Periodically renew the NAT port forwarding.
2852
                        for _, port := range forwardedPorts {
×
2853
                                err := s.natTraversal.AddPortMapping(port)
×
2854
                                if err != nil {
×
2855
                                        srvrLog.Warnf("Unable to automatically "+
×
2856
                                                "re-create port forwarding using %s: %v",
×
2857
                                                s.natTraversal.Name(), err)
×
2858
                                } else {
×
2859
                                        srvrLog.Debugf("Automatically re-created "+
×
2860
                                                "forwarding for port %d using %s to "+
×
2861
                                                "advertise external IP",
×
2862
                                                port, s.natTraversal.Name())
×
2863
                                }
×
2864
                        }
2865

2866
                        if ip.Equal(s.lastDetectedIP) {
×
2867
                                continue
×
2868
                        }
2869

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

×
2872
                        // Next, we'll craft the new addresses that will be
×
2873
                        // included in the new node announcement and advertised
×
2874
                        // to the network. Each address will consist of the new
×
2875
                        // IP detected and one of the currently advertised
×
2876
                        // ports.
×
2877
                        var newAddrs []net.Addr
×
2878
                        for _, port := range forwardedPorts {
×
2879
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2880
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2881
                                if err != nil {
×
2882
                                        srvrLog.Debugf("Unable to resolve "+
×
2883
                                                "host %v: %v", addr, err)
×
2884
                                        continue
×
2885
                                }
2886

2887
                                newAddrs = append(newAddrs, addr)
×
2888
                        }
2889

2890
                        // Skip the update if we weren't able to resolve any of
2891
                        // the new addresses.
2892
                        if len(newAddrs) == 0 {
×
2893
                                srvrLog.Debug("Skipping node announcement " +
×
2894
                                        "update due to not being able to " +
×
2895
                                        "resolve any new addresses")
×
2896
                                continue
×
2897
                        }
2898

2899
                        // Now, we'll need to update the addresses in our node's
2900
                        // announcement in order to propagate the update
2901
                        // throughout the network. We'll only include addresses
2902
                        // that have a different IP from the previous one, as
2903
                        // the previous IP is no longer valid.
2904
                        currentNodeAnn := s.getNodeAnnouncement()
×
2905

×
2906
                        for _, addr := range currentNodeAnn.Addresses {
×
2907
                                host, _, err := net.SplitHostPort(addr.String())
×
2908
                                if err != nil {
×
2909
                                        srvrLog.Debugf("Unable to determine "+
×
2910
                                                "host from address %v: %v",
×
2911
                                                addr, err)
×
2912
                                        continue
×
2913
                                }
2914

2915
                                // We'll also make sure to include external IPs
2916
                                // set manually by the user.
2917
                                _, setByUser := ipsSetByUser[addr.String()]
×
2918
                                if setByUser || host != s.lastDetectedIP.String() {
×
2919
                                        newAddrs = append(newAddrs, addr)
×
2920
                                }
×
2921
                        }
2922

2923
                        // Then, we'll generate a new timestamped node
2924
                        // announcement with the updated addresses and broadcast
2925
                        // it to our peers.
2926
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2927
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2928
                        )
×
2929
                        if err != nil {
×
2930
                                srvrLog.Debugf("Unable to generate new node "+
×
2931
                                        "announcement: %v", err)
×
2932
                                continue
×
2933
                        }
2934

2935
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2936
                        if err != nil {
×
2937
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2938
                                        "announcement to peers: %v", err)
×
2939
                                continue
×
2940
                        }
2941

2942
                        // Finally, update the last IP seen to the current one.
2943
                        s.lastDetectedIP = ip
×
2944
                case <-s.quit:
×
2945
                        break out
×
2946
                }
2947
        }
2948
}
2949

2950
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2951
// based on the server, and currently active bootstrap mechanisms as defined
2952
// within the current configuration.
2953
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2954
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2955

3✔
2956
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2957

3✔
2958
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2959
        // this can be used by default if we've already partially seeded the
3✔
2960
        // network.
3✔
2961
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2962
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2963
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2964
        )
3✔
2965
        if err != nil {
3✔
2966
                return nil, err
×
2967
        }
×
2968
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2969

3✔
2970
        // If this isn't using simnet or regtest mode, then one of our
3✔
2971
        // additional bootstrapping sources will be the set of running DNS
3✔
2972
        // seeds.
3✔
2973
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2974
                //nolint:ll
×
2975
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2976

×
2977
                // If we have a set of DNS seeds for this chain, then we'll add
×
2978
                // it as an additional bootstrapping source.
×
2979
                if ok {
×
2980
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2981
                                "seeds: %v", dnsSeeds)
×
2982

×
2983
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2984
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2985
                        )
×
2986
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2987
                }
×
2988
        }
2989

2990
        return bootStrappers, nil
3✔
2991
}
2992

2993
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2994
// needs to ignore, which is made of three parts,
2995
//   - the node itself needs to be skipped as it doesn't make sense to connect
2996
//     to itself.
2997
//   - the peers that already have connections with, as in s.peersByPub.
2998
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2999
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
3000
        s.mu.RLock()
3✔
3001
        defer s.mu.RUnlock()
3✔
3002

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

3✔
3005
        // We should ignore ourselves from bootstrapping.
3✔
3006
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3007
        ignore[selfKey] = struct{}{}
3✔
3008

3✔
3009
        // Ignore all connected peers.
3✔
3010
        for _, peer := range s.peersByPub {
3✔
3011
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3012
                ignore[nID] = struct{}{}
×
3013
        }
×
3014

3015
        // Ignore all persistent peers as they have a dedicated reconnecting
3016
        // process.
3017
        for pubKeyStr := range s.persistentPeers {
3✔
3018
                var nID autopilot.NodeID
×
3019
                copy(nID[:], []byte(pubKeyStr))
×
3020
                ignore[nID] = struct{}{}
×
3021
        }
×
3022

3023
        return ignore
3✔
3024
}
3025

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

3✔
3034
        defer s.wg.Done()
3✔
3035

3✔
3036
        // Before we continue, init the ignore peers map.
3✔
3037
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3038

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

3✔
3043
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3044
        // peers.
3✔
3045
        //
3✔
3046
        // We'll use a 15 second backoff, and double the time every time an
3✔
3047
        // epoch fails up to a ceiling.
3✔
3048
        backOff := time.Second * 15
3✔
3049

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

3✔
3055
        // We'll use the number of attempts and errors to determine if we need
3✔
3056
        // to increase the time between discovery epochs.
3✔
3057
        var epochErrors uint32 // To be used atomically.
3✔
3058
        var epochAttempts uint32
3✔
3059

3✔
3060
        for {
6✔
3061
                select {
3✔
3062
                // The ticker has just woken us up, so we'll need to check if
3063
                // we need to attempt to connect our to any more peers.
3064
                case <-sampleTicker.C:
×
3065
                        // Obtain the current number of peers, so we can gauge
×
3066
                        // if we need to sample more peers or not.
×
3067
                        s.mu.RLock()
×
3068
                        numActivePeers := uint32(len(s.peersByPub))
×
3069
                        s.mu.RUnlock()
×
3070

×
3071
                        // If we have enough peers, then we can loop back
×
3072
                        // around to the next round as we're done here.
×
3073
                        if numActivePeers >= numTargetPeers {
×
3074
                                continue
×
3075
                        }
3076

3077
                        // If all of our attempts failed during this last back
3078
                        // off period, then will increase our backoff to 5
3079
                        // minute ceiling to avoid an excessive number of
3080
                        // queries
3081
                        //
3082
                        // TODO(roasbeef): add reverse policy too?
3083

3084
                        if epochAttempts > 0 &&
×
3085
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3086

×
3087
                                sampleTicker.Stop()
×
3088

×
3089
                                backOff *= 2
×
3090
                                if backOff > bootstrapBackOffCeiling {
×
3091
                                        backOff = bootstrapBackOffCeiling
×
3092
                                }
×
3093

3094
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3095
                                        "%v", backOff)
×
3096
                                sampleTicker = time.NewTicker(backOff)
×
3097
                                continue
×
3098
                        }
3099

3100
                        atomic.StoreUint32(&epochErrors, 0)
×
3101
                        epochAttempts = 0
×
3102

×
3103
                        // Since we know need more peers, we'll compute the
×
3104
                        // exact number we need to reach our threshold.
×
3105
                        numNeeded := numTargetPeers - numActivePeers
×
3106

×
3107
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3108
                                "peers", numNeeded)
×
3109

×
3110
                        // With the number of peers we need calculated, we'll
×
3111
                        // query the network bootstrappers to sample a set of
×
3112
                        // random addrs for us.
×
3113
                        //
×
3114
                        // Before we continue, get a copy of the ignore peers
×
3115
                        // map.
×
3116
                        ignoreList = s.createBootstrapIgnorePeers()
×
3117

×
3118
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3119
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3120
                        )
×
3121
                        if err != nil {
×
3122
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3123
                                        "peers: %v", err)
×
3124
                                continue
×
3125
                        }
3126

3127
                        // Finally, we'll launch a new goroutine for each
3128
                        // prospective peer candidates.
3129
                        for _, addr := range peerAddrs {
×
3130
                                epochAttempts++
×
3131

×
3132
                                go func(a *lnwire.NetAddress) {
×
3133
                                        // TODO(roasbeef): can do AS, subnet,
×
3134
                                        // country diversity, etc
×
3135
                                        errChan := make(chan error, 1)
×
3136
                                        s.connectToPeer(
×
3137
                                                a, errChan,
×
3138
                                                s.cfg.ConnectionTimeout,
×
3139
                                        )
×
3140
                                        select {
×
3141
                                        case err := <-errChan:
×
3142
                                                if err == nil {
×
3143
                                                        return
×
3144
                                                }
×
3145

3146
                                                srvrLog.Errorf("Unable to "+
×
3147
                                                        "connect to %v: %v",
×
3148
                                                        a, err)
×
3149
                                                atomic.AddUint32(&epochErrors, 1)
×
3150
                                        case <-s.quit:
×
3151
                                        }
3152
                                }(addr)
3153
                        }
3154
                case <-s.quit:
3✔
3155
                        return
3✔
3156
                }
3157
        }
3158
}
3159

3160
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3161
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3162
// query back off each time we encounter a failure.
3163
const bootstrapBackOffCeiling = time.Minute * 5
3164

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

3✔
3172
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3173
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3174

3✔
3175
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3176
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3177
        var delaySignal <-chan time.Time
3✔
3178
        delayTime := time.Second * 2
3✔
3179

3✔
3180
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3181
        // then the main peer bootstrap logic.
3✔
3182
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3183

3✔
3184
        for attempts := 0; ; attempts++ {
6✔
3185
                // Check if the server has been requested to shut down in order
3✔
3186
                // to prevent blocking.
3✔
3187
                if s.Stopped() {
3✔
3188
                        return
×
3189
                }
×
3190

3191
                // We can exit our aggressive initial peer bootstrapping stage
3192
                // if we've reached out target number of peers.
3193
                s.mu.RLock()
3✔
3194
                numActivePeers := uint32(len(s.peersByPub))
3✔
3195
                s.mu.RUnlock()
3✔
3196

3✔
3197
                if numActivePeers >= numTargetPeers {
6✔
3198
                        return
3✔
3199
                }
3✔
3200

3201
                if attempts > 0 {
3✔
UNCOV
3202
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3203
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3204
                                attempts)
×
UNCOV
3205

×
UNCOV
3206
                        // We've completed at least one iterating and haven't
×
UNCOV
3207
                        // finished, so we'll start to insert a delay period
×
UNCOV
3208
                        // between each attempt.
×
UNCOV
3209
                        delaySignal = time.After(delayTime)
×
UNCOV
3210
                        select {
×
UNCOV
3211
                        case <-delaySignal:
×
UNCOV
3212
                        case <-s.quit:
×
UNCOV
3213
                                return
×
3214
                        }
3215

3216
                        // After our delay, we'll double the time we wait up to
3217
                        // the max back off period.
UNCOV
3218
                        delayTime *= 2
×
UNCOV
3219
                        if delayTime > backOffCeiling {
×
3220
                                delayTime = backOffCeiling
×
3221
                        }
×
3222
                }
3223

3224
                // Otherwise, we'll request for the remaining number of peers
3225
                // in order to reach our target.
3226
                peersNeeded := numTargetPeers - numActivePeers
3✔
3227
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3228
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3229
                )
3✔
3230
                if err != nil {
3✔
UNCOV
3231
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3232
                                "peers: %v", err)
×
UNCOV
3233
                        continue
×
3234
                }
3235

3236
                // Then, we'll attempt to establish a connection to the
3237
                // different peer addresses retrieved by our bootstrappers.
3238
                var wg sync.WaitGroup
3✔
3239
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3240
                        wg.Add(1)
3✔
3241
                        go func(addr *lnwire.NetAddress) {
6✔
3242
                                defer wg.Done()
3✔
3243

3✔
3244
                                errChan := make(chan error, 1)
3✔
3245
                                go s.connectToPeer(
3✔
3246
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3247
                                )
3✔
3248

3✔
3249
                                // We'll only allow this connection attempt to
3✔
3250
                                // take up to 3 seconds. This allows us to move
3✔
3251
                                // quickly by discarding peers that are slowing
3✔
3252
                                // us down.
3✔
3253
                                select {
3✔
3254
                                case err := <-errChan:
3✔
3255
                                        if err == nil {
6✔
3256
                                                return
3✔
3257
                                        }
3✔
3258
                                        srvrLog.Errorf("Unable to connect to "+
×
3259
                                                "%v: %v", addr, err)
×
3260
                                // TODO: tune timeout? 3 seconds might be *too*
3261
                                // aggressive but works well.
3262
                                case <-time.After(3 * time.Second):
×
3263
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3264
                                                "to not establishing a "+
×
3265
                                                "connection within 3 seconds",
×
3266
                                                addr)
×
3267
                                case <-s.quit:
×
3268
                                }
3269
                        }(bootstrapAddr)
3270
                }
3271

3272
                wg.Wait()
3✔
3273
        }
3274
}
3275

3276
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3277
// order to listen for inbound connections over Tor.
3278
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3279
        // Determine the different ports the server is listening on. The onion
×
3280
        // service's virtual port will map to these ports and one will be picked
×
3281
        // at random when the onion service is being accessed.
×
3282
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3283
        for _, listenAddr := range s.listenAddrs {
×
3284
                port := listenAddr.(*net.TCPAddr).Port
×
3285
                listenPorts = append(listenPorts, port)
×
3286
        }
×
3287

3288
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3289
        if err != nil {
×
3290
                return err
×
3291
        }
×
3292

3293
        // Once the port mapping has been set, we can go ahead and automatically
3294
        // create our onion service. The service's private key will be saved to
3295
        // disk in order to regain access to this service when restarting `lnd`.
3296
        onionCfg := tor.AddOnionConfig{
×
3297
                VirtualPort: defaultPeerPort,
×
3298
                TargetPorts: listenPorts,
×
3299
                Store: tor.NewOnionFile(
×
3300
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3301
                        encrypter,
×
3302
                ),
×
3303
        }
×
3304

×
3305
        switch {
×
3306
        case s.cfg.Tor.V2:
×
3307
                onionCfg.Type = tor.V2
×
3308
        case s.cfg.Tor.V3:
×
3309
                onionCfg.Type = tor.V3
×
3310
        }
3311

3312
        addr, err := s.torController.AddOnion(onionCfg)
×
3313
        if err != nil {
×
3314
                return err
×
3315
        }
×
3316

3317
        // Now that the onion service has been created, we'll add the onion
3318
        // address it can be reached at to our list of advertised addresses.
3319
        newNodeAnn, err := s.genNodeAnnouncement(
×
3320
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3321
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3322
                },
×
3323
        )
3324
        if err != nil {
×
3325
                return fmt.Errorf("unable to generate new node "+
×
3326
                        "announcement: %v", err)
×
3327
        }
×
3328

3329
        // Finally, we'll update the on-disk version of our announcement so it
3330
        // will eventually propagate to nodes in the network.
3331
        selfNode := &models.Node{
×
3332
                HaveNodeAnnouncement: true,
×
3333
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3334
                Addresses:            newNodeAnn.Addresses,
×
3335
                Alias:                newNodeAnn.Alias.String(),
×
3336
                Features: lnwire.NewFeatureVector(
×
3337
                        newNodeAnn.Features, lnwire.Features,
×
3338
                ),
×
3339
                Color:        newNodeAnn.RGBColor,
×
3340
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3341
        }
×
3342
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3343
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3344
                return fmt.Errorf("can't set self node: %w", err)
×
3345
        }
×
3346

3347
        return nil
×
3348
}
3349

3350
// findChannel finds a channel given a public key and ChannelID. It is an
3351
// optimization that is quicker than seeking for a channel given only the
3352
// ChannelID.
3353
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3354
        *channeldb.OpenChannel, error) {
3✔
3355

3✔
3356
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3357
        if err != nil {
3✔
3358
                return nil, err
×
3359
        }
×
3360

3361
        for _, channel := range nodeChans {
6✔
3362
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3363
                        return channel, nil
3✔
3364
                }
3✔
3365
        }
3366

3367
        return nil, fmt.Errorf("unable to find channel")
3✔
3368
}
3369

3370
// getNodeAnnouncement fetches the current, fully signed node announcement.
3371
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3372
        s.mu.Lock()
3✔
3373
        defer s.mu.Unlock()
3✔
3374

3✔
3375
        return *s.currentNodeAnn
3✔
3376
}
3✔
3377

3378
// genNodeAnnouncement generates and returns the current fully signed node
3379
// announcement. The time stamp of the announcement will be updated in order
3380
// to ensure it propagates through the network.
3381
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3382
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3383

3✔
3384
        s.mu.Lock()
3✔
3385
        defer s.mu.Unlock()
3✔
3386

3✔
3387
        // Create a shallow copy of the current node announcement to work on.
3✔
3388
        // This ensures the original announcement remains unchanged
3✔
3389
        // until the new announcement is fully signed and valid.
3✔
3390
        newNodeAnn := *s.currentNodeAnn
3✔
3391

3✔
3392
        // First, try to update our feature manager with the updated set of
3✔
3393
        // features.
3✔
3394
        if features != nil {
6✔
3395
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3396
                        feature.SetNodeAnn: features,
3✔
3397
                }
3✔
3398
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3399
                if err != nil {
6✔
3400
                        return lnwire.NodeAnnouncement{}, err
3✔
3401
                }
3✔
3402

3403
                // If we could successfully update our feature manager, add
3404
                // an update modifier to include these new features to our
3405
                // set.
3406
                modifiers = append(
3✔
3407
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3408
                )
3✔
3409
        }
3410

3411
        // Always update the timestamp when refreshing to ensure the update
3412
        // propagates.
3413
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3414

3✔
3415
        // Apply the requested changes to the node announcement.
3✔
3416
        for _, modifier := range modifiers {
6✔
3417
                modifier(&newNodeAnn)
3✔
3418
        }
3✔
3419

3420
        // Sign a new update after applying all of the passed modifiers.
3421
        err := netann.SignNodeAnnouncement(
3✔
3422
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3423
        )
3✔
3424
        if err != nil {
3✔
3425
                return lnwire.NodeAnnouncement{}, err
×
3426
        }
×
3427

3428
        // If signing succeeds, update the current announcement.
3429
        *s.currentNodeAnn = newNodeAnn
3✔
3430

3✔
3431
        return *s.currentNodeAnn, nil
3✔
3432
}
3433

3434
// updateAndBroadcastSelfNode generates a new node announcement
3435
// applying the giving modifiers and updating the time stamp
3436
// to ensure it propagates through the network. Then it broadcasts
3437
// it to the network.
3438
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3439
        features *lnwire.RawFeatureVector,
3440
        modifiers ...netann.NodeAnnModifier) error {
3✔
3441

3✔
3442
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3443
        if err != nil {
6✔
3444
                return fmt.Errorf("unable to generate new node "+
3✔
3445
                        "announcement: %v", err)
3✔
3446
        }
3✔
3447

3448
        // Update the on-disk version of our announcement.
3449
        // Load and modify self node istead of creating anew instance so we
3450
        // don't risk overwriting any existing values.
3451
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3452
        if err != nil {
3✔
3453
                return fmt.Errorf("unable to get current source node: %w", err)
×
3454
        }
×
3455

3456
        selfNode.HaveNodeAnnouncement = true
3✔
3457
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3458
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3459
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3460
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3461
        selfNode.Color = newNodeAnn.RGBColor
3✔
3462
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3463

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

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

3470
        // Finally, propagate it to the nodes in the network.
3471
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3472
        if err != nil {
3✔
3473
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3474
                        "announcement to peers: %v", err)
×
3475
                return err
×
3476
        }
×
3477

3478
        return nil
3✔
3479
}
3480

3481
type nodeAddresses struct {
3482
        pubKey    *btcec.PublicKey
3483
        addresses []net.Addr
3484
}
3485

3486
// establishPersistentConnections attempts to establish persistent connections
3487
// to all our direct channel collaborators. In order to promote liveness of our
3488
// active channels, we instruct the connection manager to attempt to establish
3489
// and maintain persistent connections to all our direct channel counterparties.
3490
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3491
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3492
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3493
        // since other PubKey forms can't be compared.
3✔
3494
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3495

3✔
3496
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3497
        // attempt to connect to based on our set of previous connections. Set
3✔
3498
        // the reconnection port to the default peer port.
3✔
3499
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3500
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3501
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3502
        }
×
3503

3504
        for _, node := range linkNodes {
6✔
3505
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3506
                nodeAddrs := &nodeAddresses{
3✔
3507
                        pubKey:    node.IdentityPub,
3✔
3508
                        addresses: node.Addresses,
3✔
3509
                }
3✔
3510
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3511
        }
3✔
3512

3513
        // After checking our previous connections for addresses to connect to,
3514
        // iterate through the nodes in our channel graph to find addresses
3515
        // that have been added via NodeAnnouncement messages.
3516
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3517
        // each of the nodes.
3518
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3519
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3520
                havePolicy bool, channelPeer *models.Node) error {
6✔
3521

3✔
3522
                // If the remote party has announced the channel to us, but we
3✔
3523
                // haven't yet, then we won't have a policy. However, we don't
3✔
3524
                // need this to connect to the peer, so we'll log it and move on.
3✔
3525
                if !havePolicy {
3✔
3526
                        srvrLog.Warnf("No channel policy found for "+
×
3527
                                "ChannelPoint(%v): ", chanPoint)
×
3528
                }
×
3529

3530
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3531

3✔
3532
                // Add all unique addresses from channel
3✔
3533
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3534
                // connect to for this peer.
3✔
3535
                addrSet := make(map[string]net.Addr)
3✔
3536
                for _, addr := range channelPeer.Addresses {
6✔
3537
                        switch addr.(type) {
3✔
3538
                        case *net.TCPAddr:
3✔
3539
                                addrSet[addr.String()] = addr
3✔
3540

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

3550
                // If this peer is also recorded as a link node, we'll add any
3551
                // additional addresses that have not already been selected.
3552
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3553
                if ok {
6✔
3554
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3555
                                switch lnAddress.(type) {
3✔
3556
                                case *net.TCPAddr:
3✔
3557
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3558

3559
                                // We'll only attempt to connect to Tor
3560
                                // addresses if Tor outbound support is enabled.
3561
                                case *tor.OnionAddr:
×
3562
                                        if s.cfg.Tor.Active {
×
3563
                                                //nolint:ll
×
3564
                                                addrSet[lnAddress.String()] = lnAddress
×
3565
                                        }
×
3566
                                }
3567
                        }
3568
                }
3569

3570
                // Construct a slice of the deduped addresses.
3571
                var addrs []net.Addr
3✔
3572
                for _, addr := range addrSet {
6✔
3573
                        addrs = append(addrs, addr)
3✔
3574
                }
3✔
3575

3576
                n := &nodeAddresses{
3✔
3577
                        addresses: addrs,
3✔
3578
                }
3✔
3579
                n.pubKey, err = channelPeer.PubKey()
3✔
3580
                if err != nil {
3✔
3581
                        return err
×
3582
                }
×
3583

3584
                graphAddrs[pubStr] = n
3✔
3585
                return nil
3✔
3586
        }
3587
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3588
                ctx, forEachSrcNodeChan, func() {
6✔
3589
                        clear(graphAddrs)
3✔
3590
                },
3✔
3591
        )
3592
        if err != nil {
3✔
3593
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3594
                        "%v", err)
×
3595

×
3596
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3597
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3598

×
3599
                        return err
×
3600
                }
×
3601
        }
3602

3603
        // Combine the addresses from the link nodes and the channel graph.
3604
        for pubStr, nodeAddr := range graphAddrs {
6✔
3605
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3606
        }
3✔
3607

3608
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3609
                len(nodeAddrsMap))
3✔
3610

3✔
3611
        // Acquire and hold server lock until all persistent connection requests
3✔
3612
        // have been recorded and sent to the connection manager.
3✔
3613
        s.mu.Lock()
3✔
3614
        defer s.mu.Unlock()
3✔
3615

3✔
3616
        // Iterate through the combined list of addresses from prior links and
3✔
3617
        // node announcements and attempt to reconnect to each node.
3✔
3618
        var numOutboundConns int
3✔
3619
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3620
                // Add this peer to the set of peers we should maintain a
3✔
3621
                // persistent connection with. We set the value to false to
3✔
3622
                // indicate that we should not continue to reconnect if the
3✔
3623
                // number of channels returns to zero, since this peer has not
3✔
3624
                // been requested as perm by the user.
3✔
3625
                s.persistentPeers[pubStr] = false
3✔
3626
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3627
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3628
                }
3✔
3629

3630
                for _, address := range nodeAddr.addresses {
6✔
3631
                        // Create a wrapper address which couples the IP and
3✔
3632
                        // the pubkey so the brontide authenticated connection
3✔
3633
                        // can be established.
3✔
3634
                        lnAddr := &lnwire.NetAddress{
3✔
3635
                                IdentityKey: nodeAddr.pubKey,
3✔
3636
                                Address:     address,
3✔
3637
                        }
3✔
3638

3✔
3639
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3640
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3641
                }
3✔
3642

3643
                // We'll connect to the first 10 peers immediately, then
3644
                // randomly stagger any remaining connections if the
3645
                // stagger initial reconnect flag is set. This ensures
3646
                // that mobile nodes or nodes with a small number of
3647
                // channels obtain connectivity quickly, but larger
3648
                // nodes are able to disperse the costs of connecting to
3649
                // all peers at once.
3650
                if numOutboundConns < numInstantInitReconnect ||
3✔
3651
                        !s.cfg.StaggerInitialReconnect {
6✔
3652

3✔
3653
                        go s.connectToPersistentPeer(pubStr)
3✔
3654
                } else {
3✔
3655
                        go s.delayInitialReconnect(pubStr)
×
3656
                }
×
3657

3658
                numOutboundConns++
3✔
3659
        }
3660

3661
        return nil
3✔
3662
}
3663

3664
// delayInitialReconnect will attempt a reconnection to the given peer after
3665
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3666
//
3667
// NOTE: This method MUST be run as a goroutine.
3668
func (s *server) delayInitialReconnect(pubStr string) {
×
3669
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3670
        select {
×
3671
        case <-time.After(delay):
×
3672
                s.connectToPersistentPeer(pubStr)
×
3673
        case <-s.quit:
×
3674
        }
3675
}
3676

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

3✔
3683
        s.mu.Lock()
3✔
3684
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3685
                delete(s.persistentPeers, pubKeyStr)
3✔
3686
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3687
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3688
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3689
                s.mu.Unlock()
3✔
3690

3✔
3691
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3692
                        "peer has no open channels", compressedPubKey)
3✔
3693

3✔
3694
                return
3✔
3695
        }
3✔
3696
        s.mu.Unlock()
3✔
3697
}
3698

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

3716
// BroadcastMessage sends a request to the server to broadcast a set of
3717
// messages to all peers other than the one specified by the `skips` parameter.
3718
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3719
// the target peers.
3720
//
3721
// NOTE: This function is safe for concurrent access.
3722
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3723
        msgs ...lnwire.Message) error {
3✔
3724

3✔
3725
        // Filter out peers found in the skips map. We synchronize access to
3✔
3726
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3727
        // exact set of peers present at the time of invocation.
3✔
3728
        s.mu.RLock()
3✔
3729
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3730
        for pubStr, sPeer := range s.peersByPub {
6✔
3731
                if skips != nil {
6✔
3732
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3733
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3734
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3735
                                continue
3✔
3736
                        }
3737
                }
3738

3739
                peers = append(peers, sPeer)
3✔
3740
        }
3741
        s.mu.RUnlock()
3✔
3742

3✔
3743
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3744
        // all messages to each of peers.
3✔
3745
        var wg sync.WaitGroup
3✔
3746
        for _, sPeer := range peers {
6✔
3747
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3748
                        sPeer.PubKey())
3✔
3749

3✔
3750
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3751
                wg.Add(1)
3✔
3752
                s.wg.Add(1)
3✔
3753
                go func(p lnpeer.Peer) {
6✔
3754
                        defer s.wg.Done()
3✔
3755
                        defer wg.Done()
3✔
3756

3✔
3757
                        p.SendMessageLazy(false, msgs...)
3✔
3758
                }(sPeer)
3✔
3759
        }
3760

3761
        // Wait for all messages to have been dispatched before returning to
3762
        // caller.
3763
        wg.Wait()
3✔
3764

3✔
3765
        return nil
3✔
3766
}
3767

3768
// NotifyWhenOnline can be called by other subsystems to get notified when a
3769
// particular peer comes online. The peer itself is sent across the peerChan.
3770
//
3771
// NOTE: This function is safe for concurrent access.
3772
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3773
        peerChan chan<- lnpeer.Peer) {
3✔
3774

3✔
3775
        s.mu.Lock()
3✔
3776

3✔
3777
        // Compute the target peer's identifier.
3✔
3778
        pubStr := string(peerKey[:])
3✔
3779

3✔
3780
        // Check if peer is connected.
3✔
3781
        peer, ok := s.peersByPub[pubStr]
3✔
3782
        if ok {
6✔
3783
                // Unlock here so that the mutex isn't held while we are
3✔
3784
                // waiting for the peer to become active.
3✔
3785
                s.mu.Unlock()
3✔
3786

3✔
3787
                // Wait until the peer signals that it is actually active
3✔
3788
                // rather than only in the server's maps.
3✔
3789
                select {
3✔
3790
                case <-peer.ActiveSignal():
3✔
UNCOV
3791
                case <-peer.QuitSignal():
×
UNCOV
3792
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3793
                        // and return.
×
UNCOV
3794
                        s.mu.Lock()
×
UNCOV
3795
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3796
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3797
                        )
×
UNCOV
3798
                        s.mu.Unlock()
×
UNCOV
3799
                        return
×
3800
                }
3801

3802
                // Connected, can return early.
3803
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3804

3✔
3805
                select {
3✔
3806
                case peerChan <- peer:
3✔
3807
                case <-s.quit:
1✔
3808
                }
3809

3810
                return
3✔
3811
        }
3812

3813
        // Not connected, store this listener such that it can be notified when
3814
        // the peer comes online.
3815
        s.peerConnectedListeners[pubStr] = append(
3✔
3816
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3817
        )
3✔
3818
        s.mu.Unlock()
3✔
3819
}
3820

3821
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3822
// the given public key has been disconnected. The notification is signaled by
3823
// closing the channel returned.
3824
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3825
        s.mu.Lock()
3✔
3826
        defer s.mu.Unlock()
3✔
3827

3✔
3828
        c := make(chan struct{})
3✔
3829

3✔
3830
        // If the peer is already offline, we can immediately trigger the
3✔
3831
        // notification.
3✔
3832
        peerPubKeyStr := string(peerPubKey[:])
3✔
3833
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3834
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3835
                close(c)
×
3836
                return c
×
3837
        }
×
3838

3839
        // Otherwise, the peer is online, so we'll keep track of the channel to
3840
        // trigger the notification once the server detects the peer
3841
        // disconnects.
3842
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3843
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3844
        )
3✔
3845

3✔
3846
        return c
3✔
3847
}
3848

3849
// FindPeer will return the peer that corresponds to the passed in public key.
3850
// This function is used by the funding manager, allowing it to update the
3851
// daemon's local representation of the remote peer.
3852
//
3853
// NOTE: This function is safe for concurrent access.
3854
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3855
        s.mu.RLock()
3✔
3856
        defer s.mu.RUnlock()
3✔
3857

3✔
3858
        pubStr := string(peerKey.SerializeCompressed())
3✔
3859

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

3863
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3864
// which should be a string representation of the peer's serialized, compressed
3865
// public key.
3866
//
3867
// NOTE: This function is safe for concurrent access.
3868
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3869
        s.mu.RLock()
3✔
3870
        defer s.mu.RUnlock()
3✔
3871

3✔
3872
        return s.findPeerByPubStr(pubStr)
3✔
3873
}
3✔
3874

3875
// findPeerByPubStr is an internal method that retrieves the specified peer from
3876
// the server's internal state using.
3877
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3878
        peer, ok := s.peersByPub[pubStr]
3✔
3879
        if !ok {
6✔
3880
                return nil, ErrPeerNotConnected
3✔
3881
        }
3✔
3882

3883
        return peer, nil
3✔
3884
}
3885

3886
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3887
// exponential backoff. If no previous backoff was known, the default is
3888
// returned.
3889
func (s *server) nextPeerBackoff(pubStr string,
3890
        startTime time.Time) time.Duration {
3✔
3891

3✔
3892
        // Now, determine the appropriate backoff to use for the retry.
3✔
3893
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3894
        if !ok {
6✔
3895
                // If an existing backoff was unknown, use the default.
3✔
3896
                return s.cfg.MinBackoff
3✔
3897
        }
3✔
3898

3899
        // If the peer failed to start properly, we'll just use the previous
3900
        // backoff to compute the subsequent randomized exponential backoff
3901
        // duration. This will roughly double on average.
3902
        if startTime.IsZero() {
3✔
3903
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3904
        }
×
3905

3906
        // The peer succeeded in starting. If the connection didn't last long
3907
        // enough to be considered stable, we'll continue to back off retries
3908
        // with this peer.
3909
        connDuration := time.Since(startTime)
3✔
3910
        if connDuration < defaultStableConnDuration {
6✔
3911
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3912
        }
3✔
3913

3914
        // The peer succeed in starting and this was stable peer, so we'll
3915
        // reduce the timeout duration by the length of the connection after
3916
        // applying randomized exponential backoff. We'll only apply this in the
3917
        // case that:
3918
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3919
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3920
        if relaxedBackoff > s.cfg.MinBackoff {
×
3921
                return relaxedBackoff
×
3922
        }
×
3923

3924
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3925
        // the stable connection lasted much longer than our previous backoff.
3926
        // To reward such good behavior, we'll reconnect after the default
3927
        // timeout.
3928
        return s.cfg.MinBackoff
×
3929
}
3930

3931
// shouldDropLocalConnection determines if our local connection to a remote peer
3932
// should be dropped in the case of concurrent connection establishment. In
3933
// order to deterministically decide which connection should be dropped, we'll
3934
// utilize the ordering of the local and remote public key. If we didn't use
3935
// such a tie breaker, then we risk _both_ connections erroneously being
3936
// dropped.
3937
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3938
        localPubBytes := local.SerializeCompressed()
×
3939
        remotePubPbytes := remote.SerializeCompressed()
×
3940

×
3941
        // The connection that comes from the node with a "smaller" pubkey
×
3942
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3943
        // should drop our established connection.
×
3944
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3945
}
×
3946

3947
// InboundPeerConnected initializes a new peer in response to a new inbound
3948
// connection.
3949
//
3950
// NOTE: This function is safe for concurrent access.
3951
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3952
        // Exit early if we have already been instructed to shutdown, this
3✔
3953
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3954
        if s.Stopped() {
3✔
3955
                return
×
3956
        }
×
3957

3958
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3959
        pubSer := nodePub.SerializeCompressed()
3✔
3960
        pubStr := string(pubSer)
3✔
3961

3✔
3962
        var pubBytes [33]byte
3✔
3963
        copy(pubBytes[:], pubSer)
3✔
3964

3✔
3965
        s.mu.Lock()
3✔
3966
        defer s.mu.Unlock()
3✔
3967

3✔
3968
        // If we already have an outbound connection to this peer, then ignore
3✔
3969
        // this new connection.
3✔
3970
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3971
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3972
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3973
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3974

3✔
3975
                conn.Close()
3✔
3976
                return
3✔
3977
        }
3✔
3978

3979
        // If we already have a valid connection that is scheduled to take
3980
        // precedence once the prior peer has finished disconnecting, we'll
3981
        // ignore this connection.
3982
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3983
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3984
                        "scheduled", conn.RemoteAddr(), p)
×
3985
                conn.Close()
×
3986
                return
×
3987
        }
×
3988

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

3✔
3991
        // Check to see if we already have a connection with this peer. If so,
3✔
3992
        // we may need to drop our existing connection. This prevents us from
3✔
3993
        // having duplicate connections to the same peer. We forgo adding a
3✔
3994
        // default case as we expect these to be the only error values returned
3✔
3995
        // from findPeerByPubStr.
3✔
3996
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3997
        switch err {
3✔
3998
        case ErrPeerNotConnected:
3✔
3999
                // We were unable to locate an existing connection with the
3✔
4000
                // target peer, proceed to connect.
3✔
4001
                s.cancelConnReqs(pubStr, nil)
3✔
4002
                s.peerConnected(conn, nil, true)
3✔
4003

4004
        case nil:
3✔
4005
                ctx := btclog.WithCtx(
3✔
4006
                        context.TODO(),
3✔
4007
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4008
                )
3✔
4009

3✔
4010
                // We already have a connection with the incoming peer. If the
3✔
4011
                // connection we've already established should be kept and is
3✔
4012
                // not of the same type of the new connection (inbound), then
3✔
4013
                // we'll close out the new connection s.t there's only a single
3✔
4014
                // connection between us.
3✔
4015
                localPub := s.identityECDH.PubKey()
3✔
4016
                if !connectedPeer.Inbound() &&
3✔
4017
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4018

×
4019
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4020
                                "peer, but already have outbound "+
×
4021
                                "connection, dropping conn",
×
4022
                                fmt.Errorf("already have outbound conn"))
×
4023
                        conn.Close()
×
4024
                        return
×
4025
                }
×
4026

4027
                // Otherwise, if we should drop the connection, then we'll
4028
                // disconnect our already connected peer.
4029
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4030

3✔
4031
                s.cancelConnReqs(pubStr, nil)
3✔
4032

3✔
4033
                // Remove the current peer from the server's internal state and
3✔
4034
                // signal that the peer termination watcher does not need to
3✔
4035
                // execute for this peer.
3✔
4036
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4037
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4038
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4039
                        s.peerConnected(conn, nil, true)
3✔
4040
                }
3✔
4041
        }
4042
}
4043

4044
// OutboundPeerConnected initializes a new peer in response to a new outbound
4045
// connection.
4046
// NOTE: This function is safe for concurrent access.
4047
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4048
        // Exit early if we have already been instructed to shutdown, this
3✔
4049
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4050
        if s.Stopped() {
3✔
4051
                return
×
4052
        }
×
4053

4054
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4055
        pubSer := nodePub.SerializeCompressed()
3✔
4056
        pubStr := string(pubSer)
3✔
4057

3✔
4058
        var pubBytes [33]byte
3✔
4059
        copy(pubBytes[:], pubSer)
3✔
4060

3✔
4061
        s.mu.Lock()
3✔
4062
        defer s.mu.Unlock()
3✔
4063

3✔
4064
        // If we already have an inbound connection to this peer, then ignore
3✔
4065
        // this new connection.
3✔
4066
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4067
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4068
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4069
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4070

3✔
4071
                if connReq != nil {
6✔
4072
                        s.connMgr.Remove(connReq.ID())
3✔
4073
                }
3✔
4074
                conn.Close()
3✔
4075
                return
3✔
4076
        }
4077
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4078
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4079
                s.connMgr.Remove(connReq.ID())
×
4080
                conn.Close()
×
4081
                return
×
4082
        }
×
4083

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

×
4090
                if connReq != nil {
×
4091
                        s.connMgr.Remove(connReq.ID())
×
4092
                }
×
4093

4094
                conn.Close()
×
4095
                return
×
4096
        }
4097

4098
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4099
                conn.RemoteAddr())
3✔
4100

3✔
4101
        if connReq != nil {
6✔
4102
                // A successful connection was returned by the connmgr.
3✔
4103
                // Immediately cancel all pending requests, excluding the
3✔
4104
                // outbound connection we just established.
3✔
4105
                ignore := connReq.ID()
3✔
4106
                s.cancelConnReqs(pubStr, &ignore)
3✔
4107
        } else {
6✔
4108
                // This was a successful connection made by some other
3✔
4109
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4110
                s.cancelConnReqs(pubStr, nil)
3✔
4111
        }
3✔
4112

4113
        // If we already have a connection with this peer, decide whether or not
4114
        // we need to drop the stale connection. We forgo adding a default case
4115
        // as we expect these to be the only error values returned from
4116
        // findPeerByPubStr.
4117
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4118
        switch err {
3✔
4119
        case ErrPeerNotConnected:
3✔
4120
                // We were unable to locate an existing connection with the
3✔
4121
                // target peer, proceed to connect.
3✔
4122
                s.peerConnected(conn, connReq, false)
3✔
4123

4124
        case nil:
3✔
4125
                ctx := btclog.WithCtx(
3✔
4126
                        context.TODO(),
3✔
4127
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4128
                )
3✔
4129

3✔
4130
                // We already have a connection with the incoming peer. If the
3✔
4131
                // connection we've already established should be kept and is
3✔
4132
                // not of the same type of the new connection (outbound), then
3✔
4133
                // we'll close out the new connection s.t there's only a single
3✔
4134
                // connection between us.
3✔
4135
                localPub := s.identityECDH.PubKey()
3✔
4136
                if connectedPeer.Inbound() &&
3✔
4137
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4138

×
4139
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4140
                                "to peer, but already have inbound "+
×
4141
                                "connection, dropping conn",
×
4142
                                fmt.Errorf("already have inbound conn"))
×
4143
                        if connReq != nil {
×
4144
                                s.connMgr.Remove(connReq.ID())
×
4145
                        }
×
4146
                        conn.Close()
×
4147
                        return
×
4148
                }
4149

4150
                // Otherwise, _their_ connection should be dropped. So we'll
4151
                // disconnect the peer and send the now obsolete peer to the
4152
                // server for garbage collection.
4153
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4154

3✔
4155
                // Remove the current peer from the server's internal state and
3✔
4156
                // signal that the peer termination watcher does not need to
3✔
4157
                // execute for this peer.
3✔
4158
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4159
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4160
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4161
                        s.peerConnected(conn, connReq, false)
3✔
4162
                }
3✔
4163
        }
4164
}
4165

4166
// UnassignedConnID is the default connection ID that a request can have before
4167
// it actually is submitted to the connmgr.
4168
// TODO(conner): move into connmgr package, or better, add connmgr method for
4169
// generating atomic IDs
4170
const UnassignedConnID uint64 = 0
4171

4172
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4173
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4174
// Afterwards, each connection request removed from the connmgr. The caller can
4175
// optionally specify a connection ID to ignore, which prevents us from
4176
// canceling a successful request. All persistent connreqs for the provided
4177
// pubkey are discarded after the operationjw.
4178
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4179
        // First, cancel any lingering persistent retry attempts, which will
3✔
4180
        // prevent retries for any with backoffs that are still maturing.
3✔
4181
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4182
                close(cancelChan)
3✔
4183
                delete(s.persistentRetryCancels, pubStr)
3✔
4184
        }
3✔
4185

4186
        // Next, check to see if we have any outstanding persistent connection
4187
        // requests to this peer. If so, then we'll remove all of these
4188
        // connection requests, and also delete the entry from the map.
4189
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4190
        if !ok {
6✔
4191
                return
3✔
4192
        }
3✔
4193

4194
        for _, connReq := range connReqs {
6✔
4195
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4196

3✔
4197
                // Atomically capture the current request identifier.
3✔
4198
                connID := connReq.ID()
3✔
4199

3✔
4200
                // Skip any zero IDs, this indicates the request has not
3✔
4201
                // yet been schedule.
3✔
4202
                if connID == UnassignedConnID {
3✔
4203
                        continue
×
4204
                }
4205

4206
                // Skip a particular connection ID if instructed.
4207
                if skip != nil && connID == *skip {
6✔
4208
                        continue
3✔
4209
                }
4210

4211
                s.connMgr.Remove(connID)
3✔
4212
        }
4213

4214
        delete(s.persistentConnReqs, pubStr)
3✔
4215
}
4216

4217
// handleCustomMessage dispatches an incoming custom peers message to
4218
// subscribers.
4219
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4220
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4221
                peer, msg.Type)
3✔
4222

3✔
4223
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4224
                Peer: peer,
3✔
4225
                Msg:  msg,
3✔
4226
        })
3✔
4227
}
3✔
4228

4229
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4230
// messages.
4231
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4232
        return s.customMessageServer.Subscribe()
3✔
4233
}
3✔
4234

4235
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4236
// the channelNotifier's NotifyOpenChannelEvent.
4237
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4238
        remotePub *btcec.PublicKey) {
3✔
4239

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

4246
        // Notify subscribers about this open channel event.
4247
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4248
}
4249

4250
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4251
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4252
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4253
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4254

3✔
4255
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4256
        // peer.
3✔
4257
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4258
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4259
                        "channel[%v] pending open",
×
4260
                        remotePub.SerializeCompressed(), op)
×
4261
        }
×
4262

4263
        // Notify subscribers about this event.
4264
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4265
}
4266

4267
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4268
// calls the channelNotifier's NotifyFundingTimeout.
4269
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4270
        remotePub *btcec.PublicKey) {
3✔
4271

3✔
4272
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4273
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4274
        if err != nil {
3✔
4275
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4276
                        "channel[%v] pending close",
×
4277
                        remotePub.SerializeCompressed(), op)
×
4278
        }
×
4279

4280
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4281
                // If we encounter an error while attempting to disconnect the
×
4282
                // peer, log the error.
×
4283
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4284
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4285
                }
×
4286
        }
4287

4288
        // Notify subscribers about this event.
4289
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4290
}
4291

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

3✔
4299
        brontideConn := conn.(*brontide.Conn)
3✔
4300
        addr := conn.RemoteAddr()
3✔
4301
        pubKey := brontideConn.RemotePub()
3✔
4302

3✔
4303
        // Only restrict access for inbound connections, which means if the
3✔
4304
        // remote node's public key is banned or the restricted slots are used
3✔
4305
        // up, we will drop the connection.
3✔
4306
        //
3✔
4307
        // TODO(yy): Consider perform this check in
3✔
4308
        // `peerAccessMan.addPeerAccess`.
3✔
4309
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4310
        if inbound && err != nil {
3✔
4311
                pubSer := pubKey.SerializeCompressed()
×
4312

×
4313
                // Clean up the persistent peer maps if we're dropping this
×
4314
                // connection.
×
4315
                s.bannedPersistentPeerConnection(string(pubSer))
×
4316

×
4317
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4318
                        "of restricted-access connection slots: %v.", pubSer,
×
4319
                        err)
×
4320

×
4321
                conn.Close()
×
4322

×
4323
                return
×
4324
        }
×
4325

4326
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4327
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4328

3✔
4329
        peerAddr := &lnwire.NetAddress{
3✔
4330
                IdentityKey: pubKey,
3✔
4331
                Address:     addr,
3✔
4332
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4333
        }
3✔
4334

3✔
4335
        // With the brontide connection established, we'll now craft the feature
3✔
4336
        // vectors to advertise to the remote node.
3✔
4337
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4338
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4339

3✔
4340
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4341
        // found, create a fresh buffer.
3✔
4342
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4343
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4344
        if !ok {
6✔
4345
                var err error
3✔
4346
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4347
                if err != nil {
3✔
4348
                        srvrLog.Errorf("unable to create peer %v", err)
×
4349
                        return
×
4350
                }
×
4351
        }
4352

4353
        // If we directly set the peer.Config TowerClient member to the
4354
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4355
        // the peer.Config's TowerClient member will not evaluate to nil even
4356
        // though the underlying value is nil. To avoid this gotcha which can
4357
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4358
        // TowerClient if needed.
4359
        var towerClient wtclient.ClientManager
3✔
4360
        if s.towerClientMgr != nil {
6✔
4361
                towerClient = s.towerClientMgr
3✔
4362
        }
3✔
4363

4364
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4365
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4366

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

3✔
4410
                        return s.genNodeAnnouncement(nil)
3✔
4411
                },
3✔
4412

4413
                PongBuf: s.pongBuf,
4414

4415
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4416

4417
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4418

4419
                FundingManager: s.fundingMgr,
4420

4421
                Hodl:                    s.cfg.Hodl,
4422
                UnsafeReplay:            s.cfg.UnsafeReplay,
4423
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4424
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4425
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4426
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4427
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4428
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4429
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4430
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4431
                HandleCustomMessage:    s.handleCustomMessage,
4432
                GetAliases:             s.aliasMgr.GetAliases,
4433
                RequestAlias:           s.aliasMgr.RequestAlias,
4434
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4435
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4436
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4437
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4438
                MaxFeeExposure:         thresholdMSats,
4439
                Quit:                   s.quit,
4440
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4441
                AuxSigner:              s.implCfg.AuxSigner,
4442
                MsgRouter:              s.implCfg.MsgRouter,
4443
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4444
                AuxResolver:            s.implCfg.AuxContractResolver,
4445
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4446
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4447
                ShouldFwdExpEndorsement: func() bool {
3✔
4448
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4449
                                return false
3✔
4450
                        }
3✔
4451

4452
                        return clock.NewDefaultClock().Now().Before(
3✔
4453
                                EndorsementExperimentEnd,
3✔
4454
                        )
3✔
4455
                },
4456
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4457
        }
4458

4459
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4460
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4461

3✔
4462
        p := peer.NewBrontide(pCfg)
3✔
4463

3✔
4464
        // Update the access manager with the access permission for this peer.
3✔
4465
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4466

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

3✔
4470
        s.addPeer(p)
3✔
4471

3✔
4472
        // Once we have successfully added the peer to the server, we can
3✔
4473
        // delete the previous error buffer from the server's map of error
3✔
4474
        // buffers.
3✔
4475
        delete(s.peerErrors, pkStr)
3✔
4476

3✔
4477
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4478
        // includes sending and receiving Init messages, which would be a DOS
3✔
4479
        // vector if we held the server's mutex throughout the procedure.
3✔
4480
        s.wg.Add(1)
3✔
4481
        go s.peerInitializer(p)
3✔
4482
}
4483

4484
// addPeer adds the passed peer to the server's global state of all active
4485
// peers.
4486
func (s *server) addPeer(p *peer.Brontide) {
3✔
4487
        if p == nil {
3✔
4488
                return
×
4489
        }
×
4490

4491
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4492

3✔
4493
        // Ignore new peers if we're shutting down.
3✔
4494
        if s.Stopped() {
3✔
4495
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4496
                        pubBytes)
×
4497
                p.Disconnect(ErrServerShuttingDown)
×
4498

×
4499
                return
×
4500
        }
×
4501

4502
        // Track the new peer in our indexes so we can quickly look it up either
4503
        // according to its public key, or its peer ID.
4504
        // TODO(roasbeef): pipe all requests through to the
4505
        // queryHandler/peerManager
4506

4507
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4508
        // be human-readable.
4509
        pubStr := string(pubBytes)
3✔
4510

3✔
4511
        s.peersByPub[pubStr] = p
3✔
4512

3✔
4513
        if p.Inbound() {
6✔
4514
                s.inboundPeers[pubStr] = p
3✔
4515
        } else {
6✔
4516
                s.outboundPeers[pubStr] = p
3✔
4517
        }
3✔
4518

4519
        // Inform the peer notifier of a peer online event so that it can be reported
4520
        // to clients listening for peer events.
4521
        var pubKey [33]byte
3✔
4522
        copy(pubKey[:], pubBytes)
3✔
4523
}
4524

4525
// peerInitializer asynchronously starts a newly connected peer after it has
4526
// been added to the server's peer map. This method sets up a
4527
// peerTerminationWatcher for the given peer, and ensures that it executes even
4528
// if the peer failed to start. In the event of a successful connection, this
4529
// method reads the negotiated, local feature-bits and spawns the appropriate
4530
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4531
// be signaled of the new peer once the method returns.
4532
//
4533
// NOTE: This MUST be launched as a goroutine.
4534
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4535
        defer s.wg.Done()
3✔
4536

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

3✔
4539
        // Avoid initializing peers while the server is exiting.
3✔
4540
        if s.Stopped() {
3✔
4541
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4542
                        pubBytes)
×
4543
                return
×
4544
        }
×
4545

4546
        // Create a channel that will be used to signal a successful start of
4547
        // the link. This prevents the peer termination watcher from beginning
4548
        // its duty too early.
4549
        ready := make(chan struct{})
3✔
4550

3✔
4551
        // Before starting the peer, launch a goroutine to watch for the
3✔
4552
        // unexpected termination of this peer, which will ensure all resources
3✔
4553
        // are properly cleaned up, and re-establish persistent connections when
3✔
4554
        // necessary. The peer termination watcher will be short circuited if
3✔
4555
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4556
        // that the server has already handled the removal of this peer.
3✔
4557
        s.wg.Add(1)
3✔
4558
        go s.peerTerminationWatcher(p, ready)
3✔
4559

3✔
4560
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4561
        // will unblock the peerTerminationWatcher.
3✔
4562
        if err := p.Start(); err != nil {
6✔
4563
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4564

3✔
4565
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4566
                return
3✔
4567
        }
3✔
4568

4569
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4570
        // was successful, and to begin watching the peer's wait group.
4571
        close(ready)
3✔
4572

3✔
4573
        s.mu.Lock()
3✔
4574
        defer s.mu.Unlock()
3✔
4575

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

3✔
4579
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4580
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4581
        pubStr := string(pubBytes)
3✔
4582
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4583
                select {
3✔
4584
                case peerChan <- p:
3✔
4585
                case <-s.quit:
×
4586
                        return
×
4587
                }
4588
        }
4589
        delete(s.peerConnectedListeners, pubStr)
3✔
4590

3✔
4591
        // Since the peer has been fully initialized, now it's time to notify
3✔
4592
        // the RPC about the peer online event.
3✔
4593
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4594
}
4595

4596
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4597
// and then cleans up all resources allocated to the peer, notifies relevant
4598
// sub-systems of its demise, and finally handles re-connecting to the peer if
4599
// it's persistent. If the server intentionally disconnects a peer, it should
4600
// have a corresponding entry in the ignorePeerTermination map which will cause
4601
// the cleanup routine to exit early. The passed `ready` chan is used to
4602
// synchronize when WaitForDisconnect should begin watching on the peer's
4603
// waitgroup. The ready chan should only be signaled if the peer starts
4604
// successfully, otherwise the peer should be disconnected instead.
4605
//
4606
// NOTE: This MUST be launched as a goroutine.
4607
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4608
        defer s.wg.Done()
3✔
4609

3✔
4610
        ctx := btclog.WithCtx(
3✔
4611
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4612
        )
3✔
4613

3✔
4614
        p.WaitForDisconnect(ready)
3✔
4615

3✔
4616
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4617

3✔
4618
        // If the server is exiting then we can bail out early ourselves as all
3✔
4619
        // the other sub-systems will already be shutting down.
3✔
4620
        if s.Stopped() {
6✔
4621
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4622
                return
3✔
4623
        }
3✔
4624

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

3✔
4631
        pubKey := p.IdentityKey()
3✔
4632

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

3✔
4637
        // Tell the switch to remove all links associated with this peer.
3✔
4638
        // Passing nil as the target link indicates that all links associated
3✔
4639
        // with this interface should be closed.
3✔
4640
        //
3✔
4641
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4642
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4643
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4644
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4645
        }
×
4646

4647
        for _, link := range links {
6✔
4648
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4649
        }
3✔
4650

4651
        s.mu.Lock()
3✔
4652
        defer s.mu.Unlock()
3✔
4653

3✔
4654
        // If there were any notification requests for when this peer
3✔
4655
        // disconnected, we can trigger them now.
3✔
4656
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4657
        pubStr := string(pubKey.SerializeCompressed())
3✔
4658
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4659
                close(offlineChan)
3✔
4660
        }
3✔
4661
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4662

3✔
4663
        // If the server has already removed this peer, we can short circuit the
3✔
4664
        // peer termination watcher and skip cleanup.
3✔
4665
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4666
                delete(s.ignorePeerTermination, p)
3✔
4667

3✔
4668
                pubKey := p.PubKey()
3✔
4669
                pubStr := string(pubKey[:])
3✔
4670

3✔
4671
                // If a connection callback is present, we'll go ahead and
3✔
4672
                // execute it now that previous peer has fully disconnected. If
3✔
4673
                // the callback is not present, this likely implies the peer was
3✔
4674
                // purposefully disconnected via RPC, and that no reconnect
3✔
4675
                // should be attempted.
3✔
4676
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4677
                if ok {
6✔
4678
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4679
                        connCallback()
3✔
4680
                }
3✔
4681
                return
3✔
4682
        }
4683

4684
        // First, cleanup any remaining state the server has regarding the peer
4685
        // in question.
4686
        s.removePeerUnsafe(ctx, p)
3✔
4687

3✔
4688
        // Next, check to see if this is a persistent peer or not.
3✔
4689
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4690
                return
3✔
4691
        }
3✔
4692

4693
        // Get the last address that we used to connect to the peer.
4694
        addrs := []net.Addr{
3✔
4695
                p.NetAddress().Address,
3✔
4696
        }
3✔
4697

3✔
4698
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4699
        // reconnection purposes.
3✔
4700
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4701
        switch {
3✔
4702
        // We found advertised addresses, so use them.
4703
        case err == nil:
3✔
4704
                addrs = advertisedAddrs
3✔
4705

4706
        // The peer doesn't have an advertised address.
4707
        case err == errNoAdvertisedAddr:
3✔
4708
                // If it is an outbound peer then we fall back to the existing
3✔
4709
                // peer address.
3✔
4710
                if !p.Inbound() {
6✔
4711
                        break
3✔
4712
                }
4713

4714
                // Fall back to the existing peer address if
4715
                // we're not accepting connections over Tor.
4716
                if s.torController == nil {
6✔
4717
                        break
3✔
4718
                }
4719

4720
                // If we are, the peer's address won't be known
4721
                // to us (we'll see a private address, which is
4722
                // the address used by our onion service to dial
4723
                // to lnd), so we don't have enough information
4724
                // to attempt a reconnect.
4725
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4726
                        "to inbound peer without advertised address")
×
4727
                return
×
4728

4729
        // We came across an error retrieving an advertised
4730
        // address, log it, and fall back to the existing peer
4731
        // address.
4732
        default:
3✔
4733
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4734
                        "address for peer", err)
3✔
4735
        }
4736

4737
        // Make an easy lookup map so that we can check if an address
4738
        // is already in the address list that we have stored for this peer.
4739
        existingAddrs := make(map[string]bool)
3✔
4740
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4741
                existingAddrs[addr.String()] = true
3✔
4742
        }
3✔
4743

4744
        // Add any missing addresses for this peer to persistentPeerAddr.
4745
        for _, addr := range addrs {
6✔
4746
                if existingAddrs[addr.String()] {
3✔
4747
                        continue
×
4748
                }
4749

4750
                s.persistentPeerAddrs[pubStr] = append(
3✔
4751
                        s.persistentPeerAddrs[pubStr],
3✔
4752
                        &lnwire.NetAddress{
3✔
4753
                                IdentityKey: p.IdentityKey(),
3✔
4754
                                Address:     addr,
3✔
4755
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4756
                        },
3✔
4757
                )
3✔
4758
        }
4759

4760
        // Record the computed backoff in the backoff map.
4761
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4762
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4763

3✔
4764
        // Initialize a retry canceller for this peer if one does not
3✔
4765
        // exist.
3✔
4766
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4767
        if !ok {
6✔
4768
                cancelChan = make(chan struct{})
3✔
4769
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4770
        }
3✔
4771

4772
        // We choose not to wait group this go routine since the Connect
4773
        // call can stall for arbitrarily long if we shutdown while an
4774
        // outbound connection attempt is being made.
4775
        go func() {
6✔
4776
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4777
                        "re-establishment to persistent peer",
3✔
4778
                        "reconnecting_in", backoff)
3✔
4779

3✔
4780
                select {
3✔
4781
                case <-time.After(backoff):
3✔
4782
                case <-cancelChan:
3✔
4783
                        return
3✔
4784
                case <-s.quit:
3✔
4785
                        return
3✔
4786
                }
4787

4788
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4789
                        "connection")
3✔
4790

3✔
4791
                s.connectToPersistentPeer(pubStr)
3✔
4792
        }()
4793
}
4794

4795
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4796
// to connect to the peer. It creates connection requests if there are
4797
// currently none for a given address and it removes old connection requests
4798
// if the associated address is no longer in the latest address list for the
4799
// peer.
4800
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4801
        s.mu.Lock()
3✔
4802
        defer s.mu.Unlock()
3✔
4803

3✔
4804
        // Create an easy lookup map of the addresses we have stored for the
3✔
4805
        // peer. We will remove entries from this map if we have existing
3✔
4806
        // connection requests for the associated address and then any leftover
3✔
4807
        // entries will indicate which addresses we should create new
3✔
4808
        // connection requests for.
3✔
4809
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4810
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4811
                addrMap[addr.String()] = addr
3✔
4812
        }
3✔
4813

4814
        // Go through each of the existing connection requests and
4815
        // check if they correspond to the latest set of addresses. If
4816
        // there is a connection requests that does not use one of the latest
4817
        // advertised addresses then remove that connection request.
4818
        var updatedConnReqs []*connmgr.ConnReq
3✔
4819
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4820
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4821

3✔
4822
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4823
                // If the existing connection request is using one of the
4824
                // latest advertised addresses for the peer then we add it to
4825
                // updatedConnReqs and remove the associated address from
4826
                // addrMap so that we don't recreate this connReq later on.
4827
                case true:
×
4828
                        updatedConnReqs = append(
×
4829
                                updatedConnReqs, connReq,
×
4830
                        )
×
4831
                        delete(addrMap, lnAddr)
×
4832

4833
                // If the existing connection request is using an address that
4834
                // is not one of the latest advertised addresses for the peer
4835
                // then we remove the connecting request from the connection
4836
                // manager.
4837
                case false:
3✔
4838
                        srvrLog.Info(
3✔
4839
                                "Removing conn req:", connReq.Addr.String(),
3✔
4840
                        )
3✔
4841
                        s.connMgr.Remove(connReq.ID())
3✔
4842
                }
4843
        }
4844

4845
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4846

3✔
4847
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4848
        if !ok {
6✔
4849
                cancelChan = make(chan struct{})
3✔
4850
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4851
        }
3✔
4852

4853
        // Any addresses left in addrMap are new ones that we have not made
4854
        // connection requests for. So create new connection requests for those.
4855
        // If there is more than one address in the address map, stagger the
4856
        // creation of the connection requests for those.
4857
        go func() {
6✔
4858
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4859
                defer ticker.Stop()
3✔
4860

3✔
4861
                for _, addr := range addrMap {
6✔
4862
                        // Send the persistent connection request to the
3✔
4863
                        // connection manager, saving the request itself so we
3✔
4864
                        // can cancel/restart the process as needed.
3✔
4865
                        connReq := &connmgr.ConnReq{
3✔
4866
                                Addr:      addr,
3✔
4867
                                Permanent: true,
3✔
4868
                        }
3✔
4869

3✔
4870
                        s.mu.Lock()
3✔
4871
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4872
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4873
                        )
3✔
4874
                        s.mu.Unlock()
3✔
4875

3✔
4876
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4877
                                "channel peer %v", addr)
3✔
4878

3✔
4879
                        go s.connMgr.Connect(connReq)
3✔
4880

3✔
4881
                        select {
3✔
4882
                        case <-s.quit:
3✔
4883
                                return
3✔
4884
                        case <-cancelChan:
3✔
4885
                                return
3✔
4886
                        case <-ticker.C:
3✔
4887
                        }
4888
                }
4889
        }()
4890
}
4891

4892
// removePeerUnsafe removes the passed peer from the server's state of all
4893
// active peers.
4894
//
4895
// NOTE: Server mutex must be held when calling this function.
4896
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4897
        if p == nil {
3✔
4898
                return
×
4899
        }
×
4900

4901
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4902

3✔
4903
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4904
        // will be disconnected in the server shutdown process.
3✔
4905
        if s.Stopped() {
3✔
4906
                return
×
4907
        }
×
4908

4909
        // Capture the peer's public key and string representation.
4910
        pKey := p.PubKey()
3✔
4911
        pubSer := pKey[:]
3✔
4912
        pubStr := string(pubSer)
3✔
4913

3✔
4914
        delete(s.peersByPub, pubStr)
3✔
4915

3✔
4916
        if p.Inbound() {
6✔
4917
                delete(s.inboundPeers, pubStr)
3✔
4918
        } else {
6✔
4919
                delete(s.outboundPeers, pubStr)
3✔
4920
        }
3✔
4921

4922
        // When removing the peer we make sure to disconnect it asynchronously
4923
        // to avoid blocking the main server goroutine because it is holding the
4924
        // server's mutex. Disconnecting the peer might block and wait until the
4925
        // peer has fully started up. This can happen if an inbound and outbound
4926
        // race condition occurs.
4927
        s.wg.Add(1)
3✔
4928
        go func() {
6✔
4929
                defer s.wg.Done()
3✔
4930

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

3✔
4933
                // If this peer had an active persistent connection request,
3✔
4934
                // remove it.
3✔
4935
                if p.ConnReq() != nil {
6✔
4936
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4937
                }
3✔
4938

4939
                // Remove the peer's access permission from the access manager.
4940
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4941
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4942

3✔
4943
                // Copy the peer's error buffer across to the server if it has
3✔
4944
                // any items in it so that we can restore peer errors across
3✔
4945
                // connections. We need to look up the error after the peer has
3✔
4946
                // been disconnected because we write the error in the
3✔
4947
                // `Disconnect` method.
3✔
4948
                s.mu.Lock()
3✔
4949
                if p.ErrorBuffer().Total() > 0 {
6✔
4950
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4951
                }
3✔
4952
                s.mu.Unlock()
3✔
4953

3✔
4954
                // Inform the peer notifier of a peer offline event so that it
3✔
4955
                // can be reported to clients listening for peer events.
3✔
4956
                var pubKey [33]byte
3✔
4957
                copy(pubKey[:], pubSer)
3✔
4958

3✔
4959
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4960
        }()
4961
}
4962

4963
// ConnectToPeer requests that the server connect to a Lightning Network peer
4964
// at the specified address. This function will *block* until either a
4965
// connection is established, or the initial handshake process fails.
4966
//
4967
// NOTE: This function is safe for concurrent access.
4968
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4969
        perm bool, timeout time.Duration) error {
3✔
4970

3✔
4971
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4972

3✔
4973
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4974
        // better granularity.  In certain conditions, this method requires
3✔
4975
        // making an outbound connection to a remote peer, which requires the
3✔
4976
        // lock to be released, and subsequently reacquired.
3✔
4977
        s.mu.Lock()
3✔
4978

3✔
4979
        // Ensure we're not already connected to this peer.
3✔
4980
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4981

3✔
4982
        // When there's no error it means we already have a connection with this
3✔
4983
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4984
        // set, we will ignore the existing connection and continue.
3✔
4985
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4986
                s.mu.Unlock()
3✔
4987
                return &errPeerAlreadyConnected{peer: peer}
3✔
4988
        }
3✔
4989

4990
        // Peer was not found, continue to pursue connection with peer.
4991

4992
        // If there's already a pending connection request for this pubkey,
4993
        // then we ignore this request to ensure we don't create a redundant
4994
        // connection.
4995
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4996
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4997
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4998
        }
3✔
4999

5000
        // If there's not already a pending or active connection to this node,
5001
        // then instruct the connection manager to attempt to establish a
5002
        // persistent connection to the peer.
5003
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5004
        if perm {
6✔
5005
                connReq := &connmgr.ConnReq{
3✔
5006
                        Addr:      addr,
3✔
5007
                        Permanent: true,
3✔
5008
                }
3✔
5009

3✔
5010
                // Since the user requested a permanent connection, we'll set
3✔
5011
                // the entry to true which will tell the server to continue
3✔
5012
                // reconnecting even if the number of channels with this peer is
3✔
5013
                // zero.
3✔
5014
                s.persistentPeers[targetPub] = true
3✔
5015
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5016
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5017
                }
3✔
5018
                s.persistentConnReqs[targetPub] = append(
3✔
5019
                        s.persistentConnReqs[targetPub], connReq,
3✔
5020
                )
3✔
5021
                s.mu.Unlock()
3✔
5022

3✔
5023
                go s.connMgr.Connect(connReq)
3✔
5024

3✔
5025
                return nil
3✔
5026
        }
5027
        s.mu.Unlock()
3✔
5028

3✔
5029
        // If we're not making a persistent connection, then we'll attempt to
3✔
5030
        // connect to the target peer. If the we can't make the connection, or
3✔
5031
        // the crypto negotiation breaks down, then return an error to the
3✔
5032
        // caller.
3✔
5033
        errChan := make(chan error, 1)
3✔
5034
        s.connectToPeer(addr, errChan, timeout)
3✔
5035

3✔
5036
        select {
3✔
5037
        case err := <-errChan:
3✔
5038
                return err
3✔
5039
        case <-s.quit:
×
5040
                return ErrServerShuttingDown
×
5041
        }
5042
}
5043

5044
// connectToPeer establishes a connection to a remote peer. errChan is used to
5045
// notify the caller if the connection attempt has failed. Otherwise, it will be
5046
// closed.
5047
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5048
        errChan chan<- error, timeout time.Duration) {
3✔
5049

3✔
5050
        conn, err := brontide.Dial(
3✔
5051
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5052
        )
3✔
5053
        if err != nil {
6✔
5054
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5055
                select {
3✔
5056
                case errChan <- err:
3✔
5057
                case <-s.quit:
×
5058
                }
5059
                return
3✔
5060
        }
5061

5062
        close(errChan)
3✔
5063

3✔
5064
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5065
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5066

3✔
5067
        s.OutboundPeerConnected(nil, conn)
3✔
5068
}
5069

5070
// DisconnectPeer sends the request to server to close the connection with peer
5071
// identified by public key.
5072
//
5073
// NOTE: This function is safe for concurrent access.
5074
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5075
        pubBytes := pubKey.SerializeCompressed()
3✔
5076
        pubStr := string(pubBytes)
3✔
5077

3✔
5078
        s.mu.Lock()
3✔
5079
        defer s.mu.Unlock()
3✔
5080

3✔
5081
        // Check that were actually connected to this peer. If not, then we'll
3✔
5082
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5083
        // currently connected to.
3✔
5084
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5085
        if err == ErrPeerNotConnected {
6✔
5086
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5087
        }
3✔
5088

5089
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5090

3✔
5091
        s.cancelConnReqs(pubStr, nil)
3✔
5092

3✔
5093
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5094
        // them from this map so we don't attempt to re-connect after we
3✔
5095
        // disconnect.
3✔
5096
        delete(s.persistentPeers, pubStr)
3✔
5097
        delete(s.persistentPeersBackoff, pubStr)
3✔
5098

3✔
5099
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5100
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5101
        //
3✔
5102
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5103
        // goroutine because we might hold the server's mutex.
3✔
5104
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5105

3✔
5106
        return nil
3✔
5107
}
5108

5109
// OpenChannel sends a request to the server to open a channel to the specified
5110
// peer identified by nodeKey with the passed channel funding parameters.
5111
//
5112
// NOTE: This function is safe for concurrent access.
5113
func (s *server) OpenChannel(
5114
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5115

3✔
5116
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5117
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5118
        // not blocked if the caller is not reading the updates.
3✔
5119
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5120
        req.Err = make(chan error, 1)
3✔
5121

3✔
5122
        // First attempt to locate the target peer to open a channel with, if
3✔
5123
        // we're unable to locate the peer then this request will fail.
3✔
5124
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5125
        s.mu.RLock()
3✔
5126
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5127
        if !ok {
3✔
5128
                s.mu.RUnlock()
×
5129

×
5130
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5131
                return req.Updates, req.Err
×
5132
        }
×
5133
        req.Peer = peer
3✔
5134
        s.mu.RUnlock()
3✔
5135

3✔
5136
        // We'll wait until the peer is active before beginning the channel
3✔
5137
        // opening process.
3✔
5138
        select {
3✔
5139
        case <-peer.ActiveSignal():
3✔
5140
        case <-peer.QuitSignal():
×
5141
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5142
                return req.Updates, req.Err
×
5143
        case <-s.quit:
×
5144
                req.Err <- ErrServerShuttingDown
×
5145
                return req.Updates, req.Err
×
5146
        }
5147

5148
        // If the fee rate wasn't specified at this point we fail the funding
5149
        // because of the missing fee rate information. The caller of the
5150
        // `OpenChannel` method needs to make sure that default values for the
5151
        // fee rate are set beforehand.
5152
        if req.FundingFeePerKw == 0 {
3✔
5153
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5154
                        "the channel opening transaction")
×
5155

×
5156
                return req.Updates, req.Err
×
5157
        }
×
5158

5159
        // Spawn a goroutine to send the funding workflow request to the funding
5160
        // manager. This allows the server to continue handling queries instead
5161
        // of blocking on this request which is exported as a synchronous
5162
        // request to the outside world.
5163
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5164

3✔
5165
        return req.Updates, req.Err
3✔
5166
}
5167

5168
// Peers returns a slice of all active peers.
5169
//
5170
// NOTE: This function is safe for concurrent access.
5171
func (s *server) Peers() []*peer.Brontide {
3✔
5172
        s.mu.RLock()
3✔
5173
        defer s.mu.RUnlock()
3✔
5174

3✔
5175
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5176
        for _, peer := range s.peersByPub {
6✔
5177
                peers = append(peers, peer)
3✔
5178
        }
3✔
5179

5180
        return peers
3✔
5181
}
5182

5183
// computeNextBackoff uses a truncated exponential backoff to compute the next
5184
// backoff using the value of the exiting backoff. The returned duration is
5185
// randomized in either direction by 1/20 to prevent tight loops from
5186
// stabilizing.
5187
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5188
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5189
        nextBackoff := 2 * currBackoff
3✔
5190
        if nextBackoff > maxBackoff {
6✔
5191
                nextBackoff = maxBackoff
3✔
5192
        }
3✔
5193

5194
        // Using 1/10 of our duration as a margin, compute a random offset to
5195
        // avoid the nodes entering connection cycles.
5196
        margin := nextBackoff / 10
3✔
5197

3✔
5198
        var wiggle big.Int
3✔
5199
        wiggle.SetUint64(uint64(margin))
3✔
5200
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5201
                // Randomizing is not mission critical, so we'll just return the
×
5202
                // current backoff.
×
5203
                return nextBackoff
×
5204
        }
×
5205

5206
        // Otherwise add in our wiggle, but subtract out half of the margin so
5207
        // that the backoff can tweaked by 1/20 in either direction.
5208
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5209
}
5210

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

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

3✔
5219
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5220
        if err != nil {
3✔
5221
                return nil, err
×
5222
        }
×
5223

5224
        node, err := s.graphDB.FetchNode(ctx, vertex)
3✔
5225
        if err != nil {
6✔
5226
                return nil, err
3✔
5227
        }
3✔
5228

5229
        if len(node.Addresses) == 0 {
6✔
5230
                return nil, errNoAdvertisedAddr
3✔
5231
        }
3✔
5232

5233
        return node.Addresses, nil
3✔
5234
}
5235

5236
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5237
// channel update for a target channel.
5238
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5239
        *lnwire.ChannelUpdate1, error) {
3✔
5240

3✔
5241
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5242
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5243
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5244
                if err != nil {
6✔
5245
                        return nil, err
3✔
5246
                }
3✔
5247

5248
                return netann.ExtractChannelUpdate(
3✔
5249
                        ourPubKey[:], info, edge1, edge2,
3✔
5250
                )
3✔
5251
        }
5252
}
5253

5254
// applyChannelUpdate applies the channel update to the different sub-systems of
5255
// the server. The useAlias boolean denotes whether or not to send an alias in
5256
// place of the real SCID.
5257
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5258
        op *wire.OutPoint, useAlias bool) error {
3✔
5259

3✔
5260
        var (
3✔
5261
                peerAlias    *lnwire.ShortChannelID
3✔
5262
                defaultAlias lnwire.ShortChannelID
3✔
5263
        )
3✔
5264

3✔
5265
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5266

3✔
5267
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5268
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5269
        if useAlias {
6✔
5270
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5271
                if foundAlias != defaultAlias {
6✔
5272
                        peerAlias = &foundAlias
3✔
5273
                }
3✔
5274
        }
5275

5276
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5277
                update, discovery.RemoteAlias(peerAlias),
3✔
5278
        )
3✔
5279
        select {
3✔
5280
        case err := <-errChan:
3✔
5281
                return err
3✔
5282
        case <-s.quit:
×
5283
                return ErrServerShuttingDown
×
5284
        }
5285
}
5286

5287
// SendCustomMessage sends a custom message to the peer with the specified
5288
// pubkey.
5289
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5290
        data []byte) error {
3✔
5291

3✔
5292
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5293
        if err != nil {
6✔
5294
                return err
3✔
5295
        }
3✔
5296

5297
        // We'll wait until the peer is active.
5298
        select {
3✔
5299
        case <-peer.ActiveSignal():
3✔
5300
        case <-peer.QuitSignal():
×
5301
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5302
        case <-s.quit:
×
5303
                return ErrServerShuttingDown
×
5304
        }
5305

5306
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5307
        if err != nil {
6✔
5308
                return err
3✔
5309
        }
3✔
5310

5311
        // Send the message as low-priority. For now we assume that all
5312
        // application-defined message are low priority.
5313
        return peer.SendMessageLazy(true, msg)
3✔
5314
}
5315

5316
// newSweepPkScriptGen creates closure that generates a new public key script
5317
// which should be used to sweep any funds into the on-chain wallet.
5318
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5319
// (p2wkh) output.
5320
func newSweepPkScriptGen(
5321
        wallet lnwallet.WalletController,
5322
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5323

3✔
5324
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5325
                sweepAddr, err := wallet.NewAddress(
3✔
5326
                        lnwallet.TaprootPubkey, false,
3✔
5327
                        lnwallet.DefaultAccountName,
3✔
5328
                )
3✔
5329
                if err != nil {
3✔
5330
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5331
                }
×
5332

5333
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5334
                if err != nil {
3✔
5335
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5336
                }
×
5337

5338
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5339
                        wallet, netParams, addr,
3✔
5340
                )
3✔
5341
                if err != nil {
3✔
5342
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5343
                }
×
5344

5345
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5346
                        DeliveryAddress: addr,
3✔
5347
                        InternalKey:     internalKeyDesc,
3✔
5348
                })
3✔
5349
        }
5350
}
5351

5352
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5353
// finished.
5354
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5355
        // Get a list of closed channels.
3✔
5356
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5357
        if err != nil {
3✔
5358
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5359
                return nil
×
5360
        }
×
5361

5362
        // Save the SCIDs in a map.
5363
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5364
        for _, c := range channels {
6✔
5365
                // If the channel is not pending, its FC has been finalized.
3✔
5366
                if !c.IsPending {
6✔
5367
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5368
                }
3✔
5369
        }
5370

5371
        // Double check whether the reported closed channel has indeed finished
5372
        // closing.
5373
        //
5374
        // NOTE: There are misalignments regarding when a channel's FC is
5375
        // marked as finalized. We double check the pending channels to make
5376
        // sure the returned SCIDs are indeed terminated.
5377
        //
5378
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5379
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5380
        if err != nil {
3✔
5381
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5382
                return nil
×
5383
        }
×
5384

5385
        for _, c := range pendings {
6✔
5386
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5387
                        continue
3✔
5388
                }
5389

5390
                // If the channel is still reported as pending, remove it from
5391
                // the map.
5392
                delete(closedSCIDs, c.ShortChannelID)
×
5393

×
5394
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5395
                        c.ShortChannelID)
×
5396
        }
5397

5398
        return closedSCIDs
3✔
5399
}
5400

5401
// getStartingBeat returns the current beat. This is used during the startup to
5402
// initialize blockbeat consumers.
5403
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5404
        // beat is the current blockbeat.
3✔
5405
        var beat *chainio.Beat
3✔
5406

3✔
5407
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5408
        // we will skip fetching the best block.
3✔
5409
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5410
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5411
                        "mode")
×
5412

×
5413
                return &chainio.Beat{}, nil
×
5414
        }
×
5415

5416
        // We should get a notification with the current best block immediately
5417
        // by passing a nil block.
5418
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5419
        if err != nil {
3✔
5420
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5421
        }
×
5422
        defer blockEpochs.Cancel()
3✔
5423

3✔
5424
        // We registered for the block epochs with a nil request. The notifier
3✔
5425
        // should send us the current best block immediately. So we need to
3✔
5426
        // wait for it here because we need to know the current best height.
3✔
5427
        select {
3✔
5428
        case bestBlock := <-blockEpochs.Epochs:
3✔
5429
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5430
                        bestBlock.Hash, bestBlock.Height)
3✔
5431

3✔
5432
                // Update the current blockbeat.
3✔
5433
                beat = chainio.NewBeat(*bestBlock)
3✔
5434

5435
        case <-s.quit:
×
5436
                srvrLog.Debug("LND shutting down")
×
5437
        }
5438

5439
        return beat, nil
3✔
5440
}
5441

5442
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5443
// point has an active RBF chan closer.
5444
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5445
        chanPoint wire.OutPoint) bool {
3✔
5446

3✔
5447
        pubBytes := peerPub.SerializeCompressed()
3✔
5448

3✔
5449
        s.mu.RLock()
3✔
5450
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5451
        s.mu.RUnlock()
3✔
5452
        if !ok {
3✔
5453
                return false
×
5454
        }
×
5455

5456
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5457
}
5458

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

3✔
5467
        // First, we'll attempt to look up the channel based on it's
3✔
5468
        // ChannelPoint.
3✔
5469
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5470
        if err != nil {
3✔
5471
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5472
        }
×
5473

5474
        // From the channel, we can now get the pubkey of the peer, then use
5475
        // that to eventually get the chan closer.
5476
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5477

3✔
5478
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5479
        s.mu.RLock()
3✔
5480
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5481
        s.mu.RUnlock()
3✔
5482
        if !ok {
3✔
5483
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5484
                        "not online", chanPoint)
×
5485
        }
×
5486

5487
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5488
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5489
        )
3✔
5490
        if err != nil {
3✔
5491
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5492
                        "%w", err)
×
5493
        }
×
5494

5495
        return closeUpdates, nil
3✔
5496
}
5497

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

3✔
5506
        // If the channel is present in the switch, then the request should flow
3✔
5507
        // through the switch instead.
3✔
5508
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5509
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5510
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5511
                        "invalid request", chanPoint)
×
5512
        }
×
5513

5514
        // At this point, we know that the channel isn't present in the link, so
5515
        // we'll check to see if we have an entry in the active chan closer map.
5516
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5517
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5518
        )
3✔
5519
        if err != nil {
3✔
5520
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5521
                        "ChannelPoint(%v)", chanPoint)
×
5522
        }
×
5523

5524
        return updates, nil
3✔
5525
}
5526

5527
// setSelfNode configures and sets the server's self node. It sets the node
5528
// announcement, signs it, and updates the source node in the graph. When
5529
// determining values such as color and alias, the method prioritizes values
5530
// set in the config, then values previously persisted on disk, and finally
5531
// falls back to the defaults.
5532
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5533
        listenAddrs []net.Addr) error {
3✔
5534

3✔
5535
        // If we were requested to automatically configure port forwarding,
3✔
5536
        // we'll use the ports that the server will be listening on.
3✔
5537
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
3✔
5538
        for _, ip := range s.cfg.ExternalIPs {
6✔
5539
                externalIPStrings = append(externalIPStrings, ip.String())
3✔
5540
        }
3✔
5541
        if s.natTraversal != nil {
3✔
5542
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5543
                for _, listenAddr := range listenAddrs {
×
5544
                        // At this point, the listen addresses should have
×
5545
                        // already been normalized, so it's safe to ignore the
×
5546
                        // errors.
×
5547
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5548
                        port, _ := strconv.Atoi(portStr)
×
5549

×
5550
                        listenPorts = append(listenPorts, uint16(port))
×
5551
                }
×
5552

5553
                ips, err := s.configurePortForwarding(listenPorts...)
×
5554
                if err != nil {
×
5555
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5556
                                "forwarding using %s: %v",
×
5557
                                s.natTraversal.Name(), err)
×
5558
                } else {
×
5559
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5560
                                "using %s to advertise external IP",
×
5561
                                s.natTraversal.Name())
×
5562
                        externalIPStrings = append(externalIPStrings, ips...)
×
5563
                }
×
5564
        }
5565

5566
        // Normalize the external IP strings to net.Addr.
5567
        addrs, err := lncfg.NormalizeAddresses(
3✔
5568
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5569
                s.cfg.net.ResolveTCPAddr,
3✔
5570
        )
3✔
5571
        if err != nil {
3✔
5572
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5573
        }
×
5574

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

5583
        var (
3✔
5584
                alias          = s.cfg.Alias
3✔
5585
                nodeLastUpdate = time.Now()
3✔
5586
        )
3✔
5587

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

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

5605
                // If an alias is not specified in the config, we'll use the
5606
                // source node's alias.
5607
                if alias == "" {
6✔
5608
                        alias = srcNode.Alias
3✔
5609
                }
3✔
5610

5611
                // If the `externalip` is not specified in the config, it means
5612
                // `addrs` will be empty, we'll use the source node's addresses.
5613
                if len(s.cfg.ExternalIPs) == 0 {
6✔
5614
                        addrs = srcNode.Addresses
3✔
5615
                }
3✔
5616

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

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

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

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

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

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

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

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

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

5681
        s.currentNodeAnn = nodeAnn
3✔
5682

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