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

lightningnetwork / lnd / 19540544585

20 Nov 2025 02:37PM UTC coverage: 65.226% (-0.003%) from 65.229%
19540544585

Pull #10178

github

web-flow
Merge 036f56a16 into 8c8662c86
Pull Request #10178: multi: add mode for external payment lifecycle management

47 of 88 new or added lines in 5 files covered. (53.41%)

84 existing lines in 18 files now uncovered.

137642 of 211022 relevant lines covered (65.23%)

20746.91 hits per line

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

69.5
/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/build"
34
        "github.com/lightningnetwork/lnd/chainio"
35
        "github.com/lightningnetwork/lnd/chainreg"
36
        "github.com/lightningnetwork/lnd/chanacceptor"
37
        "github.com/lightningnetwork/lnd/chanbackup"
38
        "github.com/lightningnetwork/lnd/chanfitness"
39
        "github.com/lightningnetwork/lnd/channeldb"
40
        "github.com/lightningnetwork/lnd/channelnotifier"
41
        "github.com/lightningnetwork/lnd/clock"
42
        "github.com/lightningnetwork/lnd/cluster"
43
        "github.com/lightningnetwork/lnd/contractcourt"
44
        "github.com/lightningnetwork/lnd/discovery"
45
        "github.com/lightningnetwork/lnd/feature"
46
        "github.com/lightningnetwork/lnd/fn/v2"
47
        "github.com/lightningnetwork/lnd/funding"
48
        "github.com/lightningnetwork/lnd/graph"
49
        graphdb "github.com/lightningnetwork/lnd/graph/db"
50
        "github.com/lightningnetwork/lnd/graph/db/models"
51
        "github.com/lightningnetwork/lnd/healthcheck"
52
        "github.com/lightningnetwork/lnd/htlcswitch"
53
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
54
        "github.com/lightningnetwork/lnd/input"
55
        "github.com/lightningnetwork/lnd/invoices"
56
        "github.com/lightningnetwork/lnd/keychain"
57
        "github.com/lightningnetwork/lnd/lncfg"
58
        "github.com/lightningnetwork/lnd/lnencrypt"
59
        "github.com/lightningnetwork/lnd/lnpeer"
60
        "github.com/lightningnetwork/lnd/lnrpc"
61
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
62
        "github.com/lightningnetwork/lnd/lnutils"
63
        "github.com/lightningnetwork/lnd/lnwallet"
64
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
65
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
66
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
67
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
68
        "github.com/lightningnetwork/lnd/lnwire"
69
        "github.com/lightningnetwork/lnd/nat"
70
        "github.com/lightningnetwork/lnd/netann"
71
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
72
        "github.com/lightningnetwork/lnd/peer"
73
        "github.com/lightningnetwork/lnd/peernotifier"
74
        "github.com/lightningnetwork/lnd/pool"
75
        "github.com/lightningnetwork/lnd/queue"
76
        "github.com/lightningnetwork/lnd/routing"
77
        "github.com/lightningnetwork/lnd/routing/localchans"
78
        "github.com/lightningnetwork/lnd/routing/route"
79
        "github.com/lightningnetwork/lnd/subscribe"
80
        "github.com/lightningnetwork/lnd/sweep"
81
        "github.com/lightningnetwork/lnd/ticker"
82
        "github.com/lightningnetwork/lnd/tor"
83
        "github.com/lightningnetwork/lnd/walletunlocker"
84
        "github.com/lightningnetwork/lnd/watchtower/blob"
85
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
86
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
87
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
88
)
89

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

234
        start sync.Once
235
        stop  sync.Once
236

237
        cfg *Config
238

239
        implCfg *ImplementationCfg
240

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

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

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

252
        chanStatusMgr *netann.ChanStatusManager
253

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

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

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

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

274
        mu sync.RWMutex
275

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

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

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

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

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

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

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

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

326
        cc *chainreg.ChainControl
327

328
        fundingMgr *funding.Manager
329

330
        graphDB *graphdb.ChannelGraph
331

332
        chanStateDB *channeldb.ChannelStateDB
333

334
        addrSource channeldb.AddrSource
335

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

340
        invoicesDB invoices.InvoiceDB
341

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

346
        aliasMgr *aliasmgr.Manager
347

348
        htlcSwitch *htlcswitch.Switch
349

350
        interceptableSwitch *htlcswitch.InterceptableSwitch
351

352
        invoices *invoices.InvoiceRegistry
353

354
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
355

356
        channelNotifier *channelnotifier.ChannelNotifier
357

358
        peerNotifier *peernotifier.PeerNotifier
359

360
        htlcNotifier *htlcswitch.HtlcNotifier
361

362
        witnessBeacon contractcourt.WitnessBeacon
363

364
        breachArbitrator *contractcourt.BreachArbitrator
365

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

369
        graphBuilder *graph.Builder
370

371
        chanRouter *routing.ChannelRouter
372

373
        controlTower routing.ControlTower
374

375
        authGossiper *discovery.AuthenticatedGossiper
376

377
        localChanMgr *localchans.Manager
378

379
        utxoNursery *contractcourt.UtxoNursery
380

381
        sweeper *sweep.UtxoSweeper
382

383
        chainArb *contractcourt.ChainArbitrator
384

385
        sphinx *hop.OnionProcessor
386

387
        towerClientMgr *wtclient.Manager
388

389
        connMgr *connmgr.ConnManager
390

391
        sigPool *lnwallet.SigPool
392

393
        writePool *pool.Write
394

395
        readPool *pool.Read
396

397
        tlsManager *TLSManager
398

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

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

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

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

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

421
        hostAnn *netann.HostAnnouncer
422

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

426
        customMessageServer *subscribe.Server
427

428
        onionMessageServer *subscribe.Server
429

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

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

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

440
        quit chan struct{}
441

442
        wg sync.WaitGroup
443
}
444

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

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

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

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

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

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

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

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

500
                                        s.mu.Lock()
3✔
501

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

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

516
                                        s.mu.Unlock()
3✔
517

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

524
        return nil
3✔
525
}
526

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
707
                listenAddrs: listenAddrs,
3✔
708

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

3✔
713
                torController: torController,
3✔
714

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

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

3✔
731
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
732

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

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

3✔
737
                tlsManager: tlsManager,
3✔
738

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

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

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

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

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

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

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

3✔
769
                return nil
3✔
770
        }
771

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1005
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
1006

3✔
1007
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1008
                cfg.Routing.StrictZombiePruning
3✔
1009

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

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

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

1058
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1059

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

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

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

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

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

1125
        s.peerAccessMan = peerAccessMan
3✔
1126

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

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

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

×
1154
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1155
                },
×
1156
        }
1157

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1444
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1445
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1446

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

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

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

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

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

1507
                        minConf := uint64(3)
×
1508
                        maxConf := uint64(6)
×
1509

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

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

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

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

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

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

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

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

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

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

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

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

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

1686
        if cfg.WtClient.Active {
6✔
1687
                policy := wtpolicy.DefaultPolicy()
3✔
1688
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1689

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

3✔
1696
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1697

3✔
1698
                if err := policy.Validate(); err != nil {
3✔
1699
                        return nil, err
×
1700
                }
×
1701

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

3✔
1708
                        return brontide.Dial(
3✔
1709
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1710
                        )
3✔
1711
                }
3✔
1712

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

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

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

1736
                        return br, channel.ChanType, nil
3✔
1737
                }
1738

1739
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1740

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

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

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

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

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

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

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

×
1809
                                        return s.genNodeAnnouncement(
×
1810
                                                nil, modifier...,
×
1811
                                        )
×
1812
                                }),
×
1813
                })
1814
        }
1815

1816
        // Create liveness monitor.
1817
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1818

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

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

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

3✔
1856
        // Finally, register the subsystems in blockbeat.
3✔
1857
        s.registerBlockConsumers()
3✔
1858

3✔
1859
        return s, nil
3✔
1860
}
1861

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

3✔
1867
        switch c := cfg.Estimator.Config().(type) {
3✔
1868
        case routing.AprioriConfig:
3✔
1869
                routerCfg.ProbabilityEstimatorType =
3✔
1870
                        routing.AprioriEstimatorName
3✔
1871

3✔
1872
                targetCfg := routerCfg.AprioriConfig
3✔
1873
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1874
                targetCfg.Weight = c.AprioriWeight
3✔
1875
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1876
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1877

1878
        case routing.BimodalConfig:
3✔
1879
                routerCfg.ProbabilityEstimatorType =
3✔
1880
                        routing.BimodalEstimatorName
3✔
1881

3✔
1882
                targetCfg := routerCfg.BimodalConfig
3✔
1883
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1884
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1885
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1886
        }
1887

1888
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1889
}
1890

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

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

3✔
1916
        data, err := u.DataToSign()
3✔
1917
        if err != nil {
3✔
1918
                return nil, err
×
1919
        }
×
1920

1921
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1922
}
1923

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

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

×
1942
                chainBackendAttempts = 0
×
1943
        }
×
1944

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

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

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

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

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

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

2004
        checks := []*healthcheck.Observation{
3✔
2005
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2006
        }
3✔
2007

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

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

3✔
2038
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2039
                        "remote signer connection",
3✔
2040
                        rpcwallet.HealthCheck(
3✔
2041
                                s.cfg.RemoteSigner,
3✔
2042

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

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

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

2082
                                if !leader {
×
2083
                                        srvrLog.Debug("Not the current leader")
×
2084
                                        return fmt.Errorf("not the current " +
×
2085
                                                "leader")
×
2086
                                }
×
2087

2088
                                return nil
×
2089
                        },
2090
                        cfg.HealthChecks.LeaderCheck.Interval,
2091
                        cfg.HealthChecks.LeaderCheck.Timeout,
2092
                        cfg.HealthChecks.LeaderCheck.Backoff,
2093
                        cfg.HealthChecks.LeaderCheck.Attempts,
2094
                )
2095

2096
                checks = append(checks, leaderCheck)
×
2097
        }
2098

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2241
                beat, err := s.getStartingBeat()
3✔
2242
                if err != nil {
3✔
2243
                        startErr = err
×
2244
                        return
×
2245
                }
×
2246

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2472
                        startErr = err
×
2473
                        return
×
2474
                }
×
2475

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

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

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

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

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

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

2517
                                copy(result[idx][:], servers)
×
2518
                        }
2519

2520
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2521
                }
2522

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

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

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

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

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

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

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

3✔
2599
                ctx := context.Background()
3✔
2600

3✔
2601
                close(s.quit)
3✔
2602

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

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

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

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

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

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

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

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

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

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

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

2750
        return nil
3✔
2751
}
2752

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

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

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

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

2782
        return externalIPs, nil
×
2783
}
2784

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

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

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

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

2820
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2821

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

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

2852
                        if ip.Equal(s.lastDetectedIP) {
×
2853
                                continue
×
2854
                        }
2855

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

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

2873
                                newAddrs = append(newAddrs, addr)
×
2874
                        }
2875

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

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

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

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

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

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

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

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

3✔
2942
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2943

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

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

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

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

2976
        return bootStrappers, nil
3✔
2977
}
2978

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

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

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

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

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

3009
        return ignore
3✔
3010
}
3011

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

3✔
3020
        defer s.wg.Done()
3✔
3021

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

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

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

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

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

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

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

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

3070
                        if epochAttempts > 0 &&
×
3071
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3072

×
3073
                                sampleTicker.Stop()
×
3074

×
3075
                                backOff *= 2
×
3076
                                if backOff > bootstrapBackOffCeiling {
×
3077
                                        backOff = bootstrapBackOffCeiling
×
3078
                                }
×
3079

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

3086
                        atomic.StoreUint32(&epochErrors, 0)
×
3087
                        epochAttempts = 0
×
3088

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
3183
                if numActivePeers >= numTargetPeers {
6✔
3184
                        return
3✔
3185
                }
3✔
3186

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

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

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

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

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

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

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

3258
                wg.Wait()
3✔
3259
        }
3260
}
3261

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

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

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

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

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

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

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

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

3332
        return nil
×
3333
}
3334

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

3✔
3341
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3342
        if err != nil {
3✔
3343
                return nil, err
×
3344
        }
×
3345

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

3352
        return nil, fmt.Errorf("unable to find channel")
3✔
3353
}
3354

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

3✔
3360
        return *s.currentNodeAnn
3✔
3361
}
3✔
3362

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

3✔
3369
        s.mu.Lock()
3✔
3370
        defer s.mu.Unlock()
3✔
3371

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

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

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

3396
        // Always update the timestamp when refreshing to ensure the update
3397
        // propagates.
3398
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3399

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

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

3413
        // If signing succeeds, update the current announcement.
3414
        *s.currentNodeAnn = newNodeAnn
3✔
3415

3✔
3416
        return *s.currentNodeAnn, nil
3✔
3417
}
3418

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

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

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

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

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

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

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

3462
        return nil
3✔
3463
}
3464

3465
type nodeAddresses struct {
3466
        pubKey    *btcec.PublicKey
3467
        addresses []net.Addr
3468
}
3469

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

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

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

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

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

3514
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3515

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

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

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

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

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

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

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

×
3580
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3581
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3582

×
3583
                        return err
×
3584
                }
×
3585
        }
3586

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

3592
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3593
                len(nodeAddrsMap))
3✔
3594

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

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

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

3✔
3623
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3624
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3625
                }
3✔
3626

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

3✔
3637
                        go s.connectToPersistentPeer(pubStr)
3✔
3638
                } else {
3✔
3639
                        go s.delayInitialReconnect(pubStr)
×
3640
                }
×
3641

3642
                numOutboundConns++
3✔
3643
        }
3644

3645
        return nil
3✔
3646
}
3647

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

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

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

3✔
3675
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3676
                        "peer has no open channels", compressedPubKey)
3✔
3677

3✔
3678
                return
3✔
3679
        }
3✔
3680
        s.mu.Unlock()
3✔
3681
}
3682

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

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

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

3723
                peers = append(peers, sPeer)
3✔
3724
        }
3725
        s.mu.RUnlock()
3✔
3726

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

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

3✔
3741
                        p.SendMessageLazy(false, msgs...)
3✔
3742
                }(sPeer)
3✔
3743
        }
3744

3745
        // Wait for all messages to have been dispatched before returning to
3746
        // caller.
3747
        wg.Wait()
3✔
3748

3✔
3749
        return nil
3✔
3750
}
3751

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

3✔
3759
        s.mu.Lock()
3✔
3760

3✔
3761
        // Compute the target peer's identifier.
3✔
3762
        pubStr := string(peerKey[:])
3✔
3763

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

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

3786
                // Connected, can return early.
3787
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3788

3✔
3789
                select {
3✔
3790
                case peerChan <- peer:
3✔
3791
                case <-s.quit:
×
3792
                }
3793

3794
                return
3✔
3795
        }
3796

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

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

3✔
3812
        c := make(chan struct{})
3✔
3813

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

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

3✔
3830
        return c
3✔
3831
}
3832

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

3✔
3842
        pubStr := string(peerKey.SerializeCompressed())
3✔
3843

3✔
3844
        return s.findPeerByPubStr(pubStr)
3✔
3845
}
3✔
3846

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

3✔
3856
        return s.findPeerByPubStr(pubStr)
3✔
3857
}
3✔
3858

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

3867
        return peer, nil
3✔
3868
}
3869

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

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

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

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

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

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

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

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

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

3942
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3943
        pubSer := nodePub.SerializeCompressed()
3✔
3944
        pubStr := string(pubSer)
3✔
3945

3✔
3946
        var pubBytes [33]byte
3✔
3947
        copy(pubBytes[:], pubSer)
3✔
3948

3✔
3949
        s.mu.Lock()
3✔
3950
        defer s.mu.Unlock()
3✔
3951

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

3✔
3959
                conn.Close()
3✔
3960
                return
3✔
3961
        }
3✔
3962

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

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

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

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

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

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

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

3✔
4015
                s.cancelConnReqs(pubStr, nil)
3✔
4016

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

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

4038
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4039
        pubSer := nodePub.SerializeCompressed()
3✔
4040
        pubStr := string(pubSer)
3✔
4041

3✔
4042
        var pubBytes [33]byte
3✔
4043
        copy(pubBytes[:], pubSer)
3✔
4044

3✔
4045
        s.mu.Lock()
3✔
4046
        defer s.mu.Unlock()
3✔
4047

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

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

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

×
4074
                if connReq != nil {
×
4075
                        s.connMgr.Remove(connReq.ID())
×
4076
                }
×
4077

4078
                conn.Close()
×
4079
                return
×
4080
        }
4081

4082
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4083
                conn.RemoteAddr())
3✔
4084

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

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

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

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

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

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

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

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

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

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

4178
        for _, connReq := range connReqs {
6✔
4179
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4180

3✔
4181
                // Atomically capture the current request identifier.
3✔
4182
                connID := connReq.ID()
3✔
4183

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

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

4195
                s.connMgr.Remove(connID)
3✔
4196
        }
4197

4198
        delete(s.persistentConnReqs, pubStr)
3✔
4199
}
4200

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

3✔
4207
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4208
                Peer: peer,
3✔
4209
                Msg:  msg,
3✔
4210
        })
3✔
4211
}
3✔
4212

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4310
                conn.Close()
×
4311

×
4312
                return
×
4313
        }
×
4314

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

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

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

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

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

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

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

3✔
4400
                        return s.genNodeAnnouncement(nil)
3✔
4401
                },
3✔
4402

4403
                PongBuf: s.pongBuf,
4404

4405
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4406

4407
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4408

4409
                FundingManager: s.fundingMgr,
4410

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

4442
                        return clock.NewDefaultClock().Now().Before(
3✔
4443
                                EndorsementExperimentEnd,
3✔
4444
                        )
3✔
4445
                },
4446
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4447
        }
4448

4449
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4450
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4451

3✔
4452
        p := peer.NewBrontide(pCfg)
3✔
4453

3✔
4454
        // Update the access manager with the access permission for this peer.
3✔
4455
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4456

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

3✔
4460
        s.addPeer(p)
3✔
4461

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

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

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

4481
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4482

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

×
4489
                return
×
4490
        }
×
4491

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

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

3✔
4501
        s.peersByPub[pubStr] = p
3✔
4502

3✔
4503
        if p.Inbound() {
6✔
4504
                s.inboundPeers[pubStr] = p
3✔
4505
        } else {
6✔
4506
                s.outboundPeers[pubStr] = p
3✔
4507
        }
3✔
4508

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

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

3✔
4527
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4528

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

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

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

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

3✔
4555
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4556
                return
3✔
4557
        }
3✔
4558

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

3✔
4563
        s.mu.Lock()
3✔
4564
        defer s.mu.Unlock()
3✔
4565

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

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

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

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

3✔
4600
        ctx := btclog.WithCtx(
3✔
4601
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4602
        )
3✔
4603

3✔
4604
        p.WaitForDisconnect(ready)
3✔
4605

3✔
4606
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4607

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

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

3✔
4621
        pubKey := p.IdentityKey()
3✔
4622

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

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

4637
        for _, link := range links {
6✔
4638
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4639
        }
3✔
4640

4641
        s.mu.Lock()
3✔
4642
        defer s.mu.Unlock()
3✔
4643

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

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

3✔
4658
                pubKey := p.PubKey()
3✔
4659
                pubStr := string(pubKey[:])
3✔
4660

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4778
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4779
                        "connection")
3✔
4780

3✔
4781
                s.connectToPersistentPeer(pubStr)
3✔
4782
        }()
4783
}
4784

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

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

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

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

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

4835
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4836

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

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

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

3✔
4860
                        s.mu.Lock()
3✔
4861
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4862
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4863
                        )
3✔
4864
                        s.mu.Unlock()
3✔
4865

3✔
4866
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4867
                                "channel peer %v", addr)
3✔
4868

3✔
4869
                        go s.connMgr.Connect(connReq)
3✔
4870

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

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

4891
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4892

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

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

3✔
4904
        delete(s.peersByPub, pubStr)
3✔
4905

3✔
4906
        if p.Inbound() {
6✔
4907
                delete(s.inboundPeers, pubStr)
3✔
4908
        } else {
6✔
4909
                delete(s.outboundPeers, pubStr)
3✔
4910
        }
3✔
4911

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

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

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

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

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

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

3✔
4949
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4950
        }()
4951
}
4952

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

3✔
4961
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4962

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

3✔
4969
        // Ensure we're not already connected to this peer.
3✔
4970
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4971

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

4980
        // Peer was not found, continue to pursue connection with peer.
4981

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

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

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

3✔
5013
                go s.connMgr.Connect(connReq)
3✔
5014

3✔
5015
                return nil
3✔
5016
        }
5017
        s.mu.Unlock()
3✔
5018

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

3✔
5026
        select {
3✔
5027
        case err := <-errChan:
3✔
5028
                return err
3✔
5029
        case <-s.quit:
×
5030
                return ErrServerShuttingDown
×
5031
        }
5032
}
5033

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

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

5052
        close(errChan)
3✔
5053

3✔
5054
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5055
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5056

3✔
5057
        s.OutboundPeerConnected(nil, conn)
3✔
5058
}
5059

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

3✔
5068
        s.mu.Lock()
3✔
5069
        defer s.mu.Unlock()
3✔
5070

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

5079
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5080

3✔
5081
        s.cancelConnReqs(pubStr, nil)
3✔
5082

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

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

3✔
5096
        return nil
3✔
5097
}
5098

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

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

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

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

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

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

×
5146
                return req.Updates, req.Err
×
5147
        }
×
5148

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

3✔
5155
        return req.Updates, req.Err
3✔
5156
}
5157

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

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

5170
        return peers
3✔
5171
}
5172

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

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

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

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

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

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

3✔
5209
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5210
        if err != nil {
3✔
5211
                return nil, err
×
5212
        }
×
5213

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

5219
        if len(node.Addresses) == 0 {
6✔
5220
                return nil, errNoAdvertisedAddr
3✔
5221
        }
3✔
5222

5223
        return node.Addresses, nil
3✔
5224
}
5225

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

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

5238
                return netann.ExtractChannelUpdate(
3✔
5239
                        ourPubKey[:], info, edge1, edge2,
3✔
5240
                )
3✔
5241
        }
5242
}
5243

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

3✔
5250
        var (
3✔
5251
                peerAlias    *lnwire.ShortChannelID
3✔
5252
                defaultAlias lnwire.ShortChannelID
3✔
5253
        )
3✔
5254

3✔
5255
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5256

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

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

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

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

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

5299
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5300
        if err != nil {
6✔
5301
                return err
3✔
5302
        }
3✔
5303

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

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

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

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

5332
        msg := lnwire.NewOnionMessage(pathKey, onion)
3✔
5333

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

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

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

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

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

5368
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5369
                        DeliveryAddress: addr,
3✔
5370
                        InternalKey:     internalKeyDesc,
3✔
5371
                })
3✔
5372
        }
5373
}
5374

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

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

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

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

5413
                // If the channel is still reported as pending, remove it from
5414
                // the map.
5415
                delete(closedSCIDs, c.ShortChannelID)
×
5416

×
5417
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5418
                        c.ShortChannelID)
×
5419
        }
5420

5421
        return closedSCIDs
3✔
5422
}
5423

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

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

×
5436
                return &chainio.Beat{}, nil
×
5437
        }
×
5438

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

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

3✔
5455
                // Update the current blockbeat.
3✔
5456
                beat = chainio.NewBeat(*bestBlock)
3✔
5457

5458
        case <-s.quit:
×
5459
                srvrLog.Debug("LND shutting down")
×
5460
        }
5461

5462
        return beat, nil
3✔
5463
}
5464

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

3✔
5470
        pubBytes := peerPub.SerializeCompressed()
3✔
5471

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

5479
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5480
}
5481

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

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

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

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

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

5518
        return closeUpdates, nil
3✔
5519
}
5520

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

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

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

5547
        return updates, nil
3✔
5548
}
5549

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

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

×
5573
                        listenPorts = append(listenPorts, uint16(port))
×
5574
                }
×
5575

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

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

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

5606
        var (
3✔
5607
                alias          = s.cfg.Alias
3✔
5608
                nodeLastUpdate = time.Now()
3✔
5609
        )
3✔
5610

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

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

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

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

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

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

5658
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5659
        if err != nil {
3✔
5660
                return err
×
5661
        }
×
5662

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

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

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

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

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

5707
        s.currentNodeAnn = nodeAnn
3✔
5708

3✔
5709
        return nil
3✔
5710
}
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

© 2026 Coveralls, Inc