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

lightningnetwork / lnd / 15956321235

29 Jun 2025 02:40PM UTC coverage: 57.8% (-9.8%) from 67.606%
15956321235

Pull #10003

github

web-flow
Merge 096fc03f1 into 6290edf14
Pull Request #10003: discovery: deterministic bootstrapping for local test networks

34 of 56 new or added lines in 4 files covered. (60.71%)

28395 existing lines in 456 files now uncovered.

98456 of 170339 relevant lines covered (57.8%)

1.79 hits per line

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

69.39
/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
// String returns a human-readable representation of the status code.
197
func (p peerAccessStatus) String() string {
3✔
198
        switch p {
3✔
199
        case peerStatusRestricted:
3✔
200
                return "restricted"
3✔
201

202
        case peerStatusTemporary:
3✔
203
                return "temporary"
3✔
204

205
        case peerStatusProtected:
3✔
206
                return "protected"
3✔
207

208
        default:
×
209
                return "unknown"
×
210
        }
211
}
212

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

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

228
        start sync.Once
229
        stop  sync.Once
230

231
        cfg *Config
232

233
        implCfg *ImplementationCfg
234

235
        // identityECDH is an ECDH capable wrapper for the private key used
236
        // to authenticate any incoming connections.
237
        identityECDH keychain.SingleKeyECDH
238

239
        // identityKeyLoc is the key locator for the above wrapped identity key.
240
        identityKeyLoc keychain.KeyLocator
241

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

246
        chanStatusMgr *netann.ChanStatusManager
247

248
        // listenAddrs is the list of addresses the server is currently
249
        // listening on.
250
        listenAddrs []net.Addr
251

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

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

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

268
        mu sync.RWMutex
269

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

279
        inboundPeers  map[string]*peer.Brontide
280
        outboundPeers map[string]*peer.Brontide
281

282
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
283
        peerDisconnectedListeners map[string][]chan<- struct{}
284

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

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

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

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

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

320
        cc *chainreg.ChainControl
321

322
        fundingMgr *funding.Manager
323

324
        graphDB *graphdb.ChannelGraph
325

326
        chanStateDB *channeldb.ChannelStateDB
327

328
        addrSource channeldb.AddrSource
329

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

334
        invoicesDB invoices.InvoiceDB
335

336
        aliasMgr *aliasmgr.Manager
337

338
        htlcSwitch *htlcswitch.Switch
339

340
        interceptableSwitch *htlcswitch.InterceptableSwitch
341

342
        invoices *invoices.InvoiceRegistry
343

344
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
345

346
        channelNotifier *channelnotifier.ChannelNotifier
347

348
        peerNotifier *peernotifier.PeerNotifier
349

350
        htlcNotifier *htlcswitch.HtlcNotifier
351

352
        witnessBeacon contractcourt.WitnessBeacon
353

354
        breachArbitrator *contractcourt.BreachArbitrator
355

356
        missionController *routing.MissionController
357
        defaultMC         *routing.MissionControl
358

359
        graphBuilder *graph.Builder
360

361
        chanRouter *routing.ChannelRouter
362

363
        controlTower routing.ControlTower
364

365
        authGossiper *discovery.AuthenticatedGossiper
366

367
        localChanMgr *localchans.Manager
368

369
        utxoNursery *contractcourt.UtxoNursery
370

371
        sweeper *sweep.UtxoSweeper
372

373
        chainArb *contractcourt.ChainArbitrator
374

375
        sphinx *hop.OnionProcessor
376

377
        towerClientMgr *wtclient.Manager
378

379
        connMgr *connmgr.ConnManager
380

381
        sigPool *lnwallet.SigPool
382

383
        writePool *pool.Write
384

385
        readPool *pool.Read
386

387
        tlsManager *TLSManager
388

389
        // featureMgr dispatches feature vectors for various contexts within the
390
        // daemon.
391
        featureMgr *feature.Manager
392

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

398
        // chansToRestore is the set of channels that upon starting, the server
399
        // should attempt to restore/recover.
400
        chansToRestore walletunlocker.ChannelsToRecover
401

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

407
        // chanEventStore tracks the behaviour of channels and their remote peers to
408
        // provide insights into their health and performance.
409
        chanEventStore *chanfitness.ChannelEventStore
410

411
        hostAnn *netann.HostAnnouncer
412

413
        // livenessMonitor monitors that lnd has access to critical resources.
414
        livenessMonitor *healthcheck.Monitor
415

416
        customMessageServer *subscribe.Server
417

418
        // txPublisher is a publisher with fee-bumping capability.
419
        txPublisher *sweep.TxPublisher
420

421
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
422
        // of new blocks.
423
        blockbeatDispatcher *chainio.BlockbeatDispatcher
424

425
        // peerAccessMan implements peer access controls.
426
        peerAccessMan *accessMan
427

428
        quit chan struct{}
429

430
        wg sync.WaitGroup
431
}
432

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

441
        s.wg.Add(1)
3✔
442
        go func() {
6✔
443
                defer func() {
6✔
444
                        graphSub.Cancel()
3✔
445
                        s.wg.Done()
3✔
446
                }()
3✔
447

448
                for {
6✔
449
                        select {
3✔
450
                        case <-s.quit:
3✔
451
                                return
3✔
452

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

460
                                for _, update := range topChange.NodeUpdates {
6✔
461
                                        pubKeyStr := string(
3✔
462
                                                update.IdentityKey.
3✔
463
                                                        SerializeCompressed(),
3✔
464
                                        )
3✔
465

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

475
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
476
                                                len(update.Addresses))
3✔
477

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

488
                                        s.mu.Lock()
3✔
489

3✔
490
                                        // Update the stored addresses for this
3✔
491
                                        // to peer to reflect the new set.
3✔
492
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
493

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

504
                                        s.mu.Unlock()
3✔
505

3✔
506
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
507
                                }
508
                        }
509
                }
510
        }()
511

512
        return nil
3✔
513
}
514

515
// CustomMessage is a custom message that is received from a peer.
516
type CustomMessage struct {
517
        // Peer is the peer pubkey
518
        Peer [33]byte
519

520
        // Msg is the custom wire message.
521
        Msg *lnwire.Custom
522
}
523

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

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

548
        if tor.IsOnionHost(host) {
3✔
549
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
550
        }
×
551

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

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

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

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

3✔
584
        var (
3✔
585
                err         error
3✔
586
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
587

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

3✔
595
        var serializedPubKey [33]byte
3✔
596
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
597

3✔
598
        netParams := cfg.ActiveNetParams.Params
3✔
599

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

3✔
606
        writeBufferPool := pool.NewWriteBuffer(
3✔
607
                pool.DefaultWriteBufferGCInterval,
3✔
608
                pool.DefaultWriteBufferExpiryInterval,
3✔
609
        )
3✔
610

3✔
611
        writePool := pool.NewWrite(
3✔
612
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
613
        )
3✔
614

3✔
615
        readBufferPool := pool.NewReadBuffer(
3✔
616
                pool.DefaultReadBufferGCInterval,
3✔
617
                pool.DefaultReadBufferExpiryInterval,
3✔
618
        )
3✔
619

3✔
620
        readPool := pool.NewRead(
3✔
621
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
622
        )
3✔
623

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

×
629
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
630
                        "aux controllers")
×
631
        }
×
632

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

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

3✔
669
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
670

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

3✔
685
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
686
                        cc.ChainNotifier,
3✔
687
                ),
3✔
688
                channelNotifier: channelnotifier.New(
3✔
689
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
690
                ),
3✔
691

3✔
692
                identityECDH:   nodeKeyECDH,
3✔
693
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
694
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
695

3✔
696
                listenAddrs: listenAddrs,
3✔
697

3✔
698
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
699
                // schedule
3✔
700
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
701

3✔
702
                torController: torController,
3✔
703

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

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

3✔
720
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
721

3✔
722
                customMessageServer: subscribe.NewServer(),
3✔
723

3✔
724
                tlsManager: tlsManager,
3✔
725

3✔
726
                featureMgr: featureMgr,
3✔
727
                quit:       make(chan struct{}),
3✔
728
        }
3✔
729

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

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

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

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

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

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

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

3✔
767
                return nil
3✔
768
        }
769

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
903
                        listenPorts = append(listenPorts, uint16(port))
×
904
                }
×
905

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

919
        // If external IP addresses have been specified, add those to the list
920
        // of this server's addresses.
921
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
922
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
923
                cfg.net.ResolveTCPAddr,
3✔
924
        )
3✔
925
        if err != nil {
3✔
926
                return nil, err
×
927
        }
×
928

929
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
930
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
931

3✔
932
        // We'll now reconstruct a node announcement based on our current
3✔
933
        // configuration so we can send it out as a sort of heart beat within
3✔
934
        // the network.
3✔
935
        //
3✔
936
        // We'll start by parsing the node color from configuration.
3✔
937
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
938
        if err != nil {
3✔
939
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
940
                return nil, err
×
941
        }
×
942

943
        // If no alias is provided, default to first 10 characters of public
944
        // key.
945
        alias := cfg.Alias
3✔
946
        if alias == "" {
6✔
947
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
948
        }
3✔
949
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
950
        if err != nil {
3✔
951
                return nil, err
×
952
        }
×
953
        selfNode := &models.LightningNode{
3✔
954
                HaveNodeAnnouncement: true,
3✔
955
                LastUpdate:           time.Now(),
3✔
956
                Addresses:            selfAddrs,
3✔
957
                Alias:                nodeAlias.String(),
3✔
958
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
959
                Color:                color,
3✔
960
        }
3✔
961
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
962

3✔
963
        // Based on the disk representation of the node announcement generated
3✔
964
        // above, we'll generate a node announcement that can go out on the
3✔
965
        // network so we can properly sign it.
3✔
966
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
967
        if err != nil {
3✔
968
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
969
        }
×
970

971
        // With the announcement generated, we'll sign it to properly
972
        // authenticate the message on the network.
973
        authSig, err := netann.SignAnnouncement(
3✔
974
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
975
        )
3✔
976
        if err != nil {
3✔
977
                return nil, fmt.Errorf("unable to generate signature for "+
×
978
                        "self node announcement: %v", err)
×
979
        }
×
980
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
981
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
982
                selfNode.AuthSigBytes,
3✔
983
        )
3✔
984
        if err != nil {
3✔
985
                return nil, err
×
986
        }
×
987

988
        // Finally, we'll update the representation on disk, and update our
989
        // cached in-memory version as well.
990
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
991
                return nil, fmt.Errorf("can't set self node: %w", err)
×
992
        }
×
993
        s.currentNodeAnn = nodeAnn
3✔
994

3✔
995
        // The router will get access to the payment ID sequencer, such that it
3✔
996
        // can generate unique payment IDs.
3✔
997
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
998
        if err != nil {
3✔
999
                return nil, err
×
1000
        }
×
1001

1002
        // Instantiate mission control with config from the sub server.
1003
        //
1004
        // TODO(joostjager): When we are further in the process of moving to sub
1005
        // servers, the mission control instance itself can be moved there too.
1006
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1007

3✔
1008
        // We only initialize a probability estimator if there's no custom one.
3✔
1009
        var estimator routing.Estimator
3✔
1010
        if cfg.Estimator != nil {
3✔
1011
                estimator = cfg.Estimator
×
1012
        } else {
3✔
1013
                switch routingConfig.ProbabilityEstimatorType {
3✔
1014
                case routing.AprioriEstimatorName:
3✔
1015
                        aCfg := routingConfig.AprioriConfig
3✔
1016
                        aprioriConfig := routing.AprioriConfig{
3✔
1017
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1018
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1019
                                AprioriWeight:         aCfg.Weight,
3✔
1020
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1021
                        }
3✔
1022

3✔
1023
                        estimator, err = routing.NewAprioriEstimator(
3✔
1024
                                aprioriConfig,
3✔
1025
                        )
3✔
1026
                        if err != nil {
3✔
1027
                                return nil, err
×
1028
                        }
×
1029

1030
                case routing.BimodalEstimatorName:
×
1031
                        bCfg := routingConfig.BimodalConfig
×
1032
                        bimodalConfig := routing.BimodalConfig{
×
1033
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1034
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1035
                                        bCfg.Scale,
×
1036
                                ),
×
1037
                                BimodalDecayTime: bCfg.DecayTime,
×
1038
                        }
×
1039

×
1040
                        estimator, err = routing.NewBimodalEstimator(
×
1041
                                bimodalConfig,
×
1042
                        )
×
1043
                        if err != nil {
×
1044
                                return nil, err
×
1045
                        }
×
1046

1047
                default:
×
1048
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1049
                                routingConfig.ProbabilityEstimatorType)
×
1050
                }
1051
        }
1052

1053
        mcCfg := &routing.MissionControlConfig{
3✔
1054
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1055
                Estimator:               estimator,
3✔
1056
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1057
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1058
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1059
        }
3✔
1060

3✔
1061
        s.missionController, err = routing.NewMissionController(
3✔
1062
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1063
        )
3✔
1064
        if err != nil {
3✔
1065
                return nil, fmt.Errorf("can't create mission control "+
×
1066
                        "manager: %w", err)
×
1067
        }
×
1068
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1069
                routing.DefaultMissionControlNamespace,
3✔
1070
        )
3✔
1071
        if err != nil {
3✔
1072
                return nil, fmt.Errorf("can't create mission control in the "+
×
1073
                        "default namespace: %w", err)
×
1074
        }
×
1075

1076
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1077
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1078
                int64(routingConfig.AttemptCost),
3✔
1079
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1080
                routingConfig.MinRouteProbability)
3✔
1081

3✔
1082
        pathFindingConfig := routing.PathFindingConfig{
3✔
1083
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1084
                        routingConfig.AttemptCost,
3✔
1085
                ),
3✔
1086
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1087
                MinProbability: routingConfig.MinRouteProbability,
3✔
1088
        }
3✔
1089

3✔
1090
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1091
        if err != nil {
3✔
1092
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1093
        }
×
1094
        paymentSessionSource := &routing.SessionSource{
3✔
1095
                GraphSessionFactory: dbs.GraphDB,
3✔
1096
                SourceNode:          sourceNode,
3✔
1097
                MissionControl:      s.defaultMC,
3✔
1098
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1099
                PathFindingConfig:   pathFindingConfig,
3✔
1100
        }
3✔
1101

3✔
1102
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1103

3✔
1104
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1105

3✔
1106
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1107
                cfg.Routing.StrictZombiePruning
3✔
1108

3✔
1109
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1110
                SelfNode:            selfNode.PubKeyBytes,
3✔
1111
                Graph:               dbs.GraphDB,
3✔
1112
                Chain:               cc.ChainIO,
3✔
1113
                ChainView:           cc.ChainView,
3✔
1114
                Notifier:            cc.ChainNotifier,
3✔
1115
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1116
                GraphPruneInterval:  time.Hour,
3✔
1117
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1118
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1119
                StrictZombiePruning: strictPruning,
3✔
1120
                IsAlias:             aliasmgr.IsAlias,
3✔
1121
        })
3✔
1122
        if err != nil {
3✔
1123
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1124
        }
×
1125

1126
        s.chanRouter, err = routing.New(routing.Config{
3✔
1127
                SelfNode:           selfNode.PubKeyBytes,
3✔
1128
                RoutingGraph:       dbs.GraphDB,
3✔
1129
                Chain:              cc.ChainIO,
3✔
1130
                Payer:              s.htlcSwitch,
3✔
1131
                Control:            s.controlTower,
3✔
1132
                MissionControl:     s.defaultMC,
3✔
1133
                SessionSource:      paymentSessionSource,
3✔
1134
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1135
                NextPaymentID:      sequencer.NextID,
3✔
1136
                PathFindingConfig:  pathFindingConfig,
3✔
1137
                Clock:              clock.NewDefaultClock(),
3✔
1138
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1139
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1140
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1141
        })
3✔
1142
        if err != nil {
3✔
1143
                return nil, fmt.Errorf("can't create router: %w", err)
×
1144
        }
×
1145

1146
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1147
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1148
        if err != nil {
3✔
1149
                return nil, err
×
1150
        }
×
1151
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1152
        if err != nil {
3✔
1153
                return nil, err
×
1154
        }
×
1155

1156
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1157

3✔
1158
        s.authGossiper = discovery.New(discovery.Config{
3✔
1159
                Graph:                 s.graphBuilder,
3✔
1160
                ChainIO:               s.cc.ChainIO,
3✔
1161
                Notifier:              s.cc.ChainNotifier,
3✔
1162
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1163
                Broadcast:             s.BroadcastMessage,
3✔
1164
                ChanSeries:            chanSeries,
3✔
1165
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1166
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1167
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1168
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1169
                        error) {
3✔
1170

×
1171
                        return s.genNodeAnnouncement(nil)
×
1172
                },
×
1173
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1174
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1175
                RetransmitTicker:        ticker.New(time.Minute * 30),
1176
                RebroadcastInterval:     time.Hour * 24,
1177
                WaitingProofStore:       waitingProofStore,
1178
                MessageStore:            gossipMessageStore,
1179
                AnnSigner:               s.nodeSigner,
1180
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1181
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1182
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1183
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1184
                MinimumBatchSize:        10,
1185
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1186
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1187
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1188
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1189
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1190
                IsAlias:                 aliasmgr.IsAlias,
1191
                SignAliasUpdate:         s.signAliasUpdate,
1192
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1193
                GetAlias:                s.aliasMgr.GetPeerAlias,
1194
                FindChannel:             s.findChannel,
1195
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1196
                ScidCloser:              scidCloserMan,
1197
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1198
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1199
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1200
        }, nodeKeyDesc)
1201

1202
        accessCfg := &accessManConfig{
3✔
1203
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1204
                        error) {
6✔
1205

3✔
1206
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1207
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1208
                                genesisHash[:],
3✔
1209
                        )
3✔
1210
                },
3✔
1211
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1212
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1213
        }
1214

1215
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1216
        if err != nil {
3✔
1217
                return nil, err
×
1218
        }
×
1219

1220
        s.peerAccessMan = peerAccessMan
3✔
1221

3✔
1222
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1223
        //nolint:ll
3✔
1224
        s.localChanMgr = &localchans.Manager{
3✔
1225
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1226
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1227
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1228
                        *models.ChannelEdgePolicy) error) error {
6✔
1229

3✔
1230
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1231
                                func(c *models.ChannelEdgeInfo,
3✔
1232
                                        e *models.ChannelEdgePolicy,
3✔
1233
                                        _ *models.ChannelEdgePolicy) error {
6✔
1234

3✔
1235
                                        // NOTE: The invoked callback here may
3✔
1236
                                        // receive a nil channel policy.
3✔
1237
                                        return cb(c, e)
3✔
1238
                                },
3✔
1239
                        )
1240
                },
1241
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1242
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1243
                FetchChannel:              s.chanStateDB.FetchChannel,
1244
                AddEdge: func(ctx context.Context,
1245
                        edge *models.ChannelEdgeInfo) error {
×
1246

×
1247
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1248
                },
×
1249
        }
1250

1251
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1252
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1253
        )
3✔
1254
        if err != nil {
3✔
1255
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1256
                return nil, err
×
1257
        }
×
1258

1259
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1260
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1261
        )
3✔
1262
        if err != nil {
3✔
1263
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1264
                return nil, err
×
1265
        }
×
1266

1267
        aggregator := sweep.NewBudgetAggregator(
3✔
1268
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1269
                s.implCfg.AuxSweeper,
3✔
1270
        )
3✔
1271

3✔
1272
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1273
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1274
                Wallet:     cc.Wallet,
3✔
1275
                Estimator:  cc.FeeEstimator,
3✔
1276
                Notifier:   cc.ChainNotifier,
3✔
1277
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1278
        })
3✔
1279

3✔
1280
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1281
                FeeEstimator: cc.FeeEstimator,
3✔
1282
                GenSweepScript: newSweepPkScriptGen(
3✔
1283
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1284
                ),
3✔
1285
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1286
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1287
                Mempool:              cc.MempoolNotifier,
3✔
1288
                Notifier:             cc.ChainNotifier,
3✔
1289
                Store:                sweeperStore,
3✔
1290
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1291
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1292
                Aggregator:           aggregator,
3✔
1293
                Publisher:            s.txPublisher,
3✔
1294
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1295
        })
3✔
1296

3✔
1297
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1298
                ChainIO:             cc.ChainIO,
3✔
1299
                ConfDepth:           1,
3✔
1300
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1301
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1302
                Notifier:            cc.ChainNotifier,
3✔
1303
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1304
                Store:               utxnStore,
3✔
1305
                SweepInput:          s.sweeper.SweepInput,
3✔
1306
                Budget:              s.cfg.Sweeper.Budget,
3✔
1307
        })
3✔
1308

3✔
1309
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1310
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1311
                closureType contractcourt.ChannelCloseType) {
6✔
1312
                // TODO(conner): Properly respect the update and error channels
3✔
1313
                // returned by CloseLink.
3✔
1314

3✔
1315
                // Instruct the switch to close the channel.  Provide no close out
3✔
1316
                // delivery script or target fee per kw because user input is not
3✔
1317
                // available when the remote peer closes the channel.
3✔
1318
                s.htlcSwitch.CloseLink(
3✔
1319
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1320
                )
3✔
1321
        }
3✔
1322

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

3✔
1327
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1328
                &contractcourt.BreachConfig{
3✔
1329
                        CloseLink: closeLink,
3✔
1330
                        DB:        s.chanStateDB,
3✔
1331
                        Estimator: s.cc.FeeEstimator,
3✔
1332
                        GenSweepScript: newSweepPkScriptGen(
3✔
1333
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1334
                        ),
3✔
1335
                        Notifier:           cc.ChainNotifier,
3✔
1336
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1337
                        ContractBreaches:   contractBreaches,
3✔
1338
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1339
                        Store: contractcourt.NewRetributionStore(
3✔
1340
                                dbs.ChanStateDB,
3✔
1341
                        ),
3✔
1342
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1343
                },
3✔
1344
        )
3✔
1345

3✔
1346
        //nolint:ll
3✔
1347
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1348
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1349
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1350
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1351
                NewSweepAddr: func() ([]byte, error) {
3✔
1352
                        addr, err := newSweepPkScriptGen(
×
1353
                                cc.Wallet, netParams,
×
1354
                        )().Unpack()
×
1355
                        if err != nil {
×
1356
                                return nil, err
×
1357
                        }
×
1358

1359
                        return addr.DeliveryAddress, nil
×
1360
                },
1361
                PublishTx: cc.Wallet.PublishTransaction,
1362
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1363
                        for _, msg := range msgs {
6✔
1364
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1365
                                if err != nil {
3✔
1366
                                        return err
×
1367
                                }
×
1368
                        }
1369
                        return nil
3✔
1370
                },
1371
                IncubateOutputs: func(chanPoint wire.OutPoint,
1372
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1373
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1374
                        broadcastHeight uint32,
1375
                        deadlineHeight fn.Option[int32]) error {
3✔
1376

3✔
1377
                        return s.utxoNursery.IncubateOutputs(
3✔
1378
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1379
                                broadcastHeight, deadlineHeight,
3✔
1380
                        )
3✔
1381
                },
3✔
1382
                PreimageDB:   s.witnessBeacon,
1383
                Notifier:     cc.ChainNotifier,
1384
                Mempool:      cc.MempoolNotifier,
1385
                Signer:       cc.Wallet.Cfg.Signer,
1386
                FeeEstimator: cc.FeeEstimator,
1387
                ChainIO:      cc.ChainIO,
1388
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1389
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1390
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1391
                        return nil
3✔
1392
                },
3✔
1393
                IsOurAddress: cc.Wallet.IsOurAddress,
1394
                ContractBreach: func(chanPoint wire.OutPoint,
1395
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1396

3✔
1397
                        // processACK will handle the BreachArbitrator ACKing
3✔
1398
                        // the event.
3✔
1399
                        finalErr := make(chan error, 1)
3✔
1400
                        processACK := func(brarErr error) {
6✔
1401
                                if brarErr != nil {
3✔
1402
                                        finalErr <- brarErr
×
1403
                                        return
×
1404
                                }
×
1405

1406
                                // If the BreachArbitrator successfully handled
1407
                                // the event, we can signal that the handoff
1408
                                // was successful.
1409
                                finalErr <- nil
3✔
1410
                        }
1411

1412
                        event := &contractcourt.ContractBreachEvent{
3✔
1413
                                ChanPoint:         chanPoint,
3✔
1414
                                ProcessACK:        processACK,
3✔
1415
                                BreachRetribution: breachRet,
3✔
1416
                        }
3✔
1417

3✔
1418
                        // Send the contract breach event to the
3✔
1419
                        // BreachArbitrator.
3✔
1420
                        select {
3✔
1421
                        case contractBreaches <- event:
3✔
1422
                        case <-s.quit:
×
1423
                                return ErrServerShuttingDown
×
1424
                        }
1425

1426
                        // We'll wait for a final error to be available from
1427
                        // the BreachArbitrator.
1428
                        select {
3✔
1429
                        case err := <-finalErr:
3✔
1430
                                return err
3✔
1431
                        case <-s.quit:
×
1432
                                return ErrServerShuttingDown
×
1433
                        }
1434
                },
1435
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1436
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1437
                },
3✔
1438
                Sweeper:                       s.sweeper,
1439
                Registry:                      s.invoices,
1440
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1441
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1442
                OnionProcessor:                s.sphinx,
1443
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1444
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1445
                Clock:                         clock.NewDefaultClock(),
1446
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1447
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1448
                HtlcNotifier:                  s.htlcNotifier,
1449
                Budget:                        *s.cfg.Sweeper.Budget,
1450

1451
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1452
                QueryIncomingCircuit: func(
1453
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1454

3✔
1455
                        // Get the circuit map.
3✔
1456
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1457

3✔
1458
                        // Lookup the outgoing circuit.
3✔
1459
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1460
                        if pc == nil {
5✔
1461
                                return nil
2✔
1462
                        }
2✔
1463

1464
                        return &pc.Incoming
3✔
1465
                },
1466
                AuxLeafStore: implCfg.AuxLeafStore,
1467
                AuxSigner:    implCfg.AuxSigner,
1468
                AuxResolver:  implCfg.AuxContractResolver,
1469
        }, dbs.ChanStateDB)
1470

1471
        // Select the configuration and funding parameters for Bitcoin.
1472
        chainCfg := cfg.Bitcoin
3✔
1473
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1474
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1475

3✔
1476
        var chanIDSeed [32]byte
3✔
1477
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1478
                return nil, err
×
1479
        }
×
1480

1481
        // Wrap the DeleteChannelEdges method so that the funding manager can
1482
        // use it without depending on several layers of indirection.
1483
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1484
                *models.ChannelEdgePolicy, error) {
6✔
1485

3✔
1486
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1487
                        scid.ToUint64(),
3✔
1488
                )
3✔
1489
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1490
                        // This is unlikely but there is a slim chance of this
×
1491
                        // being hit if lnd was killed via SIGKILL and the
×
1492
                        // funding manager was stepping through the delete
×
1493
                        // alias edge logic.
×
1494
                        return nil, nil
×
1495
                } else if err != nil {
3✔
1496
                        return nil, err
×
1497
                }
×
1498

1499
                // Grab our key to find our policy.
1500
                var ourKey [33]byte
3✔
1501
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1502

3✔
1503
                var ourPolicy *models.ChannelEdgePolicy
3✔
1504
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1505
                        ourPolicy = e1
3✔
1506
                } else {
6✔
1507
                        ourPolicy = e2
3✔
1508
                }
3✔
1509

1510
                if ourPolicy == nil {
3✔
1511
                        // Something is wrong, so return an error.
×
1512
                        return nil, fmt.Errorf("we don't have an edge")
×
1513
                }
×
1514

1515
                err = s.graphDB.DeleteChannelEdges(
3✔
1516
                        false, false, scid.ToUint64(),
3✔
1517
                )
3✔
1518
                return ourPolicy, err
3✔
1519
        }
1520

1521
        // For the reservationTimeout and the zombieSweeperInterval different
1522
        // values are set in case we are in a dev environment so enhance test
1523
        // capacilities.
1524
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1525
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1526

3✔
1527
        // Get the development config for funding manager. If we are not in
3✔
1528
        // development mode, this would be nil.
3✔
1529
        var devCfg *funding.DevConfig
3✔
1530
        if lncfg.IsDevBuild() {
6✔
1531
                devCfg = &funding.DevConfig{
3✔
1532
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1533
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1534
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1535
                }
3✔
1536

3✔
1537
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1538
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1539

3✔
1540
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1541
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1542
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1543
        }
3✔
1544

1545
        //nolint:ll
1546
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1547
                Dev:                devCfg,
3✔
1548
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1549
                IDKey:              nodeKeyDesc.PubKey,
3✔
1550
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1551
                Wallet:             cc.Wallet,
3✔
1552
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1553
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1554
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1555
                },
3✔
1556
                Notifier:     cc.ChainNotifier,
1557
                ChannelDB:    s.chanStateDB,
1558
                FeeEstimator: cc.FeeEstimator,
1559
                SignMessage:  cc.MsgSigner.SignMessage,
1560
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1561
                        error) {
3✔
1562

3✔
1563
                        return s.genNodeAnnouncement(nil)
3✔
1564
                },
3✔
1565
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1566
                NotifyWhenOnline:     s.NotifyWhenOnline,
1567
                TempChanIDSeed:       chanIDSeed,
1568
                FindChannel:          s.findChannel,
1569
                DefaultRoutingPolicy: cc.RoutingPolicy,
1570
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1571
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1572
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1573
                        // For large channels we increase the number
3✔
1574
                        // of confirmations we require for the
3✔
1575
                        // channel to be considered open. As it is
3✔
1576
                        // always the responder that gets to choose
3✔
1577
                        // value, the pushAmt is value being pushed
3✔
1578
                        // to us. This means we have more to lose
3✔
1579
                        // in the case this gets re-orged out, and
3✔
1580
                        // we will require more confirmations before
3✔
1581
                        // we consider it open.
3✔
1582

3✔
1583
                        // In case the user has explicitly specified
3✔
1584
                        // a default value for the number of
3✔
1585
                        // confirmations, we use it.
3✔
1586
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1587
                        if defaultConf != 0 {
6✔
1588
                                return defaultConf
3✔
1589
                        }
3✔
1590

1591
                        minConf := uint64(3)
×
1592
                        maxConf := uint64(6)
×
1593

×
1594
                        // If this is a wumbo channel, then we'll require the
×
1595
                        // max amount of confirmations.
×
1596
                        if chanAmt > MaxFundingAmount {
×
1597
                                return uint16(maxConf)
×
1598
                        }
×
1599

1600
                        // If not we return a value scaled linearly
1601
                        // between 3 and 6, depending on channel size.
1602
                        // TODO(halseth): Use 1 as minimum?
1603
                        maxChannelSize := uint64(
×
1604
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1605
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1606
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1607
                        if conf < minConf {
×
1608
                                conf = minConf
×
1609
                        }
×
1610
                        if conf > maxConf {
×
1611
                                conf = maxConf
×
1612
                        }
×
1613
                        return uint16(conf)
×
1614
                },
1615
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1616
                        // We scale the remote CSV delay (the time the
3✔
1617
                        // remote have to claim funds in case of a unilateral
3✔
1618
                        // close) linearly from minRemoteDelay blocks
3✔
1619
                        // for small channels, to maxRemoteDelay blocks
3✔
1620
                        // for channels of size MaxFundingAmount.
3✔
1621

3✔
1622
                        // In case the user has explicitly specified
3✔
1623
                        // a default value for the remote delay, we
3✔
1624
                        // use it.
3✔
1625
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1626
                        if defaultDelay > 0 {
6✔
1627
                                return defaultDelay
3✔
1628
                        }
3✔
1629

1630
                        // If this is a wumbo channel, then we'll require the
1631
                        // max value.
1632
                        if chanAmt > MaxFundingAmount {
×
1633
                                return maxRemoteDelay
×
1634
                        }
×
1635

1636
                        // If not we scale according to channel size.
1637
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1638
                                chanAmt / MaxFundingAmount)
×
1639
                        if delay < minRemoteDelay {
×
1640
                                delay = minRemoteDelay
×
1641
                        }
×
1642
                        if delay > maxRemoteDelay {
×
1643
                                delay = maxRemoteDelay
×
1644
                        }
×
1645
                        return delay
×
1646
                },
1647
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1648
                        peerKey *btcec.PublicKey) error {
3✔
1649

3✔
1650
                        // First, we'll mark this new peer as a persistent peer
3✔
1651
                        // for re-connection purposes. If the peer is not yet
3✔
1652
                        // tracked or the user hasn't requested it to be perm,
3✔
1653
                        // we'll set false to prevent the server from continuing
3✔
1654
                        // to connect to this peer even if the number of
3✔
1655
                        // channels with this peer is zero.
3✔
1656
                        s.mu.Lock()
3✔
1657
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1658
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1659
                                s.persistentPeers[pubStr] = false
3✔
1660
                        }
3✔
1661
                        s.mu.Unlock()
3✔
1662

3✔
1663
                        // With that taken care of, we'll send this channel to
3✔
1664
                        // the chain arb so it can react to on-chain events.
3✔
1665
                        return s.chainArb.WatchNewChannel(channel)
3✔
1666
                },
1667
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1668
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1669
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1670
                },
3✔
1671
                RequiredRemoteChanReserve: func(chanAmt,
1672
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1673

3✔
1674
                        // By default, we'll require the remote peer to maintain
3✔
1675
                        // at least 1% of the total channel capacity at all
3✔
1676
                        // times. If this value ends up dipping below the dust
3✔
1677
                        // limit, then we'll use the dust limit itself as the
3✔
1678
                        // reserve as required by BOLT #2.
3✔
1679
                        reserve := chanAmt / 100
3✔
1680
                        if reserve < dustLimit {
6✔
1681
                                reserve = dustLimit
3✔
1682
                        }
3✔
1683

1684
                        return reserve
3✔
1685
                },
1686
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1687
                        // By default, we'll allow the remote peer to fully
3✔
1688
                        // utilize the full bandwidth of the channel, minus our
3✔
1689
                        // required reserve.
3✔
1690
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1691
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1692
                },
3✔
1693
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1694
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1695
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1696
                        }
3✔
1697

1698
                        // By default, we'll permit them to utilize the full
1699
                        // channel bandwidth.
1700
                        return uint16(input.MaxHTLCNumber / 2)
×
1701
                },
1702
                ZombieSweeperInterval:         zombieSweeperInterval,
1703
                ReservationTimeout:            reservationTimeout,
1704
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1705
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1706
                MaxPendingChannels:            cfg.MaxPendingChannels,
1707
                RejectPush:                    cfg.RejectPush,
1708
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1709
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1710
                OpenChannelPredicate:          chanPredicate,
1711
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1712
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1713
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1714
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1715
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1716
                DeleteAliasEdge:      deleteAliasEdge,
1717
                AliasManager:         s.aliasMgr,
1718
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1719
                AuxFundingController: implCfg.AuxFundingController,
1720
                AuxSigner:            implCfg.AuxSigner,
1721
                AuxResolver:          implCfg.AuxContractResolver,
1722
        })
1723
        if err != nil {
3✔
1724
                return nil, err
×
1725
        }
×
1726

1727
        // Next, we'll assemble the sub-system that will maintain an on-disk
1728
        // static backup of the latest channel state.
1729
        chanNotifier := &channelNotifier{
3✔
1730
                chanNotifier: s.channelNotifier,
3✔
1731
                addrs:        s.addrSource,
3✔
1732
        }
3✔
1733
        backupFile := chanbackup.NewMultiFile(
3✔
1734
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1735
        )
3✔
1736
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1737
                ctx, s.chanStateDB, s.addrSource,
3✔
1738
        )
3✔
1739
        if err != nil {
3✔
1740
                return nil, err
×
1741
        }
×
1742
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1743
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1744
        )
3✔
1745
        if err != nil {
3✔
1746
                return nil, err
×
1747
        }
×
1748

1749
        // Assemble a peer notifier which will provide clients with subscriptions
1750
        // to peer online and offline events.
1751
        s.peerNotifier = peernotifier.New()
3✔
1752

3✔
1753
        // Create a channel event store which monitors all open channels.
3✔
1754
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1755
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1756
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1757
                },
3✔
1758
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1759
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1760
                },
3✔
1761
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1762
                Clock:           clock.NewDefaultClock(),
1763
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1764
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1765
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1766
        })
1767

1768
        if cfg.WtClient.Active {
6✔
1769
                policy := wtpolicy.DefaultPolicy()
3✔
1770
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1771

3✔
1772
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1773
                // protocol operations on sat/kw.
3✔
1774
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1775
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1776
                )
3✔
1777

3✔
1778
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1779

3✔
1780
                if err := policy.Validate(); err != nil {
3✔
1781
                        return nil, err
×
1782
                }
×
1783

1784
                // authDial is the wrapper around the btrontide.Dial for the
1785
                // watchtower.
1786
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1787
                        netAddr *lnwire.NetAddress,
3✔
1788
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1789

3✔
1790
                        return brontide.Dial(
3✔
1791
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1792
                        )
3✔
1793
                }
3✔
1794

1795
                // buildBreachRetribution is a call-back that can be used to
1796
                // query the BreachRetribution info and channel type given a
1797
                // channel ID and commitment height.
1798
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1799
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1800
                        channeldb.ChannelType, error) {
6✔
1801

3✔
1802
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1803
                                nil, chanID,
3✔
1804
                        )
3✔
1805
                        if err != nil {
3✔
1806
                                return nil, 0, err
×
1807
                        }
×
1808

1809
                        br, err := lnwallet.NewBreachRetribution(
3✔
1810
                                channel, commitHeight, 0, nil,
3✔
1811
                                implCfg.AuxLeafStore,
3✔
1812
                                implCfg.AuxContractResolver,
3✔
1813
                        )
3✔
1814
                        if err != nil {
3✔
1815
                                return nil, 0, err
×
1816
                        }
×
1817

1818
                        return br, channel.ChanType, nil
3✔
1819
                }
1820

1821
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1822

3✔
1823
                // Copy the policy for legacy channels and set the blob flag
3✔
1824
                // signalling support for anchor channels.
3✔
1825
                anchorPolicy := policy
3✔
1826
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1827

3✔
1828
                // Copy the policy for legacy channels and set the blob flag
3✔
1829
                // signalling support for taproot channels.
3✔
1830
                taprootPolicy := policy
3✔
1831
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1832
                        blob.FlagTaprootChannel,
3✔
1833
                )
3✔
1834

3✔
1835
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1836
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1837
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1838
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1839
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1840
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1841
                                error) {
6✔
1842

3✔
1843
                                return s.channelNotifier.
3✔
1844
                                        SubscribeChannelEvents()
3✔
1845
                        },
3✔
1846
                        Signer: cc.Wallet.Cfg.Signer,
1847
                        NewAddress: func() ([]byte, error) {
3✔
1848
                                addr, err := newSweepPkScriptGen(
3✔
1849
                                        cc.Wallet, netParams,
3✔
1850
                                )().Unpack()
3✔
1851
                                if err != nil {
3✔
1852
                                        return nil, err
×
1853
                                }
×
1854

1855
                                return addr.DeliveryAddress, nil
3✔
1856
                        },
1857
                        SecretKeyRing:      s.cc.KeyRing,
1858
                        Dial:               cfg.net.Dial,
1859
                        AuthDial:           authDial,
1860
                        DB:                 dbs.TowerClientDB,
1861
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1862
                        MinBackoff:         10 * time.Second,
1863
                        MaxBackoff:         5 * time.Minute,
1864
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1865
                }, policy, anchorPolicy, taprootPolicy)
1866
                if err != nil {
3✔
1867
                        return nil, err
×
1868
                }
×
1869
        }
1870

1871
        if len(cfg.ExternalHosts) != 0 {
3✔
1872
                advertisedIPs := make(map[string]struct{})
×
1873
                for _, addr := range s.currentNodeAnn.Addresses {
×
1874
                        advertisedIPs[addr.String()] = struct{}{}
×
1875
                }
×
1876

1877
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1878
                        Hosts:         cfg.ExternalHosts,
×
1879
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1880
                        LookupHost: func(host string) (net.Addr, error) {
×
1881
                                return lncfg.ParseAddressString(
×
1882
                                        host, strconv.Itoa(defaultPeerPort),
×
1883
                                        cfg.net.ResolveTCPAddr,
×
1884
                                )
×
1885
                        },
×
1886
                        AdvertisedIPs: advertisedIPs,
1887
                        AnnounceNewIPs: netann.IPAnnouncer(
1888
                                func(modifier ...netann.NodeAnnModifier) (
1889
                                        lnwire.NodeAnnouncement, error) {
×
1890

×
1891
                                        return s.genNodeAnnouncement(
×
1892
                                                nil, modifier...,
×
1893
                                        )
×
1894
                                }),
×
1895
                })
1896
        }
1897

1898
        // Create liveness monitor.
1899
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1900

3✔
1901
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1902
        for i, listenAddr := range listenAddrs {
6✔
1903
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1904
                // doesn't need to call the general lndResolveTCP function
3✔
1905
                // since we are resolving a local address.
3✔
1906

3✔
1907
                // RESOLVE: We are actually partially accepting inbound
3✔
1908
                // connection requests when we call NewListener.
3✔
1909
                listeners[i], err = brontide.NewListener(
3✔
1910
                        nodeKeyECDH, listenAddr.String(),
3✔
1911
                        // TODO(yy): remove this check and unify the inbound
3✔
1912
                        // connection check inside `InboundPeerConnected`.
3✔
1913
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1914
                )
3✔
1915
                if err != nil {
3✔
1916
                        return nil, err
×
1917
                }
×
1918
        }
1919

1920
        // Create the connection manager which will be responsible for
1921
        // maintaining persistent outbound connections and also accepting new
1922
        // incoming connections
1923
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1924
                Listeners:      listeners,
3✔
1925
                OnAccept:       s.InboundPeerConnected,
3✔
1926
                RetryDuration:  time.Second * 5,
3✔
1927
                TargetOutbound: 100,
3✔
1928
                Dial: noiseDial(
3✔
1929
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1930
                ),
3✔
1931
                OnConnection: s.OutboundPeerConnected,
3✔
1932
        })
3✔
1933
        if err != nil {
3✔
1934
                return nil, err
×
1935
        }
×
1936
        s.connMgr = cmgr
3✔
1937

3✔
1938
        // Finally, register the subsystems in blockbeat.
3✔
1939
        s.registerBlockConsumers()
3✔
1940

3✔
1941
        return s, nil
3✔
1942
}
1943

1944
// UpdateRoutingConfig is a callback function to update the routing config
1945
// values in the main cfg.
1946
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1947
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1948

3✔
1949
        switch c := cfg.Estimator.Config().(type) {
3✔
1950
        case routing.AprioriConfig:
3✔
1951
                routerCfg.ProbabilityEstimatorType =
3✔
1952
                        routing.AprioriEstimatorName
3✔
1953

3✔
1954
                targetCfg := routerCfg.AprioriConfig
3✔
1955
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1956
                targetCfg.Weight = c.AprioriWeight
3✔
1957
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1958
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1959

1960
        case routing.BimodalConfig:
3✔
1961
                routerCfg.ProbabilityEstimatorType =
3✔
1962
                        routing.BimodalEstimatorName
3✔
1963

3✔
1964
                targetCfg := routerCfg.BimodalConfig
3✔
1965
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1966
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1967
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1968
        }
1969

1970
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1971
}
1972

1973
// registerBlockConsumers registers the subsystems that consume block events.
1974
// By calling `RegisterQueue`, a list of subsystems are registered in the
1975
// blockbeat for block notifications. When a new block arrives, the subsystems
1976
// in the same queue are notified sequentially, and different queues are
1977
// notified concurrently.
1978
//
1979
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1980
// a new `RegisterQueue` call.
1981
func (s *server) registerBlockConsumers() {
3✔
1982
        // In this queue, when a new block arrives, it will be received and
3✔
1983
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1984
        consumers := []chainio.Consumer{
3✔
1985
                s.chainArb,
3✔
1986
                s.sweeper,
3✔
1987
                s.txPublisher,
3✔
1988
        }
3✔
1989
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1990
}
3✔
1991

1992
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1993
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1994
// may differ from what is on disk.
1995
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1996
        error) {
3✔
1997

3✔
1998
        data, err := u.DataToSign()
3✔
1999
        if err != nil {
3✔
2000
                return nil, err
×
2001
        }
×
2002

2003
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2004
}
2005

2006
// createLivenessMonitor creates a set of health checks using our configured
2007
// values and uses these checks to create a liveness monitor. Available
2008
// health checks,
2009
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2010
//   - diskCheck
2011
//   - tlsHealthCheck
2012
//   - torController, only created when tor is enabled.
2013
//
2014
// If a health check has been disabled by setting attempts to 0, our monitor
2015
// will not run it.
2016
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2017
        leaderElector cluster.LeaderElector) {
3✔
2018

3✔
2019
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2020
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2021
                srvrLog.Info("Disabling chain backend checks for " +
×
2022
                        "nochainbackend mode")
×
2023

×
2024
                chainBackendAttempts = 0
×
2025
        }
×
2026

2027
        chainHealthCheck := healthcheck.NewObservation(
3✔
2028
                "chain backend",
3✔
2029
                cc.HealthCheck,
3✔
2030
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2031
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2032
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2033
                chainBackendAttempts,
3✔
2034
        )
3✔
2035

3✔
2036
        diskCheck := healthcheck.NewObservation(
3✔
2037
                "disk space",
3✔
2038
                func() error {
3✔
2039
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2040
                                cfg.LndDir,
×
2041
                        )
×
2042
                        if err != nil {
×
2043
                                return err
×
2044
                        }
×
2045

2046
                        // If we have more free space than we require,
2047
                        // we return a nil error.
2048
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2049
                                return nil
×
2050
                        }
×
2051

2052
                        return fmt.Errorf("require: %v free space, got: %v",
×
2053
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2054
                                free)
×
2055
                },
2056
                cfg.HealthChecks.DiskCheck.Interval,
2057
                cfg.HealthChecks.DiskCheck.Timeout,
2058
                cfg.HealthChecks.DiskCheck.Backoff,
2059
                cfg.HealthChecks.DiskCheck.Attempts,
2060
        )
2061

2062
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2063
                "tls",
3✔
2064
                func() error {
3✔
2065
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2066
                                s.cc.KeyRing,
×
2067
                        )
×
2068
                        if err != nil {
×
2069
                                return err
×
2070
                        }
×
2071
                        if expired {
×
2072
                                return fmt.Errorf("TLS certificate is "+
×
2073
                                        "expired as of %v", expTime)
×
2074
                        }
×
2075

2076
                        // If the certificate is not outdated, no error needs
2077
                        // to be returned
2078
                        return nil
×
2079
                },
2080
                cfg.HealthChecks.TLSCheck.Interval,
2081
                cfg.HealthChecks.TLSCheck.Timeout,
2082
                cfg.HealthChecks.TLSCheck.Backoff,
2083
                cfg.HealthChecks.TLSCheck.Attempts,
2084
        )
2085

2086
        checks := []*healthcheck.Observation{
3✔
2087
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2088
        }
3✔
2089

3✔
2090
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2091
        if s.torController != nil {
3✔
2092
                torConnectionCheck := healthcheck.NewObservation(
×
2093
                        "tor connection",
×
2094
                        func() error {
×
2095
                                return healthcheck.CheckTorServiceStatus(
×
2096
                                        s.torController,
×
2097
                                        func() error {
×
2098
                                                return s.createNewHiddenService(
×
2099
                                                        context.TODO(),
×
2100
                                                )
×
2101
                                        },
×
2102
                                )
2103
                        },
2104
                        cfg.HealthChecks.TorConnection.Interval,
2105
                        cfg.HealthChecks.TorConnection.Timeout,
2106
                        cfg.HealthChecks.TorConnection.Backoff,
2107
                        cfg.HealthChecks.TorConnection.Attempts,
2108
                )
2109
                checks = append(checks, torConnectionCheck)
×
2110
        }
2111

2112
        // If remote signing is enabled, add the healthcheck for the remote
2113
        // signing RPC interface.
2114
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2115
                // Because we have two cascading timeouts here, we need to add
3✔
2116
                // some slack to the "outer" one of them in case the "inner"
3✔
2117
                // returns exactly on time.
3✔
2118
                overhead := time.Millisecond * 10
3✔
2119

3✔
2120
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2121
                        "remote signer connection",
3✔
2122
                        rpcwallet.HealthCheck(
3✔
2123
                                s.cfg.RemoteSigner,
3✔
2124

3✔
2125
                                // For the health check we might to be even
3✔
2126
                                // stricter than the initial/normal connect, so
3✔
2127
                                // we use the health check timeout here.
3✔
2128
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2129
                        ),
3✔
2130
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2131
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2132
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2133
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2134
                )
3✔
2135
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2136
        }
3✔
2137

2138
        // If we have a leader elector, we add a health check to ensure we are
2139
        // still the leader. During normal operation, we should always be the
2140
        // leader, but there are circumstances where this may change, such as
2141
        // when we lose network connectivity for long enough expiring out lease.
2142
        if leaderElector != nil {
3✔
2143
                leaderCheck := healthcheck.NewObservation(
×
2144
                        "leader status",
×
2145
                        func() error {
×
2146
                                // Check if we are still the leader. Note that
×
2147
                                // we don't need to use a timeout context here
×
2148
                                // as the healthcheck observer will handle the
×
2149
                                // timeout case for us.
×
2150
                                timeoutCtx, cancel := context.WithTimeout(
×
2151
                                        context.Background(),
×
2152
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2153
                                )
×
2154
                                defer cancel()
×
2155

×
2156
                                leader, err := leaderElector.IsLeader(
×
2157
                                        timeoutCtx,
×
2158
                                )
×
2159
                                if err != nil {
×
2160
                                        return fmt.Errorf("unable to check if "+
×
2161
                                                "still leader: %v", err)
×
2162
                                }
×
2163

2164
                                if !leader {
×
2165
                                        srvrLog.Debug("Not the current leader")
×
2166
                                        return fmt.Errorf("not the current " +
×
2167
                                                "leader")
×
2168
                                }
×
2169

2170
                                return nil
×
2171
                        },
2172
                        cfg.HealthChecks.LeaderCheck.Interval,
2173
                        cfg.HealthChecks.LeaderCheck.Timeout,
2174
                        cfg.HealthChecks.LeaderCheck.Backoff,
2175
                        cfg.HealthChecks.LeaderCheck.Attempts,
2176
                )
2177

2178
                checks = append(checks, leaderCheck)
×
2179
        }
2180

2181
        // If we have not disabled all of our health checks, we create a
2182
        // liveness monitor with our configured checks.
2183
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2184
                &healthcheck.Config{
3✔
2185
                        Checks:   checks,
3✔
2186
                        Shutdown: srvrLog.Criticalf,
3✔
2187
                },
3✔
2188
        )
3✔
2189
}
2190

2191
// Started returns true if the server has been started, and false otherwise.
2192
// NOTE: This function is safe for concurrent access.
2193
func (s *server) Started() bool {
3✔
2194
        return atomic.LoadInt32(&s.active) != 0
3✔
2195
}
3✔
2196

2197
// cleaner is used to aggregate "cleanup" functions during an operation that
2198
// starts several subsystems. In case one of the subsystem fails to start
2199
// and a proper resource cleanup is required, the "run" method achieves this
2200
// by running all these added "cleanup" functions.
2201
type cleaner []func() error
2202

2203
// add is used to add a cleanup function to be called when
2204
// the run function is executed.
2205
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2206
        return append(c, cleanup)
3✔
2207
}
3✔
2208

2209
// run is used to run all the previousely added cleanup functions.
2210
func (c cleaner) run() {
×
2211
        for i := len(c) - 1; i >= 0; i-- {
×
2212
                if err := c[i](); err != nil {
×
2213
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2214
                }
×
2215
        }
2216
}
2217

2218
// startLowLevelServices starts the low-level services of the server. These
2219
// services must be started successfully before running the main server. The
2220
// services are,
2221
// 1. the chain notifier.
2222
//
2223
// TODO(yy): identify and add more low-level services here.
2224
func (s *server) startLowLevelServices() error {
3✔
2225
        var startErr error
3✔
2226

3✔
2227
        cleanup := cleaner{}
3✔
2228

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

2234
        if startErr != nil {
3✔
2235
                cleanup.run()
×
2236
        }
×
2237

2238
        return startErr
3✔
2239
}
2240

2241
// Start starts the main daemon server, all requested listeners, and any helper
2242
// goroutines.
2243
// NOTE: This function is safe for concurrent access.
2244
//
2245
//nolint:funlen
2246
func (s *server) Start(ctx context.Context) error {
3✔
2247
        // Get the current blockbeat.
3✔
2248
        beat, err := s.getStartingBeat()
3✔
2249
        if err != nil {
3✔
2250
                return err
×
2251
        }
×
2252

2253
        var startErr error
3✔
2254

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

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

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

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

2283
                // Start the notification server. This is used so channel
2284
                // management goroutines can be notified when a funding
2285
                // transaction reaches a sufficient number of confirmations, or
2286
                // when the input for the funding transaction is spent in an
2287
                // attempt at an uncooperative close by the counterparty.
2288
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2289
                if err := s.sigPool.Start(); err != nil {
3✔
2290
                        startErr = err
×
2291
                        return
×
2292
                }
×
2293

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

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

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

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

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

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

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

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

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

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

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

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

2370
                // htlcSwitch must be started before chainArb since the latter
2371
                // relies on htlcSwitch to deliver resolution message upon
2372
                // start.
2373
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2374
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2375
                        startErr = err
×
2376
                        return
×
2377
                }
×
2378

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

2385
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
3✔
2386
                if err := s.invoiceHtlcModifier.Start(); err != nil {
3✔
2387
                        startErr = err
×
2388
                        return
×
2389
                }
×
2390

2391
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2392
                if err := s.chainArb.Start(beat); err != nil {
3✔
2393
                        startErr = err
×
2394
                        return
×
2395
                }
×
2396

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

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

2409
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2410
                if err := s.chanRouter.Start(); err != nil {
3✔
2411
                        startErr = err
×
2412
                        return
×
2413
                }
×
2414
                // The authGossiper depends on the chanRouter and therefore
2415
                // should be started after it.
2416
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2417
                if err := s.authGossiper.Start(); err != nil {
3✔
2418
                        startErr = err
×
2419
                        return
×
2420
                }
×
2421

2422
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2423
                if err := s.invoices.Start(); err != nil {
3✔
2424
                        startErr = err
×
2425
                        return
×
2426
                }
×
2427

2428
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2429
                if err := s.sphinx.Start(); err != nil {
3✔
2430
                        startErr = err
×
2431
                        return
×
2432
                }
×
2433

2434
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2435
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2436
                        startErr = err
×
2437
                        return
×
2438
                }
×
2439

2440
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2441
                if err := s.chanEventStore.Start(); err != nil {
3✔
2442
                        startErr = err
×
2443
                        return
×
2444
                }
×
2445

2446
                cleanup.add(func() error {
3✔
2447
                        s.missionController.StopStoreTickers()
×
2448
                        return nil
×
2449
                })
×
2450
                s.missionController.RunStoreTickers()
3✔
2451

3✔
2452
                // Before we start the connMgr, we'll check to see if we have
3✔
2453
                // any backups to recover. We do this now as we want to ensure
3✔
2454
                // that have all the information we need to handle channel
3✔
2455
                // recovery _before_ we even accept connections from any peers.
3✔
2456
                chanRestorer := &chanDBRestorer{
3✔
2457
                        db:         s.chanStateDB,
3✔
2458
                        secretKeys: s.cc.KeyRing,
3✔
2459
                        chainArb:   s.chainArb,
3✔
2460
                }
3✔
2461
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2462
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2463
                                s.chansToRestore.PackedSingleChanBackups,
×
2464
                                s.cc.KeyRing, chanRestorer, s,
×
2465
                        )
×
2466
                        if err != nil {
×
2467
                                startErr = fmt.Errorf("unable to unpack single "+
×
2468
                                        "backups: %v", err)
×
2469
                                return
×
2470
                        }
×
2471
                }
2472
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2473
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2474
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2475
                                s.cc.KeyRing, chanRestorer, s,
3✔
2476
                        )
3✔
2477
                        if err != nil {
3✔
2478
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2479
                                        "backup: %v", err)
×
2480
                                return
×
2481
                        }
×
2482
                }
2483

2484
                // chanSubSwapper must be started after the `channelNotifier`
2485
                // because it depends on channel events as a synchronization
2486
                // point.
2487
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2488
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2489
                        startErr = err
×
2490
                        return
×
2491
                }
×
2492

2493
                if s.torController != nil {
3✔
2494
                        cleanup = cleanup.add(s.torController.Stop)
×
2495
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2496
                                startErr = err
×
2497
                                return
×
2498
                        }
×
2499
                }
2500

2501
                if s.natTraversal != nil {
3✔
2502
                        s.wg.Add(1)
×
2503
                        go s.watchExternalIP()
×
2504
                }
×
2505

2506
                // Start connmgr last to prevent connections before init.
2507
                cleanup = cleanup.add(func() error {
3✔
2508
                        s.connMgr.Stop()
×
2509
                        return nil
×
2510
                })
×
2511

2512
                // RESOLVE: s.connMgr.Start() is called here, but
2513
                // brontide.NewListener() is called in newServer. This means
2514
                // that we are actually listening and partially accepting
2515
                // inbound connections even before the connMgr starts.
2516
                //
2517
                // TODO(yy): move the log into the connMgr's `Start` method.
2518
                srvrLog.Info("connMgr starting...")
3✔
2519
                s.connMgr.Start()
3✔
2520
                srvrLog.Debug("connMgr started")
3✔
2521

3✔
2522
                // If peers are specified as a config option, we'll add those
3✔
2523
                // peers first.
3✔
2524
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2525
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2526
                                peerAddrCfg,
3✔
2527
                        )
3✔
2528
                        if err != nil {
3✔
2529
                                startErr = fmt.Errorf("unable to parse peer "+
×
2530
                                        "pubkey from config: %v", err)
×
2531
                                return
×
2532
                        }
×
2533
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2534
                        if err != nil {
3✔
2535
                                startErr = fmt.Errorf("unable to parse peer "+
×
2536
                                        "address provided as a config option: "+
×
2537
                                        "%v", err)
×
2538
                                return
×
2539
                        }
×
2540

2541
                        peerAddr := &lnwire.NetAddress{
3✔
2542
                                IdentityKey: parsedPubkey,
3✔
2543
                                Address:     addr,
3✔
2544
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2545
                        }
3✔
2546

3✔
2547
                        err = s.ConnectToPeer(
3✔
2548
                                peerAddr, true,
3✔
2549
                                s.cfg.ConnectionTimeout,
3✔
2550
                        )
3✔
2551
                        if err != nil {
3✔
2552
                                startErr = fmt.Errorf("unable to connect to "+
×
2553
                                        "peer address provided as a config "+
×
2554
                                        "option: %v", err)
×
2555
                                return
×
2556
                        }
×
2557
                }
2558

2559
                // Subscribe to NodeAnnouncements that advertise new addresses
2560
                // our persistent peers.
2561
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2562
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2563
                                "addr: %v", err)
×
2564

×
2565
                        startErr = err
×
2566
                        return
×
2567
                }
×
2568

2569
                // With all the relevant sub-systems started, we'll now attempt
2570
                // to establish persistent connections to our direct channel
2571
                // collaborators within the network. Before doing so however,
2572
                // we'll prune our set of link nodes found within the database
2573
                // to ensure we don't reconnect to any nodes we no longer have
2574
                // open channels with.
2575
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2576
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2577

×
2578
                        startErr = err
×
2579
                        return
×
2580
                }
×
2581

2582
                if err := s.establishPersistentConnections(); err != nil {
3✔
2583
                        srvrLog.Errorf("Failed to establish persistent "+
×
2584
                                "connections: %v", err)
×
2585
                }
×
2586

2587
                // setSeedList is a helper function that turns multiple DNS seed
2588
                // server tuples from the command line or config file into the
2589
                // data structure we need and does a basic formal sanity check
2590
                // in the process.
2591
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2592
                        if len(tuples) == 0 {
×
2593
                                return
×
2594
                        }
×
2595

2596
                        result := make([][2]string, len(tuples))
×
2597
                        for idx, tuple := range tuples {
×
2598
                                tuple = strings.TrimSpace(tuple)
×
2599
                                if len(tuple) == 0 {
×
2600
                                        return
×
2601
                                }
×
2602

2603
                                servers := strings.Split(tuple, ",")
×
2604
                                if len(servers) > 2 || len(servers) == 0 {
×
2605
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2606
                                                "seed tuple: %v", servers)
×
2607
                                        return
×
2608
                                }
×
2609

2610
                                copy(result[idx][:], servers)
×
2611
                        }
2612

2613
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2614
                }
2615

2616
                // Let users overwrite the DNS seed nodes. We only allow them
2617
                // for bitcoin mainnet/testnet/signet.
2618
                if s.cfg.Bitcoin.MainNet {
3✔
2619
                        setSeedList(
×
2620
                                s.cfg.Bitcoin.DNSSeeds,
×
2621
                                chainreg.BitcoinMainnetGenesis,
×
2622
                        )
×
2623
                }
×
2624
                if s.cfg.Bitcoin.TestNet3 {
3✔
2625
                        setSeedList(
×
2626
                                s.cfg.Bitcoin.DNSSeeds,
×
2627
                                chainreg.BitcoinTestnetGenesis,
×
2628
                        )
×
2629
                }
×
2630
                if s.cfg.Bitcoin.TestNet4 {
3✔
2631
                        setSeedList(
×
2632
                                s.cfg.Bitcoin.DNSSeeds,
×
2633
                                chainreg.BitcoinTestnet4Genesis,
×
2634
                        )
×
2635
                }
×
2636
                if s.cfg.Bitcoin.SigNet {
3✔
2637
                        setSeedList(
×
2638
                                s.cfg.Bitcoin.DNSSeeds,
×
2639
                                chainreg.BitcoinSignetGenesis,
×
2640
                        )
×
2641
                }
×
2642

2643
                // If network bootstrapping hasn't been disabled, then we'll
2644
                // configure the set of active bootstrappers, and launch a
2645
                // dedicated goroutine to maintain a set of persistent
2646
                // connections.
2647
                if !s.cfg.NoNetBootstrap {
6✔
2648
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2649
                        if err != nil {
3✔
2650
                                startErr = err
×
2651
                                return
×
2652
                        }
×
2653

2654
                        s.wg.Add(1)
3✔
2655
                        go s.peerBootstrapper(
3✔
2656
                                ctx, defaultMinPeers, bootstrappers,
3✔
2657
                        )
3✔
2658
                } else {
3✔
2659
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2660
                }
3✔
2661

2662
                // Start the blockbeat after all other subsystems have been
2663
                // started so they are ready to receive new blocks.
2664
                cleanup = cleanup.add(func() error {
3✔
2665
                        s.blockbeatDispatcher.Stop()
×
2666
                        return nil
×
2667
                })
×
2668
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2669
                        startErr = err
×
2670
                        return
×
2671
                }
×
2672

2673
                // Set the active flag now that we've completed the full
2674
                // startup.
2675
                atomic.StoreInt32(&s.active, 1)
3✔
2676
        })
2677

2678
        if startErr != nil {
3✔
2679
                cleanup.run()
×
2680
        }
×
2681
        return startErr
3✔
2682
}
2683

2684
// Stop gracefully shutsdown the main daemon server. This function will signal
2685
// any active goroutines, or helper objects to exit, then blocks until they've
2686
// all successfully exited. Additionally, any/all listeners are closed.
2687
// NOTE: This function is safe for concurrent access.
2688
func (s *server) Stop() error {
3✔
2689
        s.stop.Do(func() {
6✔
2690
                atomic.StoreInt32(&s.stopping, 1)
3✔
2691

3✔
2692
                ctx := context.Background()
3✔
2693

3✔
2694
                close(s.quit)
3✔
2695

3✔
2696
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2697
                s.connMgr.Stop()
3✔
2698

3✔
2699
                // Stop dispatching blocks to other systems immediately.
3✔
2700
                s.blockbeatDispatcher.Stop()
3✔
2701

3✔
2702
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2703
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2704
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2705
                }
×
2706
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2707
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2708
                }
×
2709
                if err := s.sphinx.Stop(); err != nil {
3✔
2710
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2711
                }
×
2712
                if err := s.invoices.Stop(); err != nil {
3✔
2713
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2714
                }
×
2715
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2716
                        srvrLog.Warnf("failed to stop interceptable "+
×
2717
                                "switch: %v", err)
×
2718
                }
×
2719
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2720
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2721
                                "modifier: %v", err)
×
2722
                }
×
2723
                if err := s.chanRouter.Stop(); err != nil {
3✔
2724
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2725
                }
×
2726
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2727
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2728
                }
×
2729
                if err := s.graphDB.Stop(); err != nil {
3✔
2730
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2731
                }
×
2732
                if err := s.chainArb.Stop(); err != nil {
3✔
2733
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2734
                }
×
2735
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2736
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2737
                }
×
2738
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2739
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2740
                                err)
×
2741
                }
×
2742
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2743
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2744
                }
×
2745
                if err := s.authGossiper.Stop(); err != nil {
3✔
2746
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2747
                }
×
2748
                if err := s.sweeper.Stop(); err != nil {
3✔
2749
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2750
                }
×
2751
                if err := s.txPublisher.Stop(); err != nil {
3✔
2752
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2753
                }
×
2754
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2755
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2756
                }
×
2757
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2758
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2759
                }
×
2760
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2761
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2762
                }
×
2763

2764
                // Update channel.backup file. Make sure to do it before
2765
                // stopping chanSubSwapper.
2766
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2767
                        ctx, s.chanStateDB, s.addrSource,
3✔
2768
                )
3✔
2769
                if err != nil {
3✔
2770
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2771
                                err)
×
2772
                } else {
3✔
2773
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2774
                        if err != nil {
6✔
2775
                                srvrLog.Warnf("Manual update of channel "+
3✔
2776
                                        "backup failed: %v", err)
3✔
2777
                        }
3✔
2778
                }
2779

2780
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2781
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2782
                }
×
2783
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2784
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2785
                }
×
2786
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2787
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2788
                                err)
×
2789
                }
×
2790
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2791
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2792
                                err)
×
2793
                }
×
2794
                s.missionController.StopStoreTickers()
3✔
2795

3✔
2796
                // Disconnect from each active peers to ensure that
3✔
2797
                // peerTerminationWatchers signal completion to each peer.
3✔
2798
                for _, peer := range s.Peers() {
6✔
2799
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2800
                        if err != nil {
3✔
2801
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2802
                                        "received error: %v", peer.IdentityKey(),
×
2803
                                        err,
×
2804
                                )
×
2805
                        }
×
2806
                }
2807

2808
                // Now that all connections have been torn down, stop the tower
2809
                // client which will reliably flush all queued states to the
2810
                // tower. If this is halted for any reason, the force quit timer
2811
                // will kick in and abort to allow this method to return.
2812
                if s.towerClientMgr != nil {
6✔
2813
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2814
                                srvrLog.Warnf("Unable to shut down tower "+
×
2815
                                        "client manager: %v", err)
×
2816
                        }
×
2817
                }
2818

2819
                if s.hostAnn != nil {
3✔
2820
                        if err := s.hostAnn.Stop(); err != nil {
×
2821
                                srvrLog.Warnf("unable to shut down host "+
×
2822
                                        "annoucner: %v", err)
×
2823
                        }
×
2824
                }
2825

2826
                if s.livenessMonitor != nil {
6✔
2827
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2828
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2829
                                        "monitor: %v", err)
×
2830
                        }
×
2831
                }
2832

2833
                // Wait for all lingering goroutines to quit.
2834
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2835
                s.wg.Wait()
3✔
2836

3✔
2837
                srvrLog.Debug("Stopping buffer pools...")
3✔
2838
                s.sigPool.Stop()
3✔
2839
                s.writePool.Stop()
3✔
2840
                s.readPool.Stop()
3✔
2841
        })
2842

2843
        return nil
3✔
2844
}
2845

2846
// Stopped returns true if the server has been instructed to shutdown.
2847
// NOTE: This function is safe for concurrent access.
2848
func (s *server) Stopped() bool {
3✔
2849
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2850
}
3✔
2851

2852
// configurePortForwarding attempts to set up port forwarding for the different
2853
// ports that the server will be listening on.
2854
//
2855
// NOTE: This should only be used when using some kind of NAT traversal to
2856
// automatically set up forwarding rules.
2857
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2858
        ip, err := s.natTraversal.ExternalIP()
×
2859
        if err != nil {
×
2860
                return nil, err
×
2861
        }
×
2862
        s.lastDetectedIP = ip
×
2863

×
2864
        externalIPs := make([]string, 0, len(ports))
×
2865
        for _, port := range ports {
×
2866
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2867
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2868
                        continue
×
2869
                }
2870

2871
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2872
                externalIPs = append(externalIPs, hostIP)
×
2873
        }
2874

2875
        return externalIPs, nil
×
2876
}
2877

2878
// removePortForwarding attempts to clear the forwarding rules for the different
2879
// ports the server is currently listening on.
2880
//
2881
// NOTE: This should only be used when using some kind of NAT traversal to
2882
// automatically set up forwarding rules.
2883
func (s *server) removePortForwarding() {
×
2884
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2885
        for _, port := range forwardedPorts {
×
2886
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2887
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2888
                                "port %d: %v", port, err)
×
2889
                }
×
2890
        }
2891
}
2892

2893
// watchExternalIP continuously checks for an updated external IP address every
2894
// 15 minutes. Once a new IP address has been detected, it will automatically
2895
// handle port forwarding rules and send updated node announcements to the
2896
// currently connected peers.
2897
//
2898
// NOTE: This MUST be run as a goroutine.
2899
func (s *server) watchExternalIP() {
×
2900
        defer s.wg.Done()
×
2901

×
2902
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2903
        // up by the server.
×
2904
        defer s.removePortForwarding()
×
2905

×
2906
        // Keep track of the external IPs set by the user to avoid replacing
×
2907
        // them when detecting a new IP.
×
2908
        ipsSetByUser := make(map[string]struct{})
×
2909
        for _, ip := range s.cfg.ExternalIPs {
×
2910
                ipsSetByUser[ip.String()] = struct{}{}
×
2911
        }
×
2912

2913
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2914

×
2915
        ticker := time.NewTicker(15 * time.Minute)
×
2916
        defer ticker.Stop()
×
2917
out:
×
2918
        for {
×
2919
                select {
×
2920
                case <-ticker.C:
×
2921
                        // We'll start off by making sure a new IP address has
×
2922
                        // been detected.
×
2923
                        ip, err := s.natTraversal.ExternalIP()
×
2924
                        if err != nil {
×
2925
                                srvrLog.Debugf("Unable to retrieve the "+
×
2926
                                        "external IP address: %v", err)
×
2927
                                continue
×
2928
                        }
2929

2930
                        // Periodically renew the NAT port forwarding.
2931
                        for _, port := range forwardedPorts {
×
2932
                                err := s.natTraversal.AddPortMapping(port)
×
2933
                                if err != nil {
×
2934
                                        srvrLog.Warnf("Unable to automatically "+
×
2935
                                                "re-create port forwarding using %s: %v",
×
2936
                                                s.natTraversal.Name(), err)
×
2937
                                } else {
×
2938
                                        srvrLog.Debugf("Automatically re-created "+
×
2939
                                                "forwarding for port %d using %s to "+
×
2940
                                                "advertise external IP",
×
2941
                                                port, s.natTraversal.Name())
×
2942
                                }
×
2943
                        }
2944

2945
                        if ip.Equal(s.lastDetectedIP) {
×
2946
                                continue
×
2947
                        }
2948

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

×
2951
                        // Next, we'll craft the new addresses that will be
×
2952
                        // included in the new node announcement and advertised
×
2953
                        // to the network. Each address will consist of the new
×
2954
                        // IP detected and one of the currently advertised
×
2955
                        // ports.
×
2956
                        var newAddrs []net.Addr
×
2957
                        for _, port := range forwardedPorts {
×
2958
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2959
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2960
                                if err != nil {
×
2961
                                        srvrLog.Debugf("Unable to resolve "+
×
2962
                                                "host %v: %v", addr, err)
×
2963
                                        continue
×
2964
                                }
2965

2966
                                newAddrs = append(newAddrs, addr)
×
2967
                        }
2968

2969
                        // Skip the update if we weren't able to resolve any of
2970
                        // the new addresses.
2971
                        if len(newAddrs) == 0 {
×
2972
                                srvrLog.Debug("Skipping node announcement " +
×
2973
                                        "update due to not being able to " +
×
2974
                                        "resolve any new addresses")
×
2975
                                continue
×
2976
                        }
2977

2978
                        // Now, we'll need to update the addresses in our node's
2979
                        // announcement in order to propagate the update
2980
                        // throughout the network. We'll only include addresses
2981
                        // that have a different IP from the previous one, as
2982
                        // the previous IP is no longer valid.
2983
                        currentNodeAnn := s.getNodeAnnouncement()
×
2984

×
2985
                        for _, addr := range currentNodeAnn.Addresses {
×
2986
                                host, _, err := net.SplitHostPort(addr.String())
×
2987
                                if err != nil {
×
2988
                                        srvrLog.Debugf("Unable to determine "+
×
2989
                                                "host from address %v: %v",
×
2990
                                                addr, err)
×
2991
                                        continue
×
2992
                                }
2993

2994
                                // We'll also make sure to include external IPs
2995
                                // set manually by the user.
2996
                                _, setByUser := ipsSetByUser[addr.String()]
×
2997
                                if setByUser || host != s.lastDetectedIP.String() {
×
2998
                                        newAddrs = append(newAddrs, addr)
×
2999
                                }
×
3000
                        }
3001

3002
                        // Then, we'll generate a new timestamped node
3003
                        // announcement with the updated addresses and broadcast
3004
                        // it to our peers.
3005
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3006
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3007
                        )
×
3008
                        if err != nil {
×
3009
                                srvrLog.Debugf("Unable to generate new node "+
×
3010
                                        "announcement: %v", err)
×
3011
                                continue
×
3012
                        }
3013

3014
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3015
                        if err != nil {
×
3016
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3017
                                        "announcement to peers: %v", err)
×
3018
                                continue
×
3019
                        }
3020

3021
                        // Finally, update the last IP seen to the current one.
3022
                        s.lastDetectedIP = ip
×
3023
                case <-s.quit:
×
3024
                        break out
×
3025
                }
3026
        }
3027
}
3028

3029
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3030
// based on the server, and currently active bootstrap mechanisms as defined
3031
// within the current configuration.
3032
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
3033
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
3034

3✔
3035
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3036

3✔
3037
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
3038
        // this can be used by default if we've already partially seeded the
3✔
3039
        // network.
3✔
3040
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
3041
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
3042
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
3043
        )
3✔
3044
        if err != nil {
3✔
3045
                return nil, err
×
3046
        }
×
3047
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
3048

3✔
3049
        // If this isn't using simnet or regtest mode, then one of our
3✔
3050
        // additional bootstrapping sources will be the set of running DNS
3✔
3051
        // seeds.
3✔
3052
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
NEW
3053
                //nolint:ll
×
UNCOV
3054
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
UNCOV
3055

×
UNCOV
3056
                // If we have a set of DNS seeds for this chain, then we'll add
×
UNCOV
3057
                // it as an additional bootstrapping source.
×
UNCOV
3058
                if ok {
×
3059
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3060
                                "seeds: %v", dnsSeeds)
×
3061

×
3062
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3063
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3064
                        )
×
3065
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3066
                }
×
3067
        }
3068

3069
        return bootStrappers, nil
3✔
3070
}
3071

3072
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3073
// needs to ignore, which is made of three parts,
3074
//   - the node itself needs to be skipped as it doesn't make sense to connect
3075
//     to itself.
3076
//   - the peers that already have connections with, as in s.peersByPub.
3077
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3078
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
3079
        s.mu.RLock()
3✔
3080
        defer s.mu.RUnlock()
3✔
3081

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

3✔
3084
        // We should ignore ourselves from bootstrapping.
3✔
3085
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3086
        ignore[selfKey] = struct{}{}
3✔
3087

3✔
3088
        // Ignore all connected peers.
3✔
3089
        for _, peer := range s.peersByPub {
3✔
3090
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3091
                ignore[nID] = struct{}{}
×
3092
        }
×
3093

3094
        // Ignore all persistent peers as they have a dedicated reconnecting
3095
        // process.
3096
        for pubKeyStr := range s.persistentPeers {
3✔
3097
                var nID autopilot.NodeID
×
3098
                copy(nID[:], []byte(pubKeyStr))
×
3099
                ignore[nID] = struct{}{}
×
3100
        }
×
3101

3102
        return ignore
3✔
3103
}
3104

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

3✔
3113
        defer s.wg.Done()
3✔
3114

3✔
3115
        // Before we continue, init the ignore peers map.
3✔
3116
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3117

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

3✔
3122
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3123
        // peers.
3✔
3124
        //
3✔
3125
        // We'll use a 15 second backoff, and double the time every time an
3✔
3126
        // epoch fails up to a ceiling.
3✔
3127
        backOff := time.Second * 15
3✔
3128

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

3✔
3134
        // We'll use the number of attempts and errors to determine if we need
3✔
3135
        // to increase the time between discovery epochs.
3✔
3136
        var epochErrors uint32 // To be used atomically.
3✔
3137
        var epochAttempts uint32
3✔
3138

3✔
3139
        for {
6✔
3140
                select {
3✔
3141
                // The ticker has just woken us up, so we'll need to check if
3142
                // we need to attempt to connect our to any more peers.
3143
                case <-sampleTicker.C:
×
3144
                        // Obtain the current number of peers, so we can gauge
×
3145
                        // if we need to sample more peers or not.
×
3146
                        s.mu.RLock()
×
3147
                        numActivePeers := uint32(len(s.peersByPub))
×
3148
                        s.mu.RUnlock()
×
3149

×
3150
                        // If we have enough peers, then we can loop back
×
3151
                        // around to the next round as we're done here.
×
3152
                        if numActivePeers >= numTargetPeers {
×
3153
                                continue
×
3154
                        }
3155

3156
                        // If all of our attempts failed during this last back
3157
                        // off period, then will increase our backoff to 5
3158
                        // minute ceiling to avoid an excessive number of
3159
                        // queries
3160
                        //
3161
                        // TODO(roasbeef): add reverse policy too?
3162

3163
                        if epochAttempts > 0 &&
×
3164
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3165

×
3166
                                sampleTicker.Stop()
×
3167

×
3168
                                backOff *= 2
×
3169
                                if backOff > bootstrapBackOffCeiling {
×
3170
                                        backOff = bootstrapBackOffCeiling
×
3171
                                }
×
3172

3173
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3174
                                        "%v", backOff)
×
3175
                                sampleTicker = time.NewTicker(backOff)
×
3176
                                continue
×
3177
                        }
3178

3179
                        atomic.StoreUint32(&epochErrors, 0)
×
3180
                        epochAttempts = 0
×
3181

×
3182
                        // Since we know need more peers, we'll compute the
×
3183
                        // exact number we need to reach our threshold.
×
3184
                        numNeeded := numTargetPeers - numActivePeers
×
3185

×
3186
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3187
                                "peers", numNeeded)
×
3188

×
3189
                        // With the number of peers we need calculated, we'll
×
3190
                        // query the network bootstrappers to sample a set of
×
3191
                        // random addrs for us.
×
3192
                        //
×
3193
                        // Before we continue, get a copy of the ignore peers
×
3194
                        // map.
×
3195
                        ignoreList = s.createBootstrapIgnorePeers()
×
3196

×
3197
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3198
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3199
                        )
×
3200
                        if err != nil {
×
3201
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3202
                                        "peers: %v", err)
×
3203
                                continue
×
3204
                        }
3205

3206
                        // Finally, we'll launch a new goroutine for each
3207
                        // prospective peer candidates.
3208
                        for _, addr := range peerAddrs {
×
3209
                                epochAttempts++
×
3210

×
3211
                                go func(a *lnwire.NetAddress) {
×
3212
                                        // TODO(roasbeef): can do AS, subnet,
×
3213
                                        // country diversity, etc
×
3214
                                        errChan := make(chan error, 1)
×
3215
                                        s.connectToPeer(
×
3216
                                                a, errChan,
×
3217
                                                s.cfg.ConnectionTimeout,
×
3218
                                        )
×
3219
                                        select {
×
3220
                                        case err := <-errChan:
×
3221
                                                if err == nil {
×
3222
                                                        return
×
3223
                                                }
×
3224

3225
                                                srvrLog.Errorf("Unable to "+
×
3226
                                                        "connect to %v: %v",
×
3227
                                                        a, err)
×
3228
                                                atomic.AddUint32(&epochErrors, 1)
×
3229
                                        case <-s.quit:
×
3230
                                        }
3231
                                }(addr)
3232
                        }
3233
                case <-s.quit:
3✔
3234
                        return
3✔
3235
                }
3236
        }
3237
}
3238

3239
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3240
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3241
// query back off each time we encounter a failure.
3242
const bootstrapBackOffCeiling = time.Minute * 5
3243

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

3✔
3251
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3252
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3253

3✔
3254
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3255
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3256
        var delaySignal <-chan time.Time
3✔
3257
        delayTime := time.Second * 2
3✔
3258

3✔
3259
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3260
        // then the main peer bootstrap logic.
3✔
3261
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3262

3✔
3263
        for attempts := 0; ; attempts++ {
6✔
3264
                // Check if the server has been requested to shut down in order
3✔
3265
                // to prevent blocking.
3✔
3266
                if s.Stopped() {
3✔
3267
                        return
×
3268
                }
×
3269

3270
                // We can exit our aggressive initial peer bootstrapping stage
3271
                // if we've reached out target number of peers.
3272
                s.mu.RLock()
3✔
3273
                numActivePeers := uint32(len(s.peersByPub))
3✔
3274
                s.mu.RUnlock()
3✔
3275

3✔
3276
                if numActivePeers >= numTargetPeers {
6✔
3277
                        return
3✔
3278
                }
3✔
3279

3280
                if attempts > 0 {
3✔
UNCOV
3281
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3282
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3283
                                attempts)
×
UNCOV
3284

×
UNCOV
3285
                        // We've completed at least one iterating and haven't
×
UNCOV
3286
                        // finished, so we'll start to insert a delay period
×
UNCOV
3287
                        // between each attempt.
×
UNCOV
3288
                        delaySignal = time.After(delayTime)
×
UNCOV
3289
                        select {
×
UNCOV
3290
                        case <-delaySignal:
×
3291
                        case <-s.quit:
×
3292
                                return
×
3293
                        }
3294

3295
                        // After our delay, we'll double the time we wait up to
3296
                        // the max back off period.
UNCOV
3297
                        delayTime *= 2
×
UNCOV
3298
                        if delayTime > backOffCeiling {
×
3299
                                delayTime = backOffCeiling
×
3300
                        }
×
3301
                }
3302

3303
                // Otherwise, we'll request for the remaining number of peers
3304
                // in order to reach our target.
3305
                peersNeeded := numTargetPeers - numActivePeers
3✔
3306
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3307
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3308
                )
3✔
3309
                if err != nil {
3✔
UNCOV
3310
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3311
                                "peers: %v", err)
×
UNCOV
3312
                        continue
×
3313
                }
3314

3315
                // Then, we'll attempt to establish a connection to the
3316
                // different peer addresses retrieved by our bootstrappers.
3317
                var wg sync.WaitGroup
3✔
3318
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3319
                        wg.Add(1)
3✔
3320
                        go func(addr *lnwire.NetAddress) {
6✔
3321
                                defer wg.Done()
3✔
3322

3✔
3323
                                errChan := make(chan error, 1)
3✔
3324
                                go s.connectToPeer(
3✔
3325
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3326
                                )
3✔
3327

3✔
3328
                                // We'll only allow this connection attempt to
3✔
3329
                                // take up to 3 seconds. This allows us to move
3✔
3330
                                // quickly by discarding peers that are slowing
3✔
3331
                                // us down.
3✔
3332
                                select {
3✔
3333
                                case err := <-errChan:
3✔
3334
                                        if err == nil {
6✔
3335
                                                return
3✔
3336
                                        }
3✔
3337
                                        srvrLog.Errorf("Unable to connect to "+
×
3338
                                                "%v: %v", addr, err)
×
3339
                                // TODO: tune timeout? 3 seconds might be *too*
3340
                                // aggressive but works well.
3341
                                case <-time.After(3 * time.Second):
×
3342
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3343
                                                "to not establishing a "+
×
3344
                                                "connection within 3 seconds",
×
3345
                                                addr)
×
3346
                                case <-s.quit:
×
3347
                                }
3348
                        }(bootstrapAddr)
3349
                }
3350

3351
                wg.Wait()
3✔
3352
        }
3353
}
3354

3355
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3356
// order to listen for inbound connections over Tor.
3357
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3358
        // Determine the different ports the server is listening on. The onion
×
3359
        // service's virtual port will map to these ports and one will be picked
×
3360
        // at random when the onion service is being accessed.
×
3361
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3362
        for _, listenAddr := range s.listenAddrs {
×
3363
                port := listenAddr.(*net.TCPAddr).Port
×
3364
                listenPorts = append(listenPorts, port)
×
3365
        }
×
3366

3367
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3368
        if err != nil {
×
3369
                return err
×
3370
        }
×
3371

3372
        // Once the port mapping has been set, we can go ahead and automatically
3373
        // create our onion service. The service's private key will be saved to
3374
        // disk in order to regain access to this service when restarting `lnd`.
3375
        onionCfg := tor.AddOnionConfig{
×
3376
                VirtualPort: defaultPeerPort,
×
3377
                TargetPorts: listenPorts,
×
3378
                Store: tor.NewOnionFile(
×
3379
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3380
                        encrypter,
×
3381
                ),
×
3382
        }
×
3383

×
3384
        switch {
×
3385
        case s.cfg.Tor.V2:
×
3386
                onionCfg.Type = tor.V2
×
3387
        case s.cfg.Tor.V3:
×
3388
                onionCfg.Type = tor.V3
×
3389
        }
3390

3391
        addr, err := s.torController.AddOnion(onionCfg)
×
3392
        if err != nil {
×
3393
                return err
×
3394
        }
×
3395

3396
        // Now that the onion service has been created, we'll add the onion
3397
        // address it can be reached at to our list of advertised addresses.
3398
        newNodeAnn, err := s.genNodeAnnouncement(
×
3399
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3400
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3401
                },
×
3402
        )
3403
        if err != nil {
×
3404
                return fmt.Errorf("unable to generate new node "+
×
3405
                        "announcement: %v", err)
×
3406
        }
×
3407

3408
        // Finally, we'll update the on-disk version of our announcement so it
3409
        // will eventually propagate to nodes in the network.
3410
        selfNode := &models.LightningNode{
×
3411
                HaveNodeAnnouncement: true,
×
3412
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3413
                Addresses:            newNodeAnn.Addresses,
×
3414
                Alias:                newNodeAnn.Alias.String(),
×
3415
                Features: lnwire.NewFeatureVector(
×
3416
                        newNodeAnn.Features, lnwire.Features,
×
3417
                ),
×
3418
                Color:        newNodeAnn.RGBColor,
×
3419
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3420
        }
×
3421
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3422
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3423
                return fmt.Errorf("can't set self node: %w", err)
×
3424
        }
×
3425

3426
        return nil
×
3427
}
3428

3429
// findChannel finds a channel given a public key and ChannelID. It is an
3430
// optimization that is quicker than seeking for a channel given only the
3431
// ChannelID.
3432
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3433
        *channeldb.OpenChannel, error) {
3✔
3434

3✔
3435
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3436
        if err != nil {
3✔
3437
                return nil, err
×
3438
        }
×
3439

3440
        for _, channel := range nodeChans {
6✔
3441
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3442
                        return channel, nil
3✔
3443
                }
3✔
3444
        }
3445

3446
        return nil, fmt.Errorf("unable to find channel")
3✔
3447
}
3448

3449
// getNodeAnnouncement fetches the current, fully signed node announcement.
3450
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3451
        s.mu.Lock()
3✔
3452
        defer s.mu.Unlock()
3✔
3453

3✔
3454
        return *s.currentNodeAnn
3✔
3455
}
3✔
3456

3457
// genNodeAnnouncement generates and returns the current fully signed node
3458
// announcement. The time stamp of the announcement will be updated in order
3459
// to ensure it propagates through the network.
3460
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3461
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3462

3✔
3463
        s.mu.Lock()
3✔
3464
        defer s.mu.Unlock()
3✔
3465

3✔
3466
        // Create a shallow copy of the current node announcement to work on.
3✔
3467
        // This ensures the original announcement remains unchanged
3✔
3468
        // until the new announcement is fully signed and valid.
3✔
3469
        newNodeAnn := *s.currentNodeAnn
3✔
3470

3✔
3471
        // First, try to update our feature manager with the updated set of
3✔
3472
        // features.
3✔
3473
        if features != nil {
6✔
3474
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3475
                        feature.SetNodeAnn: features,
3✔
3476
                }
3✔
3477
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3478
                if err != nil {
6✔
3479
                        return lnwire.NodeAnnouncement{}, err
3✔
3480
                }
3✔
3481

3482
                // If we could successfully update our feature manager, add
3483
                // an update modifier to include these new features to our
3484
                // set.
3485
                modifiers = append(
3✔
3486
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3487
                )
3✔
3488
        }
3489

3490
        // Always update the timestamp when refreshing to ensure the update
3491
        // propagates.
3492
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3493

3✔
3494
        // Apply the requested changes to the node announcement.
3✔
3495
        for _, modifier := range modifiers {
6✔
3496
                modifier(&newNodeAnn)
3✔
3497
        }
3✔
3498

3499
        // Sign a new update after applying all of the passed modifiers.
3500
        err := netann.SignNodeAnnouncement(
3✔
3501
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3502
        )
3✔
3503
        if err != nil {
3✔
3504
                return lnwire.NodeAnnouncement{}, err
×
3505
        }
×
3506

3507
        // If signing succeeds, update the current announcement.
3508
        *s.currentNodeAnn = newNodeAnn
3✔
3509

3✔
3510
        return *s.currentNodeAnn, nil
3✔
3511
}
3512

3513
// updateAndBroadcastSelfNode generates a new node announcement
3514
// applying the giving modifiers and updating the time stamp
3515
// to ensure it propagates through the network. Then it broadcasts
3516
// it to the network.
3517
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3518
        features *lnwire.RawFeatureVector,
3519
        modifiers ...netann.NodeAnnModifier) error {
3✔
3520

3✔
3521
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3522
        if err != nil {
6✔
3523
                return fmt.Errorf("unable to generate new node "+
3✔
3524
                        "announcement: %v", err)
3✔
3525
        }
3✔
3526

3527
        // Update the on-disk version of our announcement.
3528
        // Load and modify self node istead of creating anew instance so we
3529
        // don't risk overwriting any existing values.
3530
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3531
        if err != nil {
3✔
3532
                return fmt.Errorf("unable to get current source node: %w", err)
×
3533
        }
×
3534

3535
        selfNode.HaveNodeAnnouncement = true
3✔
3536
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3537
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3538
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3539
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3540
        selfNode.Color = newNodeAnn.RGBColor
3✔
3541
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3542

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

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

3549
        // Finally, propagate it to the nodes in the network.
3550
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3551
        if err != nil {
3✔
3552
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3553
                        "announcement to peers: %v", err)
×
3554
                return err
×
3555
        }
×
3556

3557
        return nil
3✔
3558
}
3559

3560
type nodeAddresses struct {
3561
        pubKey    *btcec.PublicKey
3562
        addresses []net.Addr
3563
}
3564

3565
// establishPersistentConnections attempts to establish persistent connections
3566
// to all our direct channel collaborators. In order to promote liveness of our
3567
// active channels, we instruct the connection manager to attempt to establish
3568
// and maintain persistent connections to all our direct channel counterparties.
3569
func (s *server) establishPersistentConnections() error {
3✔
3570
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3571
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3572
        // since other PubKey forms can't be compared.
3✔
3573
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3574

3✔
3575
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3576
        // attempt to connect to based on our set of previous connections. Set
3✔
3577
        // the reconnection port to the default peer port.
3✔
3578
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3579
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3580
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3581
        }
×
3582

3583
        for _, node := range linkNodes {
6✔
3584
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3585
                nodeAddrs := &nodeAddresses{
3✔
3586
                        pubKey:    node.IdentityPub,
3✔
3587
                        addresses: node.Addresses,
3✔
3588
                }
3✔
3589
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3590
        }
3✔
3591

3592
        // After checking our previous connections for addresses to connect to,
3593
        // iterate through the nodes in our channel graph to find addresses
3594
        // that have been added via NodeAnnouncement messages.
3595
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3596
        // each of the nodes.
3597
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3598
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3599

3✔
3600
                // If the remote party has announced the channel to us, but we
3✔
3601
                // haven't yet, then we won't have a policy. However, we don't
3✔
3602
                // need this to connect to the peer, so we'll log it and move on.
3✔
3603
                if !havePolicy {
3✔
3604
                        srvrLog.Warnf("No channel policy found for "+
×
3605
                                "ChannelPoint(%v): ", chanPoint)
×
3606
                }
×
3607

3608
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3609

3✔
3610
                // Add all unique addresses from channel
3✔
3611
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3612
                // connect to for this peer.
3✔
3613
                addrSet := make(map[string]net.Addr)
3✔
3614
                for _, addr := range channelPeer.Addresses {
6✔
3615
                        switch addr.(type) {
3✔
3616
                        case *net.TCPAddr:
3✔
3617
                                addrSet[addr.String()] = addr
3✔
3618

3619
                        // We'll only attempt to connect to Tor addresses if Tor
3620
                        // outbound support is enabled.
3621
                        case *tor.OnionAddr:
×
3622
                                if s.cfg.Tor.Active {
×
3623
                                        addrSet[addr.String()] = addr
×
3624
                                }
×
3625
                        }
3626
                }
3627

3628
                // If this peer is also recorded as a link node, we'll add any
3629
                // additional addresses that have not already been selected.
3630
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3631
                if ok {
6✔
3632
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3633
                                switch lnAddress.(type) {
3✔
3634
                                case *net.TCPAddr:
3✔
3635
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3636

3637
                                // We'll only attempt to connect to Tor
3638
                                // addresses if Tor outbound support is enabled.
3639
                                case *tor.OnionAddr:
×
3640
                                        if s.cfg.Tor.Active {
×
3641
                                                addrSet[lnAddress.String()] = lnAddress
×
3642
                                        }
×
3643
                                }
3644
                        }
3645
                }
3646

3647
                // Construct a slice of the deduped addresses.
3648
                var addrs []net.Addr
3✔
3649
                for _, addr := range addrSet {
6✔
3650
                        addrs = append(addrs, addr)
3✔
3651
                }
3✔
3652

3653
                n := &nodeAddresses{
3✔
3654
                        addresses: addrs,
3✔
3655
                }
3✔
3656
                n.pubKey, err = channelPeer.PubKey()
3✔
3657
                if err != nil {
3✔
3658
                        return err
×
3659
                }
×
3660

3661
                nodeAddrsMap[pubStr] = n
3✔
3662
                return nil
3✔
3663
        })
3664
        if err != nil {
3✔
3665
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3666
                        "%v", err)
×
3667

×
3668
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3669
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3670

×
3671
                        return err
×
3672
                }
×
3673
        }
3674

3675
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3676
                len(nodeAddrsMap))
3✔
3677

3✔
3678
        // Acquire and hold server lock until all persistent connection requests
3✔
3679
        // have been recorded and sent to the connection manager.
3✔
3680
        s.mu.Lock()
3✔
3681
        defer s.mu.Unlock()
3✔
3682

3✔
3683
        // Iterate through the combined list of addresses from prior links and
3✔
3684
        // node announcements and attempt to reconnect to each node.
3✔
3685
        var numOutboundConns int
3✔
3686
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3687
                // Add this peer to the set of peers we should maintain a
3✔
3688
                // persistent connection with. We set the value to false to
3✔
3689
                // indicate that we should not continue to reconnect if the
3✔
3690
                // number of channels returns to zero, since this peer has not
3✔
3691
                // been requested as perm by the user.
3✔
3692
                s.persistentPeers[pubStr] = false
3✔
3693
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3694
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3695
                }
3✔
3696

3697
                for _, address := range nodeAddr.addresses {
6✔
3698
                        // Create a wrapper address which couples the IP and
3✔
3699
                        // the pubkey so the brontide authenticated connection
3✔
3700
                        // can be established.
3✔
3701
                        lnAddr := &lnwire.NetAddress{
3✔
3702
                                IdentityKey: nodeAddr.pubKey,
3✔
3703
                                Address:     address,
3✔
3704
                        }
3✔
3705

3✔
3706
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3707
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3708
                }
3✔
3709

3710
                // We'll connect to the first 10 peers immediately, then
3711
                // randomly stagger any remaining connections if the
3712
                // stagger initial reconnect flag is set. This ensures
3713
                // that mobile nodes or nodes with a small number of
3714
                // channels obtain connectivity quickly, but larger
3715
                // nodes are able to disperse the costs of connecting to
3716
                // all peers at once.
3717
                if numOutboundConns < numInstantInitReconnect ||
3✔
3718
                        !s.cfg.StaggerInitialReconnect {
6✔
3719

3✔
3720
                        go s.connectToPersistentPeer(pubStr)
3✔
3721
                } else {
3✔
3722
                        go s.delayInitialReconnect(pubStr)
×
3723
                }
×
3724

3725
                numOutboundConns++
3✔
3726
        }
3727

3728
        return nil
3✔
3729
}
3730

3731
// delayInitialReconnect will attempt a reconnection to the given peer after
3732
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3733
//
3734
// NOTE: This method MUST be run as a goroutine.
3735
func (s *server) delayInitialReconnect(pubStr string) {
×
3736
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3737
        select {
×
3738
        case <-time.After(delay):
×
3739
                s.connectToPersistentPeer(pubStr)
×
3740
        case <-s.quit:
×
3741
        }
3742
}
3743

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

3✔
3750
        s.mu.Lock()
3✔
3751
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3752
                delete(s.persistentPeers, pubKeyStr)
3✔
3753
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3754
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3755
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3756
                s.mu.Unlock()
3✔
3757

3✔
3758
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3759
                        "peer has no open channels", compressedPubKey)
3✔
3760

3✔
3761
                return
3✔
3762
        }
3✔
3763
        s.mu.Unlock()
3✔
3764
}
3765

3766
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3767
// is instead used to remove persistent peer state for a peer that has been
3768
// disconnected for good cause by the server. Currently, a gossip ban from
3769
// sending garbage and the server running out of restricted-access
3770
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3771
// future, this function may expand when more ban criteria is added.
3772
//
3773
// NOTE: The server's write lock MUST be held when this is called.
3774
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3775
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3776
                delete(s.persistentPeers, remotePub)
×
3777
                delete(s.persistentPeersBackoff, remotePub)
×
3778
                delete(s.persistentPeerAddrs, remotePub)
×
3779
                s.cancelConnReqs(remotePub, nil)
×
3780
        }
×
3781
}
3782

3783
// BroadcastMessage sends a request to the server to broadcast a set of
3784
// messages to all peers other than the one specified by the `skips` parameter.
3785
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3786
// the target peers.
3787
//
3788
// NOTE: This function is safe for concurrent access.
3789
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3790
        msgs ...lnwire.Message) error {
3✔
3791

3✔
3792
        // Filter out peers found in the skips map. We synchronize access to
3✔
3793
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3794
        // exact set of peers present at the time of invocation.
3✔
3795
        s.mu.RLock()
3✔
3796
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3797
        for pubStr, sPeer := range s.peersByPub {
6✔
3798
                if skips != nil {
6✔
3799
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3800
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3801
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3802
                                continue
3✔
3803
                        }
3804
                }
3805

3806
                peers = append(peers, sPeer)
3✔
3807
        }
3808
        s.mu.RUnlock()
3✔
3809

3✔
3810
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3811
        // all messages to each of peers.
3✔
3812
        var wg sync.WaitGroup
3✔
3813
        for _, sPeer := range peers {
6✔
3814
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3815
                        sPeer.PubKey())
3✔
3816

3✔
3817
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3818
                wg.Add(1)
3✔
3819
                s.wg.Add(1)
3✔
3820
                go func(p lnpeer.Peer) {
6✔
3821
                        defer s.wg.Done()
3✔
3822
                        defer wg.Done()
3✔
3823

3✔
3824
                        p.SendMessageLazy(false, msgs...)
3✔
3825
                }(sPeer)
3✔
3826
        }
3827

3828
        // Wait for all messages to have been dispatched before returning to
3829
        // caller.
3830
        wg.Wait()
3✔
3831

3✔
3832
        return nil
3✔
3833
}
3834

3835
// NotifyWhenOnline can be called by other subsystems to get notified when a
3836
// particular peer comes online. The peer itself is sent across the peerChan.
3837
//
3838
// NOTE: This function is safe for concurrent access.
3839
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3840
        peerChan chan<- lnpeer.Peer) {
3✔
3841

3✔
3842
        s.mu.Lock()
3✔
3843

3✔
3844
        // Compute the target peer's identifier.
3✔
3845
        pubStr := string(peerKey[:])
3✔
3846

3✔
3847
        // Check if peer is connected.
3✔
3848
        peer, ok := s.peersByPub[pubStr]
3✔
3849
        if ok {
6✔
3850
                // Unlock here so that the mutex isn't held while we are
3✔
3851
                // waiting for the peer to become active.
3✔
3852
                s.mu.Unlock()
3✔
3853

3✔
3854
                // Wait until the peer signals that it is actually active
3✔
3855
                // rather than only in the server's maps.
3✔
3856
                select {
3✔
3857
                case <-peer.ActiveSignal():
3✔
3858
                case <-peer.QuitSignal():
1✔
3859
                        // The peer quit, so we'll add the channel to the slice
1✔
3860
                        // and return.
1✔
3861
                        s.mu.Lock()
1✔
3862
                        s.peerConnectedListeners[pubStr] = append(
1✔
3863
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3864
                        )
1✔
3865
                        s.mu.Unlock()
1✔
3866
                        return
1✔
3867
                }
3868

3869
                // Connected, can return early.
3870
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3871

3✔
3872
                select {
3✔
3873
                case peerChan <- peer:
3✔
3874
                case <-s.quit:
×
3875
                }
3876

3877
                return
3✔
3878
        }
3879

3880
        // Not connected, store this listener such that it can be notified when
3881
        // the peer comes online.
3882
        s.peerConnectedListeners[pubStr] = append(
3✔
3883
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3884
        )
3✔
3885
        s.mu.Unlock()
3✔
3886
}
3887

3888
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3889
// the given public key has been disconnected. The notification is signaled by
3890
// closing the channel returned.
3891
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3892
        s.mu.Lock()
3✔
3893
        defer s.mu.Unlock()
3✔
3894

3✔
3895
        c := make(chan struct{})
3✔
3896

3✔
3897
        // If the peer is already offline, we can immediately trigger the
3✔
3898
        // notification.
3✔
3899
        peerPubKeyStr := string(peerPubKey[:])
3✔
3900
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3901
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3902
                close(c)
×
3903
                return c
×
3904
        }
×
3905

3906
        // Otherwise, the peer is online, so we'll keep track of the channel to
3907
        // trigger the notification once the server detects the peer
3908
        // disconnects.
3909
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3910
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3911
        )
3✔
3912

3✔
3913
        return c
3✔
3914
}
3915

3916
// FindPeer will return the peer that corresponds to the passed in public key.
3917
// This function is used by the funding manager, allowing it to update the
3918
// daemon's local representation of the remote peer.
3919
//
3920
// NOTE: This function is safe for concurrent access.
3921
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3922
        s.mu.RLock()
3✔
3923
        defer s.mu.RUnlock()
3✔
3924

3✔
3925
        pubStr := string(peerKey.SerializeCompressed())
3✔
3926

3✔
3927
        return s.findPeerByPubStr(pubStr)
3✔
3928
}
3✔
3929

3930
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3931
// which should be a string representation of the peer's serialized, compressed
3932
// public key.
3933
//
3934
// NOTE: This function is safe for concurrent access.
3935
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3936
        s.mu.RLock()
3✔
3937
        defer s.mu.RUnlock()
3✔
3938

3✔
3939
        return s.findPeerByPubStr(pubStr)
3✔
3940
}
3✔
3941

3942
// findPeerByPubStr is an internal method that retrieves the specified peer from
3943
// the server's internal state using.
3944
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3945
        peer, ok := s.peersByPub[pubStr]
3✔
3946
        if !ok {
6✔
3947
                return nil, ErrPeerNotConnected
3✔
3948
        }
3✔
3949

3950
        return peer, nil
3✔
3951
}
3952

3953
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3954
// exponential backoff. If no previous backoff was known, the default is
3955
// returned.
3956
func (s *server) nextPeerBackoff(pubStr string,
3957
        startTime time.Time) time.Duration {
3✔
3958

3✔
3959
        // Now, determine the appropriate backoff to use for the retry.
3✔
3960
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3961
        if !ok {
6✔
3962
                // If an existing backoff was unknown, use the default.
3✔
3963
                return s.cfg.MinBackoff
3✔
3964
        }
3✔
3965

3966
        // If the peer failed to start properly, we'll just use the previous
3967
        // backoff to compute the subsequent randomized exponential backoff
3968
        // duration. This will roughly double on average.
3969
        if startTime.IsZero() {
3✔
3970
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3971
        }
×
3972

3973
        // The peer succeeded in starting. If the connection didn't last long
3974
        // enough to be considered stable, we'll continue to back off retries
3975
        // with this peer.
3976
        connDuration := time.Since(startTime)
3✔
3977
        if connDuration < defaultStableConnDuration {
6✔
3978
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3979
        }
3✔
3980

3981
        // The peer succeed in starting and this was stable peer, so we'll
3982
        // reduce the timeout duration by the length of the connection after
3983
        // applying randomized exponential backoff. We'll only apply this in the
3984
        // case that:
3985
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3986
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3987
        if relaxedBackoff > s.cfg.MinBackoff {
×
3988
                return relaxedBackoff
×
3989
        }
×
3990

3991
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3992
        // the stable connection lasted much longer than our previous backoff.
3993
        // To reward such good behavior, we'll reconnect after the default
3994
        // timeout.
3995
        return s.cfg.MinBackoff
×
3996
}
3997

3998
// shouldDropLocalConnection determines if our local connection to a remote peer
3999
// should be dropped in the case of concurrent connection establishment. In
4000
// order to deterministically decide which connection should be dropped, we'll
4001
// utilize the ordering of the local and remote public key. If we didn't use
4002
// such a tie breaker, then we risk _both_ connections erroneously being
4003
// dropped.
4004
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4005
        localPubBytes := local.SerializeCompressed()
×
4006
        remotePubPbytes := remote.SerializeCompressed()
×
4007

×
4008
        // The connection that comes from the node with a "smaller" pubkey
×
4009
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4010
        // should drop our established connection.
×
4011
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4012
}
×
4013

4014
// InboundPeerConnected initializes a new peer in response to a new inbound
4015
// connection.
4016
//
4017
// NOTE: This function is safe for concurrent access.
4018
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4019
        // Exit early if we have already been instructed to shutdown, this
3✔
4020
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4021
        if s.Stopped() {
3✔
4022
                return
×
4023
        }
×
4024

4025
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4026
        pubSer := nodePub.SerializeCompressed()
3✔
4027
        pubStr := string(pubSer)
3✔
4028

3✔
4029
        var pubBytes [33]byte
3✔
4030
        copy(pubBytes[:], pubSer)
3✔
4031

3✔
4032
        s.mu.Lock()
3✔
4033
        defer s.mu.Unlock()
3✔
4034

3✔
4035
        // If we already have an outbound connection to this peer, then ignore
3✔
4036
        // this new connection.
3✔
4037
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4038
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4039
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4040
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4041

3✔
4042
                conn.Close()
3✔
4043
                return
3✔
4044
        }
3✔
4045

4046
        // If we already have a valid connection that is scheduled to take
4047
        // precedence once the prior peer has finished disconnecting, we'll
4048
        // ignore this connection.
4049
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4050
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4051
                        "scheduled", conn.RemoteAddr(), p)
×
4052
                conn.Close()
×
4053
                return
×
4054
        }
×
4055

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

3✔
4058
        // Check to see if we already have a connection with this peer. If so,
3✔
4059
        // we may need to drop our existing connection. This prevents us from
3✔
4060
        // having duplicate connections to the same peer. We forgo adding a
3✔
4061
        // default case as we expect these to be the only error values returned
3✔
4062
        // from findPeerByPubStr.
3✔
4063
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4064
        switch err {
3✔
4065
        case ErrPeerNotConnected:
3✔
4066
                // We were unable to locate an existing connection with the
3✔
4067
                // target peer, proceed to connect.
3✔
4068
                s.cancelConnReqs(pubStr, nil)
3✔
4069
                s.peerConnected(conn, nil, true)
3✔
4070

4071
        case nil:
3✔
4072
                // We already have a connection with the incoming peer. If the
3✔
4073
                // connection we've already established should be kept and is
3✔
4074
                // not of the same type of the new connection (inbound), then
3✔
4075
                // we'll close out the new connection s.t there's only a single
3✔
4076
                // connection between us.
3✔
4077
                localPub := s.identityECDH.PubKey()
3✔
4078
                if !connectedPeer.Inbound() &&
3✔
4079
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4080

×
4081
                        srvrLog.Warnf("Received inbound connection from "+
×
4082
                                "peer %v, but already have outbound "+
×
4083
                                "connection, dropping conn", connectedPeer)
×
4084
                        conn.Close()
×
4085
                        return
×
4086
                }
×
4087

4088
                // Otherwise, if we should drop the connection, then we'll
4089
                // disconnect our already connected peer.
4090
                srvrLog.Debugf("Disconnecting stale connection to %v",
3✔
4091
                        connectedPeer)
3✔
4092

3✔
4093
                s.cancelConnReqs(pubStr, nil)
3✔
4094

3✔
4095
                // Remove the current peer from the server's internal state and
3✔
4096
                // signal that the peer termination watcher does not need to
3✔
4097
                // execute for this peer.
3✔
4098
                s.removePeerUnsafe(connectedPeer)
3✔
4099
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4100
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4101
                        s.peerConnected(conn, nil, true)
3✔
4102
                }
3✔
4103
        }
4104
}
4105

4106
// OutboundPeerConnected initializes a new peer in response to a new outbound
4107
// connection.
4108
// NOTE: This function is safe for concurrent access.
4109
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4110
        // Exit early if we have already been instructed to shutdown, this
3✔
4111
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4112
        if s.Stopped() {
3✔
4113
                return
×
4114
        }
×
4115

4116
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4117
        pubSer := nodePub.SerializeCompressed()
3✔
4118
        pubStr := string(pubSer)
3✔
4119

3✔
4120
        var pubBytes [33]byte
3✔
4121
        copy(pubBytes[:], pubSer)
3✔
4122

3✔
4123
        s.mu.Lock()
3✔
4124
        defer s.mu.Unlock()
3✔
4125

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

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

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

×
4152
                if connReq != nil {
×
4153
                        s.connMgr.Remove(connReq.ID())
×
4154
                }
×
4155

4156
                conn.Close()
×
4157
                return
×
4158
        }
4159

4160
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4161
                conn.RemoteAddr())
3✔
4162

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

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

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

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

4206
                // Otherwise, _their_ connection should be dropped. So we'll
4207
                // disconnect the peer and send the now obsolete peer to the
4208
                // server for garbage collection.
4209
                srvrLog.Debugf("Disconnecting stale connection to %v",
3✔
4210
                        connectedPeer)
3✔
4211

3✔
4212
                // Remove the current peer from the server's internal state and
3✔
4213
                // signal that the peer termination watcher does not need to
3✔
4214
                // execute for this peer.
3✔
4215
                s.removePeerUnsafe(connectedPeer)
3✔
4216
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4217
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4218
                        s.peerConnected(conn, connReq, false)
3✔
4219
                }
3✔
4220
        }
4221
}
4222

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

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

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

4251
        for _, connReq := range connReqs {
6✔
4252
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4253

3✔
4254
                // Atomically capture the current request identifier.
3✔
4255
                connID := connReq.ID()
3✔
4256

3✔
4257
                // Skip any zero IDs, this indicates the request has not
3✔
4258
                // yet been schedule.
3✔
4259
                if connID == UnassignedConnID {
3✔
4260
                        continue
×
4261
                }
4262

4263
                // Skip a particular connection ID if instructed.
4264
                if skip != nil && connID == *skip {
6✔
4265
                        continue
3✔
4266
                }
4267

4268
                s.connMgr.Remove(connID)
3✔
4269
        }
4270

4271
        delete(s.persistentConnReqs, pubStr)
3✔
4272
}
4273

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

3✔
4280
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4281
                Peer: peer,
3✔
4282
                Msg:  msg,
3✔
4283
        })
3✔
4284
}
3✔
4285

4286
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4287
// messages.
4288
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4289
        return s.customMessageServer.Subscribe()
3✔
4290
}
3✔
4291

4292
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4293
// the channelNotifier's NotifyOpenChannelEvent.
4294
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4295
        remotePub *btcec.PublicKey) {
3✔
4296

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

4303
        // Notify subscribers about this open channel event.
4304
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4305
}
4306

4307
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4308
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4309
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4310
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4311

3✔
4312
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4313
        // peer.
3✔
4314
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4315
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4316
                        "channel[%v] pending open",
×
4317
                        remotePub.SerializeCompressed(), op)
×
4318
        }
×
4319

4320
        // Notify subscribers about this event.
4321
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4322
}
4323

4324
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4325
// calls the channelNotifier's NotifyFundingTimeout.
4326
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4327
        remotePub *btcec.PublicKey) {
3✔
4328

3✔
4329
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4330
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4331
        if err != nil {
3✔
4332
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4333
                        "channel[%v] pending close",
×
4334
                        remotePub.SerializeCompressed(), op)
×
4335
        }
×
4336

4337
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4338
                // If we encounter an error while attempting to disconnect the
×
4339
                // peer, log the error.
×
4340
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4341
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4342
                }
×
4343
        }
4344

4345
        // Notify subscribers about this event.
4346
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4347
}
4348

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

3✔
4356
        brontideConn := conn.(*brontide.Conn)
3✔
4357
        addr := conn.RemoteAddr()
3✔
4358
        pubKey := brontideConn.RemotePub()
3✔
4359

3✔
4360
        // Only restrict access for inbound connections, which means if the
3✔
4361
        // remote node's public key is banned or the restricted slots are used
3✔
4362
        // up, we will drop the connection.
3✔
4363
        //
3✔
4364
        // TODO(yy): Consider perform this check in
3✔
4365
        // `peerAccessMan.addPeerAccess`.
3✔
4366
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4367
        if inbound && err != nil {
3✔
4368
                pubSer := pubKey.SerializeCompressed()
×
4369

×
4370
                // Clean up the persistent peer maps if we're dropping this
×
4371
                // connection.
×
4372
                s.bannedPersistentPeerConnection(string(pubSer))
×
4373

×
4374
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4375
                        "of restricted-access connection slots: %v.", pubSer,
×
4376
                        err)
×
4377

×
4378
                conn.Close()
×
4379

×
4380
                return
×
4381
        }
×
4382

4383
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4384
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4385

3✔
4386
        peerAddr := &lnwire.NetAddress{
3✔
4387
                IdentityKey: pubKey,
3✔
4388
                Address:     addr,
3✔
4389
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4390
        }
3✔
4391

3✔
4392
        // With the brontide connection established, we'll now craft the feature
3✔
4393
        // vectors to advertise to the remote node.
3✔
4394
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4395
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4396

3✔
4397
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4398
        // found, create a fresh buffer.
3✔
4399
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4400
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4401
        if !ok {
6✔
4402
                var err error
3✔
4403
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4404
                if err != nil {
3✔
4405
                        srvrLog.Errorf("unable to create peer %v", err)
×
4406
                        return
×
4407
                }
×
4408
        }
4409

4410
        // If we directly set the peer.Config TowerClient member to the
4411
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4412
        // the peer.Config's TowerClient member will not evaluate to nil even
4413
        // though the underlying value is nil. To avoid this gotcha which can
4414
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4415
        // TowerClient if needed.
4416
        var towerClient wtclient.ClientManager
3✔
4417
        if s.towerClientMgr != nil {
6✔
4418
                towerClient = s.towerClientMgr
3✔
4419
        }
3✔
4420

4421
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4422
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4423

3✔
4424
        // Now that we've established a connection, create a peer, and it to the
3✔
4425
        // set of currently active peers. Configure the peer with the incoming
3✔
4426
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4427
        // offered that would trigger channel closure. In case of outgoing
3✔
4428
        // htlcs, an extra block is added to prevent the channel from being
3✔
4429
        // closed when the htlc is outstanding and a new block comes in.
3✔
4430
        pCfg := peer.Config{
3✔
4431
                Conn:                    brontideConn,
3✔
4432
                ConnReq:                 connReq,
3✔
4433
                Addr:                    peerAddr,
3✔
4434
                Inbound:                 inbound,
3✔
4435
                Features:                initFeatures,
3✔
4436
                LegacyFeatures:          legacyFeatures,
3✔
4437
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4438
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4439
                ErrorBuffer:             errBuffer,
3✔
4440
                WritePool:               s.writePool,
3✔
4441
                ReadPool:                s.readPool,
3✔
4442
                Switch:                  s.htlcSwitch,
3✔
4443
                InterceptSwitch:         s.interceptableSwitch,
3✔
4444
                ChannelDB:               s.chanStateDB,
3✔
4445
                ChannelGraph:            s.graphDB,
3✔
4446
                ChainArb:                s.chainArb,
3✔
4447
                AuthGossiper:            s.authGossiper,
3✔
4448
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4449
                ChainIO:                 s.cc.ChainIO,
3✔
4450
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4451
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4452
                SigPool:                 s.sigPool,
3✔
4453
                Wallet:                  s.cc.Wallet,
3✔
4454
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4455
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4456
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4457
                Sphinx:                  s.sphinx,
3✔
4458
                WitnessBeacon:           s.witnessBeacon,
3✔
4459
                Invoices:                s.invoices,
3✔
4460
                ChannelNotifier:         s.channelNotifier,
3✔
4461
                HtlcNotifier:            s.htlcNotifier,
3✔
4462
                TowerClient:             towerClient,
3✔
4463
                DisconnectPeer:          s.DisconnectPeer,
3✔
4464
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4465
                        lnwire.NodeAnnouncement, error) {
6✔
4466

3✔
4467
                        return s.genNodeAnnouncement(nil)
3✔
4468
                },
3✔
4469

4470
                PongBuf: s.pongBuf,
4471

4472
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4473

4474
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4475

4476
                FundingManager: s.fundingMgr,
4477

4478
                Hodl:                    s.cfg.Hodl,
4479
                UnsafeReplay:            s.cfg.UnsafeReplay,
4480
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4481
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4482
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4483
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4484
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4485
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4486
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4487
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4488
                HandleCustomMessage:    s.handleCustomMessage,
4489
                GetAliases:             s.aliasMgr.GetAliases,
4490
                RequestAlias:           s.aliasMgr.RequestAlias,
4491
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4492
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4493
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4494
                MaxFeeExposure:         thresholdMSats,
4495
                Quit:                   s.quit,
4496
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4497
                AuxSigner:              s.implCfg.AuxSigner,
4498
                MsgRouter:              s.implCfg.MsgRouter,
4499
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4500
                AuxResolver:            s.implCfg.AuxContractResolver,
4501
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4502
                ShouldFwdExpEndorsement: func() bool {
3✔
4503
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4504
                                return false
3✔
4505
                        }
3✔
4506

4507
                        return clock.NewDefaultClock().Now().Before(
3✔
4508
                                EndorsementExperimentEnd,
3✔
4509
                        )
3✔
4510
                },
4511
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4512
        }
4513

4514
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4515
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4516

3✔
4517
        p := peer.NewBrontide(pCfg)
3✔
4518

3✔
4519
        // Update the access manager with the access permission for this peer.
3✔
4520
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4521

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

3✔
4525
        s.addPeer(p)
3✔
4526

3✔
4527
        // Once we have successfully added the peer to the server, we can
3✔
4528
        // delete the previous error buffer from the server's map of error
3✔
4529
        // buffers.
3✔
4530
        delete(s.peerErrors, pkStr)
3✔
4531

3✔
4532
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4533
        // includes sending and receiving Init messages, which would be a DOS
3✔
4534
        // vector if we held the server's mutex throughout the procedure.
3✔
4535
        s.wg.Add(1)
3✔
4536
        go s.peerInitializer(p)
3✔
4537
}
4538

4539
// addPeer adds the passed peer to the server's global state of all active
4540
// peers.
4541
func (s *server) addPeer(p *peer.Brontide) {
3✔
4542
        if p == nil {
3✔
4543
                return
×
4544
        }
×
4545

4546
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4547

3✔
4548
        // Ignore new peers if we're shutting down.
3✔
4549
        if s.Stopped() {
3✔
4550
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4551
                        pubBytes)
×
4552
                p.Disconnect(ErrServerShuttingDown)
×
4553

×
4554
                return
×
4555
        }
×
4556

4557
        // Track the new peer in our indexes so we can quickly look it up either
4558
        // according to its public key, or its peer ID.
4559
        // TODO(roasbeef): pipe all requests through to the
4560
        // queryHandler/peerManager
4561

4562
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4563
        // be human-readable.
4564
        pubStr := string(pubBytes)
3✔
4565

3✔
4566
        s.peersByPub[pubStr] = p
3✔
4567

3✔
4568
        if p.Inbound() {
6✔
4569
                s.inboundPeers[pubStr] = p
3✔
4570
        } else {
6✔
4571
                s.outboundPeers[pubStr] = p
3✔
4572
        }
3✔
4573

4574
        // Inform the peer notifier of a peer online event so that it can be reported
4575
        // to clients listening for peer events.
4576
        var pubKey [33]byte
3✔
4577
        copy(pubKey[:], pubBytes)
3✔
4578

3✔
4579
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4580
}
4581

4582
// peerInitializer asynchronously starts a newly connected peer after it has
4583
// been added to the server's peer map. This method sets up a
4584
// peerTerminationWatcher for the given peer, and ensures that it executes even
4585
// if the peer failed to start. In the event of a successful connection, this
4586
// method reads the negotiated, local feature-bits and spawns the appropriate
4587
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4588
// be signaled of the new peer once the method returns.
4589
//
4590
// NOTE: This MUST be launched as a goroutine.
4591
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4592
        defer s.wg.Done()
3✔
4593

3✔
4594
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4595

3✔
4596
        // Avoid initializing peers while the server is exiting.
3✔
4597
        if s.Stopped() {
3✔
4598
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4599
                        pubBytes)
×
4600
                return
×
4601
        }
×
4602

4603
        // Create a channel that will be used to signal a successful start of
4604
        // the link. This prevents the peer termination watcher from beginning
4605
        // its duty too early.
4606
        ready := make(chan struct{})
3✔
4607

3✔
4608
        // Before starting the peer, launch a goroutine to watch for the
3✔
4609
        // unexpected termination of this peer, which will ensure all resources
3✔
4610
        // are properly cleaned up, and re-establish persistent connections when
3✔
4611
        // necessary. The peer termination watcher will be short circuited if
3✔
4612
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4613
        // that the server has already handled the removal of this peer.
3✔
4614
        s.wg.Add(1)
3✔
4615
        go s.peerTerminationWatcher(p, ready)
3✔
4616

3✔
4617
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4618
        // will unblock the peerTerminationWatcher.
3✔
4619
        if err := p.Start(); err != nil {
6✔
4620
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4621

3✔
4622
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4623
                return
3✔
4624
        }
3✔
4625

4626
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4627
        // was successful, and to begin watching the peer's wait group.
4628
        close(ready)
3✔
4629

3✔
4630
        s.mu.Lock()
3✔
4631
        defer s.mu.Unlock()
3✔
4632

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

3✔
4636
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4637
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4638
        pubStr := string(pubBytes)
3✔
4639
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4640
                select {
3✔
4641
                case peerChan <- p:
3✔
4642
                case <-s.quit:
×
4643
                        return
×
4644
                }
4645
        }
4646
        delete(s.peerConnectedListeners, pubStr)
3✔
4647
}
4648

4649
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4650
// and then cleans up all resources allocated to the peer, notifies relevant
4651
// sub-systems of its demise, and finally handles re-connecting to the peer if
4652
// it's persistent. If the server intentionally disconnects a peer, it should
4653
// have a corresponding entry in the ignorePeerTermination map which will cause
4654
// the cleanup routine to exit early. The passed `ready` chan is used to
4655
// synchronize when WaitForDisconnect should begin watching on the peer's
4656
// waitgroup. The ready chan should only be signaled if the peer starts
4657
// successfully, otherwise the peer should be disconnected instead.
4658
//
4659
// NOTE: This MUST be launched as a goroutine.
4660
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4661
        defer s.wg.Done()
3✔
4662

3✔
4663
        ctx := context.TODO()
3✔
4664

3✔
4665
        p.WaitForDisconnect(ready)
3✔
4666

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

3✔
4669
        // If the server is exiting then we can bail out early ourselves as all
3✔
4670
        // the other sub-systems will already be shutting down.
3✔
4671
        if s.Stopped() {
6✔
4672
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4673
                return
3✔
4674
        }
3✔
4675

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

3✔
4682
        pubKey := p.IdentityKey()
3✔
4683

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

3✔
4688
        // Tell the switch to remove all links associated with this peer.
3✔
4689
        // Passing nil as the target link indicates that all links associated
3✔
4690
        // with this interface should be closed.
3✔
4691
        //
3✔
4692
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4693
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4694
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4695
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4696
        }
×
4697

4698
        for _, link := range links {
6✔
4699
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4700
        }
3✔
4701

4702
        s.mu.Lock()
3✔
4703
        defer s.mu.Unlock()
3✔
4704

3✔
4705
        // If there were any notification requests for when this peer
3✔
4706
        // disconnected, we can trigger them now.
3✔
4707
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4708
        pubStr := string(pubKey.SerializeCompressed())
3✔
4709
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4710
                close(offlineChan)
3✔
4711
        }
3✔
4712
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4713

3✔
4714
        // If the server has already removed this peer, we can short circuit the
3✔
4715
        // peer termination watcher and skip cleanup.
3✔
4716
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4717
                delete(s.ignorePeerTermination, p)
3✔
4718

3✔
4719
                pubKey := p.PubKey()
3✔
4720
                pubStr := string(pubKey[:])
3✔
4721

3✔
4722
                // If a connection callback is present, we'll go ahead and
3✔
4723
                // execute it now that previous peer has fully disconnected. If
3✔
4724
                // the callback is not present, this likely implies the peer was
3✔
4725
                // purposefully disconnected via RPC, and that no reconnect
3✔
4726
                // should be attempted.
3✔
4727
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4728
                if ok {
6✔
4729
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4730
                        connCallback()
3✔
4731
                }
3✔
4732
                return
3✔
4733
        }
4734

4735
        // First, cleanup any remaining state the server has regarding the peer
4736
        // in question.
4737
        s.removePeerUnsafe(p)
3✔
4738

3✔
4739
        // Next, check to see if this is a persistent peer or not.
3✔
4740
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4741
                return
3✔
4742
        }
3✔
4743

4744
        // Get the last address that we used to connect to the peer.
4745
        addrs := []net.Addr{
3✔
4746
                p.NetAddress().Address,
3✔
4747
        }
3✔
4748

3✔
4749
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4750
        // reconnection purposes.
3✔
4751
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4752
        switch {
3✔
4753
        // We found advertised addresses, so use them.
4754
        case err == nil:
3✔
4755
                addrs = advertisedAddrs
3✔
4756

4757
        // The peer doesn't have an advertised address.
4758
        case err == errNoAdvertisedAddr:
3✔
4759
                // If it is an outbound peer then we fall back to the existing
3✔
4760
                // peer address.
3✔
4761
                if !p.Inbound() {
6✔
4762
                        break
3✔
4763
                }
4764

4765
                // Fall back to the existing peer address if
4766
                // we're not accepting connections over Tor.
4767
                if s.torController == nil {
6✔
4768
                        break
3✔
4769
                }
4770

4771
                // If we are, the peer's address won't be known
4772
                // to us (we'll see a private address, which is
4773
                // the address used by our onion service to dial
4774
                // to lnd), so we don't have enough information
4775
                // to attempt a reconnect.
4776
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4777
                        "to inbound peer %v without "+
×
4778
                        "advertised address", p)
×
4779
                return
×
4780

4781
        // We came across an error retrieving an advertised
4782
        // address, log it, and fall back to the existing peer
4783
        // address.
4784
        default:
3✔
4785
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4786
                        "address for node %x: %v", p.PubKey(),
3✔
4787
                        err)
3✔
4788
        }
4789

4790
        // Make an easy lookup map so that we can check if an address
4791
        // is already in the address list that we have stored for this peer.
4792
        existingAddrs := make(map[string]bool)
3✔
4793
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4794
                existingAddrs[addr.String()] = true
3✔
4795
        }
3✔
4796

4797
        // Add any missing addresses for this peer to persistentPeerAddr.
4798
        for _, addr := range addrs {
6✔
4799
                if existingAddrs[addr.String()] {
3✔
4800
                        continue
×
4801
                }
4802

4803
                s.persistentPeerAddrs[pubStr] = append(
3✔
4804
                        s.persistentPeerAddrs[pubStr],
3✔
4805
                        &lnwire.NetAddress{
3✔
4806
                                IdentityKey: p.IdentityKey(),
3✔
4807
                                Address:     addr,
3✔
4808
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4809
                        },
3✔
4810
                )
3✔
4811
        }
4812

4813
        // Record the computed backoff in the backoff map.
4814
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4815
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4816

3✔
4817
        // Initialize a retry canceller for this peer if one does not
3✔
4818
        // exist.
3✔
4819
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4820
        if !ok {
6✔
4821
                cancelChan = make(chan struct{})
3✔
4822
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4823
        }
3✔
4824

4825
        // We choose not to wait group this go routine since the Connect
4826
        // call can stall for arbitrarily long if we shutdown while an
4827
        // outbound connection attempt is being made.
4828
        go func() {
6✔
4829
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4830
                        "persistent peer %x in %s",
3✔
4831
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4832

3✔
4833
                select {
3✔
4834
                case <-time.After(backoff):
3✔
4835
                case <-cancelChan:
3✔
4836
                        return
3✔
4837
                case <-s.quit:
3✔
4838
                        return
3✔
4839
                }
4840

4841
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4842
                        "connection to peer %x",
3✔
4843
                        p.IdentityKey().SerializeCompressed())
3✔
4844

3✔
4845
                s.connectToPersistentPeer(pubStr)
3✔
4846
        }()
4847
}
4848

4849
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4850
// to connect to the peer. It creates connection requests if there are
4851
// currently none for a given address and it removes old connection requests
4852
// if the associated address is no longer in the latest address list for the
4853
// peer.
4854
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4855
        s.mu.Lock()
3✔
4856
        defer s.mu.Unlock()
3✔
4857

3✔
4858
        // Create an easy lookup map of the addresses we have stored for the
3✔
4859
        // peer. We will remove entries from this map if we have existing
3✔
4860
        // connection requests for the associated address and then any leftover
3✔
4861
        // entries will indicate which addresses we should create new
3✔
4862
        // connection requests for.
3✔
4863
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4864
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4865
                addrMap[addr.String()] = addr
3✔
4866
        }
3✔
4867

4868
        // Go through each of the existing connection requests and
4869
        // check if they correspond to the latest set of addresses. If
4870
        // there is a connection requests that does not use one of the latest
4871
        // advertised addresses then remove that connection request.
4872
        var updatedConnReqs []*connmgr.ConnReq
3✔
4873
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4874
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4875

3✔
4876
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4877
                // If the existing connection request is using one of the
4878
                // latest advertised addresses for the peer then we add it to
4879
                // updatedConnReqs and remove the associated address from
4880
                // addrMap so that we don't recreate this connReq later on.
4881
                case true:
×
4882
                        updatedConnReqs = append(
×
4883
                                updatedConnReqs, connReq,
×
4884
                        )
×
4885
                        delete(addrMap, lnAddr)
×
4886

4887
                // If the existing connection request is using an address that
4888
                // is not one of the latest advertised addresses for the peer
4889
                // then we remove the connecting request from the connection
4890
                // manager.
4891
                case false:
3✔
4892
                        srvrLog.Info(
3✔
4893
                                "Removing conn req:", connReq.Addr.String(),
3✔
4894
                        )
3✔
4895
                        s.connMgr.Remove(connReq.ID())
3✔
4896
                }
4897
        }
4898

4899
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4900

3✔
4901
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4902
        if !ok {
6✔
4903
                cancelChan = make(chan struct{})
3✔
4904
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4905
        }
3✔
4906

4907
        // Any addresses left in addrMap are new ones that we have not made
4908
        // connection requests for. So create new connection requests for those.
4909
        // If there is more than one address in the address map, stagger the
4910
        // creation of the connection requests for those.
4911
        go func() {
6✔
4912
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4913
                defer ticker.Stop()
3✔
4914

3✔
4915
                for _, addr := range addrMap {
6✔
4916
                        // Send the persistent connection request to the
3✔
4917
                        // connection manager, saving the request itself so we
3✔
4918
                        // can cancel/restart the process as needed.
3✔
4919
                        connReq := &connmgr.ConnReq{
3✔
4920
                                Addr:      addr,
3✔
4921
                                Permanent: true,
3✔
4922
                        }
3✔
4923

3✔
4924
                        s.mu.Lock()
3✔
4925
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4926
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4927
                        )
3✔
4928
                        s.mu.Unlock()
3✔
4929

3✔
4930
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4931
                                "channel peer %v", addr)
3✔
4932

3✔
4933
                        go s.connMgr.Connect(connReq)
3✔
4934

3✔
4935
                        select {
3✔
4936
                        case <-s.quit:
3✔
4937
                                return
3✔
4938
                        case <-cancelChan:
3✔
4939
                                return
3✔
4940
                        case <-ticker.C:
3✔
4941
                        }
4942
                }
4943
        }()
4944
}
4945

4946
// removePeerUnsafe removes the passed peer from the server's state of all
4947
// active peers.
4948
//
4949
// NOTE: Server mutex must be held when calling this function.
4950
func (s *server) removePeerUnsafe(p *peer.Brontide) {
3✔
4951
        if p == nil {
3✔
4952
                return
×
4953
        }
×
4954

4955
        srvrLog.Debugf("Removing peer %v", p)
3✔
4956

3✔
4957
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4958
        // will be disconnected in the server shutdown process.
3✔
4959
        if s.Stopped() {
3✔
4960
                return
×
4961
        }
×
4962

4963
        // Capture the peer's public key and string representation.
4964
        pKey := p.PubKey()
3✔
4965
        pubSer := pKey[:]
3✔
4966
        pubStr := string(pubSer)
3✔
4967

3✔
4968
        delete(s.peersByPub, pubStr)
3✔
4969

3✔
4970
        if p.Inbound() {
6✔
4971
                delete(s.inboundPeers, pubStr)
3✔
4972
        } else {
6✔
4973
                delete(s.outboundPeers, pubStr)
3✔
4974
        }
3✔
4975

4976
        // When removing the peer we make sure to disconnect it asynchronously
4977
        // to avoid blocking the main server goroutine because it is holding the
4978
        // server's mutex. Disconnecting the peer might block and wait until the
4979
        // peer has fully started up. This can happen if an inbound and outbound
4980
        // race condition occurs.
4981
        s.wg.Add(1)
3✔
4982
        go func() {
6✔
4983
                defer s.wg.Done()
3✔
4984

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

3✔
4987
                // If this peer had an active persistent connection request,
3✔
4988
                // remove it.
3✔
4989
                if p.ConnReq() != nil {
6✔
4990
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4991
                }
3✔
4992

4993
                // Remove the peer's access permission from the access manager.
4994
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4995
                s.peerAccessMan.removePeerAccess(peerPubStr)
3✔
4996

3✔
4997
                // Copy the peer's error buffer across to the server if it has
3✔
4998
                // any items in it so that we can restore peer errors across
3✔
4999
                // connections. We need to look up the error after the peer has
3✔
5000
                // been disconnected because we write the error in the
3✔
5001
                // `Disconnect` method.
3✔
5002
                s.mu.Lock()
3✔
5003
                if p.ErrorBuffer().Total() > 0 {
6✔
5004
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5005
                }
3✔
5006
                s.mu.Unlock()
3✔
5007

3✔
5008
                // Inform the peer notifier of a peer offline event so that it
3✔
5009
                // can be reported to clients listening for peer events.
3✔
5010
                var pubKey [33]byte
3✔
5011
                copy(pubKey[:], pubSer)
3✔
5012

3✔
5013
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5014
        }()
5015
}
5016

5017
// ConnectToPeer requests that the server connect to a Lightning Network peer
5018
// at the specified address. This function will *block* until either a
5019
// connection is established, or the initial handshake process fails.
5020
//
5021
// NOTE: This function is safe for concurrent access.
5022
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5023
        perm bool, timeout time.Duration) error {
3✔
5024

3✔
5025
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5026

3✔
5027
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5028
        // better granularity.  In certain conditions, this method requires
3✔
5029
        // making an outbound connection to a remote peer, which requires the
3✔
5030
        // lock to be released, and subsequently reacquired.
3✔
5031
        s.mu.Lock()
3✔
5032

3✔
5033
        // Ensure we're not already connected to this peer.
3✔
5034
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5035

3✔
5036
        // When there's no error it means we already have a connection with this
3✔
5037
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5038
        // set, we will ignore the existing connection and continue.
3✔
5039
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5040
                s.mu.Unlock()
3✔
5041
                return &errPeerAlreadyConnected{peer: peer}
3✔
5042
        }
3✔
5043

5044
        // Peer was not found, continue to pursue connection with peer.
5045

5046
        // If there's already a pending connection request for this pubkey,
5047
        // then we ignore this request to ensure we don't create a redundant
5048
        // connection.
5049
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5050
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5051
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5052
        }
3✔
5053

5054
        // If there's not already a pending or active connection to this node,
5055
        // then instruct the connection manager to attempt to establish a
5056
        // persistent connection to the peer.
5057
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5058
        if perm {
6✔
5059
                connReq := &connmgr.ConnReq{
3✔
5060
                        Addr:      addr,
3✔
5061
                        Permanent: true,
3✔
5062
                }
3✔
5063

3✔
5064
                // Since the user requested a permanent connection, we'll set
3✔
5065
                // the entry to true which will tell the server to continue
3✔
5066
                // reconnecting even if the number of channels with this peer is
3✔
5067
                // zero.
3✔
5068
                s.persistentPeers[targetPub] = true
3✔
5069
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5070
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5071
                }
3✔
5072
                s.persistentConnReqs[targetPub] = append(
3✔
5073
                        s.persistentConnReqs[targetPub], connReq,
3✔
5074
                )
3✔
5075
                s.mu.Unlock()
3✔
5076

3✔
5077
                go s.connMgr.Connect(connReq)
3✔
5078

3✔
5079
                return nil
3✔
5080
        }
5081
        s.mu.Unlock()
3✔
5082

3✔
5083
        // If we're not making a persistent connection, then we'll attempt to
3✔
5084
        // connect to the target peer. If the we can't make the connection, or
3✔
5085
        // the crypto negotiation breaks down, then return an error to the
3✔
5086
        // caller.
3✔
5087
        errChan := make(chan error, 1)
3✔
5088
        s.connectToPeer(addr, errChan, timeout)
3✔
5089

3✔
5090
        select {
3✔
5091
        case err := <-errChan:
3✔
5092
                return err
3✔
5093
        case <-s.quit:
×
5094
                return ErrServerShuttingDown
×
5095
        }
5096
}
5097

5098
// connectToPeer establishes a connection to a remote peer. errChan is used to
5099
// notify the caller if the connection attempt has failed. Otherwise, it will be
5100
// closed.
5101
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5102
        errChan chan<- error, timeout time.Duration) {
3✔
5103

3✔
5104
        conn, err := brontide.Dial(
3✔
5105
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5106
        )
3✔
5107
        if err != nil {
6✔
5108
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5109
                select {
3✔
5110
                case errChan <- err:
3✔
5111
                case <-s.quit:
×
5112
                }
5113
                return
3✔
5114
        }
5115

5116
        close(errChan)
3✔
5117

3✔
5118
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5119
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5120

3✔
5121
        s.OutboundPeerConnected(nil, conn)
3✔
5122
}
5123

5124
// DisconnectPeer sends the request to server to close the connection with peer
5125
// identified by public key.
5126
//
5127
// NOTE: This function is safe for concurrent access.
5128
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5129
        pubBytes := pubKey.SerializeCompressed()
3✔
5130
        pubStr := string(pubBytes)
3✔
5131

3✔
5132
        s.mu.Lock()
3✔
5133
        defer s.mu.Unlock()
3✔
5134

3✔
5135
        // Check that were actually connected to this peer. If not, then we'll
3✔
5136
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5137
        // currently connected to.
3✔
5138
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5139
        if err == ErrPeerNotConnected {
6✔
5140
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5141
        }
3✔
5142

5143
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5144

3✔
5145
        s.cancelConnReqs(pubStr, nil)
3✔
5146

3✔
5147
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5148
        // them from this map so we don't attempt to re-connect after we
3✔
5149
        // disconnect.
3✔
5150
        delete(s.persistentPeers, pubStr)
3✔
5151
        delete(s.persistentPeersBackoff, pubStr)
3✔
5152

3✔
5153
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5154
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5155
        //
3✔
5156
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5157
        // goroutine because we might hold the server's mutex.
3✔
5158
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5159

3✔
5160
        return nil
3✔
5161
}
5162

5163
// OpenChannel sends a request to the server to open a channel to the specified
5164
// peer identified by nodeKey with the passed channel funding parameters.
5165
//
5166
// NOTE: This function is safe for concurrent access.
5167
func (s *server) OpenChannel(
5168
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5169

3✔
5170
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5171
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5172
        // not blocked if the caller is not reading the updates.
3✔
5173
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5174
        req.Err = make(chan error, 1)
3✔
5175

3✔
5176
        // First attempt to locate the target peer to open a channel with, if
3✔
5177
        // we're unable to locate the peer then this request will fail.
3✔
5178
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5179
        s.mu.RLock()
3✔
5180
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5181
        if !ok {
3✔
5182
                s.mu.RUnlock()
×
5183

×
5184
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5185
                return req.Updates, req.Err
×
5186
        }
×
5187
        req.Peer = peer
3✔
5188
        s.mu.RUnlock()
3✔
5189

3✔
5190
        // We'll wait until the peer is active before beginning the channel
3✔
5191
        // opening process.
3✔
5192
        select {
3✔
5193
        case <-peer.ActiveSignal():
3✔
5194
        case <-peer.QuitSignal():
×
5195
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5196
                return req.Updates, req.Err
×
5197
        case <-s.quit:
×
5198
                req.Err <- ErrServerShuttingDown
×
5199
                return req.Updates, req.Err
×
5200
        }
5201

5202
        // If the fee rate wasn't specified at this point we fail the funding
5203
        // because of the missing fee rate information. The caller of the
5204
        // `OpenChannel` method needs to make sure that default values for the
5205
        // fee rate are set beforehand.
5206
        if req.FundingFeePerKw == 0 {
3✔
5207
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5208
                        "the channel opening transaction")
×
5209

×
5210
                return req.Updates, req.Err
×
5211
        }
×
5212

5213
        // Spawn a goroutine to send the funding workflow request to the funding
5214
        // manager. This allows the server to continue handling queries instead
5215
        // of blocking on this request which is exported as a synchronous
5216
        // request to the outside world.
5217
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5218

3✔
5219
        return req.Updates, req.Err
3✔
5220
}
5221

5222
// Peers returns a slice of all active peers.
5223
//
5224
// NOTE: This function is safe for concurrent access.
5225
func (s *server) Peers() []*peer.Brontide {
3✔
5226
        s.mu.RLock()
3✔
5227
        defer s.mu.RUnlock()
3✔
5228

3✔
5229
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5230
        for _, peer := range s.peersByPub {
6✔
5231
                peers = append(peers, peer)
3✔
5232
        }
3✔
5233

5234
        return peers
3✔
5235
}
5236

5237
// computeNextBackoff uses a truncated exponential backoff to compute the next
5238
// backoff using the value of the exiting backoff. The returned duration is
5239
// randomized in either direction by 1/20 to prevent tight loops from
5240
// stabilizing.
5241
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5242
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5243
        nextBackoff := 2 * currBackoff
3✔
5244
        if nextBackoff > maxBackoff {
6✔
5245
                nextBackoff = maxBackoff
3✔
5246
        }
3✔
5247

5248
        // Using 1/10 of our duration as a margin, compute a random offset to
5249
        // avoid the nodes entering connection cycles.
5250
        margin := nextBackoff / 10
3✔
5251

3✔
5252
        var wiggle big.Int
3✔
5253
        wiggle.SetUint64(uint64(margin))
3✔
5254
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5255
                // Randomizing is not mission critical, so we'll just return the
×
5256
                // current backoff.
×
5257
                return nextBackoff
×
5258
        }
×
5259

5260
        // Otherwise add in our wiggle, but subtract out half of the margin so
5261
        // that the backoff can tweaked by 1/20 in either direction.
5262
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5263
}
5264

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

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

3✔
5273
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5274
        if err != nil {
3✔
5275
                return nil, err
×
5276
        }
×
5277

5278
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5279
        if err != nil {
6✔
5280
                return nil, err
3✔
5281
        }
3✔
5282

5283
        if len(node.Addresses) == 0 {
6✔
5284
                return nil, errNoAdvertisedAddr
3✔
5285
        }
3✔
5286

5287
        return node.Addresses, nil
3✔
5288
}
5289

5290
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5291
// channel update for a target channel.
5292
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5293
        *lnwire.ChannelUpdate1, error) {
3✔
5294

3✔
5295
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5296
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5297
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5298
                if err != nil {
6✔
5299
                        return nil, err
3✔
5300
                }
3✔
5301

5302
                return netann.ExtractChannelUpdate(
3✔
5303
                        ourPubKey[:], info, edge1, edge2,
3✔
5304
                )
3✔
5305
        }
5306
}
5307

5308
// applyChannelUpdate applies the channel update to the different sub-systems of
5309
// the server. The useAlias boolean denotes whether or not to send an alias in
5310
// place of the real SCID.
5311
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5312
        op *wire.OutPoint, useAlias bool) error {
3✔
5313

3✔
5314
        var (
3✔
5315
                peerAlias    *lnwire.ShortChannelID
3✔
5316
                defaultAlias lnwire.ShortChannelID
3✔
5317
        )
3✔
5318

3✔
5319
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5320

3✔
5321
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5322
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5323
        if useAlias {
6✔
5324
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5325
                if foundAlias != defaultAlias {
6✔
5326
                        peerAlias = &foundAlias
3✔
5327
                }
3✔
5328
        }
5329

5330
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5331
                update, discovery.RemoteAlias(peerAlias),
3✔
5332
        )
3✔
5333
        select {
3✔
5334
        case err := <-errChan:
3✔
5335
                return err
3✔
5336
        case <-s.quit:
×
5337
                return ErrServerShuttingDown
×
5338
        }
5339
}
5340

5341
// SendCustomMessage sends a custom message to the peer with the specified
5342
// pubkey.
5343
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5344
        data []byte) error {
3✔
5345

3✔
5346
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5347
        if err != nil {
3✔
5348
                return err
×
5349
        }
×
5350

5351
        // We'll wait until the peer is active.
5352
        select {
3✔
5353
        case <-peer.ActiveSignal():
3✔
5354
        case <-peer.QuitSignal():
×
5355
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5356
        case <-s.quit:
×
5357
                return ErrServerShuttingDown
×
5358
        }
5359

5360
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5361
        if err != nil {
6✔
5362
                return err
3✔
5363
        }
3✔
5364

5365
        // Send the message as low-priority. For now we assume that all
5366
        // application-defined message are low priority.
5367
        return peer.SendMessageLazy(true, msg)
3✔
5368
}
5369

5370
// newSweepPkScriptGen creates closure that generates a new public key script
5371
// which should be used to sweep any funds into the on-chain wallet.
5372
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5373
// (p2wkh) output.
5374
func newSweepPkScriptGen(
5375
        wallet lnwallet.WalletController,
5376
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5377

3✔
5378
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5379
                sweepAddr, err := wallet.NewAddress(
3✔
5380
                        lnwallet.TaprootPubkey, false,
3✔
5381
                        lnwallet.DefaultAccountName,
3✔
5382
                )
3✔
5383
                if err != nil {
3✔
5384
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5385
                }
×
5386

5387
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5388
                if err != nil {
3✔
5389
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5390
                }
×
5391

5392
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5393
                        wallet, netParams, addr,
3✔
5394
                )
3✔
5395
                if err != nil {
3✔
5396
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5397
                }
×
5398

5399
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5400
                        DeliveryAddress: addr,
3✔
5401
                        InternalKey:     internalKeyDesc,
3✔
5402
                })
3✔
5403
        }
5404
}
5405

5406
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5407
// finished.
5408
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5409
        // Get a list of closed channels.
3✔
5410
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5411
        if err != nil {
3✔
5412
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5413
                return nil
×
5414
        }
×
5415

5416
        // Save the SCIDs in a map.
5417
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5418
        for _, c := range channels {
6✔
5419
                // If the channel is not pending, its FC has been finalized.
3✔
5420
                if !c.IsPending {
6✔
5421
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5422
                }
3✔
5423
        }
5424

5425
        // Double check whether the reported closed channel has indeed finished
5426
        // closing.
5427
        //
5428
        // NOTE: There are misalignments regarding when a channel's FC is
5429
        // marked as finalized. We double check the pending channels to make
5430
        // sure the returned SCIDs are indeed terminated.
5431
        //
5432
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5433
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5434
        if err != nil {
3✔
5435
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5436
                return nil
×
5437
        }
×
5438

5439
        for _, c := range pendings {
6✔
5440
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5441
                        continue
3✔
5442
                }
5443

5444
                // If the channel is still reported as pending, remove it from
5445
                // the map.
5446
                delete(closedSCIDs, c.ShortChannelID)
×
5447

×
5448
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5449
                        c.ShortChannelID)
×
5450
        }
5451

5452
        return closedSCIDs
3✔
5453
}
5454

5455
// getStartingBeat returns the current beat. This is used during the startup to
5456
// initialize blockbeat consumers.
5457
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5458
        // beat is the current blockbeat.
3✔
5459
        var beat *chainio.Beat
3✔
5460

3✔
5461
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5462
        // we will skip fetching the best block.
3✔
5463
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5464
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5465
                        "mode")
×
5466

×
5467
                return &chainio.Beat{}, nil
×
5468
        }
×
5469

5470
        // We should get a notification with the current best block immediately
5471
        // by passing a nil block.
5472
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5473
        if err != nil {
3✔
5474
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5475
        }
×
5476
        defer blockEpochs.Cancel()
3✔
5477

3✔
5478
        // We registered for the block epochs with a nil request. The notifier
3✔
5479
        // should send us the current best block immediately. So we need to
3✔
5480
        // wait for it here because we need to know the current best height.
3✔
5481
        select {
3✔
5482
        case bestBlock := <-blockEpochs.Epochs:
3✔
5483
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5484
                        bestBlock.Hash, bestBlock.Height)
3✔
5485

3✔
5486
                // Update the current blockbeat.
3✔
5487
                beat = chainio.NewBeat(*bestBlock)
3✔
5488

5489
        case <-s.quit:
×
5490
                srvrLog.Debug("LND shutting down")
×
5491
        }
5492

5493
        return beat, nil
3✔
5494
}
5495

5496
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5497
// point has an active RBF chan closer.
5498
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5499
        chanPoint wire.OutPoint) bool {
3✔
5500

3✔
5501
        pubBytes := peerPub.SerializeCompressed()
3✔
5502

3✔
5503
        s.mu.RLock()
3✔
5504
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5505
        s.mu.RUnlock()
3✔
5506
        if !ok {
3✔
5507
                return false
×
5508
        }
×
5509

5510
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5511
}
5512

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

3✔
5521
        // First, we'll attempt to look up the channel based on it's
3✔
5522
        // ChannelPoint.
3✔
5523
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5524
        if err != nil {
3✔
5525
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5526
        }
×
5527

5528
        // From the channel, we can now get the pubkey of the peer, then use
5529
        // that to eventually get the chan closer.
5530
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5531

3✔
5532
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5533
        s.mu.RLock()
3✔
5534
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5535
        s.mu.RUnlock()
3✔
5536
        if !ok {
3✔
5537
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5538
                        "not online", chanPoint)
×
5539
        }
×
5540

5541
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5542
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5543
        )
3✔
5544
        if err != nil {
3✔
5545
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5546
                        "%w", err)
×
5547
        }
×
5548

5549
        return closeUpdates, nil
3✔
5550
}
5551

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

3✔
5560
        // If the channel is present in the switch, then the request should flow
3✔
5561
        // through the switch instead.
3✔
5562
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5563
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5564
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5565
                        "invalid request", chanPoint)
×
5566
        }
×
5567

5568
        // At this point, we know that the channel isn't present in the link, so
5569
        // we'll check to see if we have an entry in the active chan closer map.
5570
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5571
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5572
        )
3✔
5573
        if err != nil {
3✔
5574
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5575
                        "ChannelPoint(%v)", chanPoint)
×
5576
        }
×
5577

5578
        return updates, nil
3✔
5579
}
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