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

lightningnetwork / lnd / 15569071323

10 Jun 2025 08:00PM UTC coverage: 58.363% (+0.03%) from 58.331%
15569071323

Pull #9752

github

web-flow
Merge 3e7a64ce6 into 32592dbd2
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

990 existing lines in 11 files now uncovered.

97788 of 167550 relevant lines covered (58.36%)

1.81 hits per line

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

64.19
/server.go
1
package lnd
2

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

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

84
const (
85
        // defaultMinPeers is the minimum number of peers nodes should always be
86
        // connected to.
87
        defaultMinPeers = 3
88

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

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

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

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

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

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

122
        // ErrServerShuttingDown indicates that the server is in the process of
123
        // gracefully exiting.
124
        ErrServerShuttingDown = errors.New("server is shutting down")
125

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

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

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

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

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

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

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

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

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

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

186
        // peerStatusTemporary indicates that the peer only has temporary p2p
187
        // access to the server.
188
        peerStatusTemporary
189

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

196
// peerSlotStatus determines whether a peer gets access to one of our free
197
// slots or gets to bypass this safety mechanism.
198
type peerSlotStatus struct {
199
        // state determines which privileges the peer has with our server.
200
        state peerAccessStatus
201
}
202

203
// server is the main server of the Lightning Network Daemon. The server houses
204
// global state pertaining to the wallet, database, and the rpcserver.
205
// Additionally, the server is also used as a central messaging bus to interact
206
// with any of its companion objects.
207
type server struct {
208
        active   int32 // atomic
209
        stopping int32 // atomic
210

211
        start sync.Once
212
        stop  sync.Once
213

214
        cfg *Config
215

216
        implCfg *ImplementationCfg
217

218
        // identityECDH is an ECDH capable wrapper for the private key used
219
        // to authenticate any incoming connections.
220
        identityECDH keychain.SingleKeyECDH
221

222
        // identityKeyLoc is the key locator for the above wrapped identity key.
223
        identityKeyLoc keychain.KeyLocator
224

225
        // nodeSigner is an implementation of the MessageSigner implementation
226
        // that's backed by the identity private key of the running lnd node.
227
        nodeSigner *netann.NodeSigner
228

229
        chanStatusMgr *netann.ChanStatusManager
230

231
        // listenAddrs is the list of addresses the server is currently
232
        // listening on.
233
        listenAddrs []net.Addr
234

235
        // torController is a client that will communicate with a locally
236
        // running Tor server. This client will handle initiating and
237
        // authenticating the connection to the Tor server, automatically
238
        // creating and setting up onion services, etc.
239
        torController *tor.Controller
240

241
        // natTraversal is the specific NAT traversal technique used to
242
        // automatically set up port forwarding rules in order to advertise to
243
        // the network that the node is accepting inbound connections.
244
        natTraversal nat.Traversal
245

246
        // lastDetectedIP is the last IP detected by the NAT traversal technique
247
        // above. This IP will be watched periodically in a goroutine in order
248
        // to handle dynamic IP changes.
249
        lastDetectedIP net.IP
250

251
        mu sync.RWMutex
252

253
        // peersByPub is a map of the active peers.
254
        //
255
        // NOTE: The key used here is the raw bytes of the peer's public key to
256
        // string conversion, which means it cannot be printed using `%s` as it
257
        // will just print the binary.
258
        //
259
        // TODO(yy): Use the hex string instead.
260
        peersByPub map[string]*peer.Brontide
261

262
        inboundPeers  map[string]*peer.Brontide
263
        outboundPeers map[string]*peer.Brontide
264

265
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
266
        peerDisconnectedListeners map[string][]chan<- struct{}
267

268
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
269
        // will continue to send messages even if there are no active channels
270
        // and the value below is false. Once it's pruned, all its connections
271
        // will be closed, thus the Brontide.Start will return an error.
272
        persistentPeers        map[string]bool
273
        persistentPeersBackoff map[string]time.Duration
274
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
275
        persistentConnReqs     map[string][]*connmgr.ConnReq
276
        persistentRetryCancels map[string]chan struct{}
277

278
        // peerErrors keeps a set of peer error buffers for peers that have
279
        // disconnected from us. This allows us to track historic peer errors
280
        // over connections. The string of the peer's compressed pubkey is used
281
        // as a key for this map.
282
        peerErrors map[string]*queue.CircularBuffer
283

284
        // ignorePeerTermination tracks peers for which the server has initiated
285
        // a disconnect. Adding a peer to this map causes the peer termination
286
        // watcher to short circuit in the event that peers are purposefully
287
        // disconnected.
288
        ignorePeerTermination map[*peer.Brontide]struct{}
289

290
        // scheduledPeerConnection maps a pubkey string to a callback that
291
        // should be executed in the peerTerminationWatcher the prior peer with
292
        // the same pubkey exits.  This allows the server to wait until the
293
        // prior peer has cleaned up successfully, before adding the new peer
294
        // intended to replace it.
295
        scheduledPeerConnection map[string]func()
296

297
        // pongBuf is a shared pong reply buffer we'll use across all active
298
        // peer goroutines. We know the max size of a pong message
299
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
300
        // avoid allocations each time we need to send a pong message.
301
        pongBuf []byte
302

303
        cc *chainreg.ChainControl
304

305
        fundingMgr *funding.Manager
306

307
        graphDB *graphdb.ChannelGraph
308

309
        chanStateDB *channeldb.ChannelStateDB
310

311
        addrSource channeldb.AddrSource
312

313
        // miscDB is the DB that contains all "other" databases within the main
314
        // channel DB that haven't been separated out yet.
315
        miscDB *channeldb.DB
316

317
        invoicesDB invoices.InvoiceDB
318

319
        aliasMgr *aliasmgr.Manager
320

321
        htlcSwitch *htlcswitch.Switch
322

323
        interceptableSwitch *htlcswitch.InterceptableSwitch
324

325
        invoices *invoices.InvoiceRegistry
326

327
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
328

329
        channelNotifier *channelnotifier.ChannelNotifier
330

331
        peerNotifier *peernotifier.PeerNotifier
332

333
        htlcNotifier *htlcswitch.HtlcNotifier
334

335
        witnessBeacon contractcourt.WitnessBeacon
336

337
        breachArbitrator *contractcourt.BreachArbitrator
338

339
        missionController *routing.MissionController
340
        defaultMC         *routing.MissionControl
341

342
        graphBuilder *graph.Builder
343

344
        chanRouter *routing.ChannelRouter
345

346
        controlTower routing.ControlTower
347

348
        authGossiper *discovery.AuthenticatedGossiper
349

350
        localChanMgr *localchans.Manager
351

352
        utxoNursery *contractcourt.UtxoNursery
353

354
        sweeper *sweep.UtxoSweeper
355

356
        chainArb *contractcourt.ChainArbitrator
357

358
        sphinx *hop.OnionProcessor
359

360
        towerClientMgr *wtclient.Manager
361

362
        connMgr *connmgr.ConnManager
363

364
        sigPool *lnwallet.SigPool
365

366
        writePool *pool.Write
367

368
        readPool *pool.Read
369

370
        tlsManager *TLSManager
371

372
        // featureMgr dispatches feature vectors for various contexts within the
373
        // daemon.
374
        featureMgr *feature.Manager
375

376
        // currentNodeAnn is the node announcement that has been broadcast to
377
        // the network upon startup, if the attributes of the node (us) has
378
        // changed since last start.
379
        currentNodeAnn *lnwire.NodeAnnouncement
380

381
        // chansToRestore is the set of channels that upon starting, the server
382
        // should attempt to restore/recover.
383
        chansToRestore walletunlocker.ChannelsToRecover
384

385
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
386
        // backups are consistent at all times. It interacts with the
387
        // channelNotifier to be notified of newly opened and closed channels.
388
        chanSubSwapper *chanbackup.SubSwapper
389

390
        // chanEventStore tracks the behaviour of channels and their remote peers to
391
        // provide insights into their health and performance.
392
        chanEventStore *chanfitness.ChannelEventStore
393

394
        hostAnn *netann.HostAnnouncer
395

396
        // livenessMonitor monitors that lnd has access to critical resources.
397
        livenessMonitor *healthcheck.Monitor
398

399
        customMessageServer *subscribe.Server
400

401
        // txPublisher is a publisher with fee-bumping capability.
402
        txPublisher *sweep.TxPublisher
403

404
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
405
        // of new blocks.
406
        blockbeatDispatcher *chainio.BlockbeatDispatcher
407

408
        // peerAccessMan implements peer access controls.
409
        peerAccessMan *accessMan
410

411
        quit chan struct{}
412

413
        wg sync.WaitGroup
414
}
415

416
// updatePersistentPeerAddrs subscribes to topology changes and stores
417
// advertised addresses for any NodeAnnouncements from our persisted peers.
418
func (s *server) updatePersistentPeerAddrs() error {
3✔
419
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
420
        if err != nil {
3✔
421
                return err
×
422
        }
×
423

424
        s.wg.Add(1)
3✔
425
        go func() {
6✔
426
                defer func() {
6✔
427
                        graphSub.Cancel()
3✔
428
                        s.wg.Done()
3✔
429
                }()
3✔
430

431
                for {
6✔
432
                        select {
3✔
433
                        case <-s.quit:
3✔
434
                                return
3✔
435

436
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
437
                                // If the router is shutting down, then we will
3✔
438
                                // as well.
3✔
439
                                if !ok {
3✔
440
                                        return
×
441
                                }
×
442

443
                                for _, update := range topChange.NodeUpdates {
6✔
444
                                        pubKeyStr := string(
3✔
445
                                                update.IdentityKey.
3✔
446
                                                        SerializeCompressed(),
3✔
447
                                        )
3✔
448

3✔
449
                                        // We only care about updates from
3✔
450
                                        // our persistentPeers.
3✔
451
                                        s.mu.RLock()
3✔
452
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
453
                                        s.mu.RUnlock()
3✔
454
                                        if !ok {
6✔
455
                                                continue
3✔
456
                                        }
457

458
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
459
                                                len(update.Addresses))
3✔
460

3✔
461
                                        for _, addr := range update.Addresses {
6✔
462
                                                addrs = append(addrs,
3✔
463
                                                        &lnwire.NetAddress{
3✔
464
                                                                IdentityKey: update.IdentityKey,
3✔
465
                                                                Address:     addr,
3✔
466
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
467
                                                        },
3✔
468
                                                )
3✔
469
                                        }
3✔
470

471
                                        s.mu.Lock()
3✔
472

3✔
473
                                        // Update the stored addresses for this
3✔
474
                                        // to peer to reflect the new set.
3✔
475
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
476

3✔
477
                                        // If there are no outstanding
3✔
478
                                        // connection requests for this peer
3✔
479
                                        // then our work is done since we are
3✔
480
                                        // not currently trying to connect to
3✔
481
                                        // them.
3✔
482
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
483
                                                s.mu.Unlock()
3✔
484
                                                continue
3✔
485
                                        }
486

487
                                        s.mu.Unlock()
3✔
488

3✔
489
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
490
                                }
491
                        }
492
                }
493
        }()
494

495
        return nil
3✔
496
}
497

498
// CustomMessage is a custom message that is received from a peer.
499
type CustomMessage struct {
500
        // Peer is the peer pubkey
501
        Peer [33]byte
502

503
        // Msg is the custom wire message.
504
        Msg *lnwire.Custom
505
}
506

507
// parseAddr parses an address from its string format to a net.Addr.
508
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
509
        var (
3✔
510
                host string
3✔
511
                port int
3✔
512
        )
3✔
513

3✔
514
        // Split the address into its host and port components.
3✔
515
        h, p, err := net.SplitHostPort(address)
3✔
516
        if err != nil {
3✔
517
                // If a port wasn't specified, we'll assume the address only
×
518
                // contains the host so we'll use the default port.
×
519
                host = address
×
520
                port = defaultPeerPort
×
521
        } else {
3✔
522
                // Otherwise, we'll note both the host and ports.
3✔
523
                host = h
3✔
524
                portNum, err := strconv.Atoi(p)
3✔
525
                if err != nil {
3✔
526
                        return nil, err
×
527
                }
×
528
                port = portNum
3✔
529
        }
530

531
        if tor.IsOnionHost(host) {
3✔
532
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
533
        }
×
534

535
        // If the host is part of a TCP address, we'll use the network
536
        // specific ResolveTCPAddr function in order to resolve these
537
        // addresses over Tor in order to prevent leaking your real IP
538
        // address.
539
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
540
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
541
}
542

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

3✔
548
        return func(a net.Addr) (net.Conn, error) {
6✔
549
                lnAddr := a.(*lnwire.NetAddress)
3✔
550
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
551
        }
3✔
552
}
553

554
// newServer creates a new instance of the server which is to listen using the
555
// passed listener address.
556
//
557
//nolint:funlen
558
func newServer(_ context.Context, cfg *Config, listenAddrs []net.Addr,
559
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
560
        nodeKeyDesc *keychain.KeyDescriptor,
561
        chansToRestore walletunlocker.ChannelsToRecover,
562
        chanPredicate chanacceptor.ChannelAcceptor,
563
        torController *tor.Controller, tlsManager *TLSManager,
564
        leaderElector cluster.LeaderElector,
565
        implCfg *ImplementationCfg) (*server, error) {
3✔
566

3✔
567
        var (
3✔
568
                err         error
3✔
569
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
570

3✔
571
                // We just derived the full descriptor, so we know the public
3✔
572
                // key is set on it.
3✔
573
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
574
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
575
                )
3✔
576
        )
3✔
577

3✔
578
        var serializedPubKey [33]byte
3✔
579
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
580

3✔
581
        netParams := cfg.ActiveNetParams.Params
3✔
582

3✔
583
        // Initialize the sphinx router.
3✔
584
        replayLog := htlcswitch.NewDecayedLog(
3✔
585
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
586
        )
3✔
587
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
588

3✔
589
        writeBufferPool := pool.NewWriteBuffer(
3✔
590
                pool.DefaultWriteBufferGCInterval,
3✔
591
                pool.DefaultWriteBufferExpiryInterval,
3✔
592
        )
3✔
593

3✔
594
        writePool := pool.NewWrite(
3✔
595
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
596
        )
3✔
597

3✔
598
        readBufferPool := pool.NewReadBuffer(
3✔
599
                pool.DefaultReadBufferGCInterval,
3✔
600
                pool.DefaultReadBufferExpiryInterval,
3✔
601
        )
3✔
602

3✔
603
        readPool := pool.NewRead(
3✔
604
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
605
        )
3✔
606

3✔
607
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
608
        // controller, then we'll exit as this is incompatible.
3✔
609
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
610
                implCfg.AuxFundingController.IsNone() {
3✔
611

×
612
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
613
                        "aux controllers")
×
614
        }
×
615

616
        //nolint:ll
617
        featureMgr, err := feature.NewManager(feature.Config{
3✔
618
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
619
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
620
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
621
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
622
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
623
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
624
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
625
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
626
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
627
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
628
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
629
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
630
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
631
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
632
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
633
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
634
        })
3✔
635
        if err != nil {
3✔
636
                return nil, err
×
637
        }
×
638

639
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
640
        registryConfig := invoices.RegistryConfig{
3✔
641
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
642
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
643
                Clock:                       clock.NewDefaultClock(),
3✔
644
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
645
                AcceptAMP:                   cfg.AcceptAMP,
3✔
646
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
647
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
648
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
649
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
650
        }
3✔
651

3✔
652
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
653

3✔
654
        s := &server{
3✔
655
                cfg:            cfg,
3✔
656
                implCfg:        implCfg,
3✔
657
                graphDB:        dbs.GraphDB,
3✔
658
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
659
                addrSource:     addrSource,
3✔
660
                miscDB:         dbs.ChanStateDB,
3✔
661
                invoicesDB:     dbs.InvoiceDB,
3✔
662
                cc:             cc,
3✔
663
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
664
                writePool:      writePool,
3✔
665
                readPool:       readPool,
3✔
666
                chansToRestore: chansToRestore,
3✔
667

3✔
668
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
669
                        cc.ChainNotifier,
3✔
670
                ),
3✔
671
                channelNotifier: channelnotifier.New(
3✔
672
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
673
                ),
3✔
674

3✔
675
                identityECDH:   nodeKeyECDH,
3✔
676
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
677
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
678

3✔
679
                listenAddrs: listenAddrs,
3✔
680

3✔
681
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
682
                // schedule
3✔
683
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
684

3✔
685
                torController: torController,
3✔
686

3✔
687
                persistentPeers:         make(map[string]bool),
3✔
688
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
689
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
690
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
691
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
692
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
693
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
694
                scheduledPeerConnection: make(map[string]func()),
3✔
695
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
696

3✔
697
                peersByPub:                make(map[string]*peer.Brontide),
3✔
698
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
699
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
700
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
701
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
702

3✔
703
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
704

3✔
705
                customMessageServer: subscribe.NewServer(),
3✔
706

3✔
707
                tlsManager: tlsManager,
3✔
708

3✔
709
                featureMgr: featureMgr,
3✔
710
                quit:       make(chan struct{}),
3✔
711
        }
3✔
712

3✔
713
        // Start the low-level services once they are initialized.
3✔
714
        //
3✔
715
        // TODO(yy): break the server startup into four steps,
3✔
716
        // 1. init the low-level services.
3✔
717
        // 2. start the low-level services.
3✔
718
        // 3. init the high-level services.
3✔
719
        // 4. start the high-level services.
3✔
720
        if err := s.startLowLevelServices(); err != nil {
3✔
721
                return nil, err
×
722
        }
×
723

724
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
725
        if err != nil {
3✔
726
                return nil, err
×
727
        }
×
728

729
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
730
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
731
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
732
        )
3✔
733
        s.invoices = invoices.NewRegistry(
3✔
734
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
735
        )
3✔
736

3✔
737
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
738

3✔
739
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
740
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
741

3✔
742
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
743
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
744
                if err != nil {
3✔
745
                        return err
×
746
                }
×
747

748
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
749

3✔
750
                return nil
3✔
751
        }
752

753
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
754
        if err != nil {
3✔
755
                return nil, err
×
756
        }
×
757

758
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
759
                DB:                   dbs.ChanStateDB,
3✔
760
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
761
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
762
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
763
                LocalChannelClose: func(pubKey []byte,
3✔
764
                        request *htlcswitch.ChanClose) {
6✔
765

3✔
766
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
767
                        if err != nil {
3✔
768
                                srvrLog.Errorf("unable to close channel, peer"+
×
769
                                        " with %v id can't be found: %v",
×
770
                                        pubKey, err,
×
771
                                )
×
772
                                return
×
773
                        }
×
774

775
                        peer.HandleLocalCloseChanReqs(request)
3✔
776
                },
777
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
778
                SwitchPackager:         channeldb.NewSwitchPackager(),
779
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
780
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
781
                Notifier:               s.cc.ChainNotifier,
782
                HtlcNotifier:           s.htlcNotifier,
783
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
784
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
785
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
786
                AllowCircularRoute:     cfg.AllowCircularRoute,
787
                RejectHTLC:             cfg.RejectHTLC,
788
                Clock:                  clock.NewDefaultClock(),
789
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
790
                MaxFeeExposure:         thresholdMSats,
791
                SignAliasUpdate:        s.signAliasUpdate,
792
                IsAlias:                aliasmgr.IsAlias,
793
        }, uint32(currentHeight))
794
        if err != nil {
3✔
795
                return nil, err
×
796
        }
×
797
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
798
                &htlcswitch.InterceptableSwitchConfig{
3✔
799
                        Switch:             s.htlcSwitch,
3✔
800
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
801
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
802
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
803
                        Notifier:           s.cc.ChainNotifier,
3✔
804
                },
3✔
805
        )
3✔
806
        if err != nil {
3✔
807
                return nil, err
×
808
        }
×
809

810
        s.witnessBeacon = newPreimageBeacon(
3✔
811
                dbs.ChanStateDB.NewWitnessCache(),
3✔
812
                s.interceptableSwitch.ForwardPacket,
3✔
813
        )
3✔
814

3✔
815
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
816
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
817
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
818
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
819
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
820
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
821
                MessageSigner:            s.nodeSigner,
3✔
822
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
823
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
824
                DB:                       s.chanStateDB,
3✔
825
                Graph:                    dbs.GraphDB,
3✔
826
        }
3✔
827

3✔
828
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
829
        if err != nil {
3✔
830
                return nil, err
×
831
        }
×
832
        s.chanStatusMgr = chanStatusMgr
3✔
833

3✔
834
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
835
        // port forwarding for users behind a NAT.
3✔
836
        if cfg.NAT {
3✔
837
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
838

×
839
                discoveryTimeout := time.Duration(10 * time.Second)
×
840

×
841
                ctx, cancel := context.WithTimeout(
×
842
                        context.Background(), discoveryTimeout,
×
843
                )
×
844
                defer cancel()
×
845
                upnp, err := nat.DiscoverUPnP(ctx)
×
846
                if err == nil {
×
847
                        s.natTraversal = upnp
×
848
                } else {
×
849
                        // If we were not able to discover a UPnP enabled device
×
850
                        // on the local network, we'll fall back to attempting
×
851
                        // to discover a NAT-PMP enabled device.
×
852
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
853
                                "device on the local network: %v", err)
×
854

×
855
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
856
                                "enabled device")
×
857

×
858
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
859
                        if err != nil {
×
860
                                err := fmt.Errorf("unable to discover a "+
×
861
                                        "NAT-PMP enabled device on the local "+
×
862
                                        "network: %v", err)
×
863
                                srvrLog.Error(err)
×
864
                                return nil, err
×
865
                        }
×
866

867
                        s.natTraversal = pmp
×
868
                }
869
        }
870

871
        // If we were requested to automatically configure port forwarding,
872
        // we'll use the ports that the server will be listening on.
873
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
874
        for idx, ip := range cfg.ExternalIPs {
6✔
875
                externalIPStrings[idx] = ip.String()
3✔
876
        }
3✔
877
        if s.natTraversal != nil {
3✔
878
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
879
                for _, listenAddr := range listenAddrs {
×
880
                        // At this point, the listen addresses should have
×
881
                        // already been normalized, so it's safe to ignore the
×
882
                        // errors.
×
883
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
884
                        port, _ := strconv.Atoi(portStr)
×
885

×
886
                        listenPorts = append(listenPorts, uint16(port))
×
887
                }
×
888

889
                ips, err := s.configurePortForwarding(listenPorts...)
×
890
                if err != nil {
×
891
                        srvrLog.Errorf("Unable to automatically set up port "+
×
892
                                "forwarding using %s: %v",
×
893
                                s.natTraversal.Name(), err)
×
894
                } else {
×
895
                        srvrLog.Infof("Automatically set up port forwarding "+
×
896
                                "using %s to advertise external IP",
×
897
                                s.natTraversal.Name())
×
898
                        externalIPStrings = append(externalIPStrings, ips...)
×
899
                }
×
900
        }
901

902
        // If external IP addresses have been specified, add those to the list
903
        // of this server's addresses.
904
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
905
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
906
                cfg.net.ResolveTCPAddr,
3✔
907
        )
3✔
908
        if err != nil {
3✔
909
                return nil, err
×
910
        }
×
911

912
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
913
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
914

3✔
915
        // We'll now reconstruct a node announcement based on our current
3✔
916
        // configuration so we can send it out as a sort of heart beat within
3✔
917
        // the network.
3✔
918
        //
3✔
919
        // We'll start by parsing the node color from configuration.
3✔
920
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
921
        if err != nil {
3✔
922
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
923
                return nil, err
×
924
        }
×
925

926
        // If no alias is provided, default to first 10 characters of public
927
        // key.
928
        alias := cfg.Alias
3✔
929
        if alias == "" {
6✔
930
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
931
        }
3✔
932
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
933
        if err != nil {
3✔
934
                return nil, err
×
935
        }
×
936
        selfNode := &models.LightningNode{
3✔
937
                HaveNodeAnnouncement: true,
3✔
938
                LastUpdate:           time.Now(),
3✔
939
                Addresses:            selfAddrs,
3✔
940
                Alias:                nodeAlias.String(),
3✔
941
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
942
                Color:                color,
3✔
943
        }
3✔
944
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
945

3✔
946
        // Based on the disk representation of the node announcement generated
3✔
947
        // above, we'll generate a node announcement that can go out on the
3✔
948
        // network so we can properly sign it.
3✔
949
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
950
        if err != nil {
3✔
951
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
952
        }
×
953

954
        // With the announcement generated, we'll sign it to properly
955
        // authenticate the message on the network.
956
        authSig, err := netann.SignAnnouncement(
3✔
957
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
958
        )
3✔
959
        if err != nil {
3✔
960
                return nil, fmt.Errorf("unable to generate signature for "+
×
961
                        "self node announcement: %v", err)
×
962
        }
×
963
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
964
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
965
                selfNode.AuthSigBytes,
3✔
966
        )
3✔
967
        if err != nil {
3✔
968
                return nil, err
×
969
        }
×
970

971
        // Finally, we'll update the representation on disk, and update our
972
        // cached in-memory version as well.
973
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
3✔
974
                return nil, fmt.Errorf("can't set self node: %w", err)
×
975
        }
×
976
        s.currentNodeAnn = nodeAnn
3✔
977

3✔
978
        // The router will get access to the payment ID sequencer, such that it
3✔
979
        // can generate unique payment IDs.
3✔
980
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
981
        if err != nil {
3✔
982
                return nil, err
×
983
        }
×
984

985
        // Instantiate mission control with config from the sub server.
986
        //
987
        // TODO(joostjager): When we are further in the process of moving to sub
988
        // servers, the mission control instance itself can be moved there too.
989
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
990

3✔
991
        // We only initialize a probability estimator if there's no custom one.
3✔
992
        var estimator routing.Estimator
3✔
993
        if cfg.Estimator != nil {
3✔
994
                estimator = cfg.Estimator
×
995
        } else {
3✔
996
                switch routingConfig.ProbabilityEstimatorType {
3✔
997
                case routing.AprioriEstimatorName:
3✔
998
                        aCfg := routingConfig.AprioriConfig
3✔
999
                        aprioriConfig := routing.AprioriConfig{
3✔
1000
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1001
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1002
                                AprioriWeight:         aCfg.Weight,
3✔
1003
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1004
                        }
3✔
1005

3✔
1006
                        estimator, err = routing.NewAprioriEstimator(
3✔
1007
                                aprioriConfig,
3✔
1008
                        )
3✔
1009
                        if err != nil {
3✔
1010
                                return nil, err
×
1011
                        }
×
1012

1013
                case routing.BimodalEstimatorName:
×
1014
                        bCfg := routingConfig.BimodalConfig
×
1015
                        bimodalConfig := routing.BimodalConfig{
×
1016
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1017
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1018
                                        bCfg.Scale,
×
1019
                                ),
×
1020
                                BimodalDecayTime: bCfg.DecayTime,
×
1021
                        }
×
1022

×
1023
                        estimator, err = routing.NewBimodalEstimator(
×
1024
                                bimodalConfig,
×
1025
                        )
×
1026
                        if err != nil {
×
1027
                                return nil, err
×
1028
                        }
×
1029

1030
                default:
×
1031
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1032
                                routingConfig.ProbabilityEstimatorType)
×
1033
                }
1034
        }
1035

1036
        mcCfg := &routing.MissionControlConfig{
3✔
1037
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1038
                Estimator:               estimator,
3✔
1039
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1040
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1041
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1042
        }
3✔
1043

3✔
1044
        s.missionController, err = routing.NewMissionController(
3✔
1045
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1046
        )
3✔
1047
        if err != nil {
3✔
1048
                return nil, fmt.Errorf("can't create mission control "+
×
1049
                        "manager: %w", err)
×
1050
        }
×
1051
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1052
                routing.DefaultMissionControlNamespace,
3✔
1053
        )
3✔
1054
        if err != nil {
3✔
1055
                return nil, fmt.Errorf("can't create mission control in the "+
×
1056
                        "default namespace: %w", err)
×
1057
        }
×
1058

1059
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1060
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1061
                int64(routingConfig.AttemptCost),
3✔
1062
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1063
                routingConfig.MinRouteProbability)
3✔
1064

3✔
1065
        pathFindingConfig := routing.PathFindingConfig{
3✔
1066
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1067
                        routingConfig.AttemptCost,
3✔
1068
                ),
3✔
1069
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1070
                MinProbability: routingConfig.MinRouteProbability,
3✔
1071
        }
3✔
1072

3✔
1073
        sourceNode, err := dbs.GraphDB.SourceNode()
3✔
1074
        if err != nil {
3✔
1075
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1076
        }
×
1077
        paymentSessionSource := &routing.SessionSource{
3✔
1078
                GraphSessionFactory: dbs.GraphDB,
3✔
1079
                SourceNode:          sourceNode,
3✔
1080
                MissionControl:      s.defaultMC,
3✔
1081
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1082
                PathFindingConfig:   pathFindingConfig,
3✔
1083
        }
3✔
1084

3✔
1085
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1086

3✔
1087
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1088

3✔
1089
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1090
                cfg.Routing.StrictZombiePruning
3✔
1091

3✔
1092
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1093
                SelfNode:            selfNode.PubKeyBytes,
3✔
1094
                Graph:               dbs.GraphDB,
3✔
1095
                Chain:               cc.ChainIO,
3✔
1096
                ChainView:           cc.ChainView,
3✔
1097
                Notifier:            cc.ChainNotifier,
3✔
1098
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1099
                GraphPruneInterval:  time.Hour,
3✔
1100
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1101
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1102
                StrictZombiePruning: strictPruning,
3✔
1103
                IsAlias:             aliasmgr.IsAlias,
3✔
1104
        })
3✔
1105
        if err != nil {
3✔
1106
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1107
        }
×
1108

1109
        s.chanRouter, err = routing.New(routing.Config{
3✔
1110
                SelfNode:           selfNode.PubKeyBytes,
3✔
1111
                RoutingGraph:       dbs.GraphDB,
3✔
1112
                Chain:              cc.ChainIO,
3✔
1113
                Payer:              s.htlcSwitch,
3✔
1114
                Control:            s.controlTower,
3✔
1115
                MissionControl:     s.defaultMC,
3✔
1116
                SessionSource:      paymentSessionSource,
3✔
1117
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1118
                NextPaymentID:      sequencer.NextID,
3✔
1119
                PathFindingConfig:  pathFindingConfig,
3✔
1120
                Clock:              clock.NewDefaultClock(),
3✔
1121
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1122
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1123
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1124
        })
3✔
1125
        if err != nil {
3✔
1126
                return nil, fmt.Errorf("can't create router: %w", err)
×
1127
        }
×
1128

1129
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1130
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1131
        if err != nil {
3✔
1132
                return nil, err
×
1133
        }
×
1134
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1135
        if err != nil {
3✔
1136
                return nil, err
×
1137
        }
×
1138

1139
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1140

3✔
1141
        s.authGossiper = discovery.New(discovery.Config{
3✔
1142
                Graph:                 s.graphBuilder,
3✔
1143
                ChainIO:               s.cc.ChainIO,
3✔
1144
                Notifier:              s.cc.ChainNotifier,
3✔
1145
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1146
                Broadcast:             s.BroadcastMessage,
3✔
1147
                ChanSeries:            chanSeries,
3✔
1148
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1149
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1150
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1151
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1152
                        error) {
3✔
1153

×
1154
                        return s.genNodeAnnouncement(nil)
×
1155
                },
×
1156
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1157
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1158
                RetransmitTicker:        ticker.New(time.Minute * 30),
1159
                RebroadcastInterval:     time.Hour * 24,
1160
                WaitingProofStore:       waitingProofStore,
1161
                MessageStore:            gossipMessageStore,
1162
                AnnSigner:               s.nodeSigner,
1163
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1164
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1165
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1166
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1167
                MinimumBatchSize:        10,
1168
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1169
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1170
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1171
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1172
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1173
                IsAlias:                 aliasmgr.IsAlias,
1174
                SignAliasUpdate:         s.signAliasUpdate,
1175
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1176
                GetAlias:                s.aliasMgr.GetPeerAlias,
1177
                FindChannel:             s.findChannel,
1178
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1179
                ScidCloser:              scidCloserMan,
1180
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1181
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1182
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1183
        }, nodeKeyDesc)
1184

1185
        accessCfg := &accessManConfig{
3✔
1186
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1187
                        error) {
6✔
1188

3✔
1189
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1190
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1191
                                genesisHash[:],
3✔
1192
                        )
3✔
1193
                },
3✔
1194
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1195
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1196
        }
1197

1198
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1199
        if err != nil {
3✔
1200
                return nil, err
×
1201
        }
×
1202

1203
        s.peerAccessMan = peerAccessMan
3✔
1204

3✔
1205
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1206
        //nolint:ll
3✔
1207
        s.localChanMgr = &localchans.Manager{
3✔
1208
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1209
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1210
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1211
                        *models.ChannelEdgePolicy) error) error {
6✔
1212

3✔
1213
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1214
                                func(c *models.ChannelEdgeInfo,
3✔
1215
                                        e *models.ChannelEdgePolicy,
3✔
1216
                                        _ *models.ChannelEdgePolicy) error {
6✔
1217

3✔
1218
                                        // NOTE: The invoked callback here may
3✔
1219
                                        // receive a nil channel policy.
3✔
1220
                                        return cb(c, e)
3✔
1221
                                },
3✔
1222
                        )
1223
                },
1224
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1225
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1226
                FetchChannel:              s.chanStateDB.FetchChannel,
1227
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1228
                        return s.graphBuilder.AddEdge(edge)
×
1229
                },
×
1230
        }
1231

1232
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1233
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1234
        )
3✔
1235
        if err != nil {
3✔
1236
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1237
                return nil, err
×
1238
        }
×
1239

1240
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1241
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1242
        )
3✔
1243
        if err != nil {
3✔
1244
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1245
                return nil, err
×
1246
        }
×
1247

1248
        aggregator := sweep.NewBudgetAggregator(
3✔
1249
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1250
                s.implCfg.AuxSweeper,
3✔
1251
        )
3✔
1252

3✔
1253
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1254
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1255
                Wallet:     cc.Wallet,
3✔
1256
                Estimator:  cc.FeeEstimator,
3✔
1257
                Notifier:   cc.ChainNotifier,
3✔
1258
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1259
        })
3✔
1260

3✔
1261
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1262
                FeeEstimator: cc.FeeEstimator,
3✔
1263
                GenSweepScript: newSweepPkScriptGen(
3✔
1264
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1265
                ),
3✔
1266
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1267
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1268
                Mempool:              cc.MempoolNotifier,
3✔
1269
                Notifier:             cc.ChainNotifier,
3✔
1270
                Store:                sweeperStore,
3✔
1271
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1272
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1273
                Aggregator:           aggregator,
3✔
1274
                Publisher:            s.txPublisher,
3✔
1275
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1276
        })
3✔
1277

3✔
1278
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1279
                ChainIO:             cc.ChainIO,
3✔
1280
                ConfDepth:           1,
3✔
1281
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1282
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1283
                Notifier:            cc.ChainNotifier,
3✔
1284
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1285
                Store:               utxnStore,
3✔
1286
                SweepInput:          s.sweeper.SweepInput,
3✔
1287
                Budget:              s.cfg.Sweeper.Budget,
3✔
1288
        })
3✔
1289

3✔
1290
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1291
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1292
                closureType contractcourt.ChannelCloseType) {
6✔
1293
                // TODO(conner): Properly respect the update and error channels
3✔
1294
                // returned by CloseLink.
3✔
1295

3✔
1296
                // Instruct the switch to close the channel.  Provide no close out
3✔
1297
                // delivery script or target fee per kw because user input is not
3✔
1298
                // available when the remote peer closes the channel.
3✔
1299
                s.htlcSwitch.CloseLink(
3✔
1300
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1301
                )
3✔
1302
        }
3✔
1303

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

3✔
1308
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1309
                &contractcourt.BreachConfig{
3✔
1310
                        CloseLink: closeLink,
3✔
1311
                        DB:        s.chanStateDB,
3✔
1312
                        Estimator: s.cc.FeeEstimator,
3✔
1313
                        GenSweepScript: newSweepPkScriptGen(
3✔
1314
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1315
                        ),
3✔
1316
                        Notifier:           cc.ChainNotifier,
3✔
1317
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1318
                        ContractBreaches:   contractBreaches,
3✔
1319
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1320
                        Store: contractcourt.NewRetributionStore(
3✔
1321
                                dbs.ChanStateDB,
3✔
1322
                        ),
3✔
1323
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1324
                },
3✔
1325
        )
3✔
1326

3✔
1327
        //nolint:ll
3✔
1328
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1329
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1330
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1331
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1332
                NewSweepAddr: func() ([]byte, error) {
3✔
1333
                        addr, err := newSweepPkScriptGen(
×
1334
                                cc.Wallet, netParams,
×
1335
                        )().Unpack()
×
1336
                        if err != nil {
×
1337
                                return nil, err
×
1338
                        }
×
1339

1340
                        return addr.DeliveryAddress, nil
×
1341
                },
1342
                PublishTx: cc.Wallet.PublishTransaction,
1343
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1344
                        for _, msg := range msgs {
6✔
1345
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1346
                                if err != nil {
3✔
1347
                                        return err
×
1348
                                }
×
1349
                        }
1350
                        return nil
3✔
1351
                },
1352
                IncubateOutputs: func(chanPoint wire.OutPoint,
1353
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1354
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1355
                        broadcastHeight uint32,
1356
                        deadlineHeight fn.Option[int32]) error {
3✔
1357

3✔
1358
                        return s.utxoNursery.IncubateOutputs(
3✔
1359
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1360
                                broadcastHeight, deadlineHeight,
3✔
1361
                        )
3✔
1362
                },
3✔
1363
                PreimageDB:   s.witnessBeacon,
1364
                Notifier:     cc.ChainNotifier,
1365
                Mempool:      cc.MempoolNotifier,
1366
                Signer:       cc.Wallet.Cfg.Signer,
1367
                FeeEstimator: cc.FeeEstimator,
1368
                ChainIO:      cc.ChainIO,
1369
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1370
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1371
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1372
                        return nil
3✔
1373
                },
3✔
1374
                IsOurAddress: cc.Wallet.IsOurAddress,
1375
                ContractBreach: func(chanPoint wire.OutPoint,
1376
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1377

3✔
1378
                        // processACK will handle the BreachArbitrator ACKing
3✔
1379
                        // the event.
3✔
1380
                        finalErr := make(chan error, 1)
3✔
1381
                        processACK := func(brarErr error) {
6✔
1382
                                if brarErr != nil {
3✔
1383
                                        finalErr <- brarErr
×
1384
                                        return
×
1385
                                }
×
1386

1387
                                // If the BreachArbitrator successfully handled
1388
                                // the event, we can signal that the handoff
1389
                                // was successful.
1390
                                finalErr <- nil
3✔
1391
                        }
1392

1393
                        event := &contractcourt.ContractBreachEvent{
3✔
1394
                                ChanPoint:         chanPoint,
3✔
1395
                                ProcessACK:        processACK,
3✔
1396
                                BreachRetribution: breachRet,
3✔
1397
                        }
3✔
1398

3✔
1399
                        // Send the contract breach event to the
3✔
1400
                        // BreachArbitrator.
3✔
1401
                        select {
3✔
1402
                        case contractBreaches <- event:
3✔
1403
                        case <-s.quit:
×
1404
                                return ErrServerShuttingDown
×
1405
                        }
1406

1407
                        // We'll wait for a final error to be available from
1408
                        // the BreachArbitrator.
1409
                        select {
3✔
1410
                        case err := <-finalErr:
3✔
1411
                                return err
3✔
1412
                        case <-s.quit:
×
1413
                                return ErrServerShuttingDown
×
1414
                        }
1415
                },
1416
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1417
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1418
                },
3✔
1419
                Sweeper:                       s.sweeper,
1420
                Registry:                      s.invoices,
1421
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1422
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1423
                OnionProcessor:                s.sphinx,
1424
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1425
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1426
                Clock:                         clock.NewDefaultClock(),
1427
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1428
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1429
                HtlcNotifier:                  s.htlcNotifier,
1430
                Budget:                        *s.cfg.Sweeper.Budget,
1431

1432
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1433
                QueryIncomingCircuit: func(
1434
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1435

3✔
1436
                        // Get the circuit map.
3✔
1437
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1438

3✔
1439
                        // Lookup the outgoing circuit.
3✔
1440
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1441
                        if pc == nil {
5✔
1442
                                return nil
2✔
1443
                        }
2✔
1444

1445
                        return &pc.Incoming
3✔
1446
                },
1447
                AuxLeafStore: implCfg.AuxLeafStore,
1448
                AuxSigner:    implCfg.AuxSigner,
1449
                AuxResolver:  implCfg.AuxContractResolver,
1450
        }, dbs.ChanStateDB)
1451

1452
        // Select the configuration and funding parameters for Bitcoin.
1453
        chainCfg := cfg.Bitcoin
3✔
1454
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1455
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1456

3✔
1457
        var chanIDSeed [32]byte
3✔
1458
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1459
                return nil, err
×
1460
        }
×
1461

1462
        // Wrap the DeleteChannelEdges method so that the funding manager can
1463
        // use it without depending on several layers of indirection.
1464
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1465
                *models.ChannelEdgePolicy, error) {
6✔
1466

3✔
1467
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1468
                        scid.ToUint64(),
3✔
1469
                )
3✔
1470
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1471
                        // This is unlikely but there is a slim chance of this
×
1472
                        // being hit if lnd was killed via SIGKILL and the
×
1473
                        // funding manager was stepping through the delete
×
1474
                        // alias edge logic.
×
1475
                        return nil, nil
×
1476
                } else if err != nil {
3✔
1477
                        return nil, err
×
1478
                }
×
1479

1480
                // Grab our key to find our policy.
1481
                var ourKey [33]byte
3✔
1482
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1483

3✔
1484
                var ourPolicy *models.ChannelEdgePolicy
3✔
1485
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1486
                        ourPolicy = e1
3✔
1487
                } else {
6✔
1488
                        ourPolicy = e2
3✔
1489
                }
3✔
1490

1491
                if ourPolicy == nil {
3✔
1492
                        // Something is wrong, so return an error.
×
1493
                        return nil, fmt.Errorf("we don't have an edge")
×
1494
                }
×
1495

1496
                err = s.graphDB.DeleteChannelEdges(
3✔
1497
                        false, false, scid.ToUint64(),
3✔
1498
                )
3✔
1499
                return ourPolicy, err
3✔
1500
        }
1501

1502
        // For the reservationTimeout and the zombieSweeperInterval different
1503
        // values are set in case we are in a dev environment so enhance test
1504
        // capacilities.
1505
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1506
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1507

3✔
1508
        // Get the development config for funding manager. If we are not in
3✔
1509
        // development mode, this would be nil.
3✔
1510
        var devCfg *funding.DevConfig
3✔
1511
        if lncfg.IsDevBuild() {
6✔
1512
                devCfg = &funding.DevConfig{
3✔
1513
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1514
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1515
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1516
                }
3✔
1517

3✔
1518
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1519
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1520

3✔
1521
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1522
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1523
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1524
        }
3✔
1525

1526
        //nolint:ll
1527
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1528
                Dev:                devCfg,
3✔
1529
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1530
                IDKey:              nodeKeyDesc.PubKey,
3✔
1531
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1532
                Wallet:             cc.Wallet,
3✔
1533
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1534
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1535
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1536
                },
3✔
1537
                Notifier:     cc.ChainNotifier,
1538
                ChannelDB:    s.chanStateDB,
1539
                FeeEstimator: cc.FeeEstimator,
1540
                SignMessage:  cc.MsgSigner.SignMessage,
1541
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1542
                        error) {
3✔
1543

3✔
1544
                        return s.genNodeAnnouncement(nil)
3✔
1545
                },
3✔
1546
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1547
                NotifyWhenOnline:     s.NotifyWhenOnline,
1548
                TempChanIDSeed:       chanIDSeed,
1549
                FindChannel:          s.findChannel,
1550
                DefaultRoutingPolicy: cc.RoutingPolicy,
1551
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1552
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1553
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1554
                        // For large channels we increase the number
3✔
1555
                        // of confirmations we require for the
3✔
1556
                        // channel to be considered open. As it is
3✔
1557
                        // always the responder that gets to choose
3✔
1558
                        // value, the pushAmt is value being pushed
3✔
1559
                        // to us. This means we have more to lose
3✔
1560
                        // in the case this gets re-orged out, and
3✔
1561
                        // we will require more confirmations before
3✔
1562
                        // we consider it open.
3✔
1563

3✔
1564
                        // In case the user has explicitly specified
3✔
1565
                        // a default value for the number of
3✔
1566
                        // confirmations, we use it.
3✔
1567
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1568
                        if defaultConf != 0 {
6✔
1569
                                return defaultConf
3✔
1570
                        }
3✔
1571

1572
                        minConf := uint64(3)
×
1573
                        maxConf := uint64(6)
×
1574

×
1575
                        // If this is a wumbo channel, then we'll require the
×
1576
                        // max amount of confirmations.
×
1577
                        if chanAmt > MaxFundingAmount {
×
1578
                                return uint16(maxConf)
×
1579
                        }
×
1580

1581
                        // If not we return a value scaled linearly
1582
                        // between 3 and 6, depending on channel size.
1583
                        // TODO(halseth): Use 1 as minimum?
1584
                        maxChannelSize := uint64(
×
1585
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1586
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1587
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1588
                        if conf < minConf {
×
1589
                                conf = minConf
×
1590
                        }
×
1591
                        if conf > maxConf {
×
1592
                                conf = maxConf
×
1593
                        }
×
1594
                        return uint16(conf)
×
1595
                },
1596
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1597
                        // We scale the remote CSV delay (the time the
3✔
1598
                        // remote have to claim funds in case of a unilateral
3✔
1599
                        // close) linearly from minRemoteDelay blocks
3✔
1600
                        // for small channels, to maxRemoteDelay blocks
3✔
1601
                        // for channels of size MaxFundingAmount.
3✔
1602

3✔
1603
                        // In case the user has explicitly specified
3✔
1604
                        // a default value for the remote delay, we
3✔
1605
                        // use it.
3✔
1606
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1607
                        if defaultDelay > 0 {
6✔
1608
                                return defaultDelay
3✔
1609
                        }
3✔
1610

1611
                        // If this is a wumbo channel, then we'll require the
1612
                        // max value.
1613
                        if chanAmt > MaxFundingAmount {
×
1614
                                return maxRemoteDelay
×
1615
                        }
×
1616

1617
                        // If not we scale according to channel size.
1618
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1619
                                chanAmt / MaxFundingAmount)
×
1620
                        if delay < minRemoteDelay {
×
1621
                                delay = minRemoteDelay
×
1622
                        }
×
1623
                        if delay > maxRemoteDelay {
×
1624
                                delay = maxRemoteDelay
×
1625
                        }
×
1626
                        return delay
×
1627
                },
1628
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1629
                        peerKey *btcec.PublicKey) error {
3✔
1630

3✔
1631
                        // First, we'll mark this new peer as a persistent peer
3✔
1632
                        // for re-connection purposes. If the peer is not yet
3✔
1633
                        // tracked or the user hasn't requested it to be perm,
3✔
1634
                        // we'll set false to prevent the server from continuing
3✔
1635
                        // to connect to this peer even if the number of
3✔
1636
                        // channels with this peer is zero.
3✔
1637
                        s.mu.Lock()
3✔
1638
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1639
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1640
                                s.persistentPeers[pubStr] = false
3✔
1641
                        }
3✔
1642
                        s.mu.Unlock()
3✔
1643

3✔
1644
                        // With that taken care of, we'll send this channel to
3✔
1645
                        // the chain arb so it can react to on-chain events.
3✔
1646
                        return s.chainArb.WatchNewChannel(channel)
3✔
1647
                },
1648
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1649
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1650
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1651
                },
3✔
1652
                RequiredRemoteChanReserve: func(chanAmt,
1653
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1654

3✔
1655
                        // By default, we'll require the remote peer to maintain
3✔
1656
                        // at least 1% of the total channel capacity at all
3✔
1657
                        // times. If this value ends up dipping below the dust
3✔
1658
                        // limit, then we'll use the dust limit itself as the
3✔
1659
                        // reserve as required by BOLT #2.
3✔
1660
                        reserve := chanAmt / 100
3✔
1661
                        if reserve < dustLimit {
6✔
1662
                                reserve = dustLimit
3✔
1663
                        }
3✔
1664

1665
                        return reserve
3✔
1666
                },
1667
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1668
                        // By default, we'll allow the remote peer to fully
3✔
1669
                        // utilize the full bandwidth of the channel, minus our
3✔
1670
                        // required reserve.
3✔
1671
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1672
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1673
                },
3✔
1674
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1675
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1676
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1677
                        }
3✔
1678

1679
                        // By default, we'll permit them to utilize the full
1680
                        // channel bandwidth.
1681
                        return uint16(input.MaxHTLCNumber / 2)
×
1682
                },
1683
                ZombieSweeperInterval:         zombieSweeperInterval,
1684
                ReservationTimeout:            reservationTimeout,
1685
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1686
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1687
                MaxPendingChannels:            cfg.MaxPendingChannels,
1688
                RejectPush:                    cfg.RejectPush,
1689
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1690
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1691
                OpenChannelPredicate:          chanPredicate,
1692
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1693
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1694
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1695
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1696
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1697
                DeleteAliasEdge:      deleteAliasEdge,
1698
                AliasManager:         s.aliasMgr,
1699
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1700
                AuxFundingController: implCfg.AuxFundingController,
1701
                AuxSigner:            implCfg.AuxSigner,
1702
                AuxResolver:          implCfg.AuxContractResolver,
1703
        })
1704
        if err != nil {
3✔
1705
                return nil, err
×
1706
        }
×
1707

1708
        // Next, we'll assemble the sub-system that will maintain an on-disk
1709
        // static backup of the latest channel state.
1710
        chanNotifier := &channelNotifier{
3✔
1711
                chanNotifier: s.channelNotifier,
3✔
1712
                addrs:        s.addrSource,
3✔
1713
        }
3✔
1714
        backupFile := chanbackup.NewMultiFile(
3✔
1715
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1716
        )
3✔
1717
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1718
                s.chanStateDB, s.addrSource,
3✔
1719
        )
3✔
1720
        if err != nil {
3✔
1721
                return nil, err
×
1722
        }
×
1723
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1724
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1725
        )
3✔
1726
        if err != nil {
3✔
1727
                return nil, err
×
1728
        }
×
1729

1730
        // Assemble a peer notifier which will provide clients with subscriptions
1731
        // to peer online and offline events.
1732
        s.peerNotifier = peernotifier.New()
3✔
1733

3✔
1734
        // Create a channel event store which monitors all open channels.
3✔
1735
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1736
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1737
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1738
                },
3✔
1739
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1740
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1741
                },
3✔
1742
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1743
                Clock:           clock.NewDefaultClock(),
1744
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1745
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1746
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1747
        })
1748

1749
        if cfg.WtClient.Active {
6✔
1750
                policy := wtpolicy.DefaultPolicy()
3✔
1751
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1752

3✔
1753
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1754
                // protocol operations on sat/kw.
3✔
1755
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1756
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1757
                )
3✔
1758

3✔
1759
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1760

3✔
1761
                if err := policy.Validate(); err != nil {
3✔
1762
                        return nil, err
×
1763
                }
×
1764

1765
                // authDial is the wrapper around the btrontide.Dial for the
1766
                // watchtower.
1767
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1768
                        netAddr *lnwire.NetAddress,
3✔
1769
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1770

3✔
1771
                        return brontide.Dial(
3✔
1772
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1773
                        )
3✔
1774
                }
3✔
1775

1776
                // buildBreachRetribution is a call-back that can be used to
1777
                // query the BreachRetribution info and channel type given a
1778
                // channel ID and commitment height.
1779
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1780
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1781
                        channeldb.ChannelType, error) {
6✔
1782

3✔
1783
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1784
                                nil, chanID,
3✔
1785
                        )
3✔
1786
                        if err != nil {
3✔
1787
                                return nil, 0, err
×
1788
                        }
×
1789

1790
                        br, err := lnwallet.NewBreachRetribution(
3✔
1791
                                channel, commitHeight, 0, nil,
3✔
1792
                                implCfg.AuxLeafStore,
3✔
1793
                                implCfg.AuxContractResolver,
3✔
1794
                        )
3✔
1795
                        if err != nil {
3✔
1796
                                return nil, 0, err
×
1797
                        }
×
1798

1799
                        return br, channel.ChanType, nil
3✔
1800
                }
1801

1802
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1803

3✔
1804
                // Copy the policy for legacy channels and set the blob flag
3✔
1805
                // signalling support for anchor channels.
3✔
1806
                anchorPolicy := policy
3✔
1807
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1808

3✔
1809
                // Copy the policy for legacy channels and set the blob flag
3✔
1810
                // signalling support for taproot channels.
3✔
1811
                taprootPolicy := policy
3✔
1812
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1813
                        blob.FlagTaprootChannel,
3✔
1814
                )
3✔
1815

3✔
1816
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1817
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1818
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1819
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1820
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1821
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1822
                                error) {
6✔
1823

3✔
1824
                                return s.channelNotifier.
3✔
1825
                                        SubscribeChannelEvents()
3✔
1826
                        },
3✔
1827
                        Signer: cc.Wallet.Cfg.Signer,
1828
                        NewAddress: func() ([]byte, error) {
3✔
1829
                                addr, err := newSweepPkScriptGen(
3✔
1830
                                        cc.Wallet, netParams,
3✔
1831
                                )().Unpack()
3✔
1832
                                if err != nil {
3✔
1833
                                        return nil, err
×
1834
                                }
×
1835

1836
                                return addr.DeliveryAddress, nil
3✔
1837
                        },
1838
                        SecretKeyRing:      s.cc.KeyRing,
1839
                        Dial:               cfg.net.Dial,
1840
                        AuthDial:           authDial,
1841
                        DB:                 dbs.TowerClientDB,
1842
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1843
                        MinBackoff:         10 * time.Second,
1844
                        MaxBackoff:         5 * time.Minute,
1845
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1846
                }, policy, anchorPolicy, taprootPolicy)
1847
                if err != nil {
3✔
1848
                        return nil, err
×
1849
                }
×
1850
        }
1851

1852
        if len(cfg.ExternalHosts) != 0 {
3✔
1853
                advertisedIPs := make(map[string]struct{})
×
1854
                for _, addr := range s.currentNodeAnn.Addresses {
×
1855
                        advertisedIPs[addr.String()] = struct{}{}
×
1856
                }
×
1857

1858
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1859
                        Hosts:         cfg.ExternalHosts,
×
1860
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1861
                        LookupHost: func(host string) (net.Addr, error) {
×
1862
                                return lncfg.ParseAddressString(
×
1863
                                        host, strconv.Itoa(defaultPeerPort),
×
1864
                                        cfg.net.ResolveTCPAddr,
×
1865
                                )
×
1866
                        },
×
1867
                        AdvertisedIPs: advertisedIPs,
1868
                        AnnounceNewIPs: netann.IPAnnouncer(
1869
                                func(modifier ...netann.NodeAnnModifier) (
1870
                                        lnwire.NodeAnnouncement, error) {
×
1871

×
1872
                                        return s.genNodeAnnouncement(
×
1873
                                                nil, modifier...,
×
1874
                                        )
×
1875
                                }),
×
1876
                })
1877
        }
1878

1879
        // Create liveness monitor.
1880
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1881

3✔
1882
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1883
        for i, listenAddr := range listenAddrs {
6✔
1884
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1885
                // doesn't need to call the general lndResolveTCP function
3✔
1886
                // since we are resolving a local address.
3✔
1887

3✔
1888
                // RESOLVE: We are actually partially accepting inbound
3✔
1889
                // connection requests when we call NewListener.
3✔
1890
                listeners[i], err = brontide.NewListener(
3✔
1891
                        nodeKeyECDH, listenAddr.String(),
3✔
1892
                        s.peerAccessMan.checkIncomingConnBanScore,
3✔
1893
                )
3✔
1894
                if err != nil {
3✔
1895
                        return nil, err
×
1896
                }
×
1897
        }
1898

1899
        // Create the connection manager which will be responsible for
1900
        // maintaining persistent outbound connections and also accepting new
1901
        // incoming connections
1902
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1903
                Listeners:      listeners,
3✔
1904
                OnAccept:       s.InboundPeerConnected,
3✔
1905
                RetryDuration:  time.Second * 5,
3✔
1906
                TargetOutbound: 100,
3✔
1907
                Dial: noiseDial(
3✔
1908
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1909
                ),
3✔
1910
                OnConnection: s.OutboundPeerConnected,
3✔
1911
        })
3✔
1912
        if err != nil {
3✔
1913
                return nil, err
×
1914
        }
×
1915
        s.connMgr = cmgr
3✔
1916

3✔
1917
        // Finally, register the subsystems in blockbeat.
3✔
1918
        s.registerBlockConsumers()
3✔
1919

3✔
1920
        return s, nil
3✔
1921
}
1922

1923
// UpdateRoutingConfig is a callback function to update the routing config
1924
// values in the main cfg.
1925
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1926
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1927

3✔
1928
        switch c := cfg.Estimator.Config().(type) {
3✔
1929
        case routing.AprioriConfig:
3✔
1930
                routerCfg.ProbabilityEstimatorType =
3✔
1931
                        routing.AprioriEstimatorName
3✔
1932

3✔
1933
                targetCfg := routerCfg.AprioriConfig
3✔
1934
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1935
                targetCfg.Weight = c.AprioriWeight
3✔
1936
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1937
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1938

1939
        case routing.BimodalConfig:
3✔
1940
                routerCfg.ProbabilityEstimatorType =
3✔
1941
                        routing.BimodalEstimatorName
3✔
1942

3✔
1943
                targetCfg := routerCfg.BimodalConfig
3✔
1944
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1945
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1946
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1947
        }
1948

1949
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1950
}
1951

1952
// registerBlockConsumers registers the subsystems that consume block events.
1953
// By calling `RegisterQueue`, a list of subsystems are registered in the
1954
// blockbeat for block notifications. When a new block arrives, the subsystems
1955
// in the same queue are notified sequentially, and different queues are
1956
// notified concurrently.
1957
//
1958
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1959
// a new `RegisterQueue` call.
1960
func (s *server) registerBlockConsumers() {
3✔
1961
        // In this queue, when a new block arrives, it will be received and
3✔
1962
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1963
        consumers := []chainio.Consumer{
3✔
1964
                s.chainArb,
3✔
1965
                s.sweeper,
3✔
1966
                s.txPublisher,
3✔
1967
        }
3✔
1968
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1969
}
3✔
1970

1971
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1972
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1973
// may differ from what is on disk.
1974
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1975
        error) {
3✔
1976

3✔
1977
        data, err := u.DataToSign()
3✔
1978
        if err != nil {
3✔
1979
                return nil, err
×
1980
        }
×
1981

1982
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1983
}
1984

1985
// createLivenessMonitor creates a set of health checks using our configured
1986
// values and uses these checks to create a liveness monitor. Available
1987
// health checks,
1988
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1989
//   - diskCheck
1990
//   - tlsHealthCheck
1991
//   - torController, only created when tor is enabled.
1992
//
1993
// If a health check has been disabled by setting attempts to 0, our monitor
1994
// will not run it.
1995
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1996
        leaderElector cluster.LeaderElector) {
3✔
1997

3✔
1998
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1999
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2000
                srvrLog.Info("Disabling chain backend checks for " +
×
2001
                        "nochainbackend mode")
×
2002

×
2003
                chainBackendAttempts = 0
×
2004
        }
×
2005

2006
        chainHealthCheck := healthcheck.NewObservation(
3✔
2007
                "chain backend",
3✔
2008
                cc.HealthCheck,
3✔
2009
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2010
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2011
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2012
                chainBackendAttempts,
3✔
2013
        )
3✔
2014

3✔
2015
        diskCheck := healthcheck.NewObservation(
3✔
2016
                "disk space",
3✔
2017
                func() error {
3✔
2018
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2019
                                cfg.LndDir,
×
2020
                        )
×
2021
                        if err != nil {
×
2022
                                return err
×
2023
                        }
×
2024

2025
                        // If we have more free space than we require,
2026
                        // we return a nil error.
2027
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2028
                                return nil
×
2029
                        }
×
2030

2031
                        return fmt.Errorf("require: %v free space, got: %v",
×
2032
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2033
                                free)
×
2034
                },
2035
                cfg.HealthChecks.DiskCheck.Interval,
2036
                cfg.HealthChecks.DiskCheck.Timeout,
2037
                cfg.HealthChecks.DiskCheck.Backoff,
2038
                cfg.HealthChecks.DiskCheck.Attempts,
2039
        )
2040

2041
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2042
                "tls",
3✔
2043
                func() error {
3✔
2044
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2045
                                s.cc.KeyRing,
×
2046
                        )
×
2047
                        if err != nil {
×
2048
                                return err
×
2049
                        }
×
2050
                        if expired {
×
2051
                                return fmt.Errorf("TLS certificate is "+
×
2052
                                        "expired as of %v", expTime)
×
2053
                        }
×
2054

2055
                        // If the certificate is not outdated, no error needs
2056
                        // to be returned
2057
                        return nil
×
2058
                },
2059
                cfg.HealthChecks.TLSCheck.Interval,
2060
                cfg.HealthChecks.TLSCheck.Timeout,
2061
                cfg.HealthChecks.TLSCheck.Backoff,
2062
                cfg.HealthChecks.TLSCheck.Attempts,
2063
        )
2064

2065
        checks := []*healthcheck.Observation{
3✔
2066
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2067
        }
3✔
2068

3✔
2069
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2070
        if s.torController != nil {
3✔
2071
                torConnectionCheck := healthcheck.NewObservation(
×
2072
                        "tor connection",
×
2073
                        func() error {
×
2074
                                return healthcheck.CheckTorServiceStatus(
×
2075
                                        s.torController,
×
2076
                                        s.createNewHiddenService,
×
2077
                                )
×
2078
                        },
×
2079
                        cfg.HealthChecks.TorConnection.Interval,
2080
                        cfg.HealthChecks.TorConnection.Timeout,
2081
                        cfg.HealthChecks.TorConnection.Backoff,
2082
                        cfg.HealthChecks.TorConnection.Attempts,
2083
                )
2084
                checks = append(checks, torConnectionCheck)
×
2085
        }
2086

2087
        // If remote signing is enabled, add the healthcheck for the remote
2088
        // signing RPC interface.
2089
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2090
                // Because we have two cascading timeouts here, we need to add
3✔
2091
                // some slack to the "outer" one of them in case the "inner"
3✔
2092
                // returns exactly on time.
3✔
2093
                overhead := time.Millisecond * 10
3✔
2094

3✔
2095
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2096
                        "remote signer connection",
3✔
2097
                        rpcwallet.HealthCheck(
3✔
2098
                                s.cfg.RemoteSigner,
3✔
2099

3✔
2100
                                // For the health check we might to be even
3✔
2101
                                // stricter than the initial/normal connect, so
3✔
2102
                                // we use the health check timeout here.
3✔
2103
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2104
                        ),
3✔
2105
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2106
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2107
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2108
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2109
                )
3✔
2110
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2111
        }
3✔
2112

2113
        // If we have a leader elector, we add a health check to ensure we are
2114
        // still the leader. During normal operation, we should always be the
2115
        // leader, but there are circumstances where this may change, such as
2116
        // when we lose network connectivity for long enough expiring out lease.
2117
        if leaderElector != nil {
3✔
2118
                leaderCheck := healthcheck.NewObservation(
×
2119
                        "leader status",
×
2120
                        func() error {
×
2121
                                // Check if we are still the leader. Note that
×
2122
                                // we don't need to use a timeout context here
×
2123
                                // as the healthcheck observer will handle the
×
2124
                                // timeout case for us.
×
2125
                                timeoutCtx, cancel := context.WithTimeout(
×
2126
                                        context.Background(),
×
2127
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2128
                                )
×
2129
                                defer cancel()
×
2130

×
2131
                                leader, err := leaderElector.IsLeader(
×
2132
                                        timeoutCtx,
×
2133
                                )
×
2134
                                if err != nil {
×
2135
                                        return fmt.Errorf("unable to check if "+
×
2136
                                                "still leader: %v", err)
×
2137
                                }
×
2138

2139
                                if !leader {
×
2140
                                        srvrLog.Debug("Not the current leader")
×
2141
                                        return fmt.Errorf("not the current " +
×
2142
                                                "leader")
×
2143
                                }
×
2144

2145
                                return nil
×
2146
                        },
2147
                        cfg.HealthChecks.LeaderCheck.Interval,
2148
                        cfg.HealthChecks.LeaderCheck.Timeout,
2149
                        cfg.HealthChecks.LeaderCheck.Backoff,
2150
                        cfg.HealthChecks.LeaderCheck.Attempts,
2151
                )
2152

2153
                checks = append(checks, leaderCheck)
×
2154
        }
2155

2156
        // If we have not disabled all of our health checks, we create a
2157
        // liveness monitor with our configured checks.
2158
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2159
                &healthcheck.Config{
3✔
2160
                        Checks:   checks,
3✔
2161
                        Shutdown: srvrLog.Criticalf,
3✔
2162
                },
3✔
2163
        )
3✔
2164
}
2165

2166
// Started returns true if the server has been started, and false otherwise.
2167
// NOTE: This function is safe for concurrent access.
2168
func (s *server) Started() bool {
3✔
2169
        return atomic.LoadInt32(&s.active) != 0
3✔
2170
}
3✔
2171

2172
// cleaner is used to aggregate "cleanup" functions during an operation that
2173
// starts several subsystems. In case one of the subsystem fails to start
2174
// and a proper resource cleanup is required, the "run" method achieves this
2175
// by running all these added "cleanup" functions.
2176
type cleaner []func() error
2177

2178
// add is used to add a cleanup function to be called when
2179
// the run function is executed.
2180
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2181
        return append(c, cleanup)
3✔
2182
}
3✔
2183

2184
// run is used to run all the previousely added cleanup functions.
2185
func (c cleaner) run() {
×
2186
        for i := len(c) - 1; i >= 0; i-- {
×
2187
                if err := c[i](); err != nil {
×
2188
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2189
                }
×
2190
        }
2191
}
2192

2193
// startLowLevelServices starts the low-level services of the server. These
2194
// services must be started successfully before running the main server. The
2195
// services are,
2196
// 1. the chain notifier.
2197
//
2198
// TODO(yy): identify and add more low-level services here.
2199
func (s *server) startLowLevelServices() error {
3✔
2200
        var startErr error
3✔
2201

3✔
2202
        cleanup := cleaner{}
3✔
2203

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

2209
        if startErr != nil {
3✔
2210
                cleanup.run()
×
2211
        }
×
2212

2213
        return startErr
3✔
2214
}
2215

2216
// Start starts the main daemon server, all requested listeners, and any helper
2217
// goroutines.
2218
// NOTE: This function is safe for concurrent access.
2219
//
2220
//nolint:funlen
2221
func (s *server) Start(ctx context.Context) error {
3✔
2222
        // Get the current blockbeat.
3✔
2223
        beat, err := s.getStartingBeat()
3✔
2224
        if err != nil {
3✔
2225
                return err
×
2226
        }
×
2227

2228
        var startErr error
3✔
2229

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

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

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

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

2258
                // Start the notification server. This is used so channel
2259
                // management goroutines can be notified when a funding
2260
                // transaction reaches a sufficient number of confirmations, or
2261
                // when the input for the funding transaction is spent in an
2262
                // attempt at an uncooperative close by the counterparty.
2263
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2264
                if err := s.sigPool.Start(); err != nil {
3✔
2265
                        startErr = err
×
2266
                        return
×
2267
                }
×
2268

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

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

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

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

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

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

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

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

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

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

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

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

2345
                // htlcSwitch must be started before chainArb since the latter
2346
                // relies on htlcSwitch to deliver resolution message upon
2347
                // start.
2348
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2349
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2350
                        startErr = err
×
2351
                        return
×
2352
                }
×
2353

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

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

2366
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2367
                if err := s.chainArb.Start(beat); err != nil {
3✔
2368
                        startErr = err
×
2369
                        return
×
2370
                }
×
2371

2372
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2373
                if err := s.graphDB.Start(); err != nil {
3✔
2374
                        startErr = err
×
2375
                        return
×
2376
                }
×
2377

2378
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2379
                if err := s.graphBuilder.Start(); err != nil {
3✔
2380
                        startErr = err
×
2381
                        return
×
2382
                }
×
2383

2384
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2385
                if err := s.chanRouter.Start(); err != nil {
3✔
2386
                        startErr = err
×
2387
                        return
×
2388
                }
×
2389
                // The authGossiper depends on the chanRouter and therefore
2390
                // should be started after it.
2391
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2392
                if err := s.authGossiper.Start(); err != nil {
3✔
2393
                        startErr = err
×
2394
                        return
×
2395
                }
×
2396

2397
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2398
                if err := s.invoices.Start(); err != nil {
3✔
2399
                        startErr = err
×
2400
                        return
×
2401
                }
×
2402

2403
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2404
                if err := s.sphinx.Start(); err != nil {
3✔
2405
                        startErr = err
×
2406
                        return
×
2407
                }
×
2408

2409
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2410
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2411
                        startErr = err
×
2412
                        return
×
2413
                }
×
2414

2415
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2416
                if err := s.chanEventStore.Start(); err != nil {
3✔
2417
                        startErr = err
×
2418
                        return
×
2419
                }
×
2420

2421
                cleanup.add(func() error {
3✔
2422
                        s.missionController.StopStoreTickers()
×
2423
                        return nil
×
2424
                })
×
2425
                s.missionController.RunStoreTickers()
3✔
2426

3✔
2427
                // Before we start the connMgr, we'll check to see if we have
3✔
2428
                // any backups to recover. We do this now as we want to ensure
3✔
2429
                // that have all the information we need to handle channel
3✔
2430
                // recovery _before_ we even accept connections from any peers.
3✔
2431
                chanRestorer := &chanDBRestorer{
3✔
2432
                        db:         s.chanStateDB,
3✔
2433
                        secretKeys: s.cc.KeyRing,
3✔
2434
                        chainArb:   s.chainArb,
3✔
2435
                }
3✔
2436
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2437
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2438
                                s.chansToRestore.PackedSingleChanBackups,
×
2439
                                s.cc.KeyRing, chanRestorer, s,
×
2440
                        )
×
2441
                        if err != nil {
×
2442
                                startErr = fmt.Errorf("unable to unpack single "+
×
2443
                                        "backups: %v", err)
×
2444
                                return
×
2445
                        }
×
2446
                }
2447
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2448
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2449
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2450
                                s.cc.KeyRing, chanRestorer, s,
3✔
2451
                        )
3✔
2452
                        if err != nil {
3✔
2453
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2454
                                        "backup: %v", err)
×
2455
                                return
×
2456
                        }
×
2457
                }
2458

2459
                // chanSubSwapper must be started after the `channelNotifier`
2460
                // because it depends on channel events as a synchronization
2461
                // point.
2462
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2463
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2464
                        startErr = err
×
2465
                        return
×
2466
                }
×
2467

2468
                if s.torController != nil {
3✔
2469
                        cleanup = cleanup.add(s.torController.Stop)
×
2470
                        if err := s.createNewHiddenService(); err != nil {
×
2471
                                startErr = err
×
2472
                                return
×
2473
                        }
×
2474
                }
2475

2476
                if s.natTraversal != nil {
3✔
2477
                        s.wg.Add(1)
×
2478
                        go s.watchExternalIP()
×
2479
                }
×
2480

2481
                // Start connmgr last to prevent connections before init.
2482
                cleanup = cleanup.add(func() error {
3✔
2483
                        s.connMgr.Stop()
×
2484
                        return nil
×
2485
                })
×
2486

2487
                // RESOLVE: s.connMgr.Start() is called here, but
2488
                // brontide.NewListener() is called in newServer. This means
2489
                // that we are actually listening and partially accepting
2490
                // inbound connections even before the connMgr starts.
2491
                //
2492
                // TODO(yy): move the log into the connMgr's `Start` method.
2493
                srvrLog.Info("connMgr starting...")
3✔
2494
                s.connMgr.Start()
3✔
2495
                srvrLog.Debug("connMgr started")
3✔
2496

3✔
2497
                // If peers are specified as a config option, we'll add those
3✔
2498
                // peers first.
3✔
2499
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2500
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2501
                                peerAddrCfg,
3✔
2502
                        )
3✔
2503
                        if err != nil {
3✔
2504
                                startErr = fmt.Errorf("unable to parse peer "+
×
2505
                                        "pubkey from config: %v", err)
×
2506
                                return
×
2507
                        }
×
2508
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2509
                        if err != nil {
3✔
2510
                                startErr = fmt.Errorf("unable to parse peer "+
×
2511
                                        "address provided as a config option: "+
×
2512
                                        "%v", err)
×
2513
                                return
×
2514
                        }
×
2515

2516
                        peerAddr := &lnwire.NetAddress{
3✔
2517
                                IdentityKey: parsedPubkey,
3✔
2518
                                Address:     addr,
3✔
2519
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2520
                        }
3✔
2521

3✔
2522
                        err = s.ConnectToPeer(
3✔
2523
                                peerAddr, true,
3✔
2524
                                s.cfg.ConnectionTimeout,
3✔
2525
                        )
3✔
2526
                        if err != nil {
3✔
2527
                                startErr = fmt.Errorf("unable to connect to "+
×
2528
                                        "peer address provided as a config "+
×
2529
                                        "option: %v", err)
×
2530
                                return
×
2531
                        }
×
2532
                }
2533

2534
                // Subscribe to NodeAnnouncements that advertise new addresses
2535
                // our persistent peers.
2536
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2537
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2538
                                "addr: %v", err)
×
2539

×
2540
                        startErr = err
×
2541
                        return
×
2542
                }
×
2543

2544
                // With all the relevant sub-systems started, we'll now attempt
2545
                // to establish persistent connections to our direct channel
2546
                // collaborators within the network. Before doing so however,
2547
                // we'll prune our set of link nodes found within the database
2548
                // to ensure we don't reconnect to any nodes we no longer have
2549
                // open channels with.
2550
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2551
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2552

×
2553
                        startErr = err
×
2554
                        return
×
2555
                }
×
2556

2557
                if err := s.establishPersistentConnections(); err != nil {
3✔
2558
                        srvrLog.Errorf("Failed to establish persistent "+
×
2559
                                "connections: %v", err)
×
2560
                }
×
2561

2562
                // setSeedList is a helper function that turns multiple DNS seed
2563
                // server tuples from the command line or config file into the
2564
                // data structure we need and does a basic formal sanity check
2565
                // in the process.
2566
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2567
                        if len(tuples) == 0 {
×
2568
                                return
×
2569
                        }
×
2570

2571
                        result := make([][2]string, len(tuples))
×
2572
                        for idx, tuple := range tuples {
×
2573
                                tuple = strings.TrimSpace(tuple)
×
2574
                                if len(tuple) == 0 {
×
2575
                                        return
×
2576
                                }
×
2577

2578
                                servers := strings.Split(tuple, ",")
×
2579
                                if len(servers) > 2 || len(servers) == 0 {
×
2580
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2581
                                                "seed tuple: %v", servers)
×
2582
                                        return
×
2583
                                }
×
2584

2585
                                copy(result[idx][:], servers)
×
2586
                        }
2587

2588
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2589
                }
2590

2591
                // Let users overwrite the DNS seed nodes. We only allow them
2592
                // for bitcoin mainnet/testnet/signet.
2593
                if s.cfg.Bitcoin.MainNet {
3✔
2594
                        setSeedList(
×
2595
                                s.cfg.Bitcoin.DNSSeeds,
×
2596
                                chainreg.BitcoinMainnetGenesis,
×
2597
                        )
×
2598
                }
×
2599
                if s.cfg.Bitcoin.TestNet3 {
3✔
2600
                        setSeedList(
×
2601
                                s.cfg.Bitcoin.DNSSeeds,
×
2602
                                chainreg.BitcoinTestnetGenesis,
×
2603
                        )
×
2604
                }
×
2605
                if s.cfg.Bitcoin.TestNet4 {
3✔
2606
                        setSeedList(
×
2607
                                s.cfg.Bitcoin.DNSSeeds,
×
2608
                                chainreg.BitcoinTestnet4Genesis,
×
2609
                        )
×
2610
                }
×
2611
                if s.cfg.Bitcoin.SigNet {
3✔
2612
                        setSeedList(
×
2613
                                s.cfg.Bitcoin.DNSSeeds,
×
2614
                                chainreg.BitcoinSignetGenesis,
×
2615
                        )
×
2616
                }
×
2617

2618
                // If network bootstrapping hasn't been disabled, then we'll
2619
                // configure the set of active bootstrappers, and launch a
2620
                // dedicated goroutine to maintain a set of persistent
2621
                // connections.
2622
                if shouldPeerBootstrap(s.cfg) {
3✔
2623
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2624
                        if err != nil {
×
2625
                                startErr = err
×
2626
                                return
×
2627
                        }
×
2628

2629
                        s.wg.Add(1)
×
2630
                        go s.peerBootstrapper(
×
2631
                                ctx, defaultMinPeers, bootstrappers,
×
2632
                        )
×
2633
                } else {
3✔
2634
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2635
                }
3✔
2636

2637
                // Start the blockbeat after all other subsystems have been
2638
                // started so they are ready to receive new blocks.
2639
                cleanup = cleanup.add(func() error {
3✔
2640
                        s.blockbeatDispatcher.Stop()
×
2641
                        return nil
×
2642
                })
×
2643
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2644
                        startErr = err
×
2645
                        return
×
2646
                }
×
2647

2648
                // Set the active flag now that we've completed the full
2649
                // startup.
2650
                atomic.StoreInt32(&s.active, 1)
3✔
2651
        })
2652

2653
        if startErr != nil {
3✔
2654
                cleanup.run()
×
2655
        }
×
2656
        return startErr
3✔
2657
}
2658

2659
// Stop gracefully shutsdown the main daemon server. This function will signal
2660
// any active goroutines, or helper objects to exit, then blocks until they've
2661
// all successfully exited. Additionally, any/all listeners are closed.
2662
// NOTE: This function is safe for concurrent access.
2663
func (s *server) Stop() error {
3✔
2664
        s.stop.Do(func() {
6✔
2665
                atomic.StoreInt32(&s.stopping, 1)
3✔
2666

3✔
2667
                close(s.quit)
3✔
2668

3✔
2669
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2670
                s.connMgr.Stop()
3✔
2671

3✔
2672
                // Stop dispatching blocks to other systems immediately.
3✔
2673
                s.blockbeatDispatcher.Stop()
3✔
2674

3✔
2675
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2676
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2677
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2678
                }
×
2679
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2680
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2681
                }
×
2682
                if err := s.sphinx.Stop(); err != nil {
3✔
2683
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2684
                }
×
2685
                if err := s.invoices.Stop(); err != nil {
3✔
2686
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2687
                }
×
2688
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2689
                        srvrLog.Warnf("failed to stop interceptable "+
×
2690
                                "switch: %v", err)
×
2691
                }
×
2692
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2693
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2694
                                "modifier: %v", err)
×
2695
                }
×
2696
                if err := s.chanRouter.Stop(); err != nil {
3✔
2697
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2698
                }
×
2699
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2700
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2701
                }
×
2702
                if err := s.graphDB.Stop(); err != nil {
3✔
2703
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2704
                }
×
2705
                if err := s.chainArb.Stop(); err != nil {
3✔
2706
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2707
                }
×
2708
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2709
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2710
                }
×
2711
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2712
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2713
                                err)
×
2714
                }
×
2715
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2716
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2717
                }
×
2718
                if err := s.authGossiper.Stop(); err != nil {
3✔
2719
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2720
                }
×
2721
                if err := s.sweeper.Stop(); err != nil {
3✔
2722
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2723
                }
×
2724
                if err := s.txPublisher.Stop(); err != nil {
3✔
2725
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2726
                }
×
2727
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2728
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2729
                }
×
2730
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2731
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2732
                }
×
2733
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2734
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2735
                }
×
2736

2737
                // Update channel.backup file. Make sure to do it before
2738
                // stopping chanSubSwapper.
2739
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2740
                        s.chanStateDB, s.addrSource,
3✔
2741
                )
3✔
2742
                if err != nil {
3✔
2743
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2744
                                err)
×
2745
                } else {
3✔
2746
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2747
                        if err != nil {
6✔
2748
                                srvrLog.Warnf("Manual update of channel "+
3✔
2749
                                        "backup failed: %v", err)
3✔
2750
                        }
3✔
2751
                }
2752

2753
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2754
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2755
                }
×
2756
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2757
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2758
                }
×
2759
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2760
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2761
                                err)
×
2762
                }
×
2763
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2764
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2765
                                err)
×
2766
                }
×
2767
                s.missionController.StopStoreTickers()
3✔
2768

3✔
2769
                // Disconnect from each active peers to ensure that
3✔
2770
                // peerTerminationWatchers signal completion to each peer.
3✔
2771
                for _, peer := range s.Peers() {
6✔
2772
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2773
                        if err != nil {
3✔
2774
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2775
                                        "received error: %v", peer.IdentityKey(),
×
2776
                                        err,
×
2777
                                )
×
2778
                        }
×
2779
                }
2780

2781
                // Now that all connections have been torn down, stop the tower
2782
                // client which will reliably flush all queued states to the
2783
                // tower. If this is halted for any reason, the force quit timer
2784
                // will kick in and abort to allow this method to return.
2785
                if s.towerClientMgr != nil {
6✔
2786
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2787
                                srvrLog.Warnf("Unable to shut down tower "+
×
2788
                                        "client manager: %v", err)
×
2789
                        }
×
2790
                }
2791

2792
                if s.hostAnn != nil {
3✔
2793
                        if err := s.hostAnn.Stop(); err != nil {
×
2794
                                srvrLog.Warnf("unable to shut down host "+
×
2795
                                        "annoucner: %v", err)
×
2796
                        }
×
2797
                }
2798

2799
                if s.livenessMonitor != nil {
6✔
2800
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2801
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2802
                                        "monitor: %v", err)
×
2803
                        }
×
2804
                }
2805

2806
                // Wait for all lingering goroutines to quit.
2807
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2808
                s.wg.Wait()
3✔
2809

3✔
2810
                srvrLog.Debug("Stopping buffer pools...")
3✔
2811
                s.sigPool.Stop()
3✔
2812
                s.writePool.Stop()
3✔
2813
                s.readPool.Stop()
3✔
2814
        })
2815

2816
        return nil
3✔
2817
}
2818

2819
// Stopped returns true if the server has been instructed to shutdown.
2820
// NOTE: This function is safe for concurrent access.
2821
func (s *server) Stopped() bool {
3✔
2822
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2823
}
3✔
2824

2825
// configurePortForwarding attempts to set up port forwarding for the different
2826
// ports that the server will be listening on.
2827
//
2828
// NOTE: This should only be used when using some kind of NAT traversal to
2829
// automatically set up forwarding rules.
2830
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2831
        ip, err := s.natTraversal.ExternalIP()
×
2832
        if err != nil {
×
2833
                return nil, err
×
2834
        }
×
2835
        s.lastDetectedIP = ip
×
2836

×
2837
        externalIPs := make([]string, 0, len(ports))
×
2838
        for _, port := range ports {
×
2839
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2840
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2841
                        continue
×
2842
                }
2843

2844
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2845
                externalIPs = append(externalIPs, hostIP)
×
2846
        }
2847

2848
        return externalIPs, nil
×
2849
}
2850

2851
// removePortForwarding attempts to clear the forwarding rules for the different
2852
// ports the server is currently listening on.
2853
//
2854
// NOTE: This should only be used when using some kind of NAT traversal to
2855
// automatically set up forwarding rules.
2856
func (s *server) removePortForwarding() {
×
2857
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2858
        for _, port := range forwardedPorts {
×
2859
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2860
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2861
                                "port %d: %v", port, err)
×
2862
                }
×
2863
        }
2864
}
2865

2866
// watchExternalIP continuously checks for an updated external IP address every
2867
// 15 minutes. Once a new IP address has been detected, it will automatically
2868
// handle port forwarding rules and send updated node announcements to the
2869
// currently connected peers.
2870
//
2871
// NOTE: This MUST be run as a goroutine.
2872
func (s *server) watchExternalIP() {
×
2873
        defer s.wg.Done()
×
2874

×
2875
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2876
        // up by the server.
×
2877
        defer s.removePortForwarding()
×
2878

×
2879
        // Keep track of the external IPs set by the user to avoid replacing
×
2880
        // them when detecting a new IP.
×
2881
        ipsSetByUser := make(map[string]struct{})
×
2882
        for _, ip := range s.cfg.ExternalIPs {
×
2883
                ipsSetByUser[ip.String()] = struct{}{}
×
2884
        }
×
2885

2886
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2887

×
2888
        ticker := time.NewTicker(15 * time.Minute)
×
2889
        defer ticker.Stop()
×
2890
out:
×
2891
        for {
×
2892
                select {
×
2893
                case <-ticker.C:
×
2894
                        // We'll start off by making sure a new IP address has
×
2895
                        // been detected.
×
2896
                        ip, err := s.natTraversal.ExternalIP()
×
2897
                        if err != nil {
×
2898
                                srvrLog.Debugf("Unable to retrieve the "+
×
2899
                                        "external IP address: %v", err)
×
2900
                                continue
×
2901
                        }
2902

2903
                        // Periodically renew the NAT port forwarding.
2904
                        for _, port := range forwardedPorts {
×
2905
                                err := s.natTraversal.AddPortMapping(port)
×
2906
                                if err != nil {
×
2907
                                        srvrLog.Warnf("Unable to automatically "+
×
2908
                                                "re-create port forwarding using %s: %v",
×
2909
                                                s.natTraversal.Name(), err)
×
2910
                                } else {
×
2911
                                        srvrLog.Debugf("Automatically re-created "+
×
2912
                                                "forwarding for port %d using %s to "+
×
2913
                                                "advertise external IP",
×
2914
                                                port, s.natTraversal.Name())
×
2915
                                }
×
2916
                        }
2917

2918
                        if ip.Equal(s.lastDetectedIP) {
×
2919
                                continue
×
2920
                        }
2921

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

×
2924
                        // Next, we'll craft the new addresses that will be
×
2925
                        // included in the new node announcement and advertised
×
2926
                        // to the network. Each address will consist of the new
×
2927
                        // IP detected and one of the currently advertised
×
2928
                        // ports.
×
2929
                        var newAddrs []net.Addr
×
2930
                        for _, port := range forwardedPorts {
×
2931
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2932
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2933
                                if err != nil {
×
2934
                                        srvrLog.Debugf("Unable to resolve "+
×
2935
                                                "host %v: %v", addr, err)
×
2936
                                        continue
×
2937
                                }
2938

2939
                                newAddrs = append(newAddrs, addr)
×
2940
                        }
2941

2942
                        // Skip the update if we weren't able to resolve any of
2943
                        // the new addresses.
2944
                        if len(newAddrs) == 0 {
×
2945
                                srvrLog.Debug("Skipping node announcement " +
×
2946
                                        "update due to not being able to " +
×
2947
                                        "resolve any new addresses")
×
2948
                                continue
×
2949
                        }
2950

2951
                        // Now, we'll need to update the addresses in our node's
2952
                        // announcement in order to propagate the update
2953
                        // throughout the network. We'll only include addresses
2954
                        // that have a different IP from the previous one, as
2955
                        // the previous IP is no longer valid.
2956
                        currentNodeAnn := s.getNodeAnnouncement()
×
2957

×
2958
                        for _, addr := range currentNodeAnn.Addresses {
×
2959
                                host, _, err := net.SplitHostPort(addr.String())
×
2960
                                if err != nil {
×
2961
                                        srvrLog.Debugf("Unable to determine "+
×
2962
                                                "host from address %v: %v",
×
2963
                                                addr, err)
×
2964
                                        continue
×
2965
                                }
2966

2967
                                // We'll also make sure to include external IPs
2968
                                // set manually by the user.
2969
                                _, setByUser := ipsSetByUser[addr.String()]
×
2970
                                if setByUser || host != s.lastDetectedIP.String() {
×
2971
                                        newAddrs = append(newAddrs, addr)
×
2972
                                }
×
2973
                        }
2974

2975
                        // Then, we'll generate a new timestamped node
2976
                        // announcement with the updated addresses and broadcast
2977
                        // it to our peers.
2978
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2979
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2980
                        )
×
2981
                        if err != nil {
×
2982
                                srvrLog.Debugf("Unable to generate new node "+
×
2983
                                        "announcement: %v", err)
×
2984
                                continue
×
2985
                        }
2986

2987
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2988
                        if err != nil {
×
2989
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2990
                                        "announcement to peers: %v", err)
×
2991
                                continue
×
2992
                        }
2993

2994
                        // Finally, update the last IP seen to the current one.
2995
                        s.lastDetectedIP = ip
×
2996
                case <-s.quit:
×
2997
                        break out
×
2998
                }
2999
        }
3000
}
3001

3002
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3003
// based on the server, and currently active bootstrap mechanisms as defined
3004
// within the current configuration.
3005
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3006
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3007

×
3008
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3009

×
3010
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3011
        // this can be used by default if we've already partially seeded the
×
3012
        // network.
×
3013
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3014
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3015
        if err != nil {
×
3016
                return nil, err
×
3017
        }
×
3018
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3019

×
3020
        // If this isn't simnet mode, then one of our additional bootstrapping
×
3021
        // sources will be the set of running DNS seeds.
×
3022
        if !s.cfg.Bitcoin.SimNet {
×
3023
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3024

×
3025
                // If we have a set of DNS seeds for this chain, then we'll add
×
3026
                // it as an additional bootstrapping source.
×
3027
                if ok {
×
3028
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3029
                                "seeds: %v", dnsSeeds)
×
3030

×
3031
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3032
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3033
                        )
×
3034
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3035
                }
×
3036
        }
3037

3038
        return bootStrappers, nil
×
3039
}
3040

3041
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3042
// needs to ignore, which is made of three parts,
3043
//   - the node itself needs to be skipped as it doesn't make sense to connect
3044
//     to itself.
3045
//   - the peers that already have connections with, as in s.peersByPub.
3046
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3047
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3048
        s.mu.RLock()
×
3049
        defer s.mu.RUnlock()
×
3050

×
3051
        ignore := make(map[autopilot.NodeID]struct{})
×
3052

×
3053
        // We should ignore ourselves from bootstrapping.
×
3054
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3055
        ignore[selfKey] = struct{}{}
×
3056

×
3057
        // Ignore all connected peers.
×
3058
        for _, peer := range s.peersByPub {
×
3059
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3060
                ignore[nID] = struct{}{}
×
3061
        }
×
3062

3063
        // Ignore all persistent peers as they have a dedicated reconnecting
3064
        // process.
3065
        for pubKeyStr := range s.persistentPeers {
×
3066
                var nID autopilot.NodeID
×
3067
                copy(nID[:], []byte(pubKeyStr))
×
3068
                ignore[nID] = struct{}{}
×
3069
        }
×
3070

3071
        return ignore
×
3072
}
3073

3074
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3075
// and maintain a target minimum number of outbound connections. With this
3076
// invariant, we ensure that our node is connected to a diverse set of peers
3077
// and that nodes newly joining the network receive an up to date network view
3078
// as soon as possible.
3079
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3080
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3081

×
3082
        defer s.wg.Done()
×
3083

×
3084
        // Before we continue, init the ignore peers map.
×
3085
        ignoreList := s.createBootstrapIgnorePeers()
×
3086

×
3087
        // We'll start off by aggressively attempting connections to peers in
×
3088
        // order to be a part of the network as soon as possible.
×
3089
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
×
3090

×
3091
        // Once done, we'll attempt to maintain our target minimum number of
×
3092
        // peers.
×
3093
        //
×
3094
        // We'll use a 15 second backoff, and double the time every time an
×
3095
        // epoch fails up to a ceiling.
×
3096
        backOff := time.Second * 15
×
3097

×
3098
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3099
        // see if we've reached our minimum number of peers.
×
3100
        sampleTicker := time.NewTicker(backOff)
×
3101
        defer sampleTicker.Stop()
×
3102

×
3103
        // We'll use the number of attempts and errors to determine if we need
×
3104
        // to increase the time between discovery epochs.
×
3105
        var epochErrors uint32 // To be used atomically.
×
3106
        var epochAttempts uint32
×
3107

×
3108
        for {
×
3109
                select {
×
3110
                // The ticker has just woken us up, so we'll need to check if
3111
                // we need to attempt to connect our to any more peers.
3112
                case <-sampleTicker.C:
×
3113
                        // Obtain the current number of peers, so we can gauge
×
3114
                        // if we need to sample more peers or not.
×
3115
                        s.mu.RLock()
×
3116
                        numActivePeers := uint32(len(s.peersByPub))
×
3117
                        s.mu.RUnlock()
×
3118

×
3119
                        // If we have enough peers, then we can loop back
×
3120
                        // around to the next round as we're done here.
×
3121
                        if numActivePeers >= numTargetPeers {
×
3122
                                continue
×
3123
                        }
3124

3125
                        // If all of our attempts failed during this last back
3126
                        // off period, then will increase our backoff to 5
3127
                        // minute ceiling to avoid an excessive number of
3128
                        // queries
3129
                        //
3130
                        // TODO(roasbeef): add reverse policy too?
3131

3132
                        if epochAttempts > 0 &&
×
3133
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3134

×
3135
                                sampleTicker.Stop()
×
3136

×
3137
                                backOff *= 2
×
3138
                                if backOff > bootstrapBackOffCeiling {
×
3139
                                        backOff = bootstrapBackOffCeiling
×
3140
                                }
×
3141

3142
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3143
                                        "%v", backOff)
×
3144
                                sampleTicker = time.NewTicker(backOff)
×
3145
                                continue
×
3146
                        }
3147

3148
                        atomic.StoreUint32(&epochErrors, 0)
×
3149
                        epochAttempts = 0
×
3150

×
3151
                        // Since we know need more peers, we'll compute the
×
3152
                        // exact number we need to reach our threshold.
×
3153
                        numNeeded := numTargetPeers - numActivePeers
×
3154

×
3155
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3156
                                "peers", numNeeded)
×
3157

×
3158
                        // With the number of peers we need calculated, we'll
×
3159
                        // query the network bootstrappers to sample a set of
×
3160
                        // random addrs for us.
×
3161
                        //
×
3162
                        // Before we continue, get a copy of the ignore peers
×
3163
                        // map.
×
3164
                        ignoreList = s.createBootstrapIgnorePeers()
×
3165

×
3166
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3167
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3168
                        )
×
3169
                        if err != nil {
×
3170
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3171
                                        "peers: %v", err)
×
3172
                                continue
×
3173
                        }
3174

3175
                        // Finally, we'll launch a new goroutine for each
3176
                        // prospective peer candidates.
3177
                        for _, addr := range peerAddrs {
×
3178
                                epochAttempts++
×
3179

×
3180
                                go func(a *lnwire.NetAddress) {
×
3181
                                        // TODO(roasbeef): can do AS, subnet,
×
3182
                                        // country diversity, etc
×
3183
                                        errChan := make(chan error, 1)
×
3184
                                        s.connectToPeer(
×
3185
                                                a, errChan,
×
3186
                                                s.cfg.ConnectionTimeout,
×
3187
                                        )
×
3188
                                        select {
×
3189
                                        case err := <-errChan:
×
3190
                                                if err == nil {
×
3191
                                                        return
×
3192
                                                }
×
3193

3194
                                                srvrLog.Errorf("Unable to "+
×
3195
                                                        "connect to %v: %v",
×
3196
                                                        a, err)
×
3197
                                                atomic.AddUint32(&epochErrors, 1)
×
3198
                                        case <-s.quit:
×
3199
                                        }
3200
                                }(addr)
3201
                        }
3202
                case <-s.quit:
×
3203
                        return
×
3204
                }
3205
        }
3206
}
3207

3208
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3209
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3210
// query back off each time we encounter a failure.
3211
const bootstrapBackOffCeiling = time.Minute * 5
3212

3213
// initialPeerBootstrap attempts to continuously connect to peers on startup
3214
// until the target number of peers has been reached. This ensures that nodes
3215
// receive an up to date network view as soon as possible.
3216
func (s *server) initialPeerBootstrap(ctx context.Context,
3217
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3218
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3219

×
3220
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3221
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3222

×
3223
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3224
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3225
        var delaySignal <-chan time.Time
×
3226
        delayTime := time.Second * 2
×
3227

×
3228
        // As want to be more aggressive, we'll use a lower back off celling
×
3229
        // then the main peer bootstrap logic.
×
3230
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3231

×
3232
        for attempts := 0; ; attempts++ {
×
3233
                // Check if the server has been requested to shut down in order
×
3234
                // to prevent blocking.
×
3235
                if s.Stopped() {
×
3236
                        return
×
3237
                }
×
3238

3239
                // We can exit our aggressive initial peer bootstrapping stage
3240
                // if we've reached out target number of peers.
3241
                s.mu.RLock()
×
3242
                numActivePeers := uint32(len(s.peersByPub))
×
3243
                s.mu.RUnlock()
×
3244

×
3245
                if numActivePeers >= numTargetPeers {
×
3246
                        return
×
3247
                }
×
3248

3249
                if attempts > 0 {
×
3250
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3251
                                "bootstrap peers (attempt #%v)", delayTime,
×
3252
                                attempts)
×
3253

×
3254
                        // We've completed at least one iterating and haven't
×
3255
                        // finished, so we'll start to insert a delay period
×
3256
                        // between each attempt.
×
3257
                        delaySignal = time.After(delayTime)
×
3258
                        select {
×
3259
                        case <-delaySignal:
×
3260
                        case <-s.quit:
×
3261
                                return
×
3262
                        }
3263

3264
                        // After our delay, we'll double the time we wait up to
3265
                        // the max back off period.
3266
                        delayTime *= 2
×
3267
                        if delayTime > backOffCeiling {
×
3268
                                delayTime = backOffCeiling
×
3269
                        }
×
3270
                }
3271

3272
                // Otherwise, we'll request for the remaining number of peers
3273
                // in order to reach our target.
3274
                peersNeeded := numTargetPeers - numActivePeers
×
3275
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3276
                        ctx, ignore, peersNeeded, bootstrappers...,
×
3277
                )
×
3278
                if err != nil {
×
3279
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3280
                                "peers: %v", err)
×
3281
                        continue
×
3282
                }
3283

3284
                // Then, we'll attempt to establish a connection to the
3285
                // different peer addresses retrieved by our bootstrappers.
3286
                var wg sync.WaitGroup
×
3287
                for _, bootstrapAddr := range bootstrapAddrs {
×
3288
                        wg.Add(1)
×
3289
                        go func(addr *lnwire.NetAddress) {
×
3290
                                defer wg.Done()
×
3291

×
3292
                                errChan := make(chan error, 1)
×
3293
                                go s.connectToPeer(
×
3294
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3295
                                )
×
3296

×
3297
                                // We'll only allow this connection attempt to
×
3298
                                // take up to 3 seconds. This allows us to move
×
3299
                                // quickly by discarding peers that are slowing
×
3300
                                // us down.
×
3301
                                select {
×
3302
                                case err := <-errChan:
×
3303
                                        if err == nil {
×
3304
                                                return
×
3305
                                        }
×
3306
                                        srvrLog.Errorf("Unable to connect to "+
×
3307
                                                "%v: %v", addr, err)
×
3308
                                // TODO: tune timeout? 3 seconds might be *too*
3309
                                // aggressive but works well.
3310
                                case <-time.After(3 * time.Second):
×
3311
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3312
                                                "to not establishing a "+
×
3313
                                                "connection within 3 seconds",
×
3314
                                                addr)
×
3315
                                case <-s.quit:
×
3316
                                }
3317
                        }(bootstrapAddr)
3318
                }
3319

3320
                wg.Wait()
×
3321
        }
3322
}
3323

3324
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3325
// order to listen for inbound connections over Tor.
3326
func (s *server) createNewHiddenService() error {
×
3327
        // Determine the different ports the server is listening on. The onion
×
3328
        // service's virtual port will map to these ports and one will be picked
×
3329
        // at random when the onion service is being accessed.
×
3330
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3331
        for _, listenAddr := range s.listenAddrs {
×
3332
                port := listenAddr.(*net.TCPAddr).Port
×
3333
                listenPorts = append(listenPorts, port)
×
3334
        }
×
3335

3336
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3337
        if err != nil {
×
3338
                return err
×
3339
        }
×
3340

3341
        // Once the port mapping has been set, we can go ahead and automatically
3342
        // create our onion service. The service's private key will be saved to
3343
        // disk in order to regain access to this service when restarting `lnd`.
3344
        onionCfg := tor.AddOnionConfig{
×
3345
                VirtualPort: defaultPeerPort,
×
3346
                TargetPorts: listenPorts,
×
3347
                Store: tor.NewOnionFile(
×
3348
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3349
                        encrypter,
×
3350
                ),
×
3351
        }
×
3352

×
3353
        switch {
×
3354
        case s.cfg.Tor.V2:
×
3355
                onionCfg.Type = tor.V2
×
3356
        case s.cfg.Tor.V3:
×
3357
                onionCfg.Type = tor.V3
×
3358
        }
3359

3360
        addr, err := s.torController.AddOnion(onionCfg)
×
3361
        if err != nil {
×
3362
                return err
×
3363
        }
×
3364

3365
        // Now that the onion service has been created, we'll add the onion
3366
        // address it can be reached at to our list of advertised addresses.
3367
        newNodeAnn, err := s.genNodeAnnouncement(
×
3368
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3369
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3370
                },
×
3371
        )
3372
        if err != nil {
×
3373
                return fmt.Errorf("unable to generate new node "+
×
3374
                        "announcement: %v", err)
×
3375
        }
×
3376

3377
        // Finally, we'll update the on-disk version of our announcement so it
3378
        // will eventually propagate to nodes in the network.
3379
        selfNode := &models.LightningNode{
×
3380
                HaveNodeAnnouncement: true,
×
3381
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3382
                Addresses:            newNodeAnn.Addresses,
×
3383
                Alias:                newNodeAnn.Alias.String(),
×
3384
                Features: lnwire.NewFeatureVector(
×
3385
                        newNodeAnn.Features, lnwire.Features,
×
3386
                ),
×
3387
                Color:        newNodeAnn.RGBColor,
×
3388
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3389
        }
×
3390
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3391
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3392
                return fmt.Errorf("can't set self node: %w", err)
×
3393
        }
×
3394

3395
        return nil
×
3396
}
3397

3398
// findChannel finds a channel given a public key and ChannelID. It is an
3399
// optimization that is quicker than seeking for a channel given only the
3400
// ChannelID.
3401
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3402
        *channeldb.OpenChannel, error) {
3✔
3403

3✔
3404
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3405
        if err != nil {
3✔
3406
                return nil, err
×
3407
        }
×
3408

3409
        for _, channel := range nodeChans {
6✔
3410
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3411
                        return channel, nil
3✔
3412
                }
3✔
3413
        }
3414

3415
        return nil, fmt.Errorf("unable to find channel")
3✔
3416
}
3417

3418
// getNodeAnnouncement fetches the current, fully signed node announcement.
3419
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3420
        s.mu.Lock()
3✔
3421
        defer s.mu.Unlock()
3✔
3422

3✔
3423
        return *s.currentNodeAnn
3✔
3424
}
3✔
3425

3426
// genNodeAnnouncement generates and returns the current fully signed node
3427
// announcement. The time stamp of the announcement will be updated in order
3428
// to ensure it propagates through the network.
3429
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3430
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3431

3✔
3432
        s.mu.Lock()
3✔
3433
        defer s.mu.Unlock()
3✔
3434

3✔
3435
        // First, try to update our feature manager with the updated set of
3✔
3436
        // features.
3✔
3437
        if features != nil {
6✔
3438
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3439
                        feature.SetNodeAnn: features,
3✔
3440
                }
3✔
3441
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3442
                if err != nil {
6✔
3443
                        return lnwire.NodeAnnouncement{}, err
3✔
3444
                }
3✔
3445

3446
                // If we could successfully update our feature manager, add
3447
                // an update modifier to include these new features to our
3448
                // set.
3449
                modifiers = append(
3✔
3450
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3451
                )
3✔
3452
        }
3453

3454
        // Always update the timestamp when refreshing to ensure the update
3455
        // propagates.
3456
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3457

3✔
3458
        // Apply the requested changes to the node announcement.
3✔
3459
        for _, modifier := range modifiers {
6✔
3460
                modifier(s.currentNodeAnn)
3✔
3461
        }
3✔
3462

3463
        // Sign a new update after applying all of the passed modifiers.
3464
        err := netann.SignNodeAnnouncement(
3✔
3465
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3466
        )
3✔
3467
        if err != nil {
3✔
3468
                return lnwire.NodeAnnouncement{}, err
×
3469
        }
×
3470

3471
        return *s.currentNodeAnn, nil
3✔
3472
}
3473

3474
// updateAndBroadcastSelfNode generates a new node announcement
3475
// applying the giving modifiers and updating the time stamp
3476
// to ensure it propagates through the network. Then it broadcasts
3477
// it to the network.
3478
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3479
        modifiers ...netann.NodeAnnModifier) error {
3✔
3480

3✔
3481
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3482
        if err != nil {
6✔
3483
                return fmt.Errorf("unable to generate new node "+
3✔
3484
                        "announcement: %v", err)
3✔
3485
        }
3✔
3486

3487
        // Update the on-disk version of our announcement.
3488
        // Load and modify self node istead of creating anew instance so we
3489
        // don't risk overwriting any existing values.
3490
        selfNode, err := s.graphDB.SourceNode()
3✔
3491
        if err != nil {
3✔
3492
                return fmt.Errorf("unable to get current source node: %w", err)
×
3493
        }
×
3494

3495
        selfNode.HaveNodeAnnouncement = true
3✔
3496
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3497
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3498
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3499
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3500
        selfNode.Color = newNodeAnn.RGBColor
3✔
3501
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3502

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

3✔
3505
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
3✔
3506
                return fmt.Errorf("can't set self node: %w", err)
×
3507
        }
×
3508

3509
        // Finally, propagate it to the nodes in the network.
3510
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3511
        if err != nil {
3✔
3512
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3513
                        "announcement to peers: %v", err)
×
3514
                return err
×
3515
        }
×
3516

3517
        return nil
3✔
3518
}
3519

3520
type nodeAddresses struct {
3521
        pubKey    *btcec.PublicKey
3522
        addresses []net.Addr
3523
}
3524

3525
// establishPersistentConnections attempts to establish persistent connections
3526
// to all our direct channel collaborators. In order to promote liveness of our
3527
// active channels, we instruct the connection manager to attempt to establish
3528
// and maintain persistent connections to all our direct channel counterparties.
3529
func (s *server) establishPersistentConnections() error {
3✔
3530
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3531
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3532
        // since other PubKey forms can't be compared.
3✔
3533
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3534

3✔
3535
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3536
        // attempt to connect to based on our set of previous connections. Set
3✔
3537
        // the reconnection port to the default peer port.
3✔
3538
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3539
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3540
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3541
        }
×
3542

3543
        for _, node := range linkNodes {
6✔
3544
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3545
                nodeAddrs := &nodeAddresses{
3✔
3546
                        pubKey:    node.IdentityPub,
3✔
3547
                        addresses: node.Addresses,
3✔
3548
                }
3✔
3549
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3550
        }
3✔
3551

3552
        // After checking our previous connections for addresses to connect to,
3553
        // iterate through the nodes in our channel graph to find addresses
3554
        // that have been added via NodeAnnouncement messages.
3555
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3556
        // each of the nodes.
3557
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3558
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3559

3✔
3560
                // If the remote party has announced the channel to us, but we
3✔
3561
                // haven't yet, then we won't have a policy. However, we don't
3✔
3562
                // need this to connect to the peer, so we'll log it and move on.
3✔
3563
                if !havePolicy {
3✔
3564
                        srvrLog.Warnf("No channel policy found for "+
×
3565
                                "ChannelPoint(%v): ", chanPoint)
×
3566
                }
×
3567

3568
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3569

3✔
3570
                // Add all unique addresses from channel
3✔
3571
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3572
                // connect to for this peer.
3✔
3573
                addrSet := make(map[string]net.Addr)
3✔
3574
                for _, addr := range channelPeer.Addresses {
6✔
3575
                        switch addr.(type) {
3✔
3576
                        case *net.TCPAddr:
3✔
3577
                                addrSet[addr.String()] = addr
3✔
3578

3579
                        // We'll only attempt to connect to Tor addresses if Tor
3580
                        // outbound support is enabled.
3581
                        case *tor.OnionAddr:
×
3582
                                if s.cfg.Tor.Active {
×
3583
                                        addrSet[addr.String()] = addr
×
3584
                                }
×
3585
                        }
3586
                }
3587

3588
                // If this peer is also recorded as a link node, we'll add any
3589
                // additional addresses that have not already been selected.
3590
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3591
                if ok {
6✔
3592
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3593
                                switch lnAddress.(type) {
3✔
3594
                                case *net.TCPAddr:
3✔
3595
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3596

3597
                                // We'll only attempt to connect to Tor
3598
                                // addresses if Tor outbound support is enabled.
3599
                                case *tor.OnionAddr:
×
3600
                                        if s.cfg.Tor.Active {
×
3601
                                                addrSet[lnAddress.String()] = lnAddress
×
3602
                                        }
×
3603
                                }
3604
                        }
3605
                }
3606

3607
                // Construct a slice of the deduped addresses.
3608
                var addrs []net.Addr
3✔
3609
                for _, addr := range addrSet {
6✔
3610
                        addrs = append(addrs, addr)
3✔
3611
                }
3✔
3612

3613
                n := &nodeAddresses{
3✔
3614
                        addresses: addrs,
3✔
3615
                }
3✔
3616
                n.pubKey, err = channelPeer.PubKey()
3✔
3617
                if err != nil {
3✔
3618
                        return err
×
3619
                }
×
3620

3621
                nodeAddrsMap[pubStr] = n
3✔
3622
                return nil
3✔
3623
        })
3624
        if err != nil {
3✔
3625
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3626
                        "%v", err)
×
3627

×
3628
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3629
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3630

×
3631
                        return err
×
3632
                }
×
3633
        }
3634

3635
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3636
                len(nodeAddrsMap))
3✔
3637

3✔
3638
        // Acquire and hold server lock until all persistent connection requests
3✔
3639
        // have been recorded and sent to the connection manager.
3✔
3640
        s.mu.Lock()
3✔
3641
        defer s.mu.Unlock()
3✔
3642

3✔
3643
        // Iterate through the combined list of addresses from prior links and
3✔
3644
        // node announcements and attempt to reconnect to each node.
3✔
3645
        var numOutboundConns int
3✔
3646
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3647
                // Add this peer to the set of peers we should maintain a
3✔
3648
                // persistent connection with. We set the value to false to
3✔
3649
                // indicate that we should not continue to reconnect if the
3✔
3650
                // number of channels returns to zero, since this peer has not
3✔
3651
                // been requested as perm by the user.
3✔
3652
                s.persistentPeers[pubStr] = false
3✔
3653
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3654
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3655
                }
3✔
3656

3657
                for _, address := range nodeAddr.addresses {
6✔
3658
                        // Create a wrapper address which couples the IP and
3✔
3659
                        // the pubkey so the brontide authenticated connection
3✔
3660
                        // can be established.
3✔
3661
                        lnAddr := &lnwire.NetAddress{
3✔
3662
                                IdentityKey: nodeAddr.pubKey,
3✔
3663
                                Address:     address,
3✔
3664
                        }
3✔
3665

3✔
3666
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3667
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3668
                }
3✔
3669

3670
                // We'll connect to the first 10 peers immediately, then
3671
                // randomly stagger any remaining connections if the
3672
                // stagger initial reconnect flag is set. This ensures
3673
                // that mobile nodes or nodes with a small number of
3674
                // channels obtain connectivity quickly, but larger
3675
                // nodes are able to disperse the costs of connecting to
3676
                // all peers at once.
3677
                if numOutboundConns < numInstantInitReconnect ||
3✔
3678
                        !s.cfg.StaggerInitialReconnect {
6✔
3679

3✔
3680
                        go s.connectToPersistentPeer(pubStr)
3✔
3681
                } else {
3✔
3682
                        go s.delayInitialReconnect(pubStr)
×
3683
                }
×
3684

3685
                numOutboundConns++
3✔
3686
        }
3687

3688
        return nil
3✔
3689
}
3690

3691
// delayInitialReconnect will attempt a reconnection to the given peer after
3692
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3693
//
3694
// NOTE: This method MUST be run as a goroutine.
3695
func (s *server) delayInitialReconnect(pubStr string) {
×
3696
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3697
        select {
×
3698
        case <-time.After(delay):
×
3699
                s.connectToPersistentPeer(pubStr)
×
3700
        case <-s.quit:
×
3701
        }
3702
}
3703

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

3✔
3710
        s.mu.Lock()
3✔
3711
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3712
                delete(s.persistentPeers, pubKeyStr)
3✔
3713
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3714
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3715
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3716
                s.mu.Unlock()
3✔
3717

3✔
3718
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3719
                        "peer has no open channels", compressedPubKey)
3✔
3720

3✔
3721
                return
3✔
3722
        }
3✔
3723
        s.mu.Unlock()
3✔
3724
}
3725

3726
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3727
// is instead used to remove persistent peer state for a peer that has been
3728
// disconnected for good cause by the server. Currently, a gossip ban from
3729
// sending garbage and the server running out of restricted-access
3730
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3731
// future, this function may expand when more ban criteria is added.
3732
//
3733
// NOTE: The server's write lock MUST be held when this is called.
3734
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3735
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3736
                delete(s.persistentPeers, remotePub)
×
3737
                delete(s.persistentPeersBackoff, remotePub)
×
3738
                delete(s.persistentPeerAddrs, remotePub)
×
3739
                s.cancelConnReqs(remotePub, nil)
×
3740
        }
×
3741
}
3742

3743
// BroadcastMessage sends a request to the server to broadcast a set of
3744
// messages to all peers other than the one specified by the `skips` parameter.
3745
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3746
// the target peers.
3747
//
3748
// NOTE: This function is safe for concurrent access.
3749
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3750
        msgs ...lnwire.Message) error {
3✔
3751

3✔
3752
        // Filter out peers found in the skips map. We synchronize access to
3✔
3753
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3754
        // exact set of peers present at the time of invocation.
3✔
3755
        s.mu.RLock()
3✔
3756
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3757
        for pubStr, sPeer := range s.peersByPub {
6✔
3758
                if skips != nil {
6✔
3759
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3760
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3761
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3762
                                continue
3✔
3763
                        }
3764
                }
3765

3766
                peers = append(peers, sPeer)
3✔
3767
        }
3768
        s.mu.RUnlock()
3✔
3769

3✔
3770
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3771
        // all messages to each of peers.
3✔
3772
        var wg sync.WaitGroup
3✔
3773
        for _, sPeer := range peers {
6✔
3774
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3775
                        sPeer.PubKey())
3✔
3776

3✔
3777
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3778
                wg.Add(1)
3✔
3779
                s.wg.Add(1)
3✔
3780
                go func(p lnpeer.Peer) {
6✔
3781
                        defer s.wg.Done()
3✔
3782
                        defer wg.Done()
3✔
3783

3✔
3784
                        p.SendMessageLazy(false, msgs...)
3✔
3785
                }(sPeer)
3✔
3786
        }
3787

3788
        // Wait for all messages to have been dispatched before returning to
3789
        // caller.
3790
        wg.Wait()
3✔
3791

3✔
3792
        return nil
3✔
3793
}
3794

3795
// NotifyWhenOnline can be called by other subsystems to get notified when a
3796
// particular peer comes online. The peer itself is sent across the peerChan.
3797
//
3798
// NOTE: This function is safe for concurrent access.
3799
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3800
        peerChan chan<- lnpeer.Peer) {
3✔
3801

3✔
3802
        s.mu.Lock()
3✔
3803

3✔
3804
        // Compute the target peer's identifier.
3✔
3805
        pubStr := string(peerKey[:])
3✔
3806

3✔
3807
        // Check if peer is connected.
3✔
3808
        peer, ok := s.peersByPub[pubStr]
3✔
3809
        if ok {
6✔
3810
                // Unlock here so that the mutex isn't held while we are
3✔
3811
                // waiting for the peer to become active.
3✔
3812
                s.mu.Unlock()
3✔
3813

3✔
3814
                // Wait until the peer signals that it is actually active
3✔
3815
                // rather than only in the server's maps.
3✔
3816
                select {
3✔
3817
                case <-peer.ActiveSignal():
3✔
3818
                case <-peer.QuitSignal():
1✔
3819
                        // The peer quit, so we'll add the channel to the slice
1✔
3820
                        // and return.
1✔
3821
                        s.mu.Lock()
1✔
3822
                        s.peerConnectedListeners[pubStr] = append(
1✔
3823
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3824
                        )
1✔
3825
                        s.mu.Unlock()
1✔
3826
                        return
1✔
3827
                }
3828

3829
                // Connected, can return early.
3830
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3831

3✔
3832
                select {
3✔
3833
                case peerChan <- peer:
3✔
UNCOV
3834
                case <-s.quit:
×
3835
                }
3836

3837
                return
3✔
3838
        }
3839

3840
        // Not connected, store this listener such that it can be notified when
3841
        // the peer comes online.
3842
        s.peerConnectedListeners[pubStr] = append(
3✔
3843
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3844
        )
3✔
3845
        s.mu.Unlock()
3✔
3846
}
3847

3848
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3849
// the given public key has been disconnected. The notification is signaled by
3850
// closing the channel returned.
3851
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3852
        s.mu.Lock()
3✔
3853
        defer s.mu.Unlock()
3✔
3854

3✔
3855
        c := make(chan struct{})
3✔
3856

3✔
3857
        // If the peer is already offline, we can immediately trigger the
3✔
3858
        // notification.
3✔
3859
        peerPubKeyStr := string(peerPubKey[:])
3✔
3860
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3861
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3862
                close(c)
×
3863
                return c
×
3864
        }
×
3865

3866
        // Otherwise, the peer is online, so we'll keep track of the channel to
3867
        // trigger the notification once the server detects the peer
3868
        // disconnects.
3869
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3870
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3871
        )
3✔
3872

3✔
3873
        return c
3✔
3874
}
3875

3876
// FindPeer will return the peer that corresponds to the passed in public key.
3877
// This function is used by the funding manager, allowing it to update the
3878
// daemon's local representation of the remote peer.
3879
//
3880
// NOTE: This function is safe for concurrent access.
3881
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3882
        s.mu.RLock()
3✔
3883
        defer s.mu.RUnlock()
3✔
3884

3✔
3885
        pubStr := string(peerKey.SerializeCompressed())
3✔
3886

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

3890
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3891
// which should be a string representation of the peer's serialized, compressed
3892
// public key.
3893
//
3894
// NOTE: This function is safe for concurrent access.
3895
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3896
        s.mu.RLock()
3✔
3897
        defer s.mu.RUnlock()
3✔
3898

3✔
3899
        return s.findPeerByPubStr(pubStr)
3✔
3900
}
3✔
3901

3902
// findPeerByPubStr is an internal method that retrieves the specified peer from
3903
// the server's internal state using.
3904
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3905
        peer, ok := s.peersByPub[pubStr]
3✔
3906
        if !ok {
6✔
3907
                return nil, ErrPeerNotConnected
3✔
3908
        }
3✔
3909

3910
        return peer, nil
3✔
3911
}
3912

3913
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3914
// exponential backoff. If no previous backoff was known, the default is
3915
// returned.
3916
func (s *server) nextPeerBackoff(pubStr string,
3917
        startTime time.Time) time.Duration {
3✔
3918

3✔
3919
        // Now, determine the appropriate backoff to use for the retry.
3✔
3920
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3921
        if !ok {
6✔
3922
                // If an existing backoff was unknown, use the default.
3✔
3923
                return s.cfg.MinBackoff
3✔
3924
        }
3✔
3925

3926
        // If the peer failed to start properly, we'll just use the previous
3927
        // backoff to compute the subsequent randomized exponential backoff
3928
        // duration. This will roughly double on average.
3929
        if startTime.IsZero() {
3✔
UNCOV
3930
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3931
        }
×
3932

3933
        // The peer succeeded in starting. If the connection didn't last long
3934
        // enough to be considered stable, we'll continue to back off retries
3935
        // with this peer.
3936
        connDuration := time.Since(startTime)
3✔
3937
        if connDuration < defaultStableConnDuration {
6✔
3938
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3939
        }
3✔
3940

3941
        // The peer succeed in starting and this was stable peer, so we'll
3942
        // reduce the timeout duration by the length of the connection after
3943
        // applying randomized exponential backoff. We'll only apply this in the
3944
        // case that:
3945
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3946
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3947
        if relaxedBackoff > s.cfg.MinBackoff {
×
3948
                return relaxedBackoff
×
3949
        }
×
3950

3951
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3952
        // the stable connection lasted much longer than our previous backoff.
3953
        // To reward such good behavior, we'll reconnect after the default
3954
        // timeout.
3955
        return s.cfg.MinBackoff
×
3956
}
3957

3958
// shouldDropLocalConnection determines if our local connection to a remote peer
3959
// should be dropped in the case of concurrent connection establishment. In
3960
// order to deterministically decide which connection should be dropped, we'll
3961
// utilize the ordering of the local and remote public key. If we didn't use
3962
// such a tie breaker, then we risk _both_ connections erroneously being
3963
// dropped.
3964
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3965
        localPubBytes := local.SerializeCompressed()
×
3966
        remotePubPbytes := remote.SerializeCompressed()
×
3967

×
3968
        // The connection that comes from the node with a "smaller" pubkey
×
3969
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3970
        // should drop our established connection.
×
3971
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3972
}
×
3973

3974
// InboundPeerConnected initializes a new peer in response to a new inbound
3975
// connection.
3976
//
3977
// NOTE: This function is safe for concurrent access.
3978
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3979
        // Exit early if we have already been instructed to shutdown, this
3✔
3980
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3981
        if s.Stopped() {
3✔
3982
                return
×
3983
        }
×
3984

3985
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3986
        pubSer := nodePub.SerializeCompressed()
3✔
3987
        pubStr := string(pubSer)
3✔
3988

3✔
3989
        var pubBytes [33]byte
3✔
3990
        copy(pubBytes[:], pubSer)
3✔
3991

3✔
3992
        s.mu.Lock()
3✔
3993
        defer s.mu.Unlock()
3✔
3994

3✔
3995
        // If the remote node's public key is banned, drop the connection.
3✔
3996
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
3997
        if err != nil {
3✔
3998
                // Clean up the persistent peer maps if we're dropping this
×
3999
                // connection.
×
4000
                s.bannedPersistentPeerConnection(pubStr)
×
4001

×
4002
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4003
                        "of restricted-access connection slots: %v.", pubSer,
×
4004
                        err)
×
4005

×
4006
                conn.Close()
×
4007

×
4008
                return
×
4009
        }
×
4010

4011
        // If we already have an outbound connection to this peer, then ignore
4012
        // this new connection.
4013
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4014
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4015
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4016
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4017

3✔
4018
                conn.Close()
3✔
4019
                return
3✔
4020
        }
3✔
4021

4022
        // If we already have a valid connection that is scheduled to take
4023
        // precedence once the prior peer has finished disconnecting, we'll
4024
        // ignore this connection.
4025
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4026
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4027
                        "scheduled", conn.RemoteAddr(), p)
×
4028
                conn.Close()
×
4029
                return
×
4030
        }
×
4031

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

3✔
4034
        // Check to see if we already have a connection with this peer. If so,
3✔
4035
        // we may need to drop our existing connection. This prevents us from
3✔
4036
        // having duplicate connections to the same peer. We forgo adding a
3✔
4037
        // default case as we expect these to be the only error values returned
3✔
4038
        // from findPeerByPubStr.
3✔
4039
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4040
        switch err {
3✔
4041
        case ErrPeerNotConnected:
3✔
4042
                // We were unable to locate an existing connection with the
3✔
4043
                // target peer, proceed to connect.
3✔
4044
                s.cancelConnReqs(pubStr, nil)
3✔
4045
                s.peerConnected(conn, nil, true, access)
3✔
4046

4047
        case nil:
×
4048
                // We already have a connection with the incoming peer. If the
×
4049
                // connection we've already established should be kept and is
×
4050
                // not of the same type of the new connection (inbound), then
×
4051
                // we'll close out the new connection s.t there's only a single
×
4052
                // connection between us.
×
4053
                localPub := s.identityECDH.PubKey()
×
4054
                if !connectedPeer.Inbound() &&
×
4055
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4056

×
4057
                        srvrLog.Warnf("Received inbound connection from "+
×
4058
                                "peer %v, but already have outbound "+
×
4059
                                "connection, dropping conn", connectedPeer)
×
4060
                        conn.Close()
×
4061
                        return
×
4062
                }
×
4063

4064
                // Otherwise, if we should drop the connection, then we'll
4065
                // disconnect our already connected peer.
4066
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4067
                        connectedPeer)
×
4068

×
4069
                s.cancelConnReqs(pubStr, nil)
×
4070

×
4071
                // Remove the current peer from the server's internal state and
×
4072
                // signal that the peer termination watcher does not need to
×
4073
                // execute for this peer.
×
4074
                s.removePeer(connectedPeer)
×
4075
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4076
                s.scheduledPeerConnection[pubStr] = func() {
×
4077
                        s.peerConnected(conn, nil, true, access)
×
4078
                }
×
4079
        }
4080
}
4081

4082
// OutboundPeerConnected initializes a new peer in response to a new outbound
4083
// connection.
4084
// NOTE: This function is safe for concurrent access.
4085
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4086
        // Exit early if we have already been instructed to shutdown, this
3✔
4087
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4088
        if s.Stopped() {
3✔
4089
                return
×
4090
        }
×
4091

4092
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4093
        pubSer := nodePub.SerializeCompressed()
3✔
4094
        pubStr := string(pubSer)
3✔
4095

3✔
4096
        var pubBytes [33]byte
3✔
4097
        copy(pubBytes[:], pubSer)
3✔
4098

3✔
4099
        s.mu.Lock()
3✔
4100
        defer s.mu.Unlock()
3✔
4101

3✔
4102
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4103
        if err != nil {
3✔
4104
                // Clean up the persistent peer maps if we're dropping this
×
4105
                // connection.
×
4106
                s.bannedPersistentPeerConnection(pubStr)
×
4107

×
4108
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4109
                        "of restricted-access connection slots: %v.", pubSer,
×
4110
                        err)
×
4111

×
4112
                if connReq != nil {
×
4113
                        s.connMgr.Remove(connReq.ID())
×
4114
                }
×
4115

4116
                conn.Close()
×
4117

×
4118
                return
×
4119
        }
4120

4121
        // If we already have an inbound connection to this peer, then ignore
4122
        // this new connection.
4123
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4124
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4125
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4126
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4127

3✔
4128
                if connReq != nil {
6✔
4129
                        s.connMgr.Remove(connReq.ID())
3✔
4130
                }
3✔
4131
                conn.Close()
3✔
4132
                return
3✔
4133
        }
4134
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4135
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4136
                s.connMgr.Remove(connReq.ID())
×
4137
                conn.Close()
×
4138
                return
×
4139
        }
×
4140

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

×
4147
                if connReq != nil {
×
4148
                        s.connMgr.Remove(connReq.ID())
×
4149
                }
×
4150

4151
                conn.Close()
×
4152
                return
×
4153
        }
4154

4155
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4156
                conn.RemoteAddr())
3✔
4157

3✔
4158
        if connReq != nil {
6✔
4159
                // A successful connection was returned by the connmgr.
3✔
4160
                // Immediately cancel all pending requests, excluding the
3✔
4161
                // outbound connection we just established.
3✔
4162
                ignore := connReq.ID()
3✔
4163
                s.cancelConnReqs(pubStr, &ignore)
3✔
4164
        } else {
6✔
4165
                // This was a successful connection made by some other
3✔
4166
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4167
                s.cancelConnReqs(pubStr, nil)
3✔
4168
        }
3✔
4169

4170
        // If we already have a connection with this peer, decide whether or not
4171
        // we need to drop the stale connection. We forgo adding a default case
4172
        // as we expect these to be the only error values returned from
4173
        // findPeerByPubStr.
4174
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4175
        switch err {
3✔
4176
        case ErrPeerNotConnected:
3✔
4177
                // We were unable to locate an existing connection with the
3✔
4178
                // target peer, proceed to connect.
3✔
4179
                s.peerConnected(conn, connReq, false, access)
3✔
4180

4181
        case nil:
×
4182
                // We already have a connection with the incoming peer. If the
×
4183
                // connection we've already established should be kept and is
×
4184
                // not of the same type of the new connection (outbound), then
×
4185
                // we'll close out the new connection s.t there's only a single
×
4186
                // connection between us.
×
4187
                localPub := s.identityECDH.PubKey()
×
4188
                if connectedPeer.Inbound() &&
×
4189
                        shouldDropLocalConnection(localPub, nodePub) {
×
4190

×
4191
                        srvrLog.Warnf("Established outbound connection to "+
×
4192
                                "peer %v, but already have inbound "+
×
4193
                                "connection, dropping conn", connectedPeer)
×
4194
                        if connReq != nil {
×
4195
                                s.connMgr.Remove(connReq.ID())
×
4196
                        }
×
4197
                        conn.Close()
×
4198
                        return
×
4199
                }
4200

4201
                // Otherwise, _their_ connection should be dropped. So we'll
4202
                // disconnect the peer and send the now obsolete peer to the
4203
                // server for garbage collection.
4204
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4205
                        connectedPeer)
×
4206

×
4207
                // Remove the current peer from the server's internal state and
×
4208
                // signal that the peer termination watcher does not need to
×
4209
                // execute for this peer.
×
4210
                s.removePeer(connectedPeer)
×
4211
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4212
                s.scheduledPeerConnection[pubStr] = func() {
×
4213
                        s.peerConnected(conn, connReq, false, access)
×
4214
                }
×
4215
        }
4216
}
4217

4218
// UnassignedConnID is the default connection ID that a request can have before
4219
// it actually is submitted to the connmgr.
4220
// TODO(conner): move into connmgr package, or better, add connmgr method for
4221
// generating atomic IDs
4222
const UnassignedConnID uint64 = 0
4223

4224
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4225
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4226
// Afterwards, each connection request removed from the connmgr. The caller can
4227
// optionally specify a connection ID to ignore, which prevents us from
4228
// canceling a successful request. All persistent connreqs for the provided
4229
// pubkey are discarded after the operationjw.
4230
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4231
        // First, cancel any lingering persistent retry attempts, which will
3✔
4232
        // prevent retries for any with backoffs that are still maturing.
3✔
4233
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4234
                close(cancelChan)
3✔
4235
                delete(s.persistentRetryCancels, pubStr)
3✔
4236
        }
3✔
4237

4238
        // Next, check to see if we have any outstanding persistent connection
4239
        // requests to this peer. If so, then we'll remove all of these
4240
        // connection requests, and also delete the entry from the map.
4241
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4242
        if !ok {
6✔
4243
                return
3✔
4244
        }
3✔
4245

4246
        for _, connReq := range connReqs {
6✔
4247
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4248

3✔
4249
                // Atomically capture the current request identifier.
3✔
4250
                connID := connReq.ID()
3✔
4251

3✔
4252
                // Skip any zero IDs, this indicates the request has not
3✔
4253
                // yet been schedule.
3✔
4254
                if connID == UnassignedConnID {
3✔
4255
                        continue
×
4256
                }
4257

4258
                // Skip a particular connection ID if instructed.
4259
                if skip != nil && connID == *skip {
6✔
4260
                        continue
3✔
4261
                }
4262

4263
                s.connMgr.Remove(connID)
3✔
4264
        }
4265

4266
        delete(s.persistentConnReqs, pubStr)
3✔
4267
}
4268

4269
// handleCustomMessage dispatches an incoming custom peers message to
4270
// subscribers.
4271
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4272
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4273
                peer, msg.Type)
3✔
4274

3✔
4275
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4276
                Peer: peer,
3✔
4277
                Msg:  msg,
3✔
4278
        })
3✔
4279
}
3✔
4280

4281
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4282
// messages.
4283
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4284
        return s.customMessageServer.Subscribe()
3✔
4285
}
3✔
4286

4287
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4288
// the channelNotifier's NotifyOpenChannelEvent.
4289
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4290
        remotePub *btcec.PublicKey) error {
3✔
4291

3✔
4292
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4293
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4294
                return err
3✔
4295
        }
3✔
4296

4297
        // Notify subscribers about this open channel event.
4298
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4299

3✔
4300
        return nil
3✔
4301
}
4302

4303
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4304
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4305
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4306
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
3✔
4307

3✔
4308
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4309
        // peer.
3✔
4310
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4311
                return err
×
4312
        }
×
4313

4314
        // Notify subscribers about this event.
4315
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4316

3✔
4317
        return nil
3✔
4318
}
4319

4320
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4321
// calls the channelNotifier's NotifyFundingTimeout.
4322
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4323
        remotePub *btcec.PublicKey) error {
3✔
4324

3✔
4325
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4326
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4327
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4328
                // If we encounter an error while attempting to disconnect the
×
4329
                // peer, log the error.
×
4330
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4331
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4332
                }
×
4333
        }
4334

4335
        // Notify subscribers about this event.
4336
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4337

3✔
4338
        return nil
3✔
4339
}
4340

4341
// peerConnected is a function that handles initialization a newly connected
4342
// peer by adding it to the server's global list of all active peers, and
4343
// starting all the goroutines the peer needs to function properly. The inbound
4344
// boolean should be true if the peer initiated the connection to us.
4345
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4346
        inbound bool, access peerAccessStatus) {
3✔
4347

3✔
4348
        brontideConn := conn.(*brontide.Conn)
3✔
4349
        addr := conn.RemoteAddr()
3✔
4350
        pubKey := brontideConn.RemotePub()
3✔
4351

3✔
4352
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4353
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4354

3✔
4355
        peerAddr := &lnwire.NetAddress{
3✔
4356
                IdentityKey: pubKey,
3✔
4357
                Address:     addr,
3✔
4358
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4359
        }
3✔
4360

3✔
4361
        // With the brontide connection established, we'll now craft the feature
3✔
4362
        // vectors to advertise to the remote node.
3✔
4363
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4364
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4365

3✔
4366
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4367
        // found, create a fresh buffer.
3✔
4368
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4369
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4370
        if !ok {
6✔
4371
                var err error
3✔
4372
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4373
                if err != nil {
3✔
4374
                        srvrLog.Errorf("unable to create peer %v", err)
×
4375
                        return
×
4376
                }
×
4377
        }
4378

4379
        // If we directly set the peer.Config TowerClient member to the
4380
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4381
        // the peer.Config's TowerClient member will not evaluate to nil even
4382
        // though the underlying value is nil. To avoid this gotcha which can
4383
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4384
        // TowerClient if needed.
4385
        var towerClient wtclient.ClientManager
3✔
4386
        if s.towerClientMgr != nil {
6✔
4387
                towerClient = s.towerClientMgr
3✔
4388
        }
3✔
4389

4390
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4391
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4392

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

3✔
4436
                        return s.genNodeAnnouncement(nil)
3✔
4437
                },
3✔
4438

4439
                PongBuf: s.pongBuf,
4440

4441
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4442

4443
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4444

4445
                FundingManager: s.fundingMgr,
4446

4447
                Hodl:                    s.cfg.Hodl,
4448
                UnsafeReplay:            s.cfg.UnsafeReplay,
4449
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4450
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4451
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4452
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4453
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4454
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4455
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4456
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4457
                HandleCustomMessage:    s.handleCustomMessage,
4458
                GetAliases:             s.aliasMgr.GetAliases,
4459
                RequestAlias:           s.aliasMgr.RequestAlias,
4460
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4461
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4462
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4463
                MaxFeeExposure:         thresholdMSats,
4464
                Quit:                   s.quit,
4465
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4466
                AuxSigner:              s.implCfg.AuxSigner,
4467
                MsgRouter:              s.implCfg.MsgRouter,
4468
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4469
                AuxResolver:            s.implCfg.AuxContractResolver,
4470
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4471
                ShouldFwdExpEndorsement: func() bool {
3✔
4472
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4473
                                return false
3✔
4474
                        }
3✔
4475

4476
                        return clock.NewDefaultClock().Now().Before(
3✔
4477
                                EndorsementExperimentEnd,
3✔
4478
                        )
3✔
4479
                },
4480
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4481
        }
4482

4483
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4484
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4485

3✔
4486
        p := peer.NewBrontide(pCfg)
3✔
4487

3✔
4488
        // Update the access manager with the access permission for this peer.
3✔
4489
        s.peerAccessMan.addPeerAccess(pubKey, access)
3✔
4490

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

3✔
4494
        s.addPeer(p)
3✔
4495

3✔
4496
        // Once we have successfully added the peer to the server, we can
3✔
4497
        // delete the previous error buffer from the server's map of error
3✔
4498
        // buffers.
3✔
4499
        delete(s.peerErrors, pkStr)
3✔
4500

3✔
4501
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4502
        // includes sending and receiving Init messages, which would be a DOS
3✔
4503
        // vector if we held the server's mutex throughout the procedure.
3✔
4504
        s.wg.Add(1)
3✔
4505
        go s.peerInitializer(p)
3✔
4506
}
4507

4508
// addPeer adds the passed peer to the server's global state of all active
4509
// peers.
4510
func (s *server) addPeer(p *peer.Brontide) {
3✔
4511
        if p == nil {
3✔
4512
                return
×
4513
        }
×
4514

4515
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4516

3✔
4517
        // Ignore new peers if we're shutting down.
3✔
4518
        if s.Stopped() {
3✔
4519
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4520
                        pubBytes)
×
4521
                p.Disconnect(ErrServerShuttingDown)
×
4522

×
4523
                return
×
4524
        }
×
4525

4526
        // Track the new peer in our indexes so we can quickly look it up either
4527
        // according to its public key, or its peer ID.
4528
        // TODO(roasbeef): pipe all requests through to the
4529
        // queryHandler/peerManager
4530

4531
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4532
        // be human-readable.
4533
        pubStr := string(pubBytes)
3✔
4534

3✔
4535
        s.peersByPub[pubStr] = p
3✔
4536

3✔
4537
        if p.Inbound() {
6✔
4538
                s.inboundPeers[pubStr] = p
3✔
4539
        } else {
6✔
4540
                s.outboundPeers[pubStr] = p
3✔
4541
        }
3✔
4542

4543
        // Inform the peer notifier of a peer online event so that it can be reported
4544
        // to clients listening for peer events.
4545
        var pubKey [33]byte
3✔
4546
        copy(pubKey[:], pubBytes)
3✔
4547

3✔
4548
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4549
}
4550

4551
// peerInitializer asynchronously starts a newly connected peer after it has
4552
// been added to the server's peer map. This method sets up a
4553
// peerTerminationWatcher for the given peer, and ensures that it executes even
4554
// if the peer failed to start. In the event of a successful connection, this
4555
// method reads the negotiated, local feature-bits and spawns the appropriate
4556
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4557
// be signaled of the new peer once the method returns.
4558
//
4559
// NOTE: This MUST be launched as a goroutine.
4560
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4561
        defer s.wg.Done()
3✔
4562

3✔
4563
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4564

3✔
4565
        // Avoid initializing peers while the server is exiting.
3✔
4566
        if s.Stopped() {
3✔
4567
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4568
                        pubBytes)
×
4569
                return
×
4570
        }
×
4571

4572
        // Create a channel that will be used to signal a successful start of
4573
        // the link. This prevents the peer termination watcher from beginning
4574
        // its duty too early.
4575
        ready := make(chan struct{})
3✔
4576

3✔
4577
        // Before starting the peer, launch a goroutine to watch for the
3✔
4578
        // unexpected termination of this peer, which will ensure all resources
3✔
4579
        // are properly cleaned up, and re-establish persistent connections when
3✔
4580
        // necessary. The peer termination watcher will be short circuited if
3✔
4581
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4582
        // that the server has already handled the removal of this peer.
3✔
4583
        s.wg.Add(1)
3✔
4584
        go s.peerTerminationWatcher(p, ready)
3✔
4585

3✔
4586
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4587
        // will unblock the peerTerminationWatcher.
3✔
4588
        if err := p.Start(); err != nil {
6✔
4589
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4590

3✔
4591
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4592
                return
3✔
4593
        }
3✔
4594

4595
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4596
        // was successful, and to begin watching the peer's wait group.
4597
        close(ready)
3✔
4598

3✔
4599
        s.mu.Lock()
3✔
4600
        defer s.mu.Unlock()
3✔
4601

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

3✔
4605
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4606
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4607
        pubStr := string(pubBytes)
3✔
4608
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4609
                select {
3✔
4610
                case peerChan <- p:
3✔
4611
                case <-s.quit:
×
4612
                        return
×
4613
                }
4614
        }
4615
        delete(s.peerConnectedListeners, pubStr)
3✔
4616
}
4617

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

3✔
4632
        p.WaitForDisconnect(ready)
3✔
4633

3✔
4634
        srvrLog.Debugf("Peer %v has been disconnected", p)
3✔
4635

3✔
4636
        // If the server is exiting then we can bail out early ourselves as all
3✔
4637
        // the other sub-systems will already be shutting down.
3✔
4638
        if s.Stopped() {
6✔
4639
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4640
                return
3✔
4641
        }
3✔
4642

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

3✔
4649
        pubKey := p.IdentityKey()
3✔
4650

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

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

4665
        for _, link := range links {
6✔
4666
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4667
        }
3✔
4668

4669
        s.mu.Lock()
3✔
4670
        defer s.mu.Unlock()
3✔
4671

3✔
4672
        // If there were any notification requests for when this peer
3✔
4673
        // disconnected, we can trigger them now.
3✔
4674
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4675
        pubStr := string(pubKey.SerializeCompressed())
3✔
4676
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4677
                close(offlineChan)
3✔
4678
        }
3✔
4679
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4680

3✔
4681
        // If the server has already removed this peer, we can short circuit the
3✔
4682
        // peer termination watcher and skip cleanup.
3✔
4683
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4684
                delete(s.ignorePeerTermination, p)
×
4685

×
4686
                pubKey := p.PubKey()
×
4687
                pubStr := string(pubKey[:])
×
4688

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

4702
        // First, cleanup any remaining state the server has regarding the peer
4703
        // in question.
4704
        s.removePeer(p)
3✔
4705

3✔
4706
        // Next, check to see if this is a persistent peer or not.
3✔
4707
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4708
                return
3✔
4709
        }
3✔
4710

4711
        // Get the last address that we used to connect to the peer.
4712
        addrs := []net.Addr{
3✔
4713
                p.NetAddress().Address,
3✔
4714
        }
3✔
4715

3✔
4716
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4717
        // reconnection purposes.
3✔
4718
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4719
        switch {
3✔
4720
        // We found advertised addresses, so use them.
4721
        case err == nil:
3✔
4722
                addrs = advertisedAddrs
3✔
4723

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

4732
                // Fall back to the existing peer address if
4733
                // we're not accepting connections over Tor.
4734
                if s.torController == nil {
6✔
4735
                        break
3✔
4736
                }
4737

4738
                // If we are, the peer's address won't be known
4739
                // to us (we'll see a private address, which is
4740
                // the address used by our onion service to dial
4741
                // to lnd), so we don't have enough information
4742
                // to attempt a reconnect.
4743
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4744
                        "to inbound peer %v without "+
×
4745
                        "advertised address", p)
×
4746
                return
×
4747

4748
        // We came across an error retrieving an advertised
4749
        // address, log it, and fall back to the existing peer
4750
        // address.
4751
        default:
3✔
4752
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4753
                        "address for node %x: %v", p.PubKey(),
3✔
4754
                        err)
3✔
4755
        }
4756

4757
        // Make an easy lookup map so that we can check if an address
4758
        // is already in the address list that we have stored for this peer.
4759
        existingAddrs := make(map[string]bool)
3✔
4760
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4761
                existingAddrs[addr.String()] = true
3✔
4762
        }
3✔
4763

4764
        // Add any missing addresses for this peer to persistentPeerAddr.
4765
        for _, addr := range addrs {
6✔
4766
                if existingAddrs[addr.String()] {
3✔
4767
                        continue
×
4768
                }
4769

4770
                s.persistentPeerAddrs[pubStr] = append(
3✔
4771
                        s.persistentPeerAddrs[pubStr],
3✔
4772
                        &lnwire.NetAddress{
3✔
4773
                                IdentityKey: p.IdentityKey(),
3✔
4774
                                Address:     addr,
3✔
4775
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4776
                        },
3✔
4777
                )
3✔
4778
        }
4779

4780
        // Record the computed backoff in the backoff map.
4781
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4782
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4783

3✔
4784
        // Initialize a retry canceller for this peer if one does not
3✔
4785
        // exist.
3✔
4786
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4787
        if !ok {
6✔
4788
                cancelChan = make(chan struct{})
3✔
4789
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4790
        }
3✔
4791

4792
        // We choose not to wait group this go routine since the Connect
4793
        // call can stall for arbitrarily long if we shutdown while an
4794
        // outbound connection attempt is being made.
4795
        go func() {
6✔
4796
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4797
                        "persistent peer %x in %s",
3✔
4798
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4799

3✔
4800
                select {
3✔
4801
                case <-time.After(backoff):
3✔
4802
                case <-cancelChan:
3✔
4803
                        return
3✔
4804
                case <-s.quit:
3✔
4805
                        return
3✔
4806
                }
4807

4808
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4809
                        "connection to peer %x",
3✔
4810
                        p.IdentityKey().SerializeCompressed())
3✔
4811

3✔
4812
                s.connectToPersistentPeer(pubStr)
3✔
4813
        }()
4814
}
4815

4816
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4817
// to connect to the peer. It creates connection requests if there are
4818
// currently none for a given address and it removes old connection requests
4819
// if the associated address is no longer in the latest address list for the
4820
// peer.
4821
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4822
        s.mu.Lock()
3✔
4823
        defer s.mu.Unlock()
3✔
4824

3✔
4825
        // Create an easy lookup map of the addresses we have stored for the
3✔
4826
        // peer. We will remove entries from this map if we have existing
3✔
4827
        // connection requests for the associated address and then any leftover
3✔
4828
        // entries will indicate which addresses we should create new
3✔
4829
        // connection requests for.
3✔
4830
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4831
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4832
                addrMap[addr.String()] = addr
3✔
4833
        }
3✔
4834

4835
        // Go through each of the existing connection requests and
4836
        // check if they correspond to the latest set of addresses. If
4837
        // there is a connection requests that does not use one of the latest
4838
        // advertised addresses then remove that connection request.
4839
        var updatedConnReqs []*connmgr.ConnReq
3✔
4840
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4841
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4842

3✔
4843
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4844
                // If the existing connection request is using one of the
4845
                // latest advertised addresses for the peer then we add it to
4846
                // updatedConnReqs and remove the associated address from
4847
                // addrMap so that we don't recreate this connReq later on.
4848
                case true:
×
4849
                        updatedConnReqs = append(
×
4850
                                updatedConnReqs, connReq,
×
4851
                        )
×
4852
                        delete(addrMap, lnAddr)
×
4853

4854
                // If the existing connection request is using an address that
4855
                // is not one of the latest advertised addresses for the peer
4856
                // then we remove the connecting request from the connection
4857
                // manager.
4858
                case false:
3✔
4859
                        srvrLog.Info(
3✔
4860
                                "Removing conn req:", connReq.Addr.String(),
3✔
4861
                        )
3✔
4862
                        s.connMgr.Remove(connReq.ID())
3✔
4863
                }
4864
        }
4865

4866
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4867

3✔
4868
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4869
        if !ok {
6✔
4870
                cancelChan = make(chan struct{})
3✔
4871
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4872
        }
3✔
4873

4874
        // Any addresses left in addrMap are new ones that we have not made
4875
        // connection requests for. So create new connection requests for those.
4876
        // If there is more than one address in the address map, stagger the
4877
        // creation of the connection requests for those.
4878
        go func() {
6✔
4879
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4880
                defer ticker.Stop()
3✔
4881

3✔
4882
                for _, addr := range addrMap {
6✔
4883
                        // Send the persistent connection request to the
3✔
4884
                        // connection manager, saving the request itself so we
3✔
4885
                        // can cancel/restart the process as needed.
3✔
4886
                        connReq := &connmgr.ConnReq{
3✔
4887
                                Addr:      addr,
3✔
4888
                                Permanent: true,
3✔
4889
                        }
3✔
4890

3✔
4891
                        s.mu.Lock()
3✔
4892
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4893
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4894
                        )
3✔
4895
                        s.mu.Unlock()
3✔
4896

3✔
4897
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4898
                                "channel peer %v", addr)
3✔
4899

3✔
4900
                        go s.connMgr.Connect(connReq)
3✔
4901

3✔
4902
                        select {
3✔
4903
                        case <-s.quit:
3✔
4904
                                return
3✔
4905
                        case <-cancelChan:
3✔
4906
                                return
3✔
4907
                        case <-ticker.C:
3✔
4908
                        }
4909
                }
4910
        }()
4911
}
4912

4913
// removePeer removes the passed peer from the server's state of all active
4914
// peers.
4915
func (s *server) removePeer(p *peer.Brontide) {
3✔
4916
        if p == nil {
3✔
4917
                return
×
4918
        }
×
4919

4920
        srvrLog.Debugf("removing peer %v", p)
3✔
4921

3✔
4922
        // As the peer is now finished, ensure that the TCP connection is
3✔
4923
        // closed and all of its related goroutines have exited.
3✔
4924
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
3✔
4925

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

4931
        // Ignore deleting peers if we're shutting down.
4932
        if s.Stopped() {
3✔
4933
                return
×
4934
        }
×
4935

4936
        pKey := p.PubKey()
3✔
4937
        pubSer := pKey[:]
3✔
4938
        pubStr := string(pubSer)
3✔
4939

3✔
4940
        delete(s.peersByPub, pubStr)
3✔
4941

3✔
4942
        if p.Inbound() {
6✔
4943
                delete(s.inboundPeers, pubStr)
3✔
4944
        } else {
6✔
4945
                delete(s.outboundPeers, pubStr)
3✔
4946
        }
3✔
4947

4948
        // Remove the peer's access permission from the access manager.
4949
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
3✔
4950

3✔
4951
        // Copy the peer's error buffer across to the server if it has any items
3✔
4952
        // in it so that we can restore peer errors across connections.
3✔
4953
        if p.ErrorBuffer().Total() > 0 {
6✔
4954
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4955
        }
3✔
4956

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

3✔
4962
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4963
}
4964

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

3✔
4973
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4974

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

3✔
4981
        // Ensure we're not already connected to this peer.
3✔
4982
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4983
        if err == nil {
6✔
4984
                s.mu.Unlock()
3✔
4985
                return &errPeerAlreadyConnected{peer: peer}
3✔
4986
        }
3✔
4987

4988
        // Peer was not found, continue to pursue connection with peer.
4989

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

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

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

3✔
5021
                go s.connMgr.Connect(connReq)
3✔
5022

3✔
5023
                return nil
3✔
5024
        }
5025
        s.mu.Unlock()
3✔
5026

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

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

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

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

5060
        close(errChan)
3✔
5061

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

3✔
5065
        s.OutboundPeerConnected(nil, conn)
3✔
5066
}
5067

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

3✔
5076
        s.mu.Lock()
3✔
5077
        defer s.mu.Unlock()
3✔
5078

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

5087
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5088

3✔
5089
        s.cancelConnReqs(pubStr, nil)
3✔
5090

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

3✔
5097
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5098
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
5099
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5100

3✔
5101
        return nil
3✔
5102
}
5103

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

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

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

×
5125
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5126
                return req.Updates, req.Err
×
5127
        }
×
5128
        req.Peer = peer
3✔
5129
        s.mu.RUnlock()
3✔
5130

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

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

×
5151
                return req.Updates, req.Err
×
5152
        }
×
5153

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

3✔
5160
        return req.Updates, req.Err
3✔
5161
}
5162

5163
// Peers returns a slice of all active peers.
5164
//
5165
// NOTE: This function is safe for concurrent access.
5166
func (s *server) Peers() []*peer.Brontide {
3✔
5167
        s.mu.RLock()
3✔
5168
        defer s.mu.RUnlock()
3✔
5169

3✔
5170
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5171
        for _, peer := range s.peersByPub {
6✔
5172
                peers = append(peers, peer)
3✔
5173
        }
3✔
5174

5175
        return peers
3✔
5176
}
5177

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

5189
        // Using 1/10 of our duration as a margin, compute a random offset to
5190
        // avoid the nodes entering connection cycles.
5191
        margin := nextBackoff / 10
3✔
5192

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

5201
        // Otherwise add in our wiggle, but subtract out half of the margin so
5202
        // that the backoff can tweaked by 1/20 in either direction.
5203
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5204
}
5205

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

5210
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5211
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5212
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5213
        if err != nil {
3✔
5214
                return nil, err
×
5215
        }
×
5216

5217
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5218
        if err != nil {
6✔
5219
                return nil, err
3✔
5220
        }
3✔
5221

5222
        if len(node.Addresses) == 0 {
6✔
5223
                return nil, errNoAdvertisedAddr
3✔
5224
        }
3✔
5225

5226
        return node.Addresses, nil
3✔
5227
}
5228

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

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

5241
                return netann.ExtractChannelUpdate(
3✔
5242
                        ourPubKey[:], info, edge1, edge2,
3✔
5243
                )
3✔
5244
        }
5245
}
5246

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

3✔
5253
        var (
3✔
5254
                peerAlias    *lnwire.ShortChannelID
3✔
5255
                defaultAlias lnwire.ShortChannelID
3✔
5256
        )
3✔
5257

3✔
5258
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5259

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

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

5280
// SendCustomMessage sends a custom message to the peer with the specified
5281
// pubkey.
5282
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5283
        data []byte) error {
3✔
5284

3✔
5285
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5286
        if err != nil {
3✔
5287
                return err
×
5288
        }
×
5289

5290
        // We'll wait until the peer is active.
5291
        select {
3✔
5292
        case <-peer.ActiveSignal():
3✔
5293
        case <-peer.QuitSignal():
×
5294
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5295
        case <-s.quit:
×
5296
                return ErrServerShuttingDown
×
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
// newSweepPkScriptGen creates closure that generates a new public key script
5310
// which should be used to sweep any funds into the on-chain wallet.
5311
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5312
// (p2wkh) output.
5313
func newSweepPkScriptGen(
5314
        wallet lnwallet.WalletController,
5315
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5316

3✔
5317
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5318
                sweepAddr, err := wallet.NewAddress(
3✔
5319
                        lnwallet.TaprootPubkey, false,
3✔
5320
                        lnwallet.DefaultAccountName,
3✔
5321
                )
3✔
5322
                if err != nil {
3✔
5323
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5324
                }
×
5325

5326
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5327
                if err != nil {
3✔
5328
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5329
                }
×
5330

5331
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5332
                        wallet, netParams, addr,
3✔
5333
                )
3✔
5334
                if err != nil {
3✔
5335
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5336
                }
×
5337

5338
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5339
                        DeliveryAddress: addr,
3✔
5340
                        InternalKey:     internalKeyDesc,
3✔
5341
                })
3✔
5342
        }
5343
}
5344

5345
// shouldPeerBootstrap returns true if we should attempt to perform peer
5346
// bootstrapping to actively seek our peers using the set of active network
5347
// bootstrappers.
5348
func shouldPeerBootstrap(cfg *Config) bool {
3✔
5349
        isSimnet := cfg.Bitcoin.SimNet
3✔
5350
        isSignet := cfg.Bitcoin.SigNet
3✔
5351
        isRegtest := cfg.Bitcoin.RegTest
3✔
5352
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
5353

3✔
5354
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
5355
        // covering the bootstrapping process.
3✔
5356
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
5357
}
3✔
5358

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

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

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

5392
        for _, c := range pendings {
6✔
5393
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5394
                        continue
3✔
5395
                }
5396

5397
                // If the channel is still reported as pending, remove it from
5398
                // the map.
5399
                delete(closedSCIDs, c.ShortChannelID)
×
5400

×
5401
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5402
                        c.ShortChannelID)
×
5403
        }
5404

5405
        return closedSCIDs
3✔
5406
}
5407

5408
// getStartingBeat returns the current beat. This is used during the startup to
5409
// initialize blockbeat consumers.
5410
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5411
        // beat is the current blockbeat.
3✔
5412
        var beat *chainio.Beat
3✔
5413

3✔
5414
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5415
        // we will skip fetching the best block.
3✔
5416
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5417
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5418
                        "mode")
×
5419

×
5420
                return &chainio.Beat{}, nil
×
5421
        }
×
5422

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

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

3✔
5439
                // Update the current blockbeat.
3✔
5440
                beat = chainio.NewBeat(*bestBlock)
3✔
5441

5442
        case <-s.quit:
×
5443
                srvrLog.Debug("LND shutting down")
×
5444
        }
5445

5446
        return beat, nil
3✔
5447
}
5448

5449
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5450
// point has an active RBF chan closer.
5451
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5452
        chanPoint wire.OutPoint) bool {
3✔
5453

3✔
5454
        pubBytes := peerPub.SerializeCompressed()
3✔
5455

3✔
5456
        s.mu.RLock()
3✔
5457
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5458
        s.mu.RUnlock()
3✔
5459
        if !ok {
3✔
5460
                return false
×
5461
        }
×
5462

5463
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5464
}
5465

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

3✔
5474
        // First, we'll attempt to look up the channel based on it's
3✔
5475
        // ChannelPoint.
3✔
5476
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5477
        if err != nil {
3✔
5478
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5479
        }
×
5480

5481
        // From the channel, we can now get the pubkey of the peer, then use
5482
        // that to eventually get the chan closer.
5483
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5484

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

5494
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5495
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5496
        )
3✔
5497
        if err != nil {
3✔
5498
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5499
                        "%w", err)
×
5500
        }
×
5501

5502
        return closeUpdates, nil
3✔
5503
}
5504

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

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

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

5531
        return updates, nil
3✔
5532
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc