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

lightningnetwork / lnd / 16423200982

21 Jul 2025 04:58PM UTC coverage: 57.549% (+0.01%) from 57.535%
16423200982

Pull #8825

github

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

87 of 104 new or added lines in 1 file covered. (83.65%)

59 existing lines in 8 files now uncovered.

98656 of 171429 relevant lines covered (57.55%)

1.79 hits per line

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

69.56
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

231
        start sync.Once
232
        stop  sync.Once
233

234
        cfg *Config
235

236
        implCfg *ImplementationCfg
237

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

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

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

249
        chanStatusMgr *netann.ChanStatusManager
250

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

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

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

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

271
        mu sync.RWMutex
272

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

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

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

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

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

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

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

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

323
        cc *chainreg.ChainControl
324

325
        fundingMgr *funding.Manager
326

327
        graphDB *graphdb.ChannelGraph
328

329
        chanStateDB *channeldb.ChannelStateDB
330

331
        addrSource channeldb.AddrSource
332

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

337
        invoicesDB invoices.InvoiceDB
338

339
        aliasMgr *aliasmgr.Manager
340

341
        htlcSwitch *htlcswitch.Switch
342

343
        interceptableSwitch *htlcswitch.InterceptableSwitch
344

345
        invoices *invoices.InvoiceRegistry
346

347
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
348

349
        channelNotifier *channelnotifier.ChannelNotifier
350

351
        peerNotifier *peernotifier.PeerNotifier
352

353
        htlcNotifier *htlcswitch.HtlcNotifier
354

355
        witnessBeacon contractcourt.WitnessBeacon
356

357
        breachArbitrator *contractcourt.BreachArbitrator
358

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

362
        graphBuilder *graph.Builder
363

364
        chanRouter *routing.ChannelRouter
365

366
        controlTower routing.ControlTower
367

368
        authGossiper *discovery.AuthenticatedGossiper
369

370
        localChanMgr *localchans.Manager
371

372
        utxoNursery *contractcourt.UtxoNursery
373

374
        sweeper *sweep.UtxoSweeper
375

376
        chainArb *contractcourt.ChainArbitrator
377

378
        sphinx *hop.OnionProcessor
379

380
        towerClientMgr *wtclient.Manager
381

382
        connMgr *connmgr.ConnManager
383

384
        sigPool *lnwallet.SigPool
385

386
        writePool *pool.Write
387

388
        readPool *pool.Read
389

390
        tlsManager *TLSManager
391

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

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

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

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

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

414
        hostAnn *netann.HostAnnouncer
415

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

419
        customMessageServer *subscribe.Server
420

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

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

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

431
        quit chan struct{}
432

433
        wg sync.WaitGroup
434
}
435

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

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

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

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

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

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

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

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

491
                                        s.mu.Lock()
3✔
492

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

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

507
                                        s.mu.Unlock()
3✔
508

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

515
        return nil
3✔
516
}
517

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

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

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

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

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

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

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

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

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

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

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

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

3✔
601
        netParams := cfg.ActiveNetParams.Params
3✔
602

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

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

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

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

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

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

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

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

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

3✔
672
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
673

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

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

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

3✔
699
                listenAddrs: listenAddrs,
3✔
700

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

3✔
705
                torController: torController,
3✔
706

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

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

3✔
723
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
724

3✔
725
                customMessageServer: subscribe.NewServer(),
3✔
726

3✔
727
                tlsManager: tlsManager,
3✔
728

3✔
729
                featureMgr: featureMgr,
3✔
730
                quit:       make(chan struct{}),
3✔
731
        }
3✔
732

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

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

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

3✔
757
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
758

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

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

768
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
769

3✔
770
                return nil
3✔
771
        }
772

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

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

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

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

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

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

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

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

×
859
                discoveryTimeout := time.Duration(10 * time.Second)
×
860

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

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

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

887
                        s.natTraversal = pmp
×
888
                }
889
        }
890

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

×
906
                        listenPorts = append(listenPorts, uint16(port))
×
907
                }
×
908

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

922
        // Set the self node which represents our node in the graph.
923
        err = s.setSelfNode(ctx, externalIPStrings, serializedPubKey)
3✔
924
        if err != nil {
3✔
925
                return nil, err
×
926
        }
×
927

928
        // The router will get access to the payment ID sequencer, such that it
929
        // can generate unique payment IDs.
930
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
931
        if err != nil {
3✔
932
                return nil, err
×
933
        }
×
934

935
        // Instantiate mission control with config from the sub server.
936
        //
937
        // TODO(joostjager): When we are further in the process of moving to sub
938
        // servers, the mission control instance itself can be moved there too.
939
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
940

3✔
941
        // We only initialize a probability estimator if there's no custom one.
3✔
942
        var estimator routing.Estimator
3✔
943
        if cfg.Estimator != nil {
3✔
944
                estimator = cfg.Estimator
×
945
        } else {
3✔
946
                switch routingConfig.ProbabilityEstimatorType {
3✔
947
                case routing.AprioriEstimatorName:
3✔
948
                        aCfg := routingConfig.AprioriConfig
3✔
949
                        aprioriConfig := routing.AprioriConfig{
3✔
950
                                AprioriHopProbability: aCfg.HopProbability,
3✔
951
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
952
                                AprioriWeight:         aCfg.Weight,
3✔
953
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
954
                        }
3✔
955

3✔
956
                        estimator, err = routing.NewAprioriEstimator(
3✔
957
                                aprioriConfig,
3✔
958
                        )
3✔
959
                        if err != nil {
3✔
960
                                return nil, err
×
961
                        }
×
962

963
                case routing.BimodalEstimatorName:
×
964
                        bCfg := routingConfig.BimodalConfig
×
965
                        bimodalConfig := routing.BimodalConfig{
×
966
                                BimodalNodeWeight: bCfg.NodeWeight,
×
967
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
968
                                        bCfg.Scale,
×
969
                                ),
×
970
                                BimodalDecayTime: bCfg.DecayTime,
×
971
                        }
×
972

×
973
                        estimator, err = routing.NewBimodalEstimator(
×
974
                                bimodalConfig,
×
975
                        )
×
976
                        if err != nil {
×
977
                                return nil, err
×
978
                        }
×
979

980
                default:
×
981
                        return nil, fmt.Errorf("unknown estimator type %v",
×
982
                                routingConfig.ProbabilityEstimatorType)
×
983
                }
984
        }
985

986
        mcCfg := &routing.MissionControlConfig{
3✔
987
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
988
                Estimator:               estimator,
3✔
989
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
990
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
991
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
992
        }
3✔
993

3✔
994
        s.missionController, err = routing.NewMissionController(
3✔
995
                dbs.ChanStateDB, serializedPubKey, mcCfg,
3✔
996
        )
3✔
997
        if err != nil {
3✔
998
                return nil, fmt.Errorf("can't create mission control "+
×
999
                        "manager: %w", err)
×
1000
        }
×
1001
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1002
                routing.DefaultMissionControlNamespace,
3✔
1003
        )
3✔
1004
        if err != nil {
3✔
1005
                return nil, fmt.Errorf("can't create mission control in the "+
×
1006
                        "default namespace: %w", err)
×
1007
        }
×
1008

1009
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1010
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1011
                int64(routingConfig.AttemptCost),
3✔
1012
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1013
                routingConfig.MinRouteProbability)
3✔
1014

3✔
1015
        pathFindingConfig := routing.PathFindingConfig{
3✔
1016
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1017
                        routingConfig.AttemptCost,
3✔
1018
                ),
3✔
1019
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1020
                MinProbability: routingConfig.MinRouteProbability,
3✔
1021
        }
3✔
1022

3✔
1023
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1024
        if err != nil {
3✔
1025
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1026
        }
×
1027
        paymentSessionSource := &routing.SessionSource{
3✔
1028
                GraphSessionFactory: dbs.GraphDB,
3✔
1029
                SourceNode:          sourceNode,
3✔
1030
                MissionControl:      s.defaultMC,
3✔
1031
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1032
                PathFindingConfig:   pathFindingConfig,
3✔
1033
        }
3✔
1034

3✔
1035
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1036

3✔
1037
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1038

3✔
1039
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1040
                cfg.Routing.StrictZombiePruning
3✔
1041

3✔
1042
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1043
                SelfNode:            serializedPubKey,
3✔
1044
                Graph:               dbs.GraphDB,
3✔
1045
                Chain:               cc.ChainIO,
3✔
1046
                ChainView:           cc.ChainView,
3✔
1047
                Notifier:            cc.ChainNotifier,
3✔
1048
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1049
                GraphPruneInterval:  time.Hour,
3✔
1050
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1051
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1052
                StrictZombiePruning: strictPruning,
3✔
1053
                IsAlias:             aliasmgr.IsAlias,
3✔
1054
        })
3✔
1055
        if err != nil {
3✔
1056
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1057
        }
×
1058

1059
        s.chanRouter, err = routing.New(routing.Config{
3✔
1060
                SelfNode:           serializedPubKey,
3✔
1061
                RoutingGraph:       dbs.GraphDB,
3✔
1062
                Chain:              cc.ChainIO,
3✔
1063
                Payer:              s.htlcSwitch,
3✔
1064
                Control:            s.controlTower,
3✔
1065
                MissionControl:     s.defaultMC,
3✔
1066
                SessionSource:      paymentSessionSource,
3✔
1067
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1068
                NextPaymentID:      sequencer.NextID,
3✔
1069
                PathFindingConfig:  pathFindingConfig,
3✔
1070
                Clock:              clock.NewDefaultClock(),
3✔
1071
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1072
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1073
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1074
        })
3✔
1075
        if err != nil {
3✔
1076
                return nil, fmt.Errorf("can't create router: %w", err)
×
1077
        }
×
1078

1079
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1080
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1081
        if err != nil {
3✔
1082
                return nil, err
×
1083
        }
×
1084
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1085
        if err != nil {
3✔
1086
                return nil, err
×
1087
        }
×
1088

1089
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1090

3✔
1091
        s.authGossiper = discovery.New(discovery.Config{
3✔
1092
                Graph:                 s.graphBuilder,
3✔
1093
                ChainIO:               s.cc.ChainIO,
3✔
1094
                Notifier:              s.cc.ChainNotifier,
3✔
1095
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1096
                Broadcast:             s.BroadcastMessage,
3✔
1097
                ChanSeries:            chanSeries,
3✔
1098
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1099
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1100
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1101
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1102
                        error) {
3✔
1103

×
1104
                        return s.genNodeAnnouncement(nil)
×
1105
                },
×
1106
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1107
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1108
                RetransmitTicker:        ticker.New(time.Minute * 30),
1109
                RebroadcastInterval:     time.Hour * 24,
1110
                WaitingProofStore:       waitingProofStore,
1111
                MessageStore:            gossipMessageStore,
1112
                AnnSigner:               s.nodeSigner,
1113
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1114
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1115
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1116
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1117
                MinimumBatchSize:        10,
1118
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1119
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1120
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1121
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1122
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1123
                IsAlias:                 aliasmgr.IsAlias,
1124
                SignAliasUpdate:         s.signAliasUpdate,
1125
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1126
                GetAlias:                s.aliasMgr.GetPeerAlias,
1127
                FindChannel:             s.findChannel,
1128
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1129
                ScidCloser:              scidCloserMan,
1130
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1131
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1132
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1133
        }, nodeKeyDesc)
1134

1135
        accessCfg := &accessManConfig{
3✔
1136
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1137
                        error) {
6✔
1138

3✔
1139
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1140
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1141
                                genesisHash[:],
3✔
1142
                        )
3✔
1143
                },
3✔
1144
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1145
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1146
        }
1147

1148
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1149
        if err != nil {
3✔
1150
                return nil, err
×
1151
        }
×
1152

1153
        s.peerAccessMan = peerAccessMan
3✔
1154

3✔
1155
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1156
        //nolint:ll
3✔
1157
        s.localChanMgr = &localchans.Manager{
3✔
1158
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1159
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1160
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1161
                        cb func(*models.ChannelEdgeInfo,
3✔
1162
                                *models.ChannelEdgePolicy) error,
3✔
1163
                        reset func()) error {
6✔
1164

3✔
1165
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1166
                                func(c *models.ChannelEdgeInfo,
3✔
1167
                                        e *models.ChannelEdgePolicy,
3✔
1168
                                        _ *models.ChannelEdgePolicy) error {
6✔
1169

3✔
1170
                                        // NOTE: The invoked callback here may
3✔
1171
                                        // receive a nil channel policy.
3✔
1172
                                        return cb(c, e)
3✔
1173
                                }, reset,
3✔
1174
                        )
1175
                },
1176
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1177
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1178
                FetchChannel:              s.chanStateDB.FetchChannel,
1179
                AddEdge: func(ctx context.Context,
1180
                        edge *models.ChannelEdgeInfo) error {
×
1181

×
1182
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1183
                },
×
1184
        }
1185

1186
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1187
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1188
        )
3✔
1189
        if err != nil {
3✔
1190
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1191
                return nil, err
×
1192
        }
×
1193

1194
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1195
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1196
        )
3✔
1197
        if err != nil {
3✔
1198
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1199
                return nil, err
×
1200
        }
×
1201

1202
        aggregator := sweep.NewBudgetAggregator(
3✔
1203
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1204
                s.implCfg.AuxSweeper,
3✔
1205
        )
3✔
1206

3✔
1207
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1208
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1209
                Wallet:     cc.Wallet,
3✔
1210
                Estimator:  cc.FeeEstimator,
3✔
1211
                Notifier:   cc.ChainNotifier,
3✔
1212
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1213
        })
3✔
1214

3✔
1215
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1216
                FeeEstimator: cc.FeeEstimator,
3✔
1217
                GenSweepScript: newSweepPkScriptGen(
3✔
1218
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1219
                ),
3✔
1220
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1221
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1222
                Mempool:              cc.MempoolNotifier,
3✔
1223
                Notifier:             cc.ChainNotifier,
3✔
1224
                Store:                sweeperStore,
3✔
1225
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1226
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1227
                Aggregator:           aggregator,
3✔
1228
                Publisher:            s.txPublisher,
3✔
1229
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1230
        })
3✔
1231

3✔
1232
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1233
                ChainIO:             cc.ChainIO,
3✔
1234
                ConfDepth:           1,
3✔
1235
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1236
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1237
                Notifier:            cc.ChainNotifier,
3✔
1238
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1239
                Store:               utxnStore,
3✔
1240
                SweepInput:          s.sweeper.SweepInput,
3✔
1241
                Budget:              s.cfg.Sweeper.Budget,
3✔
1242
        })
3✔
1243

3✔
1244
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1245
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1246
                closureType contractcourt.ChannelCloseType) {
6✔
1247
                // TODO(conner): Properly respect the update and error channels
3✔
1248
                // returned by CloseLink.
3✔
1249

3✔
1250
                // Instruct the switch to close the channel.  Provide no close out
3✔
1251
                // delivery script or target fee per kw because user input is not
3✔
1252
                // available when the remote peer closes the channel.
3✔
1253
                s.htlcSwitch.CloseLink(
3✔
1254
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1255
                )
3✔
1256
        }
3✔
1257

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

3✔
1262
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1263
                &contractcourt.BreachConfig{
3✔
1264
                        CloseLink: closeLink,
3✔
1265
                        DB:        s.chanStateDB,
3✔
1266
                        Estimator: s.cc.FeeEstimator,
3✔
1267
                        GenSweepScript: newSweepPkScriptGen(
3✔
1268
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1269
                        ),
3✔
1270
                        Notifier:           cc.ChainNotifier,
3✔
1271
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1272
                        ContractBreaches:   contractBreaches,
3✔
1273
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1274
                        Store: contractcourt.NewRetributionStore(
3✔
1275
                                dbs.ChanStateDB,
3✔
1276
                        ),
3✔
1277
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1278
                },
3✔
1279
        )
3✔
1280

3✔
1281
        //nolint:ll
3✔
1282
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1283
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1284
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1285
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1286
                NewSweepAddr: func() ([]byte, error) {
3✔
1287
                        addr, err := newSweepPkScriptGen(
×
1288
                                cc.Wallet, netParams,
×
1289
                        )().Unpack()
×
1290
                        if err != nil {
×
1291
                                return nil, err
×
1292
                        }
×
1293

1294
                        return addr.DeliveryAddress, nil
×
1295
                },
1296
                PublishTx: cc.Wallet.PublishTransaction,
1297
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1298
                        for _, msg := range msgs {
6✔
1299
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1300
                                if err != nil {
3✔
1301
                                        return err
×
1302
                                }
×
1303
                        }
1304
                        return nil
3✔
1305
                },
1306
                IncubateOutputs: func(chanPoint wire.OutPoint,
1307
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1308
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1309
                        broadcastHeight uint32,
1310
                        deadlineHeight fn.Option[int32]) error {
3✔
1311

3✔
1312
                        return s.utxoNursery.IncubateOutputs(
3✔
1313
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1314
                                broadcastHeight, deadlineHeight,
3✔
1315
                        )
3✔
1316
                },
3✔
1317
                PreimageDB:   s.witnessBeacon,
1318
                Notifier:     cc.ChainNotifier,
1319
                Mempool:      cc.MempoolNotifier,
1320
                Signer:       cc.Wallet.Cfg.Signer,
1321
                FeeEstimator: cc.FeeEstimator,
1322
                ChainIO:      cc.ChainIO,
1323
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1324
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1325
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1326
                        return nil
3✔
1327
                },
3✔
1328
                IsOurAddress: cc.Wallet.IsOurAddress,
1329
                ContractBreach: func(chanPoint wire.OutPoint,
1330
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1331

3✔
1332
                        // processACK will handle the BreachArbitrator ACKing
3✔
1333
                        // the event.
3✔
1334
                        finalErr := make(chan error, 1)
3✔
1335
                        processACK := func(brarErr error) {
6✔
1336
                                if brarErr != nil {
3✔
1337
                                        finalErr <- brarErr
×
1338
                                        return
×
1339
                                }
×
1340

1341
                                // If the BreachArbitrator successfully handled
1342
                                // the event, we can signal that the handoff
1343
                                // was successful.
1344
                                finalErr <- nil
3✔
1345
                        }
1346

1347
                        event := &contractcourt.ContractBreachEvent{
3✔
1348
                                ChanPoint:         chanPoint,
3✔
1349
                                ProcessACK:        processACK,
3✔
1350
                                BreachRetribution: breachRet,
3✔
1351
                        }
3✔
1352

3✔
1353
                        // Send the contract breach event to the
3✔
1354
                        // BreachArbitrator.
3✔
1355
                        select {
3✔
1356
                        case contractBreaches <- event:
3✔
1357
                        case <-s.quit:
×
1358
                                return ErrServerShuttingDown
×
1359
                        }
1360

1361
                        // We'll wait for a final error to be available from
1362
                        // the BreachArbitrator.
1363
                        select {
3✔
1364
                        case err := <-finalErr:
3✔
1365
                                return err
3✔
1366
                        case <-s.quit:
×
1367
                                return ErrServerShuttingDown
×
1368
                        }
1369
                },
1370
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1371
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1372
                },
3✔
1373
                Sweeper:                       s.sweeper,
1374
                Registry:                      s.invoices,
1375
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1376
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1377
                OnionProcessor:                s.sphinx,
1378
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1379
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1380
                Clock:                         clock.NewDefaultClock(),
1381
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1382
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1383
                HtlcNotifier:                  s.htlcNotifier,
1384
                Budget:                        *s.cfg.Sweeper.Budget,
1385

1386
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1387
                QueryIncomingCircuit: func(
1388
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1389

3✔
1390
                        // Get the circuit map.
3✔
1391
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1392

3✔
1393
                        // Lookup the outgoing circuit.
3✔
1394
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1395
                        if pc == nil {
5✔
1396
                                return nil
2✔
1397
                        }
2✔
1398

1399
                        return &pc.Incoming
3✔
1400
                },
1401
                AuxLeafStore: implCfg.AuxLeafStore,
1402
                AuxSigner:    implCfg.AuxSigner,
1403
                AuxResolver:  implCfg.AuxContractResolver,
1404
        }, dbs.ChanStateDB)
1405

1406
        // Select the configuration and funding parameters for Bitcoin.
1407
        chainCfg := cfg.Bitcoin
3✔
1408
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1409
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1410

3✔
1411
        var chanIDSeed [32]byte
3✔
1412
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1413
                return nil, err
×
1414
        }
×
1415

1416
        // Wrap the DeleteChannelEdges method so that the funding manager can
1417
        // use it without depending on several layers of indirection.
1418
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1419
                *models.ChannelEdgePolicy, error) {
6✔
1420

3✔
1421
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1422
                        scid.ToUint64(),
3✔
1423
                )
3✔
1424
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1425
                        // This is unlikely but there is a slim chance of this
×
1426
                        // being hit if lnd was killed via SIGKILL and the
×
1427
                        // funding manager was stepping through the delete
×
1428
                        // alias edge logic.
×
1429
                        return nil, nil
×
1430
                } else if err != nil {
3✔
1431
                        return nil, err
×
1432
                }
×
1433

1434
                // Grab our key to find our policy.
1435
                var ourKey [33]byte
3✔
1436
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1437

3✔
1438
                var ourPolicy *models.ChannelEdgePolicy
3✔
1439
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1440
                        ourPolicy = e1
3✔
1441
                } else {
6✔
1442
                        ourPolicy = e2
3✔
1443
                }
3✔
1444

1445
                if ourPolicy == nil {
3✔
1446
                        // Something is wrong, so return an error.
×
1447
                        return nil, fmt.Errorf("we don't have an edge")
×
1448
                }
×
1449

1450
                err = s.graphDB.DeleteChannelEdges(
3✔
1451
                        false, false, scid.ToUint64(),
3✔
1452
                )
3✔
1453
                return ourPolicy, err
3✔
1454
        }
1455

1456
        // For the reservationTimeout and the zombieSweeperInterval different
1457
        // values are set in case we are in a dev environment so enhance test
1458
        // capacilities.
1459
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1460
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1461

3✔
1462
        // Get the development config for funding manager. If we are not in
3✔
1463
        // development mode, this would be nil.
3✔
1464
        var devCfg *funding.DevConfig
3✔
1465
        if lncfg.IsDevBuild() {
6✔
1466
                devCfg = &funding.DevConfig{
3✔
1467
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1468
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1469
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1470
                }
3✔
1471

3✔
1472
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1473
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1474

3✔
1475
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1476
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1477
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1478
        }
3✔
1479

1480
        //nolint:ll
1481
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1482
                Dev:                devCfg,
3✔
1483
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1484
                IDKey:              nodeKeyDesc.PubKey,
3✔
1485
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1486
                Wallet:             cc.Wallet,
3✔
1487
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1488
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1489
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1490
                },
3✔
1491
                Notifier:     cc.ChainNotifier,
1492
                ChannelDB:    s.chanStateDB,
1493
                FeeEstimator: cc.FeeEstimator,
1494
                SignMessage:  cc.MsgSigner.SignMessage,
1495
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1496
                        error) {
3✔
1497

3✔
1498
                        return s.genNodeAnnouncement(nil)
3✔
1499
                },
3✔
1500
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1501
                NotifyWhenOnline:     s.NotifyWhenOnline,
1502
                TempChanIDSeed:       chanIDSeed,
1503
                FindChannel:          s.findChannel,
1504
                DefaultRoutingPolicy: cc.RoutingPolicy,
1505
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1506
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1507
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1508
                        // For large channels we increase the number
3✔
1509
                        // of confirmations we require for the
3✔
1510
                        // channel to be considered open. As it is
3✔
1511
                        // always the responder that gets to choose
3✔
1512
                        // value, the pushAmt is value being pushed
3✔
1513
                        // to us. This means we have more to lose
3✔
1514
                        // in the case this gets re-orged out, and
3✔
1515
                        // we will require more confirmations before
3✔
1516
                        // we consider it open.
3✔
1517

3✔
1518
                        // In case the user has explicitly specified
3✔
1519
                        // a default value for the number of
3✔
1520
                        // confirmations, we use it.
3✔
1521
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1522
                        if defaultConf != 0 {
6✔
1523
                                return defaultConf
3✔
1524
                        }
3✔
1525

1526
                        minConf := uint64(3)
×
1527
                        maxConf := uint64(6)
×
1528

×
1529
                        // If this is a wumbo channel, then we'll require the
×
1530
                        // max amount of confirmations.
×
1531
                        if chanAmt > MaxFundingAmount {
×
1532
                                return uint16(maxConf)
×
1533
                        }
×
1534

1535
                        // If not we return a value scaled linearly
1536
                        // between 3 and 6, depending on channel size.
1537
                        // TODO(halseth): Use 1 as minimum?
1538
                        maxChannelSize := uint64(
×
1539
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1540
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1541
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1542
                        if conf < minConf {
×
1543
                                conf = minConf
×
1544
                        }
×
1545
                        if conf > maxConf {
×
1546
                                conf = maxConf
×
1547
                        }
×
1548
                        return uint16(conf)
×
1549
                },
1550
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1551
                        // We scale the remote CSV delay (the time the
3✔
1552
                        // remote have to claim funds in case of a unilateral
3✔
1553
                        // close) linearly from minRemoteDelay blocks
3✔
1554
                        // for small channels, to maxRemoteDelay blocks
3✔
1555
                        // for channels of size MaxFundingAmount.
3✔
1556

3✔
1557
                        // In case the user has explicitly specified
3✔
1558
                        // a default value for the remote delay, we
3✔
1559
                        // use it.
3✔
1560
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1561
                        if defaultDelay > 0 {
6✔
1562
                                return defaultDelay
3✔
1563
                        }
3✔
1564

1565
                        // If this is a wumbo channel, then we'll require the
1566
                        // max value.
1567
                        if chanAmt > MaxFundingAmount {
×
1568
                                return maxRemoteDelay
×
1569
                        }
×
1570

1571
                        // If not we scale according to channel size.
1572
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1573
                                chanAmt / MaxFundingAmount)
×
1574
                        if delay < minRemoteDelay {
×
1575
                                delay = minRemoteDelay
×
1576
                        }
×
1577
                        if delay > maxRemoteDelay {
×
1578
                                delay = maxRemoteDelay
×
1579
                        }
×
1580
                        return delay
×
1581
                },
1582
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1583
                        peerKey *btcec.PublicKey) error {
3✔
1584

3✔
1585
                        // First, we'll mark this new peer as a persistent peer
3✔
1586
                        // for re-connection purposes. If the peer is not yet
3✔
1587
                        // tracked or the user hasn't requested it to be perm,
3✔
1588
                        // we'll set false to prevent the server from continuing
3✔
1589
                        // to connect to this peer even if the number of
3✔
1590
                        // channels with this peer is zero.
3✔
1591
                        s.mu.Lock()
3✔
1592
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1593
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1594
                                s.persistentPeers[pubStr] = false
3✔
1595
                        }
3✔
1596
                        s.mu.Unlock()
3✔
1597

3✔
1598
                        // With that taken care of, we'll send this channel to
3✔
1599
                        // the chain arb so it can react to on-chain events.
3✔
1600
                        return s.chainArb.WatchNewChannel(channel)
3✔
1601
                },
1602
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1603
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1604
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1605
                },
3✔
1606
                RequiredRemoteChanReserve: func(chanAmt,
1607
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1608

3✔
1609
                        // By default, we'll require the remote peer to maintain
3✔
1610
                        // at least 1% of the total channel capacity at all
3✔
1611
                        // times. If this value ends up dipping below the dust
3✔
1612
                        // limit, then we'll use the dust limit itself as the
3✔
1613
                        // reserve as required by BOLT #2.
3✔
1614
                        reserve := chanAmt / 100
3✔
1615
                        if reserve < dustLimit {
6✔
1616
                                reserve = dustLimit
3✔
1617
                        }
3✔
1618

1619
                        return reserve
3✔
1620
                },
1621
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1622
                        // By default, we'll allow the remote peer to fully
3✔
1623
                        // utilize the full bandwidth of the channel, minus our
3✔
1624
                        // required reserve.
3✔
1625
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1626
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1627
                },
3✔
1628
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1629
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1630
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1631
                        }
3✔
1632

1633
                        // By default, we'll permit them to utilize the full
1634
                        // channel bandwidth.
1635
                        return uint16(input.MaxHTLCNumber / 2)
×
1636
                },
1637
                ZombieSweeperInterval:         zombieSweeperInterval,
1638
                ReservationTimeout:            reservationTimeout,
1639
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1640
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1641
                MaxPendingChannels:            cfg.MaxPendingChannels,
1642
                RejectPush:                    cfg.RejectPush,
1643
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1644
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1645
                OpenChannelPredicate:          chanPredicate,
1646
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1647
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1648
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1649
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1650
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1651
                DeleteAliasEdge:      deleteAliasEdge,
1652
                AliasManager:         s.aliasMgr,
1653
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1654
                AuxFundingController: implCfg.AuxFundingController,
1655
                AuxSigner:            implCfg.AuxSigner,
1656
                AuxResolver:          implCfg.AuxContractResolver,
1657
        })
1658
        if err != nil {
3✔
1659
                return nil, err
×
1660
        }
×
1661

1662
        // Next, we'll assemble the sub-system that will maintain an on-disk
1663
        // static backup of the latest channel state.
1664
        chanNotifier := &channelNotifier{
3✔
1665
                chanNotifier: s.channelNotifier,
3✔
1666
                addrs:        s.addrSource,
3✔
1667
        }
3✔
1668
        backupFile := chanbackup.NewMultiFile(
3✔
1669
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1670
        )
3✔
1671
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1672
                ctx, s.chanStateDB, s.addrSource,
3✔
1673
        )
3✔
1674
        if err != nil {
3✔
1675
                return nil, err
×
1676
        }
×
1677
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1678
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1679
        )
3✔
1680
        if err != nil {
3✔
1681
                return nil, err
×
1682
        }
×
1683

1684
        // Assemble a peer notifier which will provide clients with subscriptions
1685
        // to peer online and offline events.
1686
        s.peerNotifier = peernotifier.New()
3✔
1687

3✔
1688
        // Create a channel event store which monitors all open channels.
3✔
1689
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1690
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1691
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1692
                },
3✔
1693
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1694
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1695
                },
3✔
1696
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1697
                Clock:           clock.NewDefaultClock(),
1698
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1699
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1700
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1701
        })
1702

1703
        if cfg.WtClient.Active {
6✔
1704
                policy := wtpolicy.DefaultPolicy()
3✔
1705
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1706

3✔
1707
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1708
                // protocol operations on sat/kw.
3✔
1709
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1710
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1711
                )
3✔
1712

3✔
1713
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1714

3✔
1715
                if err := policy.Validate(); err != nil {
3✔
1716
                        return nil, err
×
1717
                }
×
1718

1719
                // authDial is the wrapper around the btrontide.Dial for the
1720
                // watchtower.
1721
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1722
                        netAddr *lnwire.NetAddress,
3✔
1723
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1724

3✔
1725
                        return brontide.Dial(
3✔
1726
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1727
                        )
3✔
1728
                }
3✔
1729

1730
                // buildBreachRetribution is a call-back that can be used to
1731
                // query the BreachRetribution info and channel type given a
1732
                // channel ID and commitment height.
1733
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1734
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1735
                        channeldb.ChannelType, error) {
6✔
1736

3✔
1737
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1738
                                nil, chanID,
3✔
1739
                        )
3✔
1740
                        if err != nil {
3✔
1741
                                return nil, 0, err
×
1742
                        }
×
1743

1744
                        br, err := lnwallet.NewBreachRetribution(
3✔
1745
                                channel, commitHeight, 0, nil,
3✔
1746
                                implCfg.AuxLeafStore,
3✔
1747
                                implCfg.AuxContractResolver,
3✔
1748
                        )
3✔
1749
                        if err != nil {
3✔
1750
                                return nil, 0, err
×
1751
                        }
×
1752

1753
                        return br, channel.ChanType, nil
3✔
1754
                }
1755

1756
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1757

3✔
1758
                // Copy the policy for legacy channels and set the blob flag
3✔
1759
                // signalling support for anchor channels.
3✔
1760
                anchorPolicy := policy
3✔
1761
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1762

3✔
1763
                // Copy the policy for legacy channels and set the blob flag
3✔
1764
                // signalling support for taproot channels.
3✔
1765
                taprootPolicy := policy
3✔
1766
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1767
                        blob.FlagTaprootChannel,
3✔
1768
                )
3✔
1769

3✔
1770
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1771
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1772
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1773
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1774
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1775
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1776
                                error) {
6✔
1777

3✔
1778
                                return s.channelNotifier.
3✔
1779
                                        SubscribeChannelEvents()
3✔
1780
                        },
3✔
1781
                        Signer: cc.Wallet.Cfg.Signer,
1782
                        NewAddress: func() ([]byte, error) {
3✔
1783
                                addr, err := newSweepPkScriptGen(
3✔
1784
                                        cc.Wallet, netParams,
3✔
1785
                                )().Unpack()
3✔
1786
                                if err != nil {
3✔
1787
                                        return nil, err
×
1788
                                }
×
1789

1790
                                return addr.DeliveryAddress, nil
3✔
1791
                        },
1792
                        SecretKeyRing:      s.cc.KeyRing,
1793
                        Dial:               cfg.net.Dial,
1794
                        AuthDial:           authDial,
1795
                        DB:                 dbs.TowerClientDB,
1796
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1797
                        MinBackoff:         10 * time.Second,
1798
                        MaxBackoff:         5 * time.Minute,
1799
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1800
                }, policy, anchorPolicy, taprootPolicy)
1801
                if err != nil {
3✔
1802
                        return nil, err
×
1803
                }
×
1804
        }
1805

1806
        if len(cfg.ExternalHosts) != 0 {
3✔
1807
                advertisedIPs := make(map[string]struct{})
×
1808
                for _, addr := range s.currentNodeAnn.Addresses {
×
1809
                        advertisedIPs[addr.String()] = struct{}{}
×
1810
                }
×
1811

1812
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1813
                        Hosts:         cfg.ExternalHosts,
×
1814
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1815
                        LookupHost: func(host string) (net.Addr, error) {
×
1816
                                return lncfg.ParseAddressString(
×
1817
                                        host, strconv.Itoa(defaultPeerPort),
×
1818
                                        cfg.net.ResolveTCPAddr,
×
1819
                                )
×
1820
                        },
×
1821
                        AdvertisedIPs: advertisedIPs,
1822
                        AnnounceNewIPs: netann.IPAnnouncer(
1823
                                func(modifier ...netann.NodeAnnModifier) (
1824
                                        lnwire.NodeAnnouncement, error) {
×
1825

×
1826
                                        return s.genNodeAnnouncement(
×
1827
                                                nil, modifier...,
×
1828
                                        )
×
1829
                                }),
×
1830
                })
1831
        }
1832

1833
        // Create liveness monitor.
1834
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1835

3✔
1836
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1837
        for i, listenAddr := range listenAddrs {
6✔
1838
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1839
                // doesn't need to call the general lndResolveTCP function
3✔
1840
                // since we are resolving a local address.
3✔
1841

3✔
1842
                // RESOLVE: We are actually partially accepting inbound
3✔
1843
                // connection requests when we call NewListener.
3✔
1844
                listeners[i], err = brontide.NewListener(
3✔
1845
                        nodeKeyECDH, listenAddr.String(),
3✔
1846
                        // TODO(yy): remove this check and unify the inbound
3✔
1847
                        // connection check inside `InboundPeerConnected`.
3✔
1848
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1849
                )
3✔
1850
                if err != nil {
3✔
1851
                        return nil, err
×
1852
                }
×
1853
        }
1854

1855
        // Create the connection manager which will be responsible for
1856
        // maintaining persistent outbound connections and also accepting new
1857
        // incoming connections
1858
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1859
                Listeners:      listeners,
3✔
1860
                OnAccept:       s.InboundPeerConnected,
3✔
1861
                RetryDuration:  time.Second * 5,
3✔
1862
                TargetOutbound: 100,
3✔
1863
                Dial: noiseDial(
3✔
1864
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1865
                ),
3✔
1866
                OnConnection: s.OutboundPeerConnected,
3✔
1867
        })
3✔
1868
        if err != nil {
3✔
1869
                return nil, err
×
1870
        }
×
1871
        s.connMgr = cmgr
3✔
1872

3✔
1873
        // Finally, register the subsystems in blockbeat.
3✔
1874
        s.registerBlockConsumers()
3✔
1875

3✔
1876
        return s, nil
3✔
1877
}
1878

1879
// UpdateRoutingConfig is a callback function to update the routing config
1880
// values in the main cfg.
1881
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1882
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1883

3✔
1884
        switch c := cfg.Estimator.Config().(type) {
3✔
1885
        case routing.AprioriConfig:
3✔
1886
                routerCfg.ProbabilityEstimatorType =
3✔
1887
                        routing.AprioriEstimatorName
3✔
1888

3✔
1889
                targetCfg := routerCfg.AprioriConfig
3✔
1890
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1891
                targetCfg.Weight = c.AprioriWeight
3✔
1892
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1893
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1894

1895
        case routing.BimodalConfig:
3✔
1896
                routerCfg.ProbabilityEstimatorType =
3✔
1897
                        routing.BimodalEstimatorName
3✔
1898

3✔
1899
                targetCfg := routerCfg.BimodalConfig
3✔
1900
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1901
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1902
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1903
        }
1904

1905
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1906
}
1907

1908
// registerBlockConsumers registers the subsystems that consume block events.
1909
// By calling `RegisterQueue`, a list of subsystems are registered in the
1910
// blockbeat for block notifications. When a new block arrives, the subsystems
1911
// in the same queue are notified sequentially, and different queues are
1912
// notified concurrently.
1913
//
1914
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1915
// a new `RegisterQueue` call.
1916
func (s *server) registerBlockConsumers() {
3✔
1917
        // In this queue, when a new block arrives, it will be received and
3✔
1918
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1919
        consumers := []chainio.Consumer{
3✔
1920
                s.chainArb,
3✔
1921
                s.sweeper,
3✔
1922
                s.txPublisher,
3✔
1923
        }
3✔
1924
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1925
}
3✔
1926

1927
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1928
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1929
// may differ from what is on disk.
1930
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1931
        error) {
3✔
1932

3✔
1933
        data, err := u.DataToSign()
3✔
1934
        if err != nil {
3✔
1935
                return nil, err
×
1936
        }
×
1937

1938
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1939
}
1940

1941
// createLivenessMonitor creates a set of health checks using our configured
1942
// values and uses these checks to create a liveness monitor. Available
1943
// health checks,
1944
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1945
//   - diskCheck
1946
//   - tlsHealthCheck
1947
//   - torController, only created when tor is enabled.
1948
//
1949
// If a health check has been disabled by setting attempts to 0, our monitor
1950
// will not run it.
1951
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1952
        leaderElector cluster.LeaderElector) {
3✔
1953

3✔
1954
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1955
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1956
                srvrLog.Info("Disabling chain backend checks for " +
×
1957
                        "nochainbackend mode")
×
1958

×
1959
                chainBackendAttempts = 0
×
1960
        }
×
1961

1962
        chainHealthCheck := healthcheck.NewObservation(
3✔
1963
                "chain backend",
3✔
1964
                cc.HealthCheck,
3✔
1965
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1966
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1967
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1968
                chainBackendAttempts,
3✔
1969
        )
3✔
1970

3✔
1971
        diskCheck := healthcheck.NewObservation(
3✔
1972
                "disk space",
3✔
1973
                func() error {
3✔
1974
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1975
                                cfg.LndDir,
×
1976
                        )
×
1977
                        if err != nil {
×
1978
                                return err
×
1979
                        }
×
1980

1981
                        // If we have more free space than we require,
1982
                        // we return a nil error.
1983
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1984
                                return nil
×
1985
                        }
×
1986

1987
                        return fmt.Errorf("require: %v free space, got: %v",
×
1988
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1989
                                free)
×
1990
                },
1991
                cfg.HealthChecks.DiskCheck.Interval,
1992
                cfg.HealthChecks.DiskCheck.Timeout,
1993
                cfg.HealthChecks.DiskCheck.Backoff,
1994
                cfg.HealthChecks.DiskCheck.Attempts,
1995
        )
1996

1997
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1998
                "tls",
3✔
1999
                func() error {
3✔
2000
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2001
                                s.cc.KeyRing,
×
2002
                        )
×
2003
                        if err != nil {
×
2004
                                return err
×
2005
                        }
×
2006
                        if expired {
×
2007
                                return fmt.Errorf("TLS certificate is "+
×
2008
                                        "expired as of %v", expTime)
×
2009
                        }
×
2010

2011
                        // If the certificate is not outdated, no error needs
2012
                        // to be returned
2013
                        return nil
×
2014
                },
2015
                cfg.HealthChecks.TLSCheck.Interval,
2016
                cfg.HealthChecks.TLSCheck.Timeout,
2017
                cfg.HealthChecks.TLSCheck.Backoff,
2018
                cfg.HealthChecks.TLSCheck.Attempts,
2019
        )
2020

2021
        checks := []*healthcheck.Observation{
3✔
2022
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2023
        }
3✔
2024

3✔
2025
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2026
        if s.torController != nil {
3✔
2027
                torConnectionCheck := healthcheck.NewObservation(
×
2028
                        "tor connection",
×
2029
                        func() error {
×
2030
                                return healthcheck.CheckTorServiceStatus(
×
2031
                                        s.torController,
×
2032
                                        func() error {
×
2033
                                                return s.createNewHiddenService(
×
2034
                                                        context.TODO(),
×
2035
                                                )
×
2036
                                        },
×
2037
                                )
2038
                        },
2039
                        cfg.HealthChecks.TorConnection.Interval,
2040
                        cfg.HealthChecks.TorConnection.Timeout,
2041
                        cfg.HealthChecks.TorConnection.Backoff,
2042
                        cfg.HealthChecks.TorConnection.Attempts,
2043
                )
2044
                checks = append(checks, torConnectionCheck)
×
2045
        }
2046

2047
        // If remote signing is enabled, add the healthcheck for the remote
2048
        // signing RPC interface.
2049
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2050
                // Because we have two cascading timeouts here, we need to add
3✔
2051
                // some slack to the "outer" one of them in case the "inner"
3✔
2052
                // returns exactly on time.
3✔
2053
                overhead := time.Millisecond * 10
3✔
2054

3✔
2055
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2056
                        "remote signer connection",
3✔
2057
                        rpcwallet.HealthCheck(
3✔
2058
                                s.cfg.RemoteSigner,
3✔
2059

3✔
2060
                                // For the health check we might to be even
3✔
2061
                                // stricter than the initial/normal connect, so
3✔
2062
                                // we use the health check timeout here.
3✔
2063
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2064
                        ),
3✔
2065
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2066
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2067
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2068
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2069
                )
3✔
2070
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2071
        }
3✔
2072

2073
        // If we have a leader elector, we add a health check to ensure we are
2074
        // still the leader. During normal operation, we should always be the
2075
        // leader, but there are circumstances where this may change, such as
2076
        // when we lose network connectivity for long enough expiring out lease.
2077
        if leaderElector != nil {
3✔
2078
                leaderCheck := healthcheck.NewObservation(
×
2079
                        "leader status",
×
2080
                        func() error {
×
2081
                                // Check if we are still the leader. Note that
×
2082
                                // we don't need to use a timeout context here
×
2083
                                // as the healthcheck observer will handle the
×
2084
                                // timeout case for us.
×
2085
                                timeoutCtx, cancel := context.WithTimeout(
×
2086
                                        context.Background(),
×
2087
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2088
                                )
×
2089
                                defer cancel()
×
2090

×
2091
                                leader, err := leaderElector.IsLeader(
×
2092
                                        timeoutCtx,
×
2093
                                )
×
2094
                                if err != nil {
×
2095
                                        return fmt.Errorf("unable to check if "+
×
2096
                                                "still leader: %v", err)
×
2097
                                }
×
2098

2099
                                if !leader {
×
2100
                                        srvrLog.Debug("Not the current leader")
×
2101
                                        return fmt.Errorf("not the current " +
×
2102
                                                "leader")
×
2103
                                }
×
2104

2105
                                return nil
×
2106
                        },
2107
                        cfg.HealthChecks.LeaderCheck.Interval,
2108
                        cfg.HealthChecks.LeaderCheck.Timeout,
2109
                        cfg.HealthChecks.LeaderCheck.Backoff,
2110
                        cfg.HealthChecks.LeaderCheck.Attempts,
2111
                )
2112

2113
                checks = append(checks, leaderCheck)
×
2114
        }
2115

2116
        // If we have not disabled all of our health checks, we create a
2117
        // liveness monitor with our configured checks.
2118
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2119
                &healthcheck.Config{
3✔
2120
                        Checks:   checks,
3✔
2121
                        Shutdown: srvrLog.Criticalf,
3✔
2122
                },
3✔
2123
        )
3✔
2124
}
2125

2126
// Started returns true if the server has been started, and false otherwise.
2127
// NOTE: This function is safe for concurrent access.
2128
func (s *server) Started() bool {
3✔
2129
        return atomic.LoadInt32(&s.active) != 0
3✔
2130
}
3✔
2131

2132
// cleaner is used to aggregate "cleanup" functions during an operation that
2133
// starts several subsystems. In case one of the subsystem fails to start
2134
// and a proper resource cleanup is required, the "run" method achieves this
2135
// by running all these added "cleanup" functions.
2136
type cleaner []func() error
2137

2138
// add is used to add a cleanup function to be called when
2139
// the run function is executed.
2140
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2141
        return append(c, cleanup)
3✔
2142
}
3✔
2143

2144
// run is used to run all the previousely added cleanup functions.
2145
func (c cleaner) run() {
×
2146
        for i := len(c) - 1; i >= 0; i-- {
×
2147
                if err := c[i](); err != nil {
×
2148
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2149
                }
×
2150
        }
2151
}
2152

2153
// startLowLevelServices starts the low-level services of the server. These
2154
// services must be started successfully before running the main server. The
2155
// services are,
2156
// 1. the chain notifier.
2157
//
2158
// TODO(yy): identify and add more low-level services here.
2159
func (s *server) startLowLevelServices() error {
3✔
2160
        var startErr error
3✔
2161

3✔
2162
        cleanup := cleaner{}
3✔
2163

3✔
2164
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2165
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2166
                startErr = err
×
2167
        }
×
2168

2169
        if startErr != nil {
3✔
2170
                cleanup.run()
×
2171
        }
×
2172

2173
        return startErr
3✔
2174
}
2175

2176
// Start starts the main daemon server, all requested listeners, and any helper
2177
// goroutines.
2178
// NOTE: This function is safe for concurrent access.
2179
//
2180
//nolint:funlen
2181
func (s *server) Start(ctx context.Context) error {
3✔
2182
        // Get the current blockbeat.
3✔
2183
        beat, err := s.getStartingBeat()
3✔
2184
        if err != nil {
3✔
2185
                return err
×
2186
        }
×
2187

2188
        var startErr error
3✔
2189

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

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

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

2210
                if s.livenessMonitor != nil {
6✔
2211
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2212
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2213
                                startErr = err
×
2214
                                return
×
2215
                        }
×
2216
                }
2217

2218
                // Start the notification server. This is used so channel
2219
                // management goroutines can be notified when a funding
2220
                // transaction reaches a sufficient number of confirmations, or
2221
                // when the input for the funding transaction is spent in an
2222
                // attempt at an uncooperative close by the counterparty.
2223
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2224
                if err := s.sigPool.Start(); err != nil {
3✔
2225
                        startErr = err
×
2226
                        return
×
2227
                }
×
2228

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

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

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

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

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

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

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

2275
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2276
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2277
                        startErr = err
×
2278
                        return
×
2279
                }
×
2280

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

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

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

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

2305
                // htlcSwitch must be started before chainArb since the latter
2306
                // relies on htlcSwitch to deliver resolution message upon
2307
                // start.
2308
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2309
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2310
                        startErr = err
×
2311
                        return
×
2312
                }
×
2313

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

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

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

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

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

2344
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2345
                if err := s.chanRouter.Start(); err != nil {
3✔
2346
                        startErr = err
×
2347
                        return
×
2348
                }
×
2349
                // The authGossiper depends on the chanRouter and therefore
2350
                // should be started after it.
2351
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2352
                if err := s.authGossiper.Start(); err != nil {
3✔
2353
                        startErr = err
×
2354
                        return
×
2355
                }
×
2356

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

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

2369
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2370
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2371
                        startErr = err
×
2372
                        return
×
2373
                }
×
2374

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

2381
                cleanup.add(func() error {
3✔
2382
                        s.missionController.StopStoreTickers()
×
2383
                        return nil
×
2384
                })
×
2385
                s.missionController.RunStoreTickers()
3✔
2386

3✔
2387
                // Before we start the connMgr, we'll check to see if we have
3✔
2388
                // any backups to recover. We do this now as we want to ensure
3✔
2389
                // that have all the information we need to handle channel
3✔
2390
                // recovery _before_ we even accept connections from any peers.
3✔
2391
                chanRestorer := &chanDBRestorer{
3✔
2392
                        db:         s.chanStateDB,
3✔
2393
                        secretKeys: s.cc.KeyRing,
3✔
2394
                        chainArb:   s.chainArb,
3✔
2395
                }
3✔
2396
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2397
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2398
                                s.chansToRestore.PackedSingleChanBackups,
×
2399
                                s.cc.KeyRing, chanRestorer, s,
×
2400
                        )
×
2401
                        if err != nil {
×
2402
                                startErr = fmt.Errorf("unable to unpack single "+
×
2403
                                        "backups: %v", err)
×
2404
                                return
×
2405
                        }
×
2406
                }
2407
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2408
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2409
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2410
                                s.cc.KeyRing, chanRestorer, s,
3✔
2411
                        )
3✔
2412
                        if err != nil {
3✔
2413
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2414
                                        "backup: %v", err)
×
2415
                                return
×
2416
                        }
×
2417
                }
2418

2419
                // chanSubSwapper must be started after the `channelNotifier`
2420
                // because it depends on channel events as a synchronization
2421
                // point.
2422
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2423
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2424
                        startErr = err
×
2425
                        return
×
2426
                }
×
2427

2428
                if s.torController != nil {
3✔
2429
                        cleanup = cleanup.add(s.torController.Stop)
×
2430
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2431
                                startErr = err
×
2432
                                return
×
2433
                        }
×
2434
                }
2435

2436
                if s.natTraversal != nil {
3✔
2437
                        s.wg.Add(1)
×
2438
                        go s.watchExternalIP()
×
2439
                }
×
2440

2441
                // Start connmgr last to prevent connections before init.
2442
                cleanup = cleanup.add(func() error {
3✔
2443
                        s.connMgr.Stop()
×
2444
                        return nil
×
2445
                })
×
2446

2447
                // RESOLVE: s.connMgr.Start() is called here, but
2448
                // brontide.NewListener() is called in newServer. This means
2449
                // that we are actually listening and partially accepting
2450
                // inbound connections even before the connMgr starts.
2451
                //
2452
                // TODO(yy): move the log into the connMgr's `Start` method.
2453
                srvrLog.Info("connMgr starting...")
3✔
2454
                s.connMgr.Start()
3✔
2455
                srvrLog.Debug("connMgr started")
3✔
2456

3✔
2457
                // If peers are specified as a config option, we'll add those
3✔
2458
                // peers first.
3✔
2459
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2460
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2461
                                peerAddrCfg,
3✔
2462
                        )
3✔
2463
                        if err != nil {
3✔
2464
                                startErr = fmt.Errorf("unable to parse peer "+
×
2465
                                        "pubkey from config: %v", err)
×
2466
                                return
×
2467
                        }
×
2468
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2469
                        if err != nil {
3✔
2470
                                startErr = fmt.Errorf("unable to parse peer "+
×
2471
                                        "address provided as a config option: "+
×
2472
                                        "%v", err)
×
2473
                                return
×
2474
                        }
×
2475

2476
                        peerAddr := &lnwire.NetAddress{
3✔
2477
                                IdentityKey: parsedPubkey,
3✔
2478
                                Address:     addr,
3✔
2479
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2480
                        }
3✔
2481

3✔
2482
                        err = s.ConnectToPeer(
3✔
2483
                                peerAddr, true,
3✔
2484
                                s.cfg.ConnectionTimeout,
3✔
2485
                        )
3✔
2486
                        if err != nil {
3✔
2487
                                startErr = fmt.Errorf("unable to connect to "+
×
2488
                                        "peer address provided as a config "+
×
2489
                                        "option: %v", err)
×
2490
                                return
×
2491
                        }
×
2492
                }
2493

2494
                // Subscribe to NodeAnnouncements that advertise new addresses
2495
                // our persistent peers.
2496
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2497
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2498
                                "addr: %v", err)
×
2499

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

2504
                // With all the relevant sub-systems started, we'll now attempt
2505
                // to establish persistent connections to our direct channel
2506
                // collaborators within the network. Before doing so however,
2507
                // we'll prune our set of link nodes found within the database
2508
                // to ensure we don't reconnect to any nodes we no longer have
2509
                // open channels with.
2510
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2511
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2512

×
2513
                        startErr = err
×
2514
                        return
×
2515
                }
×
2516

2517
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2518
                        srvrLog.Errorf("Failed to establish persistent "+
×
2519
                                "connections: %v", err)
×
2520
                }
×
2521

2522
                // setSeedList is a helper function that turns multiple DNS seed
2523
                // server tuples from the command line or config file into the
2524
                // data structure we need and does a basic formal sanity check
2525
                // in the process.
2526
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2527
                        if len(tuples) == 0 {
×
2528
                                return
×
2529
                        }
×
2530

2531
                        result := make([][2]string, len(tuples))
×
2532
                        for idx, tuple := range tuples {
×
2533
                                tuple = strings.TrimSpace(tuple)
×
2534
                                if len(tuple) == 0 {
×
2535
                                        return
×
2536
                                }
×
2537

2538
                                servers := strings.Split(tuple, ",")
×
2539
                                if len(servers) > 2 || len(servers) == 0 {
×
2540
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2541
                                                "seed tuple: %v", servers)
×
2542
                                        return
×
2543
                                }
×
2544

2545
                                copy(result[idx][:], servers)
×
2546
                        }
2547

2548
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2549
                }
2550

2551
                // Let users overwrite the DNS seed nodes. We only allow them
2552
                // for bitcoin mainnet/testnet/signet.
2553
                if s.cfg.Bitcoin.MainNet {
3✔
2554
                        setSeedList(
×
2555
                                s.cfg.Bitcoin.DNSSeeds,
×
2556
                                chainreg.BitcoinMainnetGenesis,
×
2557
                        )
×
2558
                }
×
2559
                if s.cfg.Bitcoin.TestNet3 {
3✔
2560
                        setSeedList(
×
2561
                                s.cfg.Bitcoin.DNSSeeds,
×
2562
                                chainreg.BitcoinTestnetGenesis,
×
2563
                        )
×
2564
                }
×
2565
                if s.cfg.Bitcoin.TestNet4 {
3✔
2566
                        setSeedList(
×
2567
                                s.cfg.Bitcoin.DNSSeeds,
×
2568
                                chainreg.BitcoinTestnet4Genesis,
×
2569
                        )
×
2570
                }
×
2571
                if s.cfg.Bitcoin.SigNet {
3✔
2572
                        setSeedList(
×
2573
                                s.cfg.Bitcoin.DNSSeeds,
×
2574
                                chainreg.BitcoinSignetGenesis,
×
2575
                        )
×
2576
                }
×
2577

2578
                // If network bootstrapping hasn't been disabled, then we'll
2579
                // configure the set of active bootstrappers, and launch a
2580
                // dedicated goroutine to maintain a set of persistent
2581
                // connections.
2582
                if !s.cfg.NoNetBootstrap {
6✔
2583
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2584
                        if err != nil {
3✔
2585
                                startErr = err
×
2586
                                return
×
2587
                        }
×
2588

2589
                        s.wg.Add(1)
3✔
2590
                        go s.peerBootstrapper(
3✔
2591
                                ctx, defaultMinPeers, bootstrappers,
3✔
2592
                        )
3✔
2593
                } else {
3✔
2594
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2595
                }
3✔
2596

2597
                // Start the blockbeat after all other subsystems have been
2598
                // started so they are ready to receive new blocks.
2599
                cleanup = cleanup.add(func() error {
3✔
2600
                        s.blockbeatDispatcher.Stop()
×
2601
                        return nil
×
2602
                })
×
2603
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2604
                        startErr = err
×
2605
                        return
×
2606
                }
×
2607

2608
                // Set the active flag now that we've completed the full
2609
                // startup.
2610
                atomic.StoreInt32(&s.active, 1)
3✔
2611
        })
2612

2613
        if startErr != nil {
3✔
2614
                cleanup.run()
×
2615
        }
×
2616
        return startErr
3✔
2617
}
2618

2619
// Stop gracefully shutsdown the main daemon server. This function will signal
2620
// any active goroutines, or helper objects to exit, then blocks until they've
2621
// all successfully exited. Additionally, any/all listeners are closed.
2622
// NOTE: This function is safe for concurrent access.
2623
func (s *server) Stop() error {
3✔
2624
        s.stop.Do(func() {
6✔
2625
                atomic.StoreInt32(&s.stopping, 1)
3✔
2626

3✔
2627
                ctx := context.Background()
3✔
2628

3✔
2629
                close(s.quit)
3✔
2630

3✔
2631
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2632
                s.connMgr.Stop()
3✔
2633

3✔
2634
                // Stop dispatching blocks to other systems immediately.
3✔
2635
                s.blockbeatDispatcher.Stop()
3✔
2636

3✔
2637
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2638
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2639
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2640
                }
×
2641
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2642
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2643
                }
×
2644
                if err := s.sphinx.Stop(); err != nil {
3✔
2645
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2646
                }
×
2647
                if err := s.invoices.Stop(); err != nil {
3✔
2648
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2649
                }
×
2650
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2651
                        srvrLog.Warnf("failed to stop interceptable "+
×
2652
                                "switch: %v", err)
×
2653
                }
×
2654
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2655
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2656
                                "modifier: %v", err)
×
2657
                }
×
2658
                if err := s.chanRouter.Stop(); err != nil {
3✔
2659
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2660
                }
×
2661
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2662
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2663
                }
×
2664
                if err := s.graphDB.Stop(); err != nil {
3✔
2665
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2666
                }
×
2667
                if err := s.chainArb.Stop(); err != nil {
3✔
2668
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2669
                }
×
2670
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2671
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2672
                }
×
2673
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2674
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2675
                                err)
×
2676
                }
×
2677
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2678
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2679
                }
×
2680
                if err := s.authGossiper.Stop(); err != nil {
3✔
2681
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2682
                }
×
2683
                if err := s.sweeper.Stop(); err != nil {
3✔
2684
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2685
                }
×
2686
                if err := s.txPublisher.Stop(); err != nil {
3✔
2687
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2688
                }
×
2689
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2690
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2691
                }
×
2692
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2693
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2694
                }
×
2695
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2696
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2697
                }
×
2698

2699
                // Update channel.backup file. Make sure to do it before
2700
                // stopping chanSubSwapper.
2701
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2702
                        ctx, s.chanStateDB, s.addrSource,
3✔
2703
                )
3✔
2704
                if err != nil {
3✔
2705
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2706
                                err)
×
2707
                } else {
3✔
2708
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2709
                        if err != nil {
6✔
2710
                                srvrLog.Warnf("Manual update of channel "+
3✔
2711
                                        "backup failed: %v", err)
3✔
2712
                        }
3✔
2713
                }
2714

2715
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2716
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2717
                }
×
2718
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2719
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2720
                }
×
2721
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2722
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2723
                                err)
×
2724
                }
×
2725
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2726
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2727
                                err)
×
2728
                }
×
2729
                s.missionController.StopStoreTickers()
3✔
2730

3✔
2731
                // Disconnect from each active peers to ensure that
3✔
2732
                // peerTerminationWatchers signal completion to each peer.
3✔
2733
                for _, peer := range s.Peers() {
6✔
2734
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2735
                        if err != nil {
3✔
2736
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2737
                                        "received error: %v", peer.IdentityKey(),
×
2738
                                        err,
×
2739
                                )
×
2740
                        }
×
2741
                }
2742

2743
                // Now that all connections have been torn down, stop the tower
2744
                // client which will reliably flush all queued states to the
2745
                // tower. If this is halted for any reason, the force quit timer
2746
                // will kick in and abort to allow this method to return.
2747
                if s.towerClientMgr != nil {
6✔
2748
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2749
                                srvrLog.Warnf("Unable to shut down tower "+
×
2750
                                        "client manager: %v", err)
×
2751
                        }
×
2752
                }
2753

2754
                if s.hostAnn != nil {
3✔
2755
                        if err := s.hostAnn.Stop(); err != nil {
×
2756
                                srvrLog.Warnf("unable to shut down host "+
×
2757
                                        "annoucner: %v", err)
×
2758
                        }
×
2759
                }
2760

2761
                if s.livenessMonitor != nil {
6✔
2762
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2763
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2764
                                        "monitor: %v", err)
×
2765
                        }
×
2766
                }
2767

2768
                // Wait for all lingering goroutines to quit.
2769
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2770
                s.wg.Wait()
3✔
2771

3✔
2772
                srvrLog.Debug("Stopping buffer pools...")
3✔
2773
                s.sigPool.Stop()
3✔
2774
                s.writePool.Stop()
3✔
2775
                s.readPool.Stop()
3✔
2776
        })
2777

2778
        return nil
3✔
2779
}
2780

2781
// Stopped returns true if the server has been instructed to shutdown.
2782
// NOTE: This function is safe for concurrent access.
2783
func (s *server) Stopped() bool {
3✔
2784
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2785
}
3✔
2786

2787
// configurePortForwarding attempts to set up port forwarding for the different
2788
// ports that the server will be listening on.
2789
//
2790
// NOTE: This should only be used when using some kind of NAT traversal to
2791
// automatically set up forwarding rules.
2792
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2793
        ip, err := s.natTraversal.ExternalIP()
×
2794
        if err != nil {
×
2795
                return nil, err
×
2796
        }
×
2797
        s.lastDetectedIP = ip
×
2798

×
2799
        externalIPs := make([]string, 0, len(ports))
×
2800
        for _, port := range ports {
×
2801
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2802
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2803
                        continue
×
2804
                }
2805

2806
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2807
                externalIPs = append(externalIPs, hostIP)
×
2808
        }
2809

2810
        return externalIPs, nil
×
2811
}
2812

2813
// removePortForwarding attempts to clear the forwarding rules for the different
2814
// ports the server is currently listening on.
2815
//
2816
// NOTE: This should only be used when using some kind of NAT traversal to
2817
// automatically set up forwarding rules.
2818
func (s *server) removePortForwarding() {
×
2819
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2820
        for _, port := range forwardedPorts {
×
2821
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2822
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2823
                                "port %d: %v", port, err)
×
2824
                }
×
2825
        }
2826
}
2827

2828
// watchExternalIP continuously checks for an updated external IP address every
2829
// 15 minutes. Once a new IP address has been detected, it will automatically
2830
// handle port forwarding rules and send updated node announcements to the
2831
// currently connected peers.
2832
//
2833
// NOTE: This MUST be run as a goroutine.
2834
func (s *server) watchExternalIP() {
×
2835
        defer s.wg.Done()
×
2836

×
2837
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2838
        // up by the server.
×
2839
        defer s.removePortForwarding()
×
2840

×
2841
        // Keep track of the external IPs set by the user to avoid replacing
×
2842
        // them when detecting a new IP.
×
2843
        ipsSetByUser := make(map[string]struct{})
×
2844
        for _, ip := range s.cfg.ExternalIPs {
×
2845
                ipsSetByUser[ip.String()] = struct{}{}
×
2846
        }
×
2847

2848
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2849

×
2850
        ticker := time.NewTicker(15 * time.Minute)
×
2851
        defer ticker.Stop()
×
2852
out:
×
2853
        for {
×
2854
                select {
×
2855
                case <-ticker.C:
×
2856
                        // We'll start off by making sure a new IP address has
×
2857
                        // been detected.
×
2858
                        ip, err := s.natTraversal.ExternalIP()
×
2859
                        if err != nil {
×
2860
                                srvrLog.Debugf("Unable to retrieve the "+
×
2861
                                        "external IP address: %v", err)
×
2862
                                continue
×
2863
                        }
2864

2865
                        // Periodically renew the NAT port forwarding.
2866
                        for _, port := range forwardedPorts {
×
2867
                                err := s.natTraversal.AddPortMapping(port)
×
2868
                                if err != nil {
×
2869
                                        srvrLog.Warnf("Unable to automatically "+
×
2870
                                                "re-create port forwarding using %s: %v",
×
2871
                                                s.natTraversal.Name(), err)
×
2872
                                } else {
×
2873
                                        srvrLog.Debugf("Automatically re-created "+
×
2874
                                                "forwarding for port %d using %s to "+
×
2875
                                                "advertise external IP",
×
2876
                                                port, s.natTraversal.Name())
×
2877
                                }
×
2878
                        }
2879

2880
                        if ip.Equal(s.lastDetectedIP) {
×
2881
                                continue
×
2882
                        }
2883

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

×
2886
                        // Next, we'll craft the new addresses that will be
×
2887
                        // included in the new node announcement and advertised
×
2888
                        // to the network. Each address will consist of the new
×
2889
                        // IP detected and one of the currently advertised
×
2890
                        // ports.
×
2891
                        var newAddrs []net.Addr
×
2892
                        for _, port := range forwardedPorts {
×
2893
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2894
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2895
                                if err != nil {
×
2896
                                        srvrLog.Debugf("Unable to resolve "+
×
2897
                                                "host %v: %v", addr, err)
×
2898
                                        continue
×
2899
                                }
2900

2901
                                newAddrs = append(newAddrs, addr)
×
2902
                        }
2903

2904
                        // Skip the update if we weren't able to resolve any of
2905
                        // the new addresses.
2906
                        if len(newAddrs) == 0 {
×
2907
                                srvrLog.Debug("Skipping node announcement " +
×
2908
                                        "update due to not being able to " +
×
2909
                                        "resolve any new addresses")
×
2910
                                continue
×
2911
                        }
2912

2913
                        // Now, we'll need to update the addresses in our node's
2914
                        // announcement in order to propagate the update
2915
                        // throughout the network. We'll only include addresses
2916
                        // that have a different IP from the previous one, as
2917
                        // the previous IP is no longer valid.
2918
                        currentNodeAnn := s.getNodeAnnouncement()
×
2919

×
2920
                        for _, addr := range currentNodeAnn.Addresses {
×
2921
                                host, _, err := net.SplitHostPort(addr.String())
×
2922
                                if err != nil {
×
2923
                                        srvrLog.Debugf("Unable to determine "+
×
2924
                                                "host from address %v: %v",
×
2925
                                                addr, err)
×
2926
                                        continue
×
2927
                                }
2928

2929
                                // We'll also make sure to include external IPs
2930
                                // set manually by the user.
2931
                                _, setByUser := ipsSetByUser[addr.String()]
×
2932
                                if setByUser || host != s.lastDetectedIP.String() {
×
2933
                                        newAddrs = append(newAddrs, addr)
×
2934
                                }
×
2935
                        }
2936

2937
                        // Then, we'll generate a new timestamped node
2938
                        // announcement with the updated addresses and broadcast
2939
                        // it to our peers.
2940
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2941
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2942
                        )
×
2943
                        if err != nil {
×
2944
                                srvrLog.Debugf("Unable to generate new node "+
×
2945
                                        "announcement: %v", err)
×
2946
                                continue
×
2947
                        }
2948

2949
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2950
                        if err != nil {
×
2951
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2952
                                        "announcement to peers: %v", err)
×
2953
                                continue
×
2954
                        }
2955

2956
                        // Finally, update the last IP seen to the current one.
2957
                        s.lastDetectedIP = ip
×
2958
                case <-s.quit:
×
2959
                        break out
×
2960
                }
2961
        }
2962
}
2963

2964
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2965
// based on the server, and currently active bootstrap mechanisms as defined
2966
// within the current configuration.
2967
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2968
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2969

3✔
2970
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2971

3✔
2972
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2973
        // this can be used by default if we've already partially seeded the
3✔
2974
        // network.
3✔
2975
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2976
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2977
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2978
        )
3✔
2979
        if err != nil {
3✔
2980
                return nil, err
×
2981
        }
×
2982
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2983

3✔
2984
        // If this isn't using simnet or regtest mode, then one of our
3✔
2985
        // additional bootstrapping sources will be the set of running DNS
3✔
2986
        // seeds.
3✔
2987
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2988
                //nolint:ll
×
2989
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2990

×
2991
                // If we have a set of DNS seeds for this chain, then we'll add
×
2992
                // it as an additional bootstrapping source.
×
2993
                if ok {
×
2994
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2995
                                "seeds: %v", dnsSeeds)
×
2996

×
2997
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2998
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2999
                        )
×
3000
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3001
                }
×
3002
        }
3003

3004
        return bootStrappers, nil
3✔
3005
}
3006

3007
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3008
// needs to ignore, which is made of three parts,
3009
//   - the node itself needs to be skipped as it doesn't make sense to connect
3010
//     to itself.
3011
//   - the peers that already have connections with, as in s.peersByPub.
3012
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3013
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
3014
        s.mu.RLock()
3✔
3015
        defer s.mu.RUnlock()
3✔
3016

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

3✔
3019
        // We should ignore ourselves from bootstrapping.
3✔
3020
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3021
        ignore[selfKey] = struct{}{}
3✔
3022

3✔
3023
        // Ignore all connected peers.
3✔
3024
        for _, peer := range s.peersByPub {
3✔
3025
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3026
                ignore[nID] = struct{}{}
×
3027
        }
×
3028

3029
        // Ignore all persistent peers as they have a dedicated reconnecting
3030
        // process.
3031
        for pubKeyStr := range s.persistentPeers {
3✔
3032
                var nID autopilot.NodeID
×
3033
                copy(nID[:], []byte(pubKeyStr))
×
3034
                ignore[nID] = struct{}{}
×
3035
        }
×
3036

3037
        return ignore
3✔
3038
}
3039

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

3✔
3048
        defer s.wg.Done()
3✔
3049

3✔
3050
        // Before we continue, init the ignore peers map.
3✔
3051
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3052

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

3✔
3057
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3058
        // peers.
3✔
3059
        //
3✔
3060
        // We'll use a 15 second backoff, and double the time every time an
3✔
3061
        // epoch fails up to a ceiling.
3✔
3062
        backOff := time.Second * 15
3✔
3063

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

3✔
3069
        // We'll use the number of attempts and errors to determine if we need
3✔
3070
        // to increase the time between discovery epochs.
3✔
3071
        var epochErrors uint32 // To be used atomically.
3✔
3072
        var epochAttempts uint32
3✔
3073

3✔
3074
        for {
6✔
3075
                select {
3✔
3076
                // The ticker has just woken us up, so we'll need to check if
3077
                // we need to attempt to connect our to any more peers.
3078
                case <-sampleTicker.C:
×
3079
                        // Obtain the current number of peers, so we can gauge
×
3080
                        // if we need to sample more peers or not.
×
3081
                        s.mu.RLock()
×
3082
                        numActivePeers := uint32(len(s.peersByPub))
×
3083
                        s.mu.RUnlock()
×
3084

×
3085
                        // If we have enough peers, then we can loop back
×
3086
                        // around to the next round as we're done here.
×
3087
                        if numActivePeers >= numTargetPeers {
×
3088
                                continue
×
3089
                        }
3090

3091
                        // If all of our attempts failed during this last back
3092
                        // off period, then will increase our backoff to 5
3093
                        // minute ceiling to avoid an excessive number of
3094
                        // queries
3095
                        //
3096
                        // TODO(roasbeef): add reverse policy too?
3097

3098
                        if epochAttempts > 0 &&
×
3099
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3100

×
3101
                                sampleTicker.Stop()
×
3102

×
3103
                                backOff *= 2
×
3104
                                if backOff > bootstrapBackOffCeiling {
×
3105
                                        backOff = bootstrapBackOffCeiling
×
3106
                                }
×
3107

3108
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3109
                                        "%v", backOff)
×
3110
                                sampleTicker = time.NewTicker(backOff)
×
3111
                                continue
×
3112
                        }
3113

3114
                        atomic.StoreUint32(&epochErrors, 0)
×
3115
                        epochAttempts = 0
×
3116

×
3117
                        // Since we know need more peers, we'll compute the
×
3118
                        // exact number we need to reach our threshold.
×
3119
                        numNeeded := numTargetPeers - numActivePeers
×
3120

×
3121
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3122
                                "peers", numNeeded)
×
3123

×
3124
                        // With the number of peers we need calculated, we'll
×
3125
                        // query the network bootstrappers to sample a set of
×
3126
                        // random addrs for us.
×
3127
                        //
×
3128
                        // Before we continue, get a copy of the ignore peers
×
3129
                        // map.
×
3130
                        ignoreList = s.createBootstrapIgnorePeers()
×
3131

×
3132
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3133
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3134
                        )
×
3135
                        if err != nil {
×
3136
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3137
                                        "peers: %v", err)
×
3138
                                continue
×
3139
                        }
3140

3141
                        // Finally, we'll launch a new goroutine for each
3142
                        // prospective peer candidates.
3143
                        for _, addr := range peerAddrs {
×
3144
                                epochAttempts++
×
3145

×
3146
                                go func(a *lnwire.NetAddress) {
×
3147
                                        // TODO(roasbeef): can do AS, subnet,
×
3148
                                        // country diversity, etc
×
3149
                                        errChan := make(chan error, 1)
×
3150
                                        s.connectToPeer(
×
3151
                                                a, errChan,
×
3152
                                                s.cfg.ConnectionTimeout,
×
3153
                                        )
×
3154
                                        select {
×
3155
                                        case err := <-errChan:
×
3156
                                                if err == nil {
×
3157
                                                        return
×
3158
                                                }
×
3159

3160
                                                srvrLog.Errorf("Unable to "+
×
3161
                                                        "connect to %v: %v",
×
3162
                                                        a, err)
×
3163
                                                atomic.AddUint32(&epochErrors, 1)
×
3164
                                        case <-s.quit:
×
3165
                                        }
3166
                                }(addr)
3167
                        }
3168
                case <-s.quit:
3✔
3169
                        return
3✔
3170
                }
3171
        }
3172
}
3173

3174
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3175
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3176
// query back off each time we encounter a failure.
3177
const bootstrapBackOffCeiling = time.Minute * 5
3178

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

3✔
3186
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3187
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3188

3✔
3189
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3190
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3191
        var delaySignal <-chan time.Time
3✔
3192
        delayTime := time.Second * 2
3✔
3193

3✔
3194
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3195
        // then the main peer bootstrap logic.
3✔
3196
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3197

3✔
3198
        for attempts := 0; ; attempts++ {
6✔
3199
                // Check if the server has been requested to shut down in order
3✔
3200
                // to prevent blocking.
3✔
3201
                if s.Stopped() {
3✔
3202
                        return
×
3203
                }
×
3204

3205
                // We can exit our aggressive initial peer bootstrapping stage
3206
                // if we've reached out target number of peers.
3207
                s.mu.RLock()
3✔
3208
                numActivePeers := uint32(len(s.peersByPub))
3✔
3209
                s.mu.RUnlock()
3✔
3210

3✔
3211
                if numActivePeers >= numTargetPeers {
6✔
3212
                        return
3✔
3213
                }
3✔
3214

3215
                if attempts > 0 {
3✔
3216
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3217
                                "bootstrap peers (attempt #%v)", delayTime,
×
3218
                                attempts)
×
3219

×
3220
                        // We've completed at least one iterating and haven't
×
3221
                        // finished, so we'll start to insert a delay period
×
3222
                        // between each attempt.
×
3223
                        delaySignal = time.After(delayTime)
×
3224
                        select {
×
3225
                        case <-delaySignal:
×
3226
                        case <-s.quit:
×
3227
                                return
×
3228
                        }
3229

3230
                        // After our delay, we'll double the time we wait up to
3231
                        // the max back off period.
3232
                        delayTime *= 2
×
3233
                        if delayTime > backOffCeiling {
×
3234
                                delayTime = backOffCeiling
×
3235
                        }
×
3236
                }
3237

3238
                // Otherwise, we'll request for the remaining number of peers
3239
                // in order to reach our target.
3240
                peersNeeded := numTargetPeers - numActivePeers
3✔
3241
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3242
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3243
                )
3✔
3244
                if err != nil {
3✔
3245
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3246
                                "peers: %v", err)
×
3247
                        continue
×
3248
                }
3249

3250
                // Then, we'll attempt to establish a connection to the
3251
                // different peer addresses retrieved by our bootstrappers.
3252
                var wg sync.WaitGroup
3✔
3253
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3254
                        wg.Add(1)
3✔
3255
                        go func(addr *lnwire.NetAddress) {
6✔
3256
                                defer wg.Done()
3✔
3257

3✔
3258
                                errChan := make(chan error, 1)
3✔
3259
                                go s.connectToPeer(
3✔
3260
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3261
                                )
3✔
3262

3✔
3263
                                // We'll only allow this connection attempt to
3✔
3264
                                // take up to 3 seconds. This allows us to move
3✔
3265
                                // quickly by discarding peers that are slowing
3✔
3266
                                // us down.
3✔
3267
                                select {
3✔
3268
                                case err := <-errChan:
3✔
3269
                                        if err == nil {
6✔
3270
                                                return
3✔
3271
                                        }
3✔
3272
                                        srvrLog.Errorf("Unable to connect to "+
×
3273
                                                "%v: %v", addr, err)
×
3274
                                // TODO: tune timeout? 3 seconds might be *too*
3275
                                // aggressive but works well.
3276
                                case <-time.After(3 * time.Second):
×
3277
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3278
                                                "to not establishing a "+
×
3279
                                                "connection within 3 seconds",
×
3280
                                                addr)
×
3281
                                case <-s.quit:
×
3282
                                }
3283
                        }(bootstrapAddr)
3284
                }
3285

3286
                wg.Wait()
3✔
3287
        }
3288
}
3289

3290
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3291
// order to listen for inbound connections over Tor.
3292
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3293
        // Determine the different ports the server is listening on. The onion
×
3294
        // service's virtual port will map to these ports and one will be picked
×
3295
        // at random when the onion service is being accessed.
×
3296
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3297
        for _, listenAddr := range s.listenAddrs {
×
3298
                port := listenAddr.(*net.TCPAddr).Port
×
3299
                listenPorts = append(listenPorts, port)
×
3300
        }
×
3301

3302
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3303
        if err != nil {
×
3304
                return err
×
3305
        }
×
3306

3307
        // Once the port mapping has been set, we can go ahead and automatically
3308
        // create our onion service. The service's private key will be saved to
3309
        // disk in order to regain access to this service when restarting `lnd`.
3310
        onionCfg := tor.AddOnionConfig{
×
3311
                VirtualPort: defaultPeerPort,
×
3312
                TargetPorts: listenPorts,
×
3313
                Store: tor.NewOnionFile(
×
3314
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3315
                        encrypter,
×
3316
                ),
×
3317
        }
×
3318

×
3319
        switch {
×
3320
        case s.cfg.Tor.V2:
×
3321
                onionCfg.Type = tor.V2
×
3322
        case s.cfg.Tor.V3:
×
3323
                onionCfg.Type = tor.V3
×
3324
        }
3325

3326
        addr, err := s.torController.AddOnion(onionCfg)
×
3327
        if err != nil {
×
3328
                return err
×
3329
        }
×
3330

3331
        // Now that the onion service has been created, we'll add the onion
3332
        // address it can be reached at to our list of advertised addresses.
3333
        newNodeAnn, err := s.genNodeAnnouncement(
×
3334
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3335
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3336
                },
×
3337
        )
3338
        if err != nil {
×
3339
                return fmt.Errorf("unable to generate new node "+
×
3340
                        "announcement: %v", err)
×
3341
        }
×
3342

3343
        // Finally, we'll update the on-disk version of our announcement so it
3344
        // will eventually propagate to nodes in the network.
3345
        selfNode := &models.LightningNode{
×
3346
                HaveNodeAnnouncement: true,
×
3347
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3348
                Addresses:            newNodeAnn.Addresses,
×
3349
                Alias:                newNodeAnn.Alias.String(),
×
3350
                Features: lnwire.NewFeatureVector(
×
3351
                        newNodeAnn.Features, lnwire.Features,
×
3352
                ),
×
3353
                Color:        newNodeAnn.RGBColor,
×
3354
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3355
        }
×
3356
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3357
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3358
                return fmt.Errorf("can't set self node: %w", err)
×
3359
        }
×
3360

3361
        return nil
×
3362
}
3363

3364
// findChannel finds a channel given a public key and ChannelID. It is an
3365
// optimization that is quicker than seeking for a channel given only the
3366
// ChannelID.
3367
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3368
        *channeldb.OpenChannel, error) {
3✔
3369

3✔
3370
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3371
        if err != nil {
3✔
3372
                return nil, err
×
3373
        }
×
3374

3375
        for _, channel := range nodeChans {
6✔
3376
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3377
                        return channel, nil
3✔
3378
                }
3✔
3379
        }
3380

3381
        return nil, fmt.Errorf("unable to find channel")
3✔
3382
}
3383

3384
// getNodeAnnouncement fetches the current, fully signed node announcement.
3385
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3386
        s.mu.Lock()
3✔
3387
        defer s.mu.Unlock()
3✔
3388

3✔
3389
        return *s.currentNodeAnn
3✔
3390
}
3✔
3391

3392
// genNodeAnnouncement generates and returns the current fully signed node
3393
// announcement. The time stamp of the announcement will be updated in order
3394
// to ensure it propagates through the network.
3395
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3396
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3397

3✔
3398
        s.mu.Lock()
3✔
3399
        defer s.mu.Unlock()
3✔
3400

3✔
3401
        // Create a shallow copy of the current node announcement to work on.
3✔
3402
        // This ensures the original announcement remains unchanged
3✔
3403
        // until the new announcement is fully signed and valid.
3✔
3404
        newNodeAnn := *s.currentNodeAnn
3✔
3405

3✔
3406
        // First, try to update our feature manager with the updated set of
3✔
3407
        // features.
3✔
3408
        if features != nil {
6✔
3409
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3410
                        feature.SetNodeAnn: features,
3✔
3411
                }
3✔
3412
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3413
                if err != nil {
6✔
3414
                        return lnwire.NodeAnnouncement{}, err
3✔
3415
                }
3✔
3416

3417
                // If we could successfully update our feature manager, add
3418
                // an update modifier to include these new features to our
3419
                // set.
3420
                modifiers = append(
3✔
3421
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3422
                )
3✔
3423
        }
3424

3425
        // Always update the timestamp when refreshing to ensure the update
3426
        // propagates.
3427
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3428

3✔
3429
        // Apply the requested changes to the node announcement.
3✔
3430
        for _, modifier := range modifiers {
6✔
3431
                modifier(&newNodeAnn)
3✔
3432
        }
3✔
3433

3434
        // Sign a new update after applying all of the passed modifiers.
3435
        err := netann.SignNodeAnnouncement(
3✔
3436
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3437
        )
3✔
3438
        if err != nil {
3✔
3439
                return lnwire.NodeAnnouncement{}, err
×
3440
        }
×
3441

3442
        // If signing succeeds, update the current announcement.
3443
        *s.currentNodeAnn = newNodeAnn
3✔
3444

3✔
3445
        return *s.currentNodeAnn, nil
3✔
3446
}
3447

3448
// updateAndBroadcastSelfNode generates a new node announcement
3449
// applying the giving modifiers and updating the time stamp
3450
// to ensure it propagates through the network. Then it broadcasts
3451
// it to the network.
3452
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3453
        features *lnwire.RawFeatureVector,
3454
        modifiers ...netann.NodeAnnModifier) error {
3✔
3455

3✔
3456
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3457
        if err != nil {
6✔
3458
                return fmt.Errorf("unable to generate new node "+
3✔
3459
                        "announcement: %v", err)
3✔
3460
        }
3✔
3461

3462
        // Update the on-disk version of our announcement.
3463
        // Load and modify self node istead of creating anew instance so we
3464
        // don't risk overwriting any existing values.
3465
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3466
        if err != nil {
3✔
3467
                return fmt.Errorf("unable to get current source node: %w", err)
×
3468
        }
×
3469

3470
        selfNode.HaveNodeAnnouncement = true
3✔
3471
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3472
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3473
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3474
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3475
        selfNode.Color = newNodeAnn.RGBColor
3✔
3476
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3477

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

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

3484
        // Finally, propagate it to the nodes in the network.
3485
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3486
        if err != nil {
3✔
3487
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3488
                        "announcement to peers: %v", err)
×
3489
                return err
×
3490
        }
×
3491

3492
        return nil
3✔
3493
}
3494

3495
type nodeAddresses struct {
3496
        pubKey    *btcec.PublicKey
3497
        addresses []net.Addr
3498
}
3499

3500
// establishPersistentConnections attempts to establish persistent connections
3501
// to all our direct channel collaborators. In order to promote liveness of our
3502
// active channels, we instruct the connection manager to attempt to establish
3503
// and maintain persistent connections to all our direct channel counterparties.
3504
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3505
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3506
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3507
        // since other PubKey forms can't be compared.
3✔
3508
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3509

3✔
3510
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3511
        // attempt to connect to based on our set of previous connections. Set
3✔
3512
        // the reconnection port to the default peer port.
3✔
3513
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3514
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3515
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3516
        }
×
3517

3518
        for _, node := range linkNodes {
6✔
3519
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3520
                nodeAddrs := &nodeAddresses{
3✔
3521
                        pubKey:    node.IdentityPub,
3✔
3522
                        addresses: node.Addresses,
3✔
3523
                }
3✔
3524
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3525
        }
3✔
3526

3527
        // After checking our previous connections for addresses to connect to,
3528
        // iterate through the nodes in our channel graph to find addresses
3529
        // that have been added via NodeAnnouncement messages.
3530
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3531
        // each of the nodes.
3532
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3533
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3534
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3535

3✔
3536
                // If the remote party has announced the channel to us, but we
3✔
3537
                // haven't yet, then we won't have a policy. However, we don't
3✔
3538
                // need this to connect to the peer, so we'll log it and move on.
3✔
3539
                if !havePolicy {
3✔
3540
                        srvrLog.Warnf("No channel policy found for "+
×
3541
                                "ChannelPoint(%v): ", chanPoint)
×
3542
                }
×
3543

3544
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3545

3✔
3546
                // Add all unique addresses from channel
3✔
3547
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3548
                // connect to for this peer.
3✔
3549
                addrSet := make(map[string]net.Addr)
3✔
3550
                for _, addr := range channelPeer.Addresses {
6✔
3551
                        switch addr.(type) {
3✔
3552
                        case *net.TCPAddr:
3✔
3553
                                addrSet[addr.String()] = addr
3✔
3554

3555
                        // We'll only attempt to connect to Tor addresses if Tor
3556
                        // outbound support is enabled.
3557
                        case *tor.OnionAddr:
×
3558
                                if s.cfg.Tor.Active {
×
3559
                                        addrSet[addr.String()] = addr
×
3560
                                }
×
3561
                        }
3562
                }
3563

3564
                // If this peer is also recorded as a link node, we'll add any
3565
                // additional addresses that have not already been selected.
3566
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3567
                if ok {
6✔
3568
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3569
                                switch lnAddress.(type) {
3✔
3570
                                case *net.TCPAddr:
3✔
3571
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3572

3573
                                // We'll only attempt to connect to Tor
3574
                                // addresses if Tor outbound support is enabled.
3575
                                case *tor.OnionAddr:
×
3576
                                        if s.cfg.Tor.Active {
×
3577
                                                //nolint:ll
×
3578
                                                addrSet[lnAddress.String()] = lnAddress
×
3579
                                        }
×
3580
                                }
3581
                        }
3582
                }
3583

3584
                // Construct a slice of the deduped addresses.
3585
                var addrs []net.Addr
3✔
3586
                for _, addr := range addrSet {
6✔
3587
                        addrs = append(addrs, addr)
3✔
3588
                }
3✔
3589

3590
                n := &nodeAddresses{
3✔
3591
                        addresses: addrs,
3✔
3592
                }
3✔
3593
                n.pubKey, err = channelPeer.PubKey()
3✔
3594
                if err != nil {
3✔
3595
                        return err
×
3596
                }
×
3597

3598
                graphAddrs[pubStr] = n
3✔
3599
                return nil
3✔
3600
        }
3601
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3602
                ctx, forEachSrcNodeChan, func() {
6✔
3603
                        clear(graphAddrs)
3✔
3604
                },
3✔
3605
        )
3606
        if err != nil {
3✔
3607
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3608
                        "%v", err)
×
3609

×
3610
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3611
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3612

×
3613
                        return err
×
3614
                }
×
3615
        }
3616

3617
        // Combine the addresses from the link nodes and the channel graph.
3618
        for pubStr, nodeAddr := range graphAddrs {
6✔
3619
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3620
        }
3✔
3621

3622
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3623
                len(nodeAddrsMap))
3✔
3624

3✔
3625
        // Acquire and hold server lock until all persistent connection requests
3✔
3626
        // have been recorded and sent to the connection manager.
3✔
3627
        s.mu.Lock()
3✔
3628
        defer s.mu.Unlock()
3✔
3629

3✔
3630
        // Iterate through the combined list of addresses from prior links and
3✔
3631
        // node announcements and attempt to reconnect to each node.
3✔
3632
        var numOutboundConns int
3✔
3633
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3634
                // Add this peer to the set of peers we should maintain a
3✔
3635
                // persistent connection with. We set the value to false to
3✔
3636
                // indicate that we should not continue to reconnect if the
3✔
3637
                // number of channels returns to zero, since this peer has not
3✔
3638
                // been requested as perm by the user.
3✔
3639
                s.persistentPeers[pubStr] = false
3✔
3640
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3641
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3642
                }
3✔
3643

3644
                for _, address := range nodeAddr.addresses {
6✔
3645
                        // Create a wrapper address which couples the IP and
3✔
3646
                        // the pubkey so the brontide authenticated connection
3✔
3647
                        // can be established.
3✔
3648
                        lnAddr := &lnwire.NetAddress{
3✔
3649
                                IdentityKey: nodeAddr.pubKey,
3✔
3650
                                Address:     address,
3✔
3651
                        }
3✔
3652

3✔
3653
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3654
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3655
                }
3✔
3656

3657
                // We'll connect to the first 10 peers immediately, then
3658
                // randomly stagger any remaining connections if the
3659
                // stagger initial reconnect flag is set. This ensures
3660
                // that mobile nodes or nodes with a small number of
3661
                // channels obtain connectivity quickly, but larger
3662
                // nodes are able to disperse the costs of connecting to
3663
                // all peers at once.
3664
                if numOutboundConns < numInstantInitReconnect ||
3✔
3665
                        !s.cfg.StaggerInitialReconnect {
6✔
3666

3✔
3667
                        go s.connectToPersistentPeer(pubStr)
3✔
3668
                } else {
3✔
3669
                        go s.delayInitialReconnect(pubStr)
×
3670
                }
×
3671

3672
                numOutboundConns++
3✔
3673
        }
3674

3675
        return nil
3✔
3676
}
3677

3678
// delayInitialReconnect will attempt a reconnection to the given peer after
3679
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3680
//
3681
// NOTE: This method MUST be run as a goroutine.
3682
func (s *server) delayInitialReconnect(pubStr string) {
×
3683
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3684
        select {
×
3685
        case <-time.After(delay):
×
3686
                s.connectToPersistentPeer(pubStr)
×
3687
        case <-s.quit:
×
3688
        }
3689
}
3690

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

3✔
3697
        s.mu.Lock()
3✔
3698
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3699
                delete(s.persistentPeers, pubKeyStr)
3✔
3700
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3701
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3702
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3703
                s.mu.Unlock()
3✔
3704

3✔
3705
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3706
                        "peer has no open channels", compressedPubKey)
3✔
3707

3✔
3708
                return
3✔
3709
        }
3✔
3710
        s.mu.Unlock()
3✔
3711
}
3712

3713
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3714
// is instead used to remove persistent peer state for a peer that has been
3715
// disconnected for good cause by the server. Currently, a gossip ban from
3716
// sending garbage and the server running out of restricted-access
3717
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3718
// future, this function may expand when more ban criteria is added.
3719
//
3720
// NOTE: The server's write lock MUST be held when this is called.
3721
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3722
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3723
                delete(s.persistentPeers, remotePub)
×
3724
                delete(s.persistentPeersBackoff, remotePub)
×
3725
                delete(s.persistentPeerAddrs, remotePub)
×
3726
                s.cancelConnReqs(remotePub, nil)
×
3727
        }
×
3728
}
3729

3730
// BroadcastMessage sends a request to the server to broadcast a set of
3731
// messages to all peers other than the one specified by the `skips` parameter.
3732
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3733
// the target peers.
3734
//
3735
// NOTE: This function is safe for concurrent access.
3736
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3737
        msgs ...lnwire.Message) error {
3✔
3738

3✔
3739
        // Filter out peers found in the skips map. We synchronize access to
3✔
3740
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3741
        // exact set of peers present at the time of invocation.
3✔
3742
        s.mu.RLock()
3✔
3743
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3744
        for pubStr, sPeer := range s.peersByPub {
6✔
3745
                if skips != nil {
6✔
3746
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3747
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3748
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3749
                                continue
3✔
3750
                        }
3751
                }
3752

3753
                peers = append(peers, sPeer)
3✔
3754
        }
3755
        s.mu.RUnlock()
3✔
3756

3✔
3757
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3758
        // all messages to each of peers.
3✔
3759
        var wg sync.WaitGroup
3✔
3760
        for _, sPeer := range peers {
6✔
3761
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3762
                        sPeer.PubKey())
3✔
3763

3✔
3764
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3765
                wg.Add(1)
3✔
3766
                s.wg.Add(1)
3✔
3767
                go func(p lnpeer.Peer) {
6✔
3768
                        defer s.wg.Done()
3✔
3769
                        defer wg.Done()
3✔
3770

3✔
3771
                        p.SendMessageLazy(false, msgs...)
3✔
3772
                }(sPeer)
3✔
3773
        }
3774

3775
        // Wait for all messages to have been dispatched before returning to
3776
        // caller.
3777
        wg.Wait()
3✔
3778

3✔
3779
        return nil
3✔
3780
}
3781

3782
// NotifyWhenOnline can be called by other subsystems to get notified when a
3783
// particular peer comes online. The peer itself is sent across the peerChan.
3784
//
3785
// NOTE: This function is safe for concurrent access.
3786
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3787
        peerChan chan<- lnpeer.Peer) {
3✔
3788

3✔
3789
        s.mu.Lock()
3✔
3790

3✔
3791
        // Compute the target peer's identifier.
3✔
3792
        pubStr := string(peerKey[:])
3✔
3793

3✔
3794
        // Check if peer is connected.
3✔
3795
        peer, ok := s.peersByPub[pubStr]
3✔
3796
        if ok {
6✔
3797
                // Unlock here so that the mutex isn't held while we are
3✔
3798
                // waiting for the peer to become active.
3✔
3799
                s.mu.Unlock()
3✔
3800

3✔
3801
                // Wait until the peer signals that it is actually active
3✔
3802
                // rather than only in the server's maps.
3✔
3803
                select {
3✔
3804
                case <-peer.ActiveSignal():
3✔
UNCOV
3805
                case <-peer.QuitSignal():
×
UNCOV
3806
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3807
                        // and return.
×
UNCOV
3808
                        s.mu.Lock()
×
UNCOV
3809
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3810
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3811
                        )
×
UNCOV
3812
                        s.mu.Unlock()
×
UNCOV
3813
                        return
×
3814
                }
3815

3816
                // Connected, can return early.
3817
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3818

3✔
3819
                select {
3✔
3820
                case peerChan <- peer:
3✔
3821
                case <-s.quit:
×
3822
                }
3823

3824
                return
3✔
3825
        }
3826

3827
        // Not connected, store this listener such that it can be notified when
3828
        // the peer comes online.
3829
        s.peerConnectedListeners[pubStr] = append(
3✔
3830
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3831
        )
3✔
3832
        s.mu.Unlock()
3✔
3833
}
3834

3835
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3836
// the given public key has been disconnected. The notification is signaled by
3837
// closing the channel returned.
3838
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3839
        s.mu.Lock()
3✔
3840
        defer s.mu.Unlock()
3✔
3841

3✔
3842
        c := make(chan struct{})
3✔
3843

3✔
3844
        // If the peer is already offline, we can immediately trigger the
3✔
3845
        // notification.
3✔
3846
        peerPubKeyStr := string(peerPubKey[:])
3✔
3847
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3848
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3849
                close(c)
×
3850
                return c
×
3851
        }
×
3852

3853
        // Otherwise, the peer is online, so we'll keep track of the channel to
3854
        // trigger the notification once the server detects the peer
3855
        // disconnects.
3856
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3857
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3858
        )
3✔
3859

3✔
3860
        return c
3✔
3861
}
3862

3863
// FindPeer will return the peer that corresponds to the passed in public key.
3864
// This function is used by the funding manager, allowing it to update the
3865
// daemon's local representation of the remote peer.
3866
//
3867
// NOTE: This function is safe for concurrent access.
3868
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3869
        s.mu.RLock()
3✔
3870
        defer s.mu.RUnlock()
3✔
3871

3✔
3872
        pubStr := string(peerKey.SerializeCompressed())
3✔
3873

3✔
3874
        return s.findPeerByPubStr(pubStr)
3✔
3875
}
3✔
3876

3877
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3878
// which should be a string representation of the peer's serialized, compressed
3879
// public key.
3880
//
3881
// NOTE: This function is safe for concurrent access.
3882
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3883
        s.mu.RLock()
3✔
3884
        defer s.mu.RUnlock()
3✔
3885

3✔
3886
        return s.findPeerByPubStr(pubStr)
3✔
3887
}
3✔
3888

3889
// findPeerByPubStr is an internal method that retrieves the specified peer from
3890
// the server's internal state using.
3891
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3892
        peer, ok := s.peersByPub[pubStr]
3✔
3893
        if !ok {
6✔
3894
                return nil, ErrPeerNotConnected
3✔
3895
        }
3✔
3896

3897
        return peer, nil
3✔
3898
}
3899

3900
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3901
// exponential backoff. If no previous backoff was known, the default is
3902
// returned.
3903
func (s *server) nextPeerBackoff(pubStr string,
3904
        startTime time.Time) time.Duration {
3✔
3905

3✔
3906
        // Now, determine the appropriate backoff to use for the retry.
3✔
3907
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3908
        if !ok {
6✔
3909
                // If an existing backoff was unknown, use the default.
3✔
3910
                return s.cfg.MinBackoff
3✔
3911
        }
3✔
3912

3913
        // If the peer failed to start properly, we'll just use the previous
3914
        // backoff to compute the subsequent randomized exponential backoff
3915
        // duration. This will roughly double on average.
3916
        if startTime.IsZero() {
3✔
3917
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3918
        }
×
3919

3920
        // The peer succeeded in starting. If the connection didn't last long
3921
        // enough to be considered stable, we'll continue to back off retries
3922
        // with this peer.
3923
        connDuration := time.Since(startTime)
3✔
3924
        if connDuration < defaultStableConnDuration {
6✔
3925
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3926
        }
3✔
3927

3928
        // The peer succeed in starting and this was stable peer, so we'll
3929
        // reduce the timeout duration by the length of the connection after
3930
        // applying randomized exponential backoff. We'll only apply this in the
3931
        // case that:
3932
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3933
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3934
        if relaxedBackoff > s.cfg.MinBackoff {
×
3935
                return relaxedBackoff
×
3936
        }
×
3937

3938
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3939
        // the stable connection lasted much longer than our previous backoff.
3940
        // To reward such good behavior, we'll reconnect after the default
3941
        // timeout.
3942
        return s.cfg.MinBackoff
×
3943
}
3944

3945
// shouldDropLocalConnection determines if our local connection to a remote peer
3946
// should be dropped in the case of concurrent connection establishment. In
3947
// order to deterministically decide which connection should be dropped, we'll
3948
// utilize the ordering of the local and remote public key. If we didn't use
3949
// such a tie breaker, then we risk _both_ connections erroneously being
3950
// dropped.
3951
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3952
        localPubBytes := local.SerializeCompressed()
×
3953
        remotePubPbytes := remote.SerializeCompressed()
×
3954

×
3955
        // The connection that comes from the node with a "smaller" pubkey
×
3956
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3957
        // should drop our established connection.
×
3958
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3959
}
×
3960

3961
// InboundPeerConnected initializes a new peer in response to a new inbound
3962
// connection.
3963
//
3964
// NOTE: This function is safe for concurrent access.
3965
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3966
        // Exit early if we have already been instructed to shutdown, this
3✔
3967
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3968
        if s.Stopped() {
3✔
3969
                return
×
3970
        }
×
3971

3972
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3973
        pubSer := nodePub.SerializeCompressed()
3✔
3974
        pubStr := string(pubSer)
3✔
3975

3✔
3976
        var pubBytes [33]byte
3✔
3977
        copy(pubBytes[:], pubSer)
3✔
3978

3✔
3979
        s.mu.Lock()
3✔
3980
        defer s.mu.Unlock()
3✔
3981

3✔
3982
        // If we already have an outbound connection to this peer, then ignore
3✔
3983
        // this new connection.
3✔
3984
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3985
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3986
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3987
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3988

3✔
3989
                conn.Close()
3✔
3990
                return
3✔
3991
        }
3✔
3992

3993
        // If we already have a valid connection that is scheduled to take
3994
        // precedence once the prior peer has finished disconnecting, we'll
3995
        // ignore this connection.
3996
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3997
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3998
                        "scheduled", conn.RemoteAddr(), p)
×
3999
                conn.Close()
×
4000
                return
×
4001
        }
×
4002

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

3✔
4005
        // Check to see if we already have a connection with this peer. If so,
3✔
4006
        // we may need to drop our existing connection. This prevents us from
3✔
4007
        // having duplicate connections to the same peer. We forgo adding a
3✔
4008
        // default case as we expect these to be the only error values returned
3✔
4009
        // from findPeerByPubStr.
3✔
4010
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4011
        switch err {
3✔
4012
        case ErrPeerNotConnected:
3✔
4013
                // We were unable to locate an existing connection with the
3✔
4014
                // target peer, proceed to connect.
3✔
4015
                s.cancelConnReqs(pubStr, nil)
3✔
4016
                s.peerConnected(conn, nil, true)
3✔
4017

4018
        case nil:
3✔
4019
                ctx := btclog.WithCtx(
3✔
4020
                        context.TODO(),
3✔
4021
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4022
                )
3✔
4023

3✔
4024
                // We already have a connection with the incoming peer. If the
3✔
4025
                // connection we've already established should be kept and is
3✔
4026
                // not of the same type of the new connection (inbound), then
3✔
4027
                // we'll close out the new connection s.t there's only a single
3✔
4028
                // connection between us.
3✔
4029
                localPub := s.identityECDH.PubKey()
3✔
4030
                if !connectedPeer.Inbound() &&
3✔
4031
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4032

×
4033
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4034
                                "peer, but already have outbound "+
×
4035
                                "connection, dropping conn",
×
4036
                                fmt.Errorf("already have outbound conn"))
×
4037
                        conn.Close()
×
4038
                        return
×
4039
                }
×
4040

4041
                // Otherwise, if we should drop the connection, then we'll
4042
                // disconnect our already connected peer.
4043
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4044

3✔
4045
                s.cancelConnReqs(pubStr, nil)
3✔
4046

3✔
4047
                // Remove the current peer from the server's internal state and
3✔
4048
                // signal that the peer termination watcher does not need to
3✔
4049
                // execute for this peer.
3✔
4050
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4051
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4052
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4053
                        s.peerConnected(conn, nil, true)
3✔
4054
                }
3✔
4055
        }
4056
}
4057

4058
// OutboundPeerConnected initializes a new peer in response to a new outbound
4059
// connection.
4060
// NOTE: This function is safe for concurrent access.
4061
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4062
        // Exit early if we have already been instructed to shutdown, this
3✔
4063
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4064
        if s.Stopped() {
3✔
4065
                return
×
4066
        }
×
4067

4068
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4069
        pubSer := nodePub.SerializeCompressed()
3✔
4070
        pubStr := string(pubSer)
3✔
4071

3✔
4072
        var pubBytes [33]byte
3✔
4073
        copy(pubBytes[:], pubSer)
3✔
4074

3✔
4075
        s.mu.Lock()
3✔
4076
        defer s.mu.Unlock()
3✔
4077

3✔
4078
        // If we already have an inbound connection to this peer, then ignore
3✔
4079
        // this new connection.
3✔
4080
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4081
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4082
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4083
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4084

3✔
4085
                if connReq != nil {
6✔
4086
                        s.connMgr.Remove(connReq.ID())
3✔
4087
                }
3✔
4088
                conn.Close()
3✔
4089
                return
3✔
4090
        }
4091
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4092
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4093
                s.connMgr.Remove(connReq.ID())
×
4094
                conn.Close()
×
4095
                return
×
4096
        }
×
4097

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

×
4104
                if connReq != nil {
×
4105
                        s.connMgr.Remove(connReq.ID())
×
4106
                }
×
4107

4108
                conn.Close()
×
4109
                return
×
4110
        }
4111

4112
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4113
                conn.RemoteAddr())
3✔
4114

3✔
4115
        if connReq != nil {
6✔
4116
                // A successful connection was returned by the connmgr.
3✔
4117
                // Immediately cancel all pending requests, excluding the
3✔
4118
                // outbound connection we just established.
3✔
4119
                ignore := connReq.ID()
3✔
4120
                s.cancelConnReqs(pubStr, &ignore)
3✔
4121
        } else {
6✔
4122
                // This was a successful connection made by some other
3✔
4123
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4124
                s.cancelConnReqs(pubStr, nil)
3✔
4125
        }
3✔
4126

4127
        // If we already have a connection with this peer, decide whether or not
4128
        // we need to drop the stale connection. We forgo adding a default case
4129
        // as we expect these to be the only error values returned from
4130
        // findPeerByPubStr.
4131
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4132
        switch err {
3✔
4133
        case ErrPeerNotConnected:
3✔
4134
                // We were unable to locate an existing connection with the
3✔
4135
                // target peer, proceed to connect.
3✔
4136
                s.peerConnected(conn, connReq, false)
3✔
4137

4138
        case nil:
3✔
4139
                ctx := btclog.WithCtx(
3✔
4140
                        context.TODO(),
3✔
4141
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4142
                )
3✔
4143

3✔
4144
                // We already have a connection with the incoming peer. If the
3✔
4145
                // connection we've already established should be kept and is
3✔
4146
                // not of the same type of the new connection (outbound), then
3✔
4147
                // we'll close out the new connection s.t there's only a single
3✔
4148
                // connection between us.
3✔
4149
                localPub := s.identityECDH.PubKey()
3✔
4150
                if connectedPeer.Inbound() &&
3✔
4151
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4152

×
4153
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4154
                                "to peer, but already have inbound "+
×
4155
                                "connection, dropping conn",
×
4156
                                fmt.Errorf("already have inbound conn"))
×
4157
                        if connReq != nil {
×
4158
                                s.connMgr.Remove(connReq.ID())
×
4159
                        }
×
4160
                        conn.Close()
×
4161
                        return
×
4162
                }
4163

4164
                // Otherwise, _their_ connection should be dropped. So we'll
4165
                // disconnect the peer and send the now obsolete peer to the
4166
                // server for garbage collection.
4167
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4168

3✔
4169
                // Remove the current peer from the server's internal state and
3✔
4170
                // signal that the peer termination watcher does not need to
3✔
4171
                // execute for this peer.
3✔
4172
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4173
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4174
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4175
                        s.peerConnected(conn, connReq, false)
3✔
4176
                }
3✔
4177
        }
4178
}
4179

4180
// UnassignedConnID is the default connection ID that a request can have before
4181
// it actually is submitted to the connmgr.
4182
// TODO(conner): move into connmgr package, or better, add connmgr method for
4183
// generating atomic IDs
4184
const UnassignedConnID uint64 = 0
4185

4186
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4187
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4188
// Afterwards, each connection request removed from the connmgr. The caller can
4189
// optionally specify a connection ID to ignore, which prevents us from
4190
// canceling a successful request. All persistent connreqs for the provided
4191
// pubkey are discarded after the operationjw.
4192
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4193
        // First, cancel any lingering persistent retry attempts, which will
3✔
4194
        // prevent retries for any with backoffs that are still maturing.
3✔
4195
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4196
                close(cancelChan)
3✔
4197
                delete(s.persistentRetryCancels, pubStr)
3✔
4198
        }
3✔
4199

4200
        // Next, check to see if we have any outstanding persistent connection
4201
        // requests to this peer. If so, then we'll remove all of these
4202
        // connection requests, and also delete the entry from the map.
4203
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4204
        if !ok {
6✔
4205
                return
3✔
4206
        }
3✔
4207

4208
        for _, connReq := range connReqs {
6✔
4209
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4210

3✔
4211
                // Atomically capture the current request identifier.
3✔
4212
                connID := connReq.ID()
3✔
4213

3✔
4214
                // Skip any zero IDs, this indicates the request has not
3✔
4215
                // yet been schedule.
3✔
4216
                if connID == UnassignedConnID {
3✔
4217
                        continue
×
4218
                }
4219

4220
                // Skip a particular connection ID if instructed.
4221
                if skip != nil && connID == *skip {
6✔
4222
                        continue
3✔
4223
                }
4224

4225
                s.connMgr.Remove(connID)
3✔
4226
        }
4227

4228
        delete(s.persistentConnReqs, pubStr)
3✔
4229
}
4230

4231
// handleCustomMessage dispatches an incoming custom peers message to
4232
// subscribers.
4233
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4234
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4235
                peer, msg.Type)
3✔
4236

3✔
4237
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4238
                Peer: peer,
3✔
4239
                Msg:  msg,
3✔
4240
        })
3✔
4241
}
3✔
4242

4243
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4244
// messages.
4245
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4246
        return s.customMessageServer.Subscribe()
3✔
4247
}
3✔
4248

4249
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4250
// the channelNotifier's NotifyOpenChannelEvent.
4251
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4252
        remotePub *btcec.PublicKey) {
3✔
4253

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

4260
        // Notify subscribers about this open channel event.
4261
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4262
}
4263

4264
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4265
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4266
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4267
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4268

3✔
4269
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4270
        // peer.
3✔
4271
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4272
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4273
                        "channel[%v] pending open",
×
4274
                        remotePub.SerializeCompressed(), op)
×
4275
        }
×
4276

4277
        // Notify subscribers about this event.
4278
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4279
}
4280

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

3✔
4286
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4287
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4288
        if err != nil {
3✔
4289
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4290
                        "channel[%v] pending close",
×
4291
                        remotePub.SerializeCompressed(), op)
×
4292
        }
×
4293

4294
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4295
                // If we encounter an error while attempting to disconnect the
×
4296
                // peer, log the error.
×
4297
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4298
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4299
                }
×
4300
        }
4301

4302
        // Notify subscribers about this event.
4303
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4304
}
4305

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

3✔
4313
        brontideConn := conn.(*brontide.Conn)
3✔
4314
        addr := conn.RemoteAddr()
3✔
4315
        pubKey := brontideConn.RemotePub()
3✔
4316

3✔
4317
        // Only restrict access for inbound connections, which means if the
3✔
4318
        // remote node's public key is banned or the restricted slots are used
3✔
4319
        // up, we will drop the connection.
3✔
4320
        //
3✔
4321
        // TODO(yy): Consider perform this check in
3✔
4322
        // `peerAccessMan.addPeerAccess`.
3✔
4323
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4324
        if inbound && err != nil {
3✔
4325
                pubSer := pubKey.SerializeCompressed()
×
4326

×
4327
                // Clean up the persistent peer maps if we're dropping this
×
4328
                // connection.
×
4329
                s.bannedPersistentPeerConnection(string(pubSer))
×
4330

×
4331
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4332
                        "of restricted-access connection slots: %v.", pubSer,
×
4333
                        err)
×
4334

×
4335
                conn.Close()
×
4336

×
4337
                return
×
4338
        }
×
4339

4340
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4341
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4342

3✔
4343
        peerAddr := &lnwire.NetAddress{
3✔
4344
                IdentityKey: pubKey,
3✔
4345
                Address:     addr,
3✔
4346
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4347
        }
3✔
4348

3✔
4349
        // With the brontide connection established, we'll now craft the feature
3✔
4350
        // vectors to advertise to the remote node.
3✔
4351
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4352
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4353

3✔
4354
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4355
        // found, create a fresh buffer.
3✔
4356
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4357
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4358
        if !ok {
6✔
4359
                var err error
3✔
4360
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4361
                if err != nil {
3✔
4362
                        srvrLog.Errorf("unable to create peer %v", err)
×
4363
                        return
×
4364
                }
×
4365
        }
4366

4367
        // If we directly set the peer.Config TowerClient member to the
4368
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4369
        // the peer.Config's TowerClient member will not evaluate to nil even
4370
        // though the underlying value is nil. To avoid this gotcha which can
4371
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4372
        // TowerClient if needed.
4373
        var towerClient wtclient.ClientManager
3✔
4374
        if s.towerClientMgr != nil {
6✔
4375
                towerClient = s.towerClientMgr
3✔
4376
        }
3✔
4377

4378
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4379
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4380

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

3✔
4424
                        return s.genNodeAnnouncement(nil)
3✔
4425
                },
3✔
4426

4427
                PongBuf: s.pongBuf,
4428

4429
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4430

4431
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4432

4433
                FundingManager: s.fundingMgr,
4434

4435
                Hodl:                    s.cfg.Hodl,
4436
                UnsafeReplay:            s.cfg.UnsafeReplay,
4437
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4438
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4439
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4440
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4441
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4442
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4443
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4444
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4445
                HandleCustomMessage:    s.handleCustomMessage,
4446
                GetAliases:             s.aliasMgr.GetAliases,
4447
                RequestAlias:           s.aliasMgr.RequestAlias,
4448
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4449
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4450
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4451
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4452
                MaxFeeExposure:         thresholdMSats,
4453
                Quit:                   s.quit,
4454
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4455
                AuxSigner:              s.implCfg.AuxSigner,
4456
                MsgRouter:              s.implCfg.MsgRouter,
4457
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4458
                AuxResolver:            s.implCfg.AuxContractResolver,
4459
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4460
                ShouldFwdExpEndorsement: func() bool {
3✔
4461
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4462
                                return false
3✔
4463
                        }
3✔
4464

4465
                        return clock.NewDefaultClock().Now().Before(
3✔
4466
                                EndorsementExperimentEnd,
3✔
4467
                        )
3✔
4468
                },
4469
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4470
        }
4471

4472
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4473
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4474

3✔
4475
        p := peer.NewBrontide(pCfg)
3✔
4476

3✔
4477
        // Update the access manager with the access permission for this peer.
3✔
4478
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4479

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

3✔
4483
        s.addPeer(p)
3✔
4484

3✔
4485
        // Once we have successfully added the peer to the server, we can
3✔
4486
        // delete the previous error buffer from the server's map of error
3✔
4487
        // buffers.
3✔
4488
        delete(s.peerErrors, pkStr)
3✔
4489

3✔
4490
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4491
        // includes sending and receiving Init messages, which would be a DOS
3✔
4492
        // vector if we held the server's mutex throughout the procedure.
3✔
4493
        s.wg.Add(1)
3✔
4494
        go s.peerInitializer(p)
3✔
4495
}
4496

4497
// addPeer adds the passed peer to the server's global state of all active
4498
// peers.
4499
func (s *server) addPeer(p *peer.Brontide) {
3✔
4500
        if p == nil {
3✔
4501
                return
×
4502
        }
×
4503

4504
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4505

3✔
4506
        // Ignore new peers if we're shutting down.
3✔
4507
        if s.Stopped() {
3✔
4508
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4509
                        pubBytes)
×
4510
                p.Disconnect(ErrServerShuttingDown)
×
4511

×
4512
                return
×
4513
        }
×
4514

4515
        // Track the new peer in our indexes so we can quickly look it up either
4516
        // according to its public key, or its peer ID.
4517
        // TODO(roasbeef): pipe all requests through to the
4518
        // queryHandler/peerManager
4519

4520
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4521
        // be human-readable.
4522
        pubStr := string(pubBytes)
3✔
4523

3✔
4524
        s.peersByPub[pubStr] = p
3✔
4525

3✔
4526
        if p.Inbound() {
6✔
4527
                s.inboundPeers[pubStr] = p
3✔
4528
        } else {
6✔
4529
                s.outboundPeers[pubStr] = p
3✔
4530
        }
3✔
4531

4532
        // Inform the peer notifier of a peer online event so that it can be reported
4533
        // to clients listening for peer events.
4534
        var pubKey [33]byte
3✔
4535
        copy(pubKey[:], pubBytes)
3✔
4536
}
4537

4538
// peerInitializer asynchronously starts a newly connected peer after it has
4539
// been added to the server's peer map. This method sets up a
4540
// peerTerminationWatcher for the given peer, and ensures that it executes even
4541
// if the peer failed to start. In the event of a successful connection, this
4542
// method reads the negotiated, local feature-bits and spawns the appropriate
4543
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4544
// be signaled of the new peer once the method returns.
4545
//
4546
// NOTE: This MUST be launched as a goroutine.
4547
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4548
        defer s.wg.Done()
3✔
4549

3✔
4550
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4551

3✔
4552
        // Avoid initializing peers while the server is exiting.
3✔
4553
        if s.Stopped() {
3✔
4554
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4555
                        pubBytes)
×
4556
                return
×
4557
        }
×
4558

4559
        // Create a channel that will be used to signal a successful start of
4560
        // the link. This prevents the peer termination watcher from beginning
4561
        // its duty too early.
4562
        ready := make(chan struct{})
3✔
4563

3✔
4564
        // Before starting the peer, launch a goroutine to watch for the
3✔
4565
        // unexpected termination of this peer, which will ensure all resources
3✔
4566
        // are properly cleaned up, and re-establish persistent connections when
3✔
4567
        // necessary. The peer termination watcher will be short circuited if
3✔
4568
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4569
        // that the server has already handled the removal of this peer.
3✔
4570
        s.wg.Add(1)
3✔
4571
        go s.peerTerminationWatcher(p, ready)
3✔
4572

3✔
4573
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4574
        // will unblock the peerTerminationWatcher.
3✔
4575
        if err := p.Start(); err != nil {
6✔
4576
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4577

3✔
4578
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4579
                return
3✔
4580
        }
3✔
4581

4582
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4583
        // was successful, and to begin watching the peer's wait group.
4584
        close(ready)
3✔
4585

3✔
4586
        s.mu.Lock()
3✔
4587
        defer s.mu.Unlock()
3✔
4588

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

3✔
4592
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4593
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4594
        pubStr := string(pubBytes)
3✔
4595
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4596
                select {
3✔
4597
                case peerChan <- p:
3✔
4598
                case <-s.quit:
×
4599
                        return
×
4600
                }
4601
        }
4602
        delete(s.peerConnectedListeners, pubStr)
3✔
4603

3✔
4604
        // Since the peer has been fully initialized, now it's time to notify
3✔
4605
        // the RPC about the peer online event.
3✔
4606
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4607
}
4608

4609
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4610
// and then cleans up all resources allocated to the peer, notifies relevant
4611
// sub-systems of its demise, and finally handles re-connecting to the peer if
4612
// it's persistent. If the server intentionally disconnects a peer, it should
4613
// have a corresponding entry in the ignorePeerTermination map which will cause
4614
// the cleanup routine to exit early. The passed `ready` chan is used to
4615
// synchronize when WaitForDisconnect should begin watching on the peer's
4616
// waitgroup. The ready chan should only be signaled if the peer starts
4617
// successfully, otherwise the peer should be disconnected instead.
4618
//
4619
// NOTE: This MUST be launched as a goroutine.
4620
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4621
        defer s.wg.Done()
3✔
4622

3✔
4623
        ctx := btclog.WithCtx(
3✔
4624
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4625
        )
3✔
4626

3✔
4627
        p.WaitForDisconnect(ready)
3✔
4628

3✔
4629
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4630

3✔
4631
        // If the server is exiting then we can bail out early ourselves as all
3✔
4632
        // the other sub-systems will already be shutting down.
3✔
4633
        if s.Stopped() {
6✔
4634
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4635
                return
3✔
4636
        }
3✔
4637

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

3✔
4644
        pubKey := p.IdentityKey()
3✔
4645

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

3✔
4650
        // Tell the switch to remove all links associated with this peer.
3✔
4651
        // Passing nil as the target link indicates that all links associated
3✔
4652
        // with this interface should be closed.
3✔
4653
        //
3✔
4654
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4655
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4656
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4657
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4658
        }
×
4659

4660
        for _, link := range links {
6✔
4661
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4662
        }
3✔
4663

4664
        s.mu.Lock()
3✔
4665
        defer s.mu.Unlock()
3✔
4666

3✔
4667
        // If there were any notification requests for when this peer
3✔
4668
        // disconnected, we can trigger them now.
3✔
4669
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4670
        pubStr := string(pubKey.SerializeCompressed())
3✔
4671
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4672
                close(offlineChan)
3✔
4673
        }
3✔
4674
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4675

3✔
4676
        // If the server has already removed this peer, we can short circuit the
3✔
4677
        // peer termination watcher and skip cleanup.
3✔
4678
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4679
                delete(s.ignorePeerTermination, p)
3✔
4680

3✔
4681
                pubKey := p.PubKey()
3✔
4682
                pubStr := string(pubKey[:])
3✔
4683

3✔
4684
                // If a connection callback is present, we'll go ahead and
3✔
4685
                // execute it now that previous peer has fully disconnected. If
3✔
4686
                // the callback is not present, this likely implies the peer was
3✔
4687
                // purposefully disconnected via RPC, and that no reconnect
3✔
4688
                // should be attempted.
3✔
4689
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4690
                if ok {
6✔
4691
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4692
                        connCallback()
3✔
4693
                }
3✔
4694
                return
3✔
4695
        }
4696

4697
        // First, cleanup any remaining state the server has regarding the peer
4698
        // in question.
4699
        s.removePeerUnsafe(ctx, p)
3✔
4700

3✔
4701
        // Next, check to see if this is a persistent peer or not.
3✔
4702
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4703
                return
3✔
4704
        }
3✔
4705

4706
        // Get the last address that we used to connect to the peer.
4707
        addrs := []net.Addr{
3✔
4708
                p.NetAddress().Address,
3✔
4709
        }
3✔
4710

3✔
4711
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4712
        // reconnection purposes.
3✔
4713
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4714
        switch {
3✔
4715
        // We found advertised addresses, so use them.
4716
        case err == nil:
3✔
4717
                addrs = advertisedAddrs
3✔
4718

4719
        // The peer doesn't have an advertised address.
4720
        case err == errNoAdvertisedAddr:
3✔
4721
                // If it is an outbound peer then we fall back to the existing
3✔
4722
                // peer address.
3✔
4723
                if !p.Inbound() {
6✔
4724
                        break
3✔
4725
                }
4726

4727
                // Fall back to the existing peer address if
4728
                // we're not accepting connections over Tor.
4729
                if s.torController == nil {
6✔
4730
                        break
3✔
4731
                }
4732

4733
                // If we are, the peer's address won't be known
4734
                // to us (we'll see a private address, which is
4735
                // the address used by our onion service to dial
4736
                // to lnd), so we don't have enough information
4737
                // to attempt a reconnect.
4738
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4739
                        "to inbound peer without advertised address")
×
4740
                return
×
4741

4742
        // We came across an error retrieving an advertised
4743
        // address, log it, and fall back to the existing peer
4744
        // address.
4745
        default:
3✔
4746
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4747
                        "address for peer", err)
3✔
4748
        }
4749

4750
        // Make an easy lookup map so that we can check if an address
4751
        // is already in the address list that we have stored for this peer.
4752
        existingAddrs := make(map[string]bool)
3✔
4753
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4754
                existingAddrs[addr.String()] = true
3✔
4755
        }
3✔
4756

4757
        // Add any missing addresses for this peer to persistentPeerAddr.
4758
        for _, addr := range addrs {
6✔
4759
                if existingAddrs[addr.String()] {
3✔
4760
                        continue
×
4761
                }
4762

4763
                s.persistentPeerAddrs[pubStr] = append(
3✔
4764
                        s.persistentPeerAddrs[pubStr],
3✔
4765
                        &lnwire.NetAddress{
3✔
4766
                                IdentityKey: p.IdentityKey(),
3✔
4767
                                Address:     addr,
3✔
4768
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4769
                        },
3✔
4770
                )
3✔
4771
        }
4772

4773
        // Record the computed backoff in the backoff map.
4774
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4775
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4776

3✔
4777
        // Initialize a retry canceller for this peer if one does not
3✔
4778
        // exist.
3✔
4779
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4780
        if !ok {
6✔
4781
                cancelChan = make(chan struct{})
3✔
4782
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4783
        }
3✔
4784

4785
        // We choose not to wait group this go routine since the Connect
4786
        // call can stall for arbitrarily long if we shutdown while an
4787
        // outbound connection attempt is being made.
4788
        go func() {
6✔
4789
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4790
                        "re-establishment to persistent peer",
3✔
4791
                        "reconnecting_in", backoff)
3✔
4792

3✔
4793
                select {
3✔
4794
                case <-time.After(backoff):
3✔
4795
                case <-cancelChan:
3✔
4796
                        return
3✔
4797
                case <-s.quit:
3✔
4798
                        return
3✔
4799
                }
4800

4801
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4802
                        "connection")
3✔
4803

3✔
4804
                s.connectToPersistentPeer(pubStr)
3✔
4805
        }()
4806
}
4807

4808
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4809
// to connect to the peer. It creates connection requests if there are
4810
// currently none for a given address and it removes old connection requests
4811
// if the associated address is no longer in the latest address list for the
4812
// peer.
4813
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4814
        s.mu.Lock()
3✔
4815
        defer s.mu.Unlock()
3✔
4816

3✔
4817
        // Create an easy lookup map of the addresses we have stored for the
3✔
4818
        // peer. We will remove entries from this map if we have existing
3✔
4819
        // connection requests for the associated address and then any leftover
3✔
4820
        // entries will indicate which addresses we should create new
3✔
4821
        // connection requests for.
3✔
4822
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4823
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4824
                addrMap[addr.String()] = addr
3✔
4825
        }
3✔
4826

4827
        // Go through each of the existing connection requests and
4828
        // check if they correspond to the latest set of addresses. If
4829
        // there is a connection requests that does not use one of the latest
4830
        // advertised addresses then remove that connection request.
4831
        var updatedConnReqs []*connmgr.ConnReq
3✔
4832
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4833
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4834

3✔
4835
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4836
                // If the existing connection request is using one of the
4837
                // latest advertised addresses for the peer then we add it to
4838
                // updatedConnReqs and remove the associated address from
4839
                // addrMap so that we don't recreate this connReq later on.
4840
                case true:
×
4841
                        updatedConnReqs = append(
×
4842
                                updatedConnReqs, connReq,
×
4843
                        )
×
4844
                        delete(addrMap, lnAddr)
×
4845

4846
                // If the existing connection request is using an address that
4847
                // is not one of the latest advertised addresses for the peer
4848
                // then we remove the connecting request from the connection
4849
                // manager.
4850
                case false:
3✔
4851
                        srvrLog.Info(
3✔
4852
                                "Removing conn req:", connReq.Addr.String(),
3✔
4853
                        )
3✔
4854
                        s.connMgr.Remove(connReq.ID())
3✔
4855
                }
4856
        }
4857

4858
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4859

3✔
4860
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4861
        if !ok {
6✔
4862
                cancelChan = make(chan struct{})
3✔
4863
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4864
        }
3✔
4865

4866
        // Any addresses left in addrMap are new ones that we have not made
4867
        // connection requests for. So create new connection requests for those.
4868
        // If there is more than one address in the address map, stagger the
4869
        // creation of the connection requests for those.
4870
        go func() {
6✔
4871
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4872
                defer ticker.Stop()
3✔
4873

3✔
4874
                for _, addr := range addrMap {
6✔
4875
                        // Send the persistent connection request to the
3✔
4876
                        // connection manager, saving the request itself so we
3✔
4877
                        // can cancel/restart the process as needed.
3✔
4878
                        connReq := &connmgr.ConnReq{
3✔
4879
                                Addr:      addr,
3✔
4880
                                Permanent: true,
3✔
4881
                        }
3✔
4882

3✔
4883
                        s.mu.Lock()
3✔
4884
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4885
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4886
                        )
3✔
4887
                        s.mu.Unlock()
3✔
4888

3✔
4889
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4890
                                "channel peer %v", addr)
3✔
4891

3✔
4892
                        go s.connMgr.Connect(connReq)
3✔
4893

3✔
4894
                        select {
3✔
4895
                        case <-s.quit:
3✔
4896
                                return
3✔
4897
                        case <-cancelChan:
3✔
4898
                                return
3✔
4899
                        case <-ticker.C:
3✔
4900
                        }
4901
                }
4902
        }()
4903
}
4904

4905
// removePeerUnsafe removes the passed peer from the server's state of all
4906
// active peers.
4907
//
4908
// NOTE: Server mutex must be held when calling this function.
4909
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4910
        if p == nil {
3✔
4911
                return
×
4912
        }
×
4913

4914
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4915

3✔
4916
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4917
        // will be disconnected in the server shutdown process.
3✔
4918
        if s.Stopped() {
3✔
4919
                return
×
4920
        }
×
4921

4922
        // Capture the peer's public key and string representation.
4923
        pKey := p.PubKey()
3✔
4924
        pubSer := pKey[:]
3✔
4925
        pubStr := string(pubSer)
3✔
4926

3✔
4927
        delete(s.peersByPub, pubStr)
3✔
4928

3✔
4929
        if p.Inbound() {
6✔
4930
                delete(s.inboundPeers, pubStr)
3✔
4931
        } else {
6✔
4932
                delete(s.outboundPeers, pubStr)
3✔
4933
        }
3✔
4934

4935
        // When removing the peer we make sure to disconnect it asynchronously
4936
        // to avoid blocking the main server goroutine because it is holding the
4937
        // server's mutex. Disconnecting the peer might block and wait until the
4938
        // peer has fully started up. This can happen if an inbound and outbound
4939
        // race condition occurs.
4940
        s.wg.Add(1)
3✔
4941
        go func() {
6✔
4942
                defer s.wg.Done()
3✔
4943

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

3✔
4946
                // If this peer had an active persistent connection request,
3✔
4947
                // remove it.
3✔
4948
                if p.ConnReq() != nil {
6✔
4949
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4950
                }
3✔
4951

4952
                // Remove the peer's access permission from the access manager.
4953
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4954
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4955

3✔
4956
                // Copy the peer's error buffer across to the server if it has
3✔
4957
                // any items in it so that we can restore peer errors across
3✔
4958
                // connections. We need to look up the error after the peer has
3✔
4959
                // been disconnected because we write the error in the
3✔
4960
                // `Disconnect` method.
3✔
4961
                s.mu.Lock()
3✔
4962
                if p.ErrorBuffer().Total() > 0 {
6✔
4963
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4964
                }
3✔
4965
                s.mu.Unlock()
3✔
4966

3✔
4967
                // Inform the peer notifier of a peer offline event so that it
3✔
4968
                // can be reported to clients listening for peer events.
3✔
4969
                var pubKey [33]byte
3✔
4970
                copy(pubKey[:], pubSer)
3✔
4971

3✔
4972
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4973
        }()
4974
}
4975

4976
// ConnectToPeer requests that the server connect to a Lightning Network peer
4977
// at the specified address. This function will *block* until either a
4978
// connection is established, or the initial handshake process fails.
4979
//
4980
// NOTE: This function is safe for concurrent access.
4981
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4982
        perm bool, timeout time.Duration) error {
3✔
4983

3✔
4984
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4985

3✔
4986
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4987
        // better granularity.  In certain conditions, this method requires
3✔
4988
        // making an outbound connection to a remote peer, which requires the
3✔
4989
        // lock to be released, and subsequently reacquired.
3✔
4990
        s.mu.Lock()
3✔
4991

3✔
4992
        // Ensure we're not already connected to this peer.
3✔
4993
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4994

3✔
4995
        // When there's no error it means we already have a connection with this
3✔
4996
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4997
        // set, we will ignore the existing connection and continue.
3✔
4998
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4999
                s.mu.Unlock()
3✔
5000
                return &errPeerAlreadyConnected{peer: peer}
3✔
5001
        }
3✔
5002

5003
        // Peer was not found, continue to pursue connection with peer.
5004

5005
        // If there's already a pending connection request for this pubkey,
5006
        // then we ignore this request to ensure we don't create a redundant
5007
        // connection.
5008
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5009
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5010
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5011
        }
3✔
5012

5013
        // If there's not already a pending or active connection to this node,
5014
        // then instruct the connection manager to attempt to establish a
5015
        // persistent connection to the peer.
5016
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5017
        if perm {
6✔
5018
                connReq := &connmgr.ConnReq{
3✔
5019
                        Addr:      addr,
3✔
5020
                        Permanent: true,
3✔
5021
                }
3✔
5022

3✔
5023
                // Since the user requested a permanent connection, we'll set
3✔
5024
                // the entry to true which will tell the server to continue
3✔
5025
                // reconnecting even if the number of channels with this peer is
3✔
5026
                // zero.
3✔
5027
                s.persistentPeers[targetPub] = true
3✔
5028
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5029
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5030
                }
3✔
5031
                s.persistentConnReqs[targetPub] = append(
3✔
5032
                        s.persistentConnReqs[targetPub], connReq,
3✔
5033
                )
3✔
5034
                s.mu.Unlock()
3✔
5035

3✔
5036
                go s.connMgr.Connect(connReq)
3✔
5037

3✔
5038
                return nil
3✔
5039
        }
5040
        s.mu.Unlock()
3✔
5041

3✔
5042
        // If we're not making a persistent connection, then we'll attempt to
3✔
5043
        // connect to the target peer. If the we can't make the connection, or
3✔
5044
        // the crypto negotiation breaks down, then return an error to the
3✔
5045
        // caller.
3✔
5046
        errChan := make(chan error, 1)
3✔
5047
        s.connectToPeer(addr, errChan, timeout)
3✔
5048

3✔
5049
        select {
3✔
5050
        case err := <-errChan:
3✔
5051
                return err
3✔
5052
        case <-s.quit:
×
5053
                return ErrServerShuttingDown
×
5054
        }
5055
}
5056

5057
// connectToPeer establishes a connection to a remote peer. errChan is used to
5058
// notify the caller if the connection attempt has failed. Otherwise, it will be
5059
// closed.
5060
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5061
        errChan chan<- error, timeout time.Duration) {
3✔
5062

3✔
5063
        conn, err := brontide.Dial(
3✔
5064
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5065
        )
3✔
5066
        if err != nil {
6✔
5067
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5068
                select {
3✔
5069
                case errChan <- err:
3✔
5070
                case <-s.quit:
×
5071
                }
5072
                return
3✔
5073
        }
5074

5075
        close(errChan)
3✔
5076

3✔
5077
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5078
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5079

3✔
5080
        s.OutboundPeerConnected(nil, conn)
3✔
5081
}
5082

5083
// DisconnectPeer sends the request to server to close the connection with peer
5084
// identified by public key.
5085
//
5086
// NOTE: This function is safe for concurrent access.
5087
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5088
        pubBytes := pubKey.SerializeCompressed()
3✔
5089
        pubStr := string(pubBytes)
3✔
5090

3✔
5091
        s.mu.Lock()
3✔
5092
        defer s.mu.Unlock()
3✔
5093

3✔
5094
        // Check that were actually connected to this peer. If not, then we'll
3✔
5095
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5096
        // currently connected to.
3✔
5097
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5098
        if err == ErrPeerNotConnected {
6✔
5099
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5100
        }
3✔
5101

5102
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5103

3✔
5104
        s.cancelConnReqs(pubStr, nil)
3✔
5105

3✔
5106
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5107
        // them from this map so we don't attempt to re-connect after we
3✔
5108
        // disconnect.
3✔
5109
        delete(s.persistentPeers, pubStr)
3✔
5110
        delete(s.persistentPeersBackoff, pubStr)
3✔
5111

3✔
5112
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5113
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5114
        //
3✔
5115
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5116
        // goroutine because we might hold the server's mutex.
3✔
5117
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5118

3✔
5119
        return nil
3✔
5120
}
5121

5122
// OpenChannel sends a request to the server to open a channel to the specified
5123
// peer identified by nodeKey with the passed channel funding parameters.
5124
//
5125
// NOTE: This function is safe for concurrent access.
5126
func (s *server) OpenChannel(
5127
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5128

3✔
5129
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5130
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5131
        // not blocked if the caller is not reading the updates.
3✔
5132
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5133
        req.Err = make(chan error, 1)
3✔
5134

3✔
5135
        // First attempt to locate the target peer to open a channel with, if
3✔
5136
        // we're unable to locate the peer then this request will fail.
3✔
5137
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5138
        s.mu.RLock()
3✔
5139
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5140
        if !ok {
3✔
5141
                s.mu.RUnlock()
×
5142

×
5143
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5144
                return req.Updates, req.Err
×
5145
        }
×
5146
        req.Peer = peer
3✔
5147
        s.mu.RUnlock()
3✔
5148

3✔
5149
        // We'll wait until the peer is active before beginning the channel
3✔
5150
        // opening process.
3✔
5151
        select {
3✔
5152
        case <-peer.ActiveSignal():
3✔
5153
        case <-peer.QuitSignal():
×
5154
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5155
                return req.Updates, req.Err
×
5156
        case <-s.quit:
×
5157
                req.Err <- ErrServerShuttingDown
×
5158
                return req.Updates, req.Err
×
5159
        }
5160

5161
        // If the fee rate wasn't specified at this point we fail the funding
5162
        // because of the missing fee rate information. The caller of the
5163
        // `OpenChannel` method needs to make sure that default values for the
5164
        // fee rate are set beforehand.
5165
        if req.FundingFeePerKw == 0 {
3✔
5166
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5167
                        "the channel opening transaction")
×
5168

×
5169
                return req.Updates, req.Err
×
5170
        }
×
5171

5172
        // Spawn a goroutine to send the funding workflow request to the funding
5173
        // manager. This allows the server to continue handling queries instead
5174
        // of blocking on this request which is exported as a synchronous
5175
        // request to the outside world.
5176
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5177

3✔
5178
        return req.Updates, req.Err
3✔
5179
}
5180

5181
// Peers returns a slice of all active peers.
5182
//
5183
// NOTE: This function is safe for concurrent access.
5184
func (s *server) Peers() []*peer.Brontide {
3✔
5185
        s.mu.RLock()
3✔
5186
        defer s.mu.RUnlock()
3✔
5187

3✔
5188
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5189
        for _, peer := range s.peersByPub {
6✔
5190
                peers = append(peers, peer)
3✔
5191
        }
3✔
5192

5193
        return peers
3✔
5194
}
5195

5196
// computeNextBackoff uses a truncated exponential backoff to compute the next
5197
// backoff using the value of the exiting backoff. The returned duration is
5198
// randomized in either direction by 1/20 to prevent tight loops from
5199
// stabilizing.
5200
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5201
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5202
        nextBackoff := 2 * currBackoff
3✔
5203
        if nextBackoff > maxBackoff {
6✔
5204
                nextBackoff = maxBackoff
3✔
5205
        }
3✔
5206

5207
        // Using 1/10 of our duration as a margin, compute a random offset to
5208
        // avoid the nodes entering connection cycles.
5209
        margin := nextBackoff / 10
3✔
5210

3✔
5211
        var wiggle big.Int
3✔
5212
        wiggle.SetUint64(uint64(margin))
3✔
5213
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5214
                // Randomizing is not mission critical, so we'll just return the
×
5215
                // current backoff.
×
5216
                return nextBackoff
×
5217
        }
×
5218

5219
        // Otherwise add in our wiggle, but subtract out half of the margin so
5220
        // that the backoff can tweaked by 1/20 in either direction.
5221
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5222
}
5223

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

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

3✔
5232
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5233
        if err != nil {
3✔
5234
                return nil, err
×
5235
        }
×
5236

5237
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5238
        if err != nil {
6✔
5239
                return nil, err
3✔
5240
        }
3✔
5241

5242
        if len(node.Addresses) == 0 {
6✔
5243
                return nil, errNoAdvertisedAddr
3✔
5244
        }
3✔
5245

5246
        return node.Addresses, nil
3✔
5247
}
5248

5249
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5250
// channel update for a target channel.
5251
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5252
        *lnwire.ChannelUpdate1, error) {
3✔
5253

3✔
5254
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5255
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5256
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5257
                if err != nil {
6✔
5258
                        return nil, err
3✔
5259
                }
3✔
5260

5261
                return netann.ExtractChannelUpdate(
3✔
5262
                        ourPubKey[:], info, edge1, edge2,
3✔
5263
                )
3✔
5264
        }
5265
}
5266

5267
// applyChannelUpdate applies the channel update to the different sub-systems of
5268
// the server. The useAlias boolean denotes whether or not to send an alias in
5269
// place of the real SCID.
5270
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5271
        op *wire.OutPoint, useAlias bool) error {
3✔
5272

3✔
5273
        var (
3✔
5274
                peerAlias    *lnwire.ShortChannelID
3✔
5275
                defaultAlias lnwire.ShortChannelID
3✔
5276
        )
3✔
5277

3✔
5278
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5279

3✔
5280
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5281
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5282
        if useAlias {
6✔
5283
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5284
                if foundAlias != defaultAlias {
6✔
5285
                        peerAlias = &foundAlias
3✔
5286
                }
3✔
5287
        }
5288

5289
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5290
                update, discovery.RemoteAlias(peerAlias),
3✔
5291
        )
3✔
5292
        select {
3✔
5293
        case err := <-errChan:
3✔
5294
                return err
3✔
5295
        case <-s.quit:
×
5296
                return ErrServerShuttingDown
×
5297
        }
5298
}
5299

5300
// SendCustomMessage sends a custom message to the peer with the specified
5301
// pubkey.
5302
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5303
        data []byte) error {
3✔
5304

3✔
5305
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5306
        if err != nil {
6✔
5307
                return err
3✔
5308
        }
3✔
5309

5310
        // We'll wait until the peer is active.
5311
        select {
3✔
5312
        case <-peer.ActiveSignal():
3✔
5313
        case <-peer.QuitSignal():
×
5314
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5315
        case <-s.quit:
×
5316
                return ErrServerShuttingDown
×
5317
        }
5318

5319
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5320
        if err != nil {
6✔
5321
                return err
3✔
5322
        }
3✔
5323

5324
        // Send the message as low-priority. For now we assume that all
5325
        // application-defined message are low priority.
5326
        return peer.SendMessageLazy(true, msg)
3✔
5327
}
5328

5329
// newSweepPkScriptGen creates closure that generates a new public key script
5330
// which should be used to sweep any funds into the on-chain wallet.
5331
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5332
// (p2wkh) output.
5333
func newSweepPkScriptGen(
5334
        wallet lnwallet.WalletController,
5335
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5336

3✔
5337
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5338
                sweepAddr, err := wallet.NewAddress(
3✔
5339
                        lnwallet.TaprootPubkey, false,
3✔
5340
                        lnwallet.DefaultAccountName,
3✔
5341
                )
3✔
5342
                if err != nil {
3✔
5343
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5344
                }
×
5345

5346
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5347
                if err != nil {
3✔
5348
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5349
                }
×
5350

5351
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5352
                        wallet, netParams, addr,
3✔
5353
                )
3✔
5354
                if err != nil {
3✔
5355
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5356
                }
×
5357

5358
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5359
                        DeliveryAddress: addr,
3✔
5360
                        InternalKey:     internalKeyDesc,
3✔
5361
                })
3✔
5362
        }
5363
}
5364

5365
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5366
// finished.
5367
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5368
        // Get a list of closed channels.
3✔
5369
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5370
        if err != nil {
3✔
5371
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5372
                return nil
×
5373
        }
×
5374

5375
        // Save the SCIDs in a map.
5376
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5377
        for _, c := range channels {
6✔
5378
                // If the channel is not pending, its FC has been finalized.
3✔
5379
                if !c.IsPending {
6✔
5380
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5381
                }
3✔
5382
        }
5383

5384
        // Double check whether the reported closed channel has indeed finished
5385
        // closing.
5386
        //
5387
        // NOTE: There are misalignments regarding when a channel's FC is
5388
        // marked as finalized. We double check the pending channels to make
5389
        // sure the returned SCIDs are indeed terminated.
5390
        //
5391
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5392
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5393
        if err != nil {
3✔
5394
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5395
                return nil
×
5396
        }
×
5397

5398
        for _, c := range pendings {
6✔
5399
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5400
                        continue
3✔
5401
                }
5402

5403
                // If the channel is still reported as pending, remove it from
5404
                // the map.
5405
                delete(closedSCIDs, c.ShortChannelID)
×
5406

×
5407
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5408
                        c.ShortChannelID)
×
5409
        }
5410

5411
        return closedSCIDs
3✔
5412
}
5413

5414
// getStartingBeat returns the current beat. This is used during the startup to
5415
// initialize blockbeat consumers.
5416
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5417
        // beat is the current blockbeat.
3✔
5418
        var beat *chainio.Beat
3✔
5419

3✔
5420
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5421
        // we will skip fetching the best block.
3✔
5422
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5423
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5424
                        "mode")
×
5425

×
5426
                return &chainio.Beat{}, nil
×
5427
        }
×
5428

5429
        // We should get a notification with the current best block immediately
5430
        // by passing a nil block.
5431
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5432
        if err != nil {
3✔
5433
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5434
        }
×
5435
        defer blockEpochs.Cancel()
3✔
5436

3✔
5437
        // We registered for the block epochs with a nil request. The notifier
3✔
5438
        // should send us the current best block immediately. So we need to
3✔
5439
        // wait for it here because we need to know the current best height.
3✔
5440
        select {
3✔
5441
        case bestBlock := <-blockEpochs.Epochs:
3✔
5442
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5443
                        bestBlock.Hash, bestBlock.Height)
3✔
5444

3✔
5445
                // Update the current blockbeat.
3✔
5446
                beat = chainio.NewBeat(*bestBlock)
3✔
5447

5448
        case <-s.quit:
×
5449
                srvrLog.Debug("LND shutting down")
×
5450
        }
5451

5452
        return beat, nil
3✔
5453
}
5454

5455
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5456
// point has an active RBF chan closer.
5457
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5458
        chanPoint wire.OutPoint) bool {
3✔
5459

3✔
5460
        pubBytes := peerPub.SerializeCompressed()
3✔
5461

3✔
5462
        s.mu.RLock()
3✔
5463
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5464
        s.mu.RUnlock()
3✔
5465
        if !ok {
3✔
5466
                return false
×
5467
        }
×
5468

5469
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5470
}
5471

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

3✔
5480
        // First, we'll attempt to look up the channel based on it's
3✔
5481
        // ChannelPoint.
3✔
5482
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5483
        if err != nil {
3✔
5484
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5485
        }
×
5486

5487
        // From the channel, we can now get the pubkey of the peer, then use
5488
        // that to eventually get the chan closer.
5489
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5490

3✔
5491
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5492
        s.mu.RLock()
3✔
5493
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5494
        s.mu.RUnlock()
3✔
5495
        if !ok {
3✔
5496
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5497
                        "not online", chanPoint)
×
5498
        }
×
5499

5500
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5501
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5502
        )
3✔
5503
        if err != nil {
3✔
5504
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5505
                        "%w", err)
×
5506
        }
×
5507

5508
        return closeUpdates, nil
3✔
5509
}
5510

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

3✔
5519
        // If the channel is present in the switch, then the request should flow
3✔
5520
        // through the switch instead.
3✔
5521
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5522
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5523
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5524
                        "invalid request", chanPoint)
×
5525
        }
×
5526

5527
        // At this point, we know that the channel isn't present in the link, so
5528
        // we'll check to see if we have an entry in the active chan closer map.
5529
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5530
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5531
        )
3✔
5532
        if err != nil {
3✔
5533
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5534
                        "ChannelPoint(%v)", chanPoint)
×
5535
        }
×
5536

5537
        return updates, nil
3✔
5538
}
5539

5540
// setSelfNode configures and sets the node's identity. It sets the node
5541
// announcement, signs it, and updates the source node in the graph. When
5542
// determining values such as color and alias, the method prioritizes values
5543
// set in the config, then values previously persisted on disk, and finally
5544
// falls back to the defaults.
5545
func (s *server) setSelfNode(ctx context.Context, externalIPStrings []string,
5546
        serializedPubKey [33]byte) error {
3✔
5547

3✔
5548
        var (
3✔
5549
                color          color.RGBA
3✔
5550
                alias          = s.cfg.Alias
3✔
5551
                addrs          []net.Addr
3✔
5552
                nodeLastUpdate = time.Now()
3✔
5553
                err            error
3✔
5554
        )
3✔
5555

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

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

5573
        // To avoid having duplicate addresses, we'll only add addresses from
5574
        // the source node that are not already in our address list yet.
5575
        addressMap := make(map[string]struct{}, len(addrs))
3✔
5576
        // Populate the map with the existing addresses.
3✔
5577
        for _, existingAddr := range addrs {
6✔
5578
                addressMap[existingAddr.String()] = struct{}{}
3✔
5579
        }
3✔
5580

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

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

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

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

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

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

5627
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5628
        if err != nil {
3✔
NEW
5629
                return err
×
NEW
5630
        }
×
5631

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

3✔
5643
        copy(selfNode.PubKeyBytes[:], serializedPubKey[:])
3✔
5644

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

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

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

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

5677
        s.currentNodeAnn = nodeAnn
3✔
5678

3✔
5679
        return nil
3✔
5680
}
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