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

lightningnetwork / lnd / 19616403112

23 Nov 2025 07:49PM UTC coverage: 65.173% (-0.06%) from 65.229%
19616403112

Pull #10390

github

web-flow
Merge bf85a3dc9 into 8c8662c86
Pull Request #10390: Defer Channel Cleanup after a channel is closed to avoid kv-sql stress

53 of 206 new or added lines in 4 files covered. (25.73%)

127 existing lines in 27 files now uncovered.

137610 of 211145 relevant lines covered (65.17%)

20759.97 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

233
        start sync.Once
234
        stop  sync.Once
235

236
        cfg *Config
237

238
        implCfg *ImplementationCfg
239

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

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

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

251
        chanStatusMgr *netann.ChanStatusManager
252

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

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

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

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

273
        mu sync.RWMutex
274

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

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

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

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

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

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

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

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

325
        cc *chainreg.ChainControl
326

327
        fundingMgr *funding.Manager
328

329
        graphDB *graphdb.ChannelGraph
330

331
        chanStateDB *channeldb.ChannelStateDB
332

333
        addrSource channeldb.AddrSource
334

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

339
        invoicesDB invoices.InvoiceDB
340

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

345
        aliasMgr *aliasmgr.Manager
346

347
        htlcSwitch *htlcswitch.Switch
348

349
        interceptableSwitch *htlcswitch.InterceptableSwitch
350

351
        invoices *invoices.InvoiceRegistry
352

353
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
354

355
        channelNotifier *channelnotifier.ChannelNotifier
356

357
        peerNotifier *peernotifier.PeerNotifier
358

359
        htlcNotifier *htlcswitch.HtlcNotifier
360

361
        witnessBeacon contractcourt.WitnessBeacon
362

363
        breachArbitrator *contractcourt.BreachArbitrator
364

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

368
        graphBuilder *graph.Builder
369

370
        chanRouter *routing.ChannelRouter
371

372
        controlTower routing.ControlTower
373

374
        authGossiper *discovery.AuthenticatedGossiper
375

376
        localChanMgr *localchans.Manager
377

378
        utxoNursery *contractcourt.UtxoNursery
379

380
        sweeper *sweep.UtxoSweeper
381

382
        chainArb *contractcourt.ChainArbitrator
383

384
        sphinx *hop.OnionProcessor
385

386
        towerClientMgr *wtclient.Manager
387

388
        connMgr *connmgr.ConnManager
389

390
        sigPool *lnwallet.SigPool
391

392
        writePool *pool.Write
393

394
        readPool *pool.Read
395

396
        tlsManager *TLSManager
397

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

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

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

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

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

420
        hostAnn *netann.HostAnnouncer
421

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

425
        customMessageServer *subscribe.Server
426

427
        onionMessageServer *subscribe.Server
428

429
        // txPublisher is a publisher with fee-bumping capability.
430
        txPublisher *sweep.TxPublisher
431

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

436
        // peerAccessMan implements peer access controls.
437
        peerAccessMan *accessMan
438

439
        quit chan struct{}
440

441
        wg sync.WaitGroup
442
}
443

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

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

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

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

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

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

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

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

499
                                        s.mu.Lock()
3✔
500

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

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

515
                                        s.mu.Unlock()
3✔
516

3✔
517
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
518
                                }
519
                        }
520
                }
521
        }()
522

523
        return nil
3✔
524
}
525

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

531
        // Msg is the custom wire message.
532
        Msg *lnwire.Custom
533
}
534

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

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

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

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

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

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

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

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

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

3✔
606
        netParams := cfg.ActiveNetParams.Params
3✔
607

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

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

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

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

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

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

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

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

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

3✔
678
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
679

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

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

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

3✔
706
                listenAddrs: listenAddrs,
3✔
707

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

3✔
712
                torController: torController,
3✔
713

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

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

3✔
730
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
731

3✔
732
                customMessageServer: subscribe.NewServer(),
3✔
733

3✔
734
                onionMessageServer: subscribe.NewServer(),
3✔
735

3✔
736
                tlsManager: tlsManager,
3✔
737

3✔
738
                featureMgr: featureMgr,
3✔
739
                quit:       make(chan struct{}),
3✔
740
        }
3✔
741

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

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

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

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

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

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

3✔
768
                return nil
3✔
769
        }
770

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1104
        accessCfg := &accessManConfig{
3✔
1105
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1106
                        error) {
6✔
1107

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

1117
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1118
        if err != nil {
3✔
1119
                return nil, err
×
1120
        }
×
1121

1122
        s.peerAccessMan = peerAccessMan
3✔
1123

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

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

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

×
1151
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1152
                },
×
1153
        }
1154

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

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

1171
        aggregator := sweep.NewBudgetAggregator(
3✔
1172
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1173
                s.implCfg.AuxSweeper,
3✔
1174
        )
3✔
1175

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

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

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

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

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

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

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

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

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

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

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

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

1316
                        event := &contractcourt.ContractBreachEvent{
3✔
1317
                                ChanPoint:         chanPoint,
3✔
1318
                                ProcessACK:        processACK,
3✔
1319
                                BreachRetribution: breachRet,
3✔
1320
                        }
3✔
1321

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

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

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

3✔
1359
                        // Get the circuit map.
3✔
1360
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1361

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

1368
                        return &pc.Incoming
3✔
1369
                },
1370
                AuxLeafStore: implCfg.AuxLeafStore,
1371
                AuxSigner:    implCfg.AuxSigner,
1372
                AuxResolver:  implCfg.AuxContractResolver,
1373
        }, dbs.ChanStateDB)
1374

1375
        // Select the configuration and funding parameters for Bitcoin.
1376
        chainCfg := cfg.Bitcoin
3✔
1377
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1378
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1379

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

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

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

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

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

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

1419
                err = s.graphDB.DeleteChannelEdges(
3✔
1420
                        false, false, scid.ToUint64(),
3✔
1421
                )
3✔
1422
                return ourPolicy, err
3✔
1423
        }
1424

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

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

3✔
1441
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1442
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1443

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

1449
        // Attempt to parse the provided upfront-shutdown address (if any).
1450
        script, err := chancloser.ParseUpfrontShutdownAddress(
3✔
1451
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
3✔
1452
        )
3✔
1453
        if err != nil {
3✔
1454
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
1455
                        err)
×
1456
        }
×
1457

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

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

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

1504
                        minConf := uint64(3)
×
1505
                        maxConf := uint64(6)
×
1506

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

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

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

1543
                        // If this is a wumbo channel, then we'll require the
1544
                        // max value.
1545
                        if chanAmt > MaxFundingAmount {
×
1546
                                return maxRemoteDelay
×
1547
                        }
×
1548

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

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

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

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

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

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

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

1664
        // Assemble a peer notifier which will provide clients with subscriptions
1665
        // to peer online and offline events.
1666
        s.peerNotifier = peernotifier.New()
3✔
1667

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

1683
        if cfg.WtClient.Active {
6✔
1684
                policy := wtpolicy.DefaultPolicy()
3✔
1685
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1686

3✔
1687
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1688
                // protocol operations on sat/kw.
3✔
1689
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1690
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1691
                )
3✔
1692

3✔
1693
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1694

3✔
1695
                if err := policy.Validate(); err != nil {
3✔
1696
                        return nil, err
×
1697
                }
×
1698

1699
                // authDial is the wrapper around the btrontide.Dial for the
1700
                // watchtower.
1701
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1702
                        netAddr *lnwire.NetAddress,
3✔
1703
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1704

3✔
1705
                        return brontide.Dial(
3✔
1706
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1707
                        )
3✔
1708
                }
3✔
1709

1710
                // buildBreachRetribution is a call-back that can be used to
1711
                // query the BreachRetribution info and channel type given a
1712
                // channel ID and commitment height.
1713
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1714
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1715
                        channeldb.ChannelType, error) {
6✔
1716

3✔
1717
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1718
                                nil, chanID,
3✔
1719
                        )
3✔
1720
                        if err != nil {
3✔
1721
                                return nil, 0, err
×
1722
                        }
×
1723

1724
                        br, err := lnwallet.NewBreachRetribution(
3✔
1725
                                channel, commitHeight, 0, nil,
3✔
1726
                                implCfg.AuxLeafStore,
3✔
1727
                                implCfg.AuxContractResolver,
3✔
1728
                        )
3✔
1729
                        if err != nil {
3✔
1730
                                return nil, 0, err
×
1731
                        }
×
1732

1733
                        return br, channel.ChanType, nil
3✔
1734
                }
1735

1736
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1737

3✔
1738
                // Copy the policy for legacy channels and set the blob flag
3✔
1739
                // signalling support for anchor channels.
3✔
1740
                anchorPolicy := policy
3✔
1741
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1742

3✔
1743
                // Copy the policy for legacy channels and set the blob flag
3✔
1744
                // signalling support for taproot channels.
3✔
1745
                taprootPolicy := policy
3✔
1746
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1747
                        blob.FlagTaprootChannel,
3✔
1748
                )
3✔
1749

3✔
1750
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1751
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1752
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1753
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1754
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1755
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1756
                                error) {
6✔
1757

3✔
1758
                                return s.channelNotifier.
3✔
1759
                                        SubscribeChannelEvents()
3✔
1760
                        },
3✔
1761
                        Signer: cc.Wallet.Cfg.Signer,
1762
                        NewAddress: func() ([]byte, error) {
3✔
1763
                                addr, err := newSweepPkScriptGen(
3✔
1764
                                        cc.Wallet, netParams,
3✔
1765
                                )().Unpack()
3✔
1766
                                if err != nil {
3✔
1767
                                        return nil, err
×
1768
                                }
×
1769

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

1786
        if len(cfg.ExternalHosts) != 0 {
3✔
1787
                advertisedIPs := make(map[string]struct{})
×
1788
                for _, addr := range s.currentNodeAnn.Addresses {
×
1789
                        advertisedIPs[addr.String()] = struct{}{}
×
1790
                }
×
1791

1792
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1793
                        Hosts:         cfg.ExternalHosts,
×
1794
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1795
                        LookupHost: func(host string) (net.Addr, error) {
×
1796
                                return lncfg.ParseAddressString(
×
1797
                                        host, strconv.Itoa(defaultPeerPort),
×
1798
                                        cfg.net.ResolveTCPAddr,
×
1799
                                )
×
1800
                        },
×
1801
                        AdvertisedIPs: advertisedIPs,
1802
                        AnnounceNewIPs: netann.IPAnnouncer(
1803
                                func(modifier ...netann.NodeAnnModifier) (
1804
                                        lnwire.NodeAnnouncement1, error) {
×
1805

×
1806
                                        return s.genNodeAnnouncement(
×
1807
                                                nil, modifier...,
×
1808
                                        )
×
1809
                                }),
×
1810
                })
1811
        }
1812

1813
        // Create liveness monitor.
1814
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1815

3✔
1816
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1817
        for i, listenAddr := range listenAddrs {
6✔
1818
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1819
                // doesn't need to call the general lndResolveTCP function
3✔
1820
                // since we are resolving a local address.
3✔
1821

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

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

3✔
1853
        // Finally, register the subsystems in blockbeat.
3✔
1854
        s.registerBlockConsumers()
3✔
1855

3✔
1856
        return s, nil
3✔
1857
}
1858

1859
// UpdateRoutingConfig is a callback function to update the routing config
1860
// values in the main cfg.
1861
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1862
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1863

3✔
1864
        switch c := cfg.Estimator.Config().(type) {
3✔
1865
        case routing.AprioriConfig:
3✔
1866
                routerCfg.ProbabilityEstimatorType =
3✔
1867
                        routing.AprioriEstimatorName
3✔
1868

3✔
1869
                targetCfg := routerCfg.AprioriConfig
3✔
1870
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1871
                targetCfg.Weight = c.AprioriWeight
3✔
1872
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1873
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1874

1875
        case routing.BimodalConfig:
3✔
1876
                routerCfg.ProbabilityEstimatorType =
3✔
1877
                        routing.BimodalEstimatorName
3✔
1878

3✔
1879
                targetCfg := routerCfg.BimodalConfig
3✔
1880
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1881
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1882
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1883
        }
1884

1885
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1886
}
1887

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

1907
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1908
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1909
// may differ from what is on disk.
1910
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1911
        error) {
3✔
1912

3✔
1913
        data, err := u.DataToSign()
3✔
1914
        if err != nil {
3✔
1915
                return nil, err
×
1916
        }
×
1917

1918
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1919
}
1920

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

3✔
1934
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1935
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1936
                srvrLog.Info("Disabling chain backend checks for " +
×
1937
                        "nochainbackend mode")
×
1938

×
1939
                chainBackendAttempts = 0
×
1940
        }
×
1941

1942
        chainHealthCheck := healthcheck.NewObservation(
3✔
1943
                "chain backend",
3✔
1944
                cc.HealthCheck,
3✔
1945
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1946
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1947
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1948
                chainBackendAttempts,
3✔
1949
        )
3✔
1950

3✔
1951
        diskCheck := healthcheck.NewObservation(
3✔
1952
                "disk space",
3✔
1953
                func() error {
3✔
1954
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1955
                                cfg.LndDir,
×
1956
                        )
×
1957
                        if err != nil {
×
1958
                                return err
×
1959
                        }
×
1960

1961
                        // If we have more free space than we require,
1962
                        // we return a nil error.
1963
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1964
                                return nil
×
1965
                        }
×
1966

1967
                        return fmt.Errorf("require: %v free space, got: %v",
×
1968
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1969
                                free)
×
1970
                },
1971
                cfg.HealthChecks.DiskCheck.Interval,
1972
                cfg.HealthChecks.DiskCheck.Timeout,
1973
                cfg.HealthChecks.DiskCheck.Backoff,
1974
                cfg.HealthChecks.DiskCheck.Attempts,
1975
        )
1976

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

1991
                        // If the certificate is not outdated, no error needs
1992
                        // to be returned
1993
                        return nil
×
1994
                },
1995
                cfg.HealthChecks.TLSCheck.Interval,
1996
                cfg.HealthChecks.TLSCheck.Timeout,
1997
                cfg.HealthChecks.TLSCheck.Backoff,
1998
                cfg.HealthChecks.TLSCheck.Attempts,
1999
        )
2000

2001
        checks := []*healthcheck.Observation{
3✔
2002
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2003
        }
3✔
2004

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

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

3✔
2035
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2036
                        "remote signer connection",
3✔
2037
                        rpcwallet.HealthCheck(
3✔
2038
                                s.cfg.RemoteSigner,
3✔
2039

3✔
2040
                                // For the health check we might to be even
3✔
2041
                                // stricter than the initial/normal connect, so
3✔
2042
                                // we use the health check timeout here.
3✔
2043
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2044
                        ),
3✔
2045
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2046
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2047
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2048
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2049
                )
3✔
2050
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2051
        }
3✔
2052

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

×
2071
                                leader, err := leaderElector.IsLeader(
×
2072
                                        timeoutCtx,
×
2073
                                )
×
2074
                                if err != nil {
×
2075
                                        return fmt.Errorf("unable to check if "+
×
2076
                                                "still leader: %v", err)
×
2077
                                }
×
2078

2079
                                if !leader {
×
2080
                                        srvrLog.Debug("Not the current leader")
×
2081
                                        return fmt.Errorf("not the current " +
×
2082
                                                "leader")
×
2083
                                }
×
2084

2085
                                return nil
×
2086
                        },
2087
                        cfg.HealthChecks.LeaderCheck.Interval,
2088
                        cfg.HealthChecks.LeaderCheck.Timeout,
2089
                        cfg.HealthChecks.LeaderCheck.Backoff,
2090
                        cfg.HealthChecks.LeaderCheck.Attempts,
2091
                )
2092

2093
                checks = append(checks, leaderCheck)
×
2094
        }
2095

2096
        // If we have not disabled all of our health checks, we create a
2097
        // liveness monitor with our configured checks.
2098
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2099
                &healthcheck.Config{
3✔
2100
                        Checks:   checks,
3✔
2101
                        Shutdown: srvrLog.Criticalf,
3✔
2102
                },
3✔
2103
        )
3✔
2104
}
2105

2106
// Started returns true if the server has been started, and false otherwise.
2107
// NOTE: This function is safe for concurrent access.
2108
func (s *server) Started() bool {
3✔
2109
        return atomic.LoadInt32(&s.active) != 0
3✔
2110
}
3✔
2111

2112
// cleaner is used to aggregate "cleanup" functions during an operation that
2113
// starts several subsystems. In case one of the subsystem fails to start
2114
// and a proper resource cleanup is required, the "run" method achieves this
2115
// by running all these added "cleanup" functions.
2116
type cleaner []func() error
2117

2118
// add is used to add a cleanup function to be called when
2119
// the run function is executed.
2120
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2121
        return append(c, cleanup)
3✔
2122
}
3✔
2123

2124
// run is used to run all the previousely added cleanup functions.
2125
func (c cleaner) run() {
×
2126
        for i := len(c) - 1; i >= 0; i-- {
×
2127
                if err := c[i](); err != nil {
×
2128
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2129
                }
×
2130
        }
2131
}
2132

2133
// Start starts the main daemon server, all requested listeners, and any helper
2134
// goroutines.
2135
// NOTE: This function is safe for concurrent access.
2136
//
2137
//nolint:funlen
2138
func (s *server) Start(ctx context.Context) error {
3✔
2139
        var startErr error
3✔
2140

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

3✔
2146
        s.start.Do(func() {
6✔
2147
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2148
                if err := s.customMessageServer.Start(); err != nil {
3✔
2149
                        startErr = err
×
2150
                        return
×
2151
                }
×
2152

2153
                cleanup = cleanup.add(s.onionMessageServer.Stop)
3✔
2154
                if err := s.onionMessageServer.Start(); err != nil {
3✔
2155
                        startErr = err
×
2156
                        return
×
2157
                }
×
2158

2159
                if s.hostAnn != nil {
3✔
2160
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2161
                        if err := s.hostAnn.Start(); err != nil {
×
2162
                                startErr = err
×
2163
                                return
×
2164
                        }
×
2165
                }
2166

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

2175
                // Start the notification server. This is used so channel
2176
                // management goroutines can be notified when a funding
2177
                // transaction reaches a sufficient number of confirmations, or
2178
                // when the input for the funding transaction is spent in an
2179
                // attempt at an uncooperative close by the counterparty.
2180
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2181
                if err := s.sigPool.Start(); err != nil {
3✔
2182
                        startErr = err
×
2183
                        return
×
2184
                }
×
2185

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

2192
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2193
                if err := s.readPool.Start(); err != nil {
3✔
2194
                        startErr = err
×
2195
                        return
×
2196
                }
×
2197

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

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

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

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

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

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

2238
                beat, err := s.getStartingBeat()
3✔
2239
                if err != nil {
3✔
2240
                        startErr = err
×
2241
                        return
×
2242
                }
×
2243

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2350
                cleanup.add(func() error {
3✔
2351
                        s.missionController.StopStoreTickers()
×
2352
                        return nil
×
2353
                })
×
2354
                s.missionController.RunStoreTickers()
3✔
2355

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

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

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

2405
                if s.natTraversal != nil {
3✔
2406
                        s.wg.Add(1)
×
2407
                        go s.watchExternalIP()
×
2408
                }
×
2409

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

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

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

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

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

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

×
2469
                        startErr = err
×
2470
                        return
×
2471
                }
×
2472

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

×
2482
                        startErr = err
×
2483
                        return
×
2484
                }
×
2485

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

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

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

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

2514
                                copy(result[idx][:], servers)
×
2515
                        }
2516

2517
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2518
                }
2519

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

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

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

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

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

2582
        if startErr != nil {
3✔
2583
                cleanup.run()
×
2584
        }
×
2585
        return startErr
3✔
2586
}
2587

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

3✔
2596
                ctx := context.Background()
3✔
2597

3✔
2598
                close(s.quit)
3✔
2599

3✔
2600
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2601
                s.connMgr.Stop()
3✔
2602

3✔
2603
                // Stop dispatching blocks to other systems immediately.
3✔
2604
                s.blockbeatDispatcher.Stop()
3✔
2605

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

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

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

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

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

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

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

2737
                // Wait for all lingering goroutines to quit.
2738
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2739
                s.wg.Wait()
3✔
2740

3✔
2741
                srvrLog.Debug("Stopping buffer pools...")
3✔
2742
                s.sigPool.Stop()
3✔
2743
                s.writePool.Stop()
3✔
2744
                s.readPool.Stop()
3✔
2745
        })
2746

2747
        return nil
3✔
2748
}
2749

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

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

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

2775
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2776
                externalIPs = append(externalIPs, hostIP)
×
2777
        }
2778

2779
        return externalIPs, nil
×
2780
}
2781

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

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

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

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

2817
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2818

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

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

2849
                        if ip.Equal(s.lastDetectedIP) {
×
2850
                                continue
×
2851
                        }
2852

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

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

2870
                                newAddrs = append(newAddrs, addr)
×
2871
                        }
2872

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

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

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

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

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

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

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

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

3✔
2939
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2940

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

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

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

×
2966
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2967
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2968
                        )
×
2969
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2970
                }
×
2971
        }
2972

2973
        return bootStrappers, nil
3✔
2974
}
2975

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

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

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

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

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

3006
        return ignore
3✔
3007
}
3008

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

3✔
3017
        defer s.wg.Done()
3✔
3018

3✔
3019
        // Before we continue, init the ignore peers map.
3✔
3020
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3021

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

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

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

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

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

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

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

3067
                        if epochAttempts > 0 &&
×
3068
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3069

×
3070
                                sampleTicker.Stop()
×
3071

×
3072
                                backOff *= 2
×
3073
                                if backOff > bootstrapBackOffCeiling {
×
3074
                                        backOff = bootstrapBackOffCeiling
×
3075
                                }
×
3076

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

3083
                        atomic.StoreUint32(&epochErrors, 0)
×
3084
                        epochAttempts = 0
×
3085

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

×
3090
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3091
                                "peers", numNeeded)
×
3092

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

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

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

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

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

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

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

3✔
3155
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3156
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3157

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

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

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

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

3✔
3180
                if numActivePeers >= numTargetPeers {
6✔
3181
                        return
3✔
3182
                }
3✔
3183

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

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

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

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

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

3✔
3227
                                errChan := make(chan error, 1)
3✔
3228
                                go s.connectToPeer(
3✔
3229
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3230
                                )
3✔
3231

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

3255
                wg.Wait()
3✔
3256
        }
3257
}
3258

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

3271
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3272
        if err != nil {
×
3273
                return err
×
3274
        }
×
3275

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

×
3288
        switch {
×
3289
        case s.cfg.Tor.V2:
×
3290
                onionCfg.Type = tor.V2
×
3291
        case s.cfg.Tor.V3:
×
3292
                onionCfg.Type = tor.V3
×
3293
        }
3294

3295
        addr, err := s.torController.AddOnion(onionCfg)
×
3296
        if err != nil {
×
3297
                return err
×
3298
        }
×
3299

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

3312
        // Finally, we'll update the on-disk version of our announcement so it
3313
        // will eventually propagate to nodes in the network.
3314
        selfNode := models.NewV1Node(
×
3315
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
3316
                        Addresses:    newNodeAnn.Addresses,
×
3317
                        Features:     newNodeAnn.Features,
×
3318
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3319
                        Color:        newNodeAnn.RGBColor,
×
3320
                        Alias:        newNodeAnn.Alias.String(),
×
3321
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3322
                },
×
3323
        )
×
3324

×
3325
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3326
                return fmt.Errorf("can't set self node: %w", err)
×
3327
        }
×
3328

3329
        return nil
×
3330
}
3331

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

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

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

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

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

3✔
3357
        return *s.currentNodeAnn
3✔
3358
}
3✔
3359

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

3✔
3366
        s.mu.Lock()
3✔
3367
        defer s.mu.Unlock()
3✔
3368

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

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

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

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

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

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

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

3✔
3413
        return *s.currentNodeAnn, nil
3✔
3414
}
3415

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

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

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

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

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

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

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

3459
        return nil
3✔
3460
}
3461

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
3580
                        return err
×
3581
                }
×
3582
        }
3583

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

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

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

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

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

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

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

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

3639
                numOutboundConns++
3✔
3640
        }
3641

3642
        return nil
3✔
3643
}
3644

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
3746
        return nil
3✔
3747
}
3748

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

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

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

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

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

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

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

3791
                return
3✔
3792
        }
3793

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

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

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

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

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

3✔
3827
        return c
3✔
3828
}
3829

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

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

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

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

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

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

3864
        return peer, nil
3✔
3865
}
3866

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4216
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4217
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4218
        return s.onionMessageServer.Subscribe()
3✔
4219
}
3✔
4220

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4307
                conn.Close()
×
4308

×
4309
                return
×
4310
        }
×
4311

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

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

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

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

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

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

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

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

4400
                PongBuf: s.pongBuf,
4401

4402
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4403

4404
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4405

4406
                FundingManager: s.fundingMgr,
4407

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

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

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

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

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

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

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

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

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

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

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

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

×
4486
                return
×
4487
        }
×
4488

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5049
        close(errChan)
3✔
5050

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

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

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

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

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

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

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

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

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

3✔
5093
        return nil
3✔
5094
}
5095

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

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

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

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

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

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

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

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

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

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

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

5167
        return peers
3✔
5168
}
5169

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5296
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5297
        if err != nil {
6✔
5298
                return err
3✔
5299
        }
3✔
5300

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

5306
// SendOnionMessage sends a custom message to the peer with the specified
5307
// pubkey.
5308
// TODO(gijs): change this message to include path finding.
5309
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
5310
        pathKey *btcec.PublicKey, onion []byte) error {
3✔
5311

3✔
5312
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5313
        if err != nil {
3✔
5314
                return err
×
5315
        }
×
5316

5317
        // We'll wait until the peer is active, but also listen for
5318
        // cancellation.
5319
        select {
3✔
5320
        case <-peer.ActiveSignal():
3✔
5321
        case <-peer.QuitSignal():
×
5322
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5323
        case <-s.quit:
×
5324
                return ErrServerShuttingDown
×
5325
        case <-ctx.Done():
×
5326
                return ctx.Err()
×
5327
        }
5328

5329
        msg := lnwire.NewOnionMessage(pathKey, onion)
3✔
5330

3✔
5331
        // Send the message as low-priority. For now we assume that all
3✔
5332
        // application-defined message are low priority.
3✔
5333
        return peer.SendMessageLazy(true, msg)
3✔
5334
}
5335

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

3✔
5344
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5345
                sweepAddr, err := wallet.NewAddress(
3✔
5346
                        lnwallet.TaprootPubkey, false,
3✔
5347
                        lnwallet.DefaultAccountName,
3✔
5348
                )
3✔
5349
                if err != nil {
3✔
5350
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5351
                }
×
5352

5353
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5354
                if err != nil {
3✔
5355
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5356
                }
×
5357

5358
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5359
                        wallet, netParams, addr,
3✔
5360
                )
3✔
5361
                if err != nil {
3✔
5362
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5363
                }
×
5364

5365
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5366
                        DeliveryAddress: addr,
3✔
5367
                        InternalKey:     internalKeyDesc,
3✔
5368
                })
3✔
5369
        }
5370
}
5371

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

5382
        // Save the SCIDs in a map.
5383
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5384
        for _, c := range channels {
6✔
5385
                // If the channel is not pending, its FC has been finalized.
3✔
5386
                if !c.IsPending {
6✔
5387
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5388
                }
3✔
5389
        }
5390

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

5405
        for _, c := range pendings {
6✔
5406
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5407
                        continue
3✔
5408
                }
5409

5410
                // If the channel is still reported as pending, remove it from
5411
                // the map.
5412
                delete(closedSCIDs, c.ShortChannelID)
×
5413

×
5414
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5415
                        c.ShortChannelID)
×
5416
        }
5417

5418
        return closedSCIDs
3✔
5419
}
5420

5421
// getStartingBeat returns the current beat. This is used during the startup to
5422
// initialize blockbeat consumers.
5423
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5424
        // beat is the current blockbeat.
3✔
5425
        var beat *chainio.Beat
3✔
5426

3✔
5427
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5428
        // we will skip fetching the best block.
3✔
5429
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5430
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5431
                        "mode")
×
5432

×
5433
                return &chainio.Beat{}, nil
×
5434
        }
×
5435

5436
        // We should get a notification with the current best block immediately
5437
        // by passing a nil block.
5438
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5439
        if err != nil {
3✔
5440
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5441
        }
×
5442
        defer blockEpochs.Cancel()
3✔
5443

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

3✔
5452
                // Update the current blockbeat.
3✔
5453
                beat = chainio.NewBeat(*bestBlock)
3✔
5454

5455
        case <-s.quit:
×
5456
                srvrLog.Debug("LND shutting down")
×
5457
        }
5458

5459
        return beat, nil
3✔
5460
}
5461

5462
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5463
// point has an active RBF chan closer.
5464
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5465
        chanPoint wire.OutPoint) bool {
3✔
5466

3✔
5467
        pubBytes := peerPub.SerializeCompressed()
3✔
5468

3✔
5469
        s.mu.RLock()
3✔
5470
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5471
        s.mu.RUnlock()
3✔
5472
        if !ok {
3✔
5473
                return false
×
5474
        }
×
5475

5476
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5477
}
5478

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

3✔
5487
        // First, we'll attempt to look up the channel based on it's
3✔
5488
        // ChannelPoint.
3✔
5489
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5490
        if err != nil {
3✔
5491
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5492
        }
×
5493

5494
        // From the channel, we can now get the pubkey of the peer, then use
5495
        // that to eventually get the chan closer.
5496
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5497

3✔
5498
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5499
        s.mu.RLock()
3✔
5500
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5501
        s.mu.RUnlock()
3✔
5502
        if !ok {
3✔
5503
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5504
                        "not online", chanPoint)
×
5505
        }
×
5506

5507
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5508
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5509
        )
3✔
5510
        if err != nil {
3✔
5511
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5512
                        "%w", err)
×
5513
        }
×
5514

5515
        return closeUpdates, nil
3✔
5516
}
5517

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

3✔
5526
        // If the channel is present in the switch, then the request should flow
3✔
5527
        // through the switch instead.
3✔
5528
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5529
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5530
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5531
                        "invalid request", chanPoint)
×
5532
        }
×
5533

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

5544
        return updates, nil
3✔
5545
}
5546

5547
// setSelfNode configures and sets the server's self node. It sets the node
5548
// announcement, signs it, and updates the source node in the graph. When
5549
// determining values such as color and alias, the method prioritizes values
5550
// set in the config, then values previously persisted on disk, and finally
5551
// falls back to the defaults.
5552
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5553
        listenAddrs []net.Addr) error {
3✔
5554

3✔
5555
        // If we were requested to automatically configure port forwarding,
3✔
5556
        // we'll use the ports that the server will be listening on.
3✔
5557
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
3✔
5558
        for _, ip := range s.cfg.ExternalIPs {
6✔
5559
                externalIPStrings = append(externalIPStrings, ip.String())
3✔
5560
        }
3✔
5561
        if s.natTraversal != nil {
3✔
5562
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5563
                for _, listenAddr := range listenAddrs {
×
5564
                        // At this point, the listen addresses should have
×
5565
                        // already been normalized, so it's safe to ignore the
×
5566
                        // errors.
×
5567
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5568
                        port, _ := strconv.Atoi(portStr)
×
5569

×
5570
                        listenPorts = append(listenPorts, uint16(port))
×
5571
                }
×
5572

5573
                ips, err := s.configurePortForwarding(listenPorts...)
×
5574
                if err != nil {
×
5575
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5576
                                "forwarding using %s: %v",
×
5577
                                s.natTraversal.Name(), err)
×
5578
                } else {
×
5579
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5580
                                "using %s to advertise external IP",
×
5581
                                s.natTraversal.Name())
×
5582
                        externalIPStrings = append(externalIPStrings, ips...)
×
5583
                }
×
5584
        }
5585

5586
        // Normalize the external IP strings to net.Addr.
5587
        addrs, err := lncfg.NormalizeAddresses(
3✔
5588
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5589
                s.cfg.net.ResolveTCPAddr,
3✔
5590
        )
3✔
5591
        if err != nil {
3✔
5592
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5593
        }
×
5594

5595
        // Parse the color from config. We will update this later if the config
5596
        // color is not changed from default (#3399FF) and we have a value in
5597
        // the source node.
5598
        nodeColor, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5599
        if err != nil {
3✔
5600
                return fmt.Errorf("unable to parse color: %w", err)
×
5601
        }
×
5602

5603
        var (
3✔
5604
                alias          = s.cfg.Alias
3✔
5605
                nodeLastUpdate = time.Now()
3✔
5606
        )
3✔
5607

3✔
5608
        srcNode, err := s.graphDB.SourceNode(ctx)
3✔
5609
        switch {
3✔
5610
        case err == nil:
3✔
5611
                // If we have a source node persisted in the DB already, then we
3✔
5612
                // just need to make sure that the new LastUpdate time is at
3✔
5613
                // least one second after the last update time.
3✔
5614
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
5615
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
5616
                }
3✔
5617

5618
                // If the color is not changed from default, it means that we
5619
                // didn't specify a different color in the config. We'll use the
5620
                // source node's color.
5621
                if s.cfg.Color == defaultColor {
6✔
5622
                        srcNode.Color.WhenSome(func(rgba color.RGBA) {
6✔
5623
                                nodeColor = rgba
3✔
5624
                        })
3✔
5625
                }
5626

5627
                // If an alias is not specified in the config, we'll use the
5628
                // source node's alias.
5629
                if alias == "" {
6✔
5630
                        srcNode.Alias.WhenSome(func(s string) {
6✔
5631
                                alias = s
3✔
5632
                        })
3✔
5633
                }
5634

5635
                // If the `externalip` is not specified in the config, it means
5636
                // `addrs` will be empty, we'll use the source node's addresses.
5637
                if len(s.cfg.ExternalIPs) == 0 {
6✔
5638
                        addrs = srcNode.Addresses
3✔
5639
                }
3✔
5640

5641
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5642
                // If an alias is not specified in the config, we'll use the
3✔
5643
                // default, which is the first 10 bytes of the serialized
3✔
5644
                // pubkey.
3✔
5645
                if alias == "" {
6✔
5646
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5647
                }
3✔
5648

5649
        // If the above cases are not matched, then we have an unhandled non
5650
        // nil error.
5651
        default:
×
5652
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5653
        }
5654

5655
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5656
        if err != nil {
3✔
5657
                return err
×
5658
        }
×
5659

5660
        // TODO(abdulkbk): potentially find a way to use the source node's
5661
        // features in the self node.
5662
        selfNode := models.NewV1Node(
3✔
5663
                nodePub, &models.NodeV1Fields{
3✔
5664
                        Alias:      nodeAlias.String(),
3✔
5665
                        Color:      nodeColor,
3✔
5666
                        LastUpdate: nodeLastUpdate,
3✔
5667
                        Addresses:  addrs,
3✔
5668
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
3✔
5669
                },
3✔
5670
        )
3✔
5671

3✔
5672
        // Based on the disk representation of the node announcement generated
3✔
5673
        // above, we'll generate a node announcement that can go out on the
3✔
5674
        // network so we can properly sign it.
3✔
5675
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5676
        if err != nil {
3✔
5677
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5678
        }
×
5679

5680
        // With the announcement generated, we'll sign it to properly
5681
        // authenticate the message on the network.
5682
        authSig, err := netann.SignAnnouncement(
3✔
5683
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5684
        )
3✔
5685
        if err != nil {
3✔
5686
                return fmt.Errorf("unable to generate signature for self node "+
×
5687
                        "announcement: %v", err)
×
5688
        }
×
5689

5690
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5691
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5692
                selfNode.AuthSigBytes,
3✔
5693
        )
3✔
5694
        if err != nil {
3✔
5695
                return err
×
5696
        }
×
5697

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

5704
        s.currentNodeAnn = nodeAnn
3✔
5705

3✔
5706
        return nil
3✔
5707
}
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